civetweb.c 443 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836
  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. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. #ifndef CIVETWEB_HEADER_INCLUDED
  101. /* Include the header file here, so the CivetWeb interface is defined for the
  102. * entire implementation, including the following forward definitions. */
  103. #include "civetweb.h"
  104. #endif
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __clang__
  116. /* When using -Weverything, clang does not accept it's own headers
  117. * in a release build configuration. Disable what is too much in
  118. * -Weverything. */
  119. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  120. #endif
  121. #ifdef __MACH__ /* Apple OSX section */
  122. #ifdef __clang__
  123. /* Avoid warnings for Xopen 7.00 and higher */
  124. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  125. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  126. #endif
  127. #define CLOCK_MONOTONIC (1)
  128. #define CLOCK_REALTIME (2)
  129. #include <sys/errno.h>
  130. #include <sys/time.h>
  131. #include <mach/clock.h>
  132. #include <mach/mach.h>
  133. #include <mach/mach_time.h>
  134. #include <assert.h>
  135. /* clock_gettime is not implemented on OSX prior to 10.12 */
  136. static int
  137. _civet_clock_gettime(int clk_id, struct timespec *t)
  138. {
  139. memset(t, 0, sizeof(*t));
  140. if (clk_id == CLOCK_REALTIME) {
  141. struct timeval now;
  142. int rv = gettimeofday(&now, NULL);
  143. if (rv) {
  144. return rv;
  145. }
  146. t->tv_sec = now.tv_sec;
  147. t->tv_nsec = now.tv_usec * 1000;
  148. return 0;
  149. } else if (clk_id == CLOCK_MONOTONIC) {
  150. static uint64_t clock_start_time = 0;
  151. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  152. uint64_t now = mach_absolute_time();
  153. if (clock_start_time == 0) {
  154. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  155. #if defined(DEBUG)
  156. assert(mach_status == KERN_SUCCESS);
  157. #else
  158. /* appease "unused variable" warning for release builds */
  159. (void)mach_status;
  160. #endif
  161. clock_start_time = now;
  162. }
  163. now = (uint64_t)((double)(now - clock_start_time)
  164. * (double)timebase_ifo.numer
  165. / (double)timebase_ifo.denom);
  166. t->tv_sec = now / 1000000000;
  167. t->tv_nsec = now % 1000000000;
  168. return 0;
  169. }
  170. return -1; /* EINVAL - Clock ID is unknown */
  171. }
  172. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  173. #ifdef __CLOCK_AVAILABILITY
  174. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  175. * declared but it may be NULL at runtime. So we need to check before using
  176. * it. */
  177. static int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #include <stdint.h>
  200. #ifndef INT64_MAX
  201. #define INT64_MAX (9223372036854775807)
  202. #endif
  203. #ifndef MAX_WORKER_THREADS
  204. #define MAX_WORKER_THREADS (1024 * 64)
  205. #endif
  206. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  207. #define SOCKET_TIMEOUT_QUANTUM (2000)
  208. #endif
  209. #define SHUTDOWN_RD (0)
  210. #define SHUTDOWN_WR (1)
  211. #define SHUTDOWN_BOTH (2)
  212. mg_static_assert(MAX_WORKER_THREADS >= 1,
  213. "worker threads must be a positive number");
  214. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  215. "size_t data type size check");
  216. #if defined(_WIN32) \
  217. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  218. #include <windows.h>
  219. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  220. #include <ws2tcpip.h>
  221. typedef const char *SOCK_OPT_TYPE;
  222. #if !defined(PATH_MAX)
  223. #define PATH_MAX (MAX_PATH)
  224. #endif
  225. #if !defined(PATH_MAX)
  226. #define PATH_MAX (4096)
  227. #endif
  228. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  229. #ifndef _IN_PORT_T
  230. #ifndef in_port_t
  231. #define in_port_t u_short
  232. #endif
  233. #endif
  234. #ifndef _WIN32_WCE
  235. #include <process.h>
  236. #include <direct.h>
  237. #include <io.h>
  238. #else /* _WIN32_WCE */
  239. #define NO_CGI /* WinCE has no pipes */
  240. #define NO_POPEN /* WinCE has no popen */
  241. typedef long off_t;
  242. #define errno ((int)(GetLastError()))
  243. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  244. #endif /* _WIN32_WCE */
  245. #define MAKEUQUAD(lo, hi) \
  246. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  247. #define RATE_DIFF (10000000) /* 100 nsecs */
  248. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  249. #define SYS2UNIX_TIME(lo, hi) \
  250. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  251. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  252. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  253. * Also use _strtoui64 on modern M$ compilers */
  254. #if defined(_MSC_VER)
  255. #if (_MSC_VER < 1300)
  256. #define STRX(x) #x
  257. #define STR(x) STRX(x)
  258. #define __func__ __FILE__ ":" STR(__LINE__)
  259. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  260. #define strtoll(x, y, z) (_atoi64(x))
  261. #else
  262. #define __func__ __FUNCTION__
  263. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  264. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  265. #endif
  266. #endif /* _MSC_VER */
  267. #define ERRNO ((int)(GetLastError()))
  268. #define NO_SOCKLEN_T
  269. #if defined(_WIN64) || defined(__MINGW64__)
  270. #define SSL_LIB "ssleay64.dll"
  271. #define CRYPTO_LIB "libeay64.dll"
  272. #else
  273. #define SSL_LIB "ssleay32.dll"
  274. #define CRYPTO_LIB "libeay32.dll"
  275. #endif
  276. #define O_NONBLOCK (0)
  277. #ifndef W_OK
  278. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  279. #endif
  280. #if !defined(EWOULDBLOCK)
  281. #define EWOULDBLOCK WSAEWOULDBLOCK
  282. #endif /* !EWOULDBLOCK */
  283. #define _POSIX_
  284. #define INT64_FMT "I64d"
  285. #define UINT64_FMT "I64u"
  286. #define WINCDECL __cdecl
  287. #define vsnprintf_impl _vsnprintf
  288. #define access _access
  289. #define mg_sleep(x) (Sleep(x))
  290. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  291. #ifndef popen
  292. #define popen(x, y) (_popen(x, y))
  293. #endif
  294. #ifndef pclose
  295. #define pclose(x) (_pclose(x))
  296. #endif
  297. #define close(x) (_close(x))
  298. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  299. #define RTLD_LAZY (0)
  300. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  301. #define fdopen(x, y) (_fdopen((x), (y)))
  302. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  303. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  304. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  305. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  306. #define sleep(x) (Sleep((x)*1000))
  307. #define rmdir(x) (_rmdir(x))
  308. #define timegm(x) (_mkgmtime(x))
  309. #if !defined(fileno)
  310. #define fileno(x) (_fileno(x))
  311. #endif /* !fileno MINGW #defines fileno */
  312. typedef HANDLE pthread_mutex_t;
  313. typedef DWORD pthread_key_t;
  314. typedef HANDLE pthread_t;
  315. typedef struct {
  316. CRITICAL_SECTION threadIdSec;
  317. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  318. } pthread_cond_t;
  319. #ifndef __clockid_t_defined
  320. typedef DWORD clockid_t;
  321. #endif
  322. #ifndef CLOCK_MONOTONIC
  323. #define CLOCK_MONOTONIC (1)
  324. #endif
  325. #ifndef CLOCK_REALTIME
  326. #define CLOCK_REALTIME (2)
  327. #endif
  328. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  329. #define _TIMESPEC_DEFINED
  330. #endif
  331. #ifndef _TIMESPEC_DEFINED
  332. struct timespec {
  333. time_t tv_sec; /* seconds */
  334. long tv_nsec; /* nanoseconds */
  335. };
  336. #endif
  337. #if !defined(WIN_PTHREADS_TIME_H)
  338. #define MUST_IMPLEMENT_CLOCK_GETTIME
  339. #endif
  340. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  341. #define clock_gettime mg_clock_gettime
  342. static int
  343. clock_gettime(clockid_t clk_id, struct timespec *tp)
  344. {
  345. FILETIME ft;
  346. ULARGE_INTEGER li;
  347. BOOL ok = FALSE;
  348. double d;
  349. static double perfcnt_per_sec = 0.0;
  350. if (tp) {
  351. memset(tp, 0, sizeof(*tp));
  352. if (clk_id == CLOCK_REALTIME) {
  353. GetSystemTimeAsFileTime(&ft);
  354. li.LowPart = ft.dwLowDateTime;
  355. li.HighPart = ft.dwHighDateTime;
  356. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  357. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  358. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  359. ok = TRUE;
  360. } else if (clk_id == CLOCK_MONOTONIC) {
  361. if (perfcnt_per_sec == 0.0) {
  362. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  363. perfcnt_per_sec = 1.0 / li.QuadPart;
  364. }
  365. if (perfcnt_per_sec != 0.0) {
  366. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  367. d = li.QuadPart * perfcnt_per_sec;
  368. tp->tv_sec = (time_t)d;
  369. d -= tp->tv_sec;
  370. tp->tv_nsec = (long)(d * 1.0E9);
  371. ok = TRUE;
  372. }
  373. }
  374. }
  375. return ok ? 0 : -1;
  376. }
  377. #endif
  378. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  379. static int pthread_mutex_lock(pthread_mutex_t *);
  380. static int pthread_mutex_unlock(pthread_mutex_t *);
  381. static void path_to_unicode(const struct mg_connection *conn,
  382. const char *path,
  383. wchar_t *wbuf,
  384. size_t wbuf_len);
  385. /* All file operations need to be rewritten to solve #246. */
  386. #include "file_ops.inl"
  387. struct mg_file;
  388. static const char *
  389. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  390. /* POSIX dirent interface */
  391. struct dirent {
  392. char d_name[PATH_MAX];
  393. };
  394. typedef struct DIR {
  395. HANDLE handle;
  396. WIN32_FIND_DATAW info;
  397. struct dirent result;
  398. } DIR;
  399. #if defined(_WIN32) && !defined(POLLIN)
  400. #ifndef HAVE_POLL
  401. struct pollfd {
  402. SOCKET fd;
  403. short events;
  404. short revents;
  405. };
  406. #define POLLIN (0x0300)
  407. #endif
  408. #endif
  409. /* Mark required libraries */
  410. #if defined(_MSC_VER)
  411. #pragma comment(lib, "Ws2_32.lib")
  412. #endif
  413. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. #include <sys/wait.h>
  416. #include <sys/socket.h>
  417. #include <sys/poll.h>
  418. #include <netinet/in.h>
  419. #include <arpa/inet.h>
  420. #include <sys/time.h>
  421. #include <sys/utsname.h>
  422. #include <stdint.h>
  423. #include <inttypes.h>
  424. #include <netdb.h>
  425. #include <netinet/tcp.h>
  426. typedef const void *SOCK_OPT_TYPE;
  427. #if defined(ANDROID)
  428. typedef unsigned short int in_port_t;
  429. #endif
  430. #include <pwd.h>
  431. #include <unistd.h>
  432. #include <grp.h>
  433. #include <dirent.h>
  434. #define vsnprintf_impl vsnprintf
  435. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  436. #include <dlfcn.h>
  437. #endif
  438. #include <pthread.h>
  439. #if defined(__MACH__)
  440. #define SSL_LIB "libssl.dylib"
  441. #define CRYPTO_LIB "libcrypto.dylib"
  442. #else
  443. #if !defined(SSL_LIB)
  444. #define SSL_LIB "libssl.so"
  445. #endif
  446. #if !defined(CRYPTO_LIB)
  447. #define CRYPTO_LIB "libcrypto.so"
  448. #endif
  449. #endif
  450. #ifndef O_BINARY
  451. #define O_BINARY (0)
  452. #endif /* O_BINARY */
  453. #define closesocket(a) (close(a))
  454. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  455. #define mg_remove(conn, x) (remove(x))
  456. #define mg_sleep(x) (usleep((x)*1000))
  457. #define mg_opendir(conn, x) (opendir(x))
  458. #define mg_closedir(x) (closedir(x))
  459. #define mg_readdir(x) (readdir(x))
  460. #define ERRNO (errno)
  461. #define INVALID_SOCKET (-1)
  462. #define INT64_FMT PRId64
  463. #define UINT64_FMT PRIu64
  464. typedef int SOCKET;
  465. #define WINCDECL
  466. #if defined(__hpux)
  467. /* HPUX 11 does not have monotonic, fall back to realtime */
  468. #ifndef CLOCK_MONOTONIC
  469. #define CLOCK_MONOTONIC CLOCK_REALTIME
  470. #endif
  471. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  472. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  473. * the prototypes use int* rather than socklen_t* which matches the
  474. * actual library expectation. When called with the wrong size arg
  475. * accept() returns a zero client inet addr and check_acl() always
  476. * fails. Since socklen_t is widely used below, just force replace
  477. * their typedef with int. - DTL
  478. */
  479. #define socklen_t int
  480. #endif /* hpux */
  481. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  482. WINDOWS / UNIX include block */
  483. /* va_copy should always be a macro, C99 and C++11 - DTL */
  484. #ifndef va_copy
  485. #define va_copy(x, y) ((x) = (y))
  486. #endif
  487. #ifdef _WIN32
  488. /* Create substitutes for POSIX functions in Win32. */
  489. #if defined(__MINGW32__)
  490. /* Show no warning in case system functions are not used. */
  491. #pragma GCC diagnostic push
  492. #pragma GCC diagnostic ignored "-Wunused-function"
  493. #endif
  494. static CRITICAL_SECTION global_log_file_lock;
  495. static DWORD
  496. pthread_self(void)
  497. {
  498. return GetCurrentThreadId();
  499. }
  500. static int
  501. pthread_key_create(
  502. pthread_key_t *key,
  503. void (*_ignored)(void *) /* destructor not supported for Windows */
  504. )
  505. {
  506. (void)_ignored;
  507. if ((key != 0)) {
  508. *key = TlsAlloc();
  509. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  510. }
  511. return -2;
  512. }
  513. static int
  514. pthread_key_delete(pthread_key_t key)
  515. {
  516. return TlsFree(key) ? 0 : 1;
  517. }
  518. static int
  519. pthread_setspecific(pthread_key_t key, void *value)
  520. {
  521. return TlsSetValue(key, value) ? 0 : 1;
  522. }
  523. static void *
  524. pthread_getspecific(pthread_key_t key)
  525. {
  526. return TlsGetValue(key);
  527. }
  528. #if defined(__MINGW32__)
  529. /* Enable unused function warning again */
  530. #pragma GCC diagnostic pop
  531. #endif
  532. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  533. #else
  534. static pthread_mutexattr_t pthread_mutex_attr;
  535. #endif /* _WIN32 */
  536. #define PASSWORDS_FILE_NAME ".htpasswd"
  537. #define CGI_ENVIRONMENT_SIZE (4096)
  538. #define MAX_CGI_ENVIR_VARS (256)
  539. #define MG_BUF_LEN (8192)
  540. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  541. #if defined(_WIN32_WCE)
  542. /* Create substitutes for POSIX functions in Win32. */
  543. #if defined(__MINGW32__)
  544. /* Show no warning in case system functions are not used. */
  545. #pragma GCC diagnostic push
  546. #pragma GCC diagnostic ignored "-Wunused-function"
  547. #endif
  548. static time_t
  549. time(time_t *ptime)
  550. {
  551. time_t t;
  552. SYSTEMTIME st;
  553. FILETIME ft;
  554. GetSystemTime(&st);
  555. SystemTimeToFileTime(&st, &ft);
  556. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  557. if (ptime != NULL) {
  558. *ptime = t;
  559. }
  560. return t;
  561. }
  562. static struct tm *
  563. localtime_s(const time_t *ptime, struct tm *ptm)
  564. {
  565. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  566. FILETIME ft, lft;
  567. SYSTEMTIME st;
  568. TIME_ZONE_INFORMATION tzinfo;
  569. if (ptm == NULL) {
  570. return NULL;
  571. }
  572. *(int64_t *)&ft = t;
  573. FileTimeToLocalFileTime(&ft, &lft);
  574. FileTimeToSystemTime(&lft, &st);
  575. ptm->tm_year = st.wYear - 1900;
  576. ptm->tm_mon = st.wMonth - 1;
  577. ptm->tm_wday = st.wDayOfWeek;
  578. ptm->tm_mday = st.wDay;
  579. ptm->tm_hour = st.wHour;
  580. ptm->tm_min = st.wMinute;
  581. ptm->tm_sec = st.wSecond;
  582. ptm->tm_yday = 0; /* hope nobody uses this */
  583. ptm->tm_isdst =
  584. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  585. return ptm;
  586. }
  587. static struct tm *
  588. gmtime_s(const time_t *ptime, struct tm *ptm)
  589. {
  590. /* FIXME(lsm): fix this. */
  591. return localtime_s(ptime, ptm);
  592. }
  593. static int mg_atomic_inc(volatile int *addr);
  594. static struct tm tm_array[MAX_WORKER_THREADS];
  595. static int tm_index = 0;
  596. static struct tm *
  597. localtime(const time_t *ptime)
  598. {
  599. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  600. return localtime_s(ptime, tm_array + i);
  601. }
  602. static struct tm *
  603. gmtime(const time_t *ptime)
  604. {
  605. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  606. return gmtime_s(ptime, tm_array + i);
  607. }
  608. static size_t
  609. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  610. {
  611. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  612. * for WinCE"); */
  613. return 0;
  614. }
  615. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  616. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  617. #define remove(f) mg_remove(NULL, f)
  618. static int
  619. rename(const char *a, const char *b)
  620. {
  621. wchar_t wa[PATH_MAX];
  622. wchar_t wb[PATH_MAX];
  623. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  624. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  625. return MoveFileW(wa, wb) ? 0 : -1;
  626. }
  627. struct stat {
  628. int64_t st_size;
  629. time_t st_mtime;
  630. };
  631. static int
  632. stat(const char *name, struct stat *st)
  633. {
  634. wchar_t wbuf[PATH_MAX];
  635. WIN32_FILE_ATTRIBUTE_DATA attr;
  636. time_t creation_time, write_time;
  637. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  638. memset(&attr, 0, sizeof(attr));
  639. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  640. st->st_size =
  641. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  642. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  643. attr.ftLastWriteTime.dwHighDateTime);
  644. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  645. attr.ftCreationTime.dwHighDateTime);
  646. if (creation_time > write_time) {
  647. st->st_mtime = creation_time;
  648. } else {
  649. st->st_mtime = write_time;
  650. }
  651. return 0;
  652. }
  653. #define access(x, a) 1 /* not required anyway */
  654. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  655. /* Values from errno.h in Windows SDK (Visual Studio). */
  656. #define EEXIST 17
  657. #define EACCES 13
  658. #define ENOENT 2
  659. #if defined(__MINGW32__)
  660. /* Enable unused function warning again */
  661. #pragma GCC diagnostic pop
  662. #endif
  663. #endif /* defined(_WIN32_WCE) */
  664. static int
  665. mg_atomic_inc(volatile int *addr)
  666. {
  667. int ret;
  668. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  669. /* Depending on the SDK, this function uses either
  670. * (volatile unsigned int *) or (volatile LONG *),
  671. * so whatever you use, the other SDK is likely to raise a warning. */
  672. ret = InterlockedIncrement((volatile long *)addr);
  673. #elif defined(__GNUC__) \
  674. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  675. ret = __sync_add_and_fetch(addr, 1);
  676. #else
  677. ret = (++(*addr));
  678. #endif
  679. return ret;
  680. }
  681. static int
  682. mg_atomic_dec(volatile int *addr)
  683. {
  684. int ret;
  685. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  686. /* Depending on the SDK, this function uses either
  687. * (volatile unsigned int *) or (volatile LONG *),
  688. * so whatever you use, the other SDK is likely to raise a warning. */
  689. ret = InterlockedDecrement((volatile long *)addr);
  690. #elif defined(__GNUC__) \
  691. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  692. ret = __sync_sub_and_fetch(addr, 1);
  693. #else
  694. ret = (--(*addr));
  695. #endif
  696. return ret;
  697. }
  698. #if defined(__GNUC__) || defined(__MINGW32__)
  699. /* Show no warning in case system functions are not used. */
  700. #define GCC_VERSION \
  701. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  702. #if GCC_VERSION >= 40500
  703. #pragma GCC diagnostic push
  704. #pragma GCC diagnostic ignored "-Wunused-function"
  705. #endif /* GCC_VERSION >= 40500 */
  706. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  707. #if defined(__clang__)
  708. /* Show no warning in case system functions are not used. */
  709. #pragma clang diagnostic push
  710. #pragma clang diagnostic ignored "-Wunused-function"
  711. #endif
  712. #if defined(USE_SERVER_STATS)
  713. static int64_t
  714. mg_atomic_add(volatile int64_t *addr, int64_t value)
  715. {
  716. int64_t ret;
  717. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  718. ret = InterlockedAdd64(addr, value);
  719. #elif defined(__GNUC__) \
  720. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  721. ret = __sync_add_and_fetch(addr, value);
  722. #else
  723. ret = (++(*addr));
  724. #endif
  725. return ret;
  726. }
  727. #endif
  728. #if defined(__GNUC__)
  729. /* Show no warning in case system functions are not used. */
  730. #if GCC_VERSION >= 40500
  731. #pragma GCC diagnostic pop
  732. #endif /* GCC_VERSION >= 40500 */
  733. #endif /* defined(__GNUC__) */
  734. #if defined(__clang__)
  735. /* Show no warning in case system functions are not used. */
  736. #pragma clang diagnostic pop
  737. #endif
  738. #if defined(USE_SERVER_STATS)
  739. struct mg_memory_stat {
  740. volatile int64_t totalMemUsed;
  741. volatile int64_t maxMemUsed;
  742. volatile int blockCount;
  743. };
  744. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  745. static void *
  746. mg_malloc_ex(size_t size,
  747. struct mg_context *ctx,
  748. const char *file,
  749. unsigned line)
  750. {
  751. void *data = malloc(size + 2 * sizeof(uintptr_t));
  752. void *memory = 0;
  753. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  754. #if defined(MEMORY_DEBUGGING)
  755. char mallocStr[256];
  756. #else
  757. (void)file;
  758. (void)line;
  759. #endif
  760. if (data) {
  761. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  762. if (mmem > mstat->maxMemUsed) {
  763. /* could use atomic compare exchange, but this
  764. * seems overkill for statistics data */
  765. mstat->maxMemUsed = mmem;
  766. }
  767. mg_atomic_inc(&mstat->blockCount);
  768. ((uintptr_t *)data)[0] = size;
  769. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  770. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  771. }
  772. #if defined(MEMORY_DEBUGGING)
  773. sprintf(mallocStr,
  774. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  775. memory,
  776. (unsigned long)size,
  777. (unsigned long)mstat->totalMemUsed,
  778. (unsigned long)mstat->blockCount,
  779. file,
  780. line);
  781. #if defined(_WIN32)
  782. OutputDebugStringA(mallocStr);
  783. #else
  784. DEBUG_TRACE("%s", mallocStr);
  785. #endif
  786. #endif
  787. return memory;
  788. }
  789. static void *
  790. mg_calloc_ex(size_t count,
  791. size_t size,
  792. struct mg_context *ctx,
  793. const char *file,
  794. unsigned line)
  795. {
  796. void *data = mg_malloc_ex(size * count, ctx, file, line);
  797. if (data) {
  798. memset(data, 0, size * count);
  799. }
  800. return data;
  801. }
  802. static void
  803. mg_free_ex(void *memory, const char *file, unsigned line)
  804. {
  805. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  806. #if defined(MEMORY_DEBUGGING)
  807. char mallocStr[256];
  808. #else
  809. (void)file;
  810. (void)line;
  811. #endif
  812. if (memory) {
  813. uintptr_t size = ((uintptr_t *)data)[0];
  814. struct mg_memory_stat *mstat =
  815. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  816. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  817. mg_atomic_dec(&mstat->blockCount);
  818. #if defined(MEMORY_DEBUGGING)
  819. sprintf(mallocStr,
  820. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  821. memory,
  822. (unsigned long)size,
  823. (unsigned long)mstat->totalMemUsed,
  824. (unsigned long)mstat->blockCount,
  825. file,
  826. line);
  827. #if defined(_WIN32)
  828. OutputDebugStringA(mallocStr);
  829. #else
  830. DEBUG_TRACE("%s", mallocStr);
  831. #endif
  832. #endif
  833. free(data);
  834. }
  835. }
  836. static void *
  837. mg_realloc_ex(void *memory,
  838. size_t newsize,
  839. struct mg_context *ctx,
  840. const char *file,
  841. unsigned line)
  842. {
  843. void *data;
  844. void *_realloc;
  845. uintptr_t oldsize;
  846. #if defined(MEMORY_DEBUGGING)
  847. char mallocStr[256];
  848. #else
  849. (void)file;
  850. (void)line;
  851. #endif
  852. if (newsize) {
  853. if (memory) {
  854. /* Reallocate existing block */
  855. struct mg_memory_stat *mstat;
  856. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  857. oldsize = ((uintptr_t *)data)[0];
  858. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  859. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  860. if (_realloc) {
  861. data = _realloc;
  862. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  863. #if defined(MEMORY_DEBUGGING)
  864. sprintf(mallocStr,
  865. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  866. memory,
  867. (unsigned long)oldsize,
  868. (unsigned long)mstat->totalMemUsed,
  869. (unsigned long)mstat->blockCount,
  870. file,
  871. line);
  872. #if defined(_WIN32)
  873. OutputDebugStringA(mallocStr);
  874. #else
  875. DEBUG_TRACE("%s", mallocStr);
  876. #endif
  877. #endif
  878. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  879. #if defined(MEMORY_DEBUGGING)
  880. sprintf(mallocStr,
  881. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  882. memory,
  883. (unsigned long)newsize,
  884. (unsigned long)mstat->totalMemUsed,
  885. (unsigned long)mstat->blockCount,
  886. file,
  887. line);
  888. #if defined(_WIN32)
  889. OutputDebugStringA(mallocStr);
  890. #else
  891. DEBUG_TRACE("%s", mallocStr);
  892. #endif
  893. #endif
  894. *(uintptr_t *)data = newsize;
  895. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  896. } else {
  897. #if defined(MEMORY_DEBUGGING)
  898. #if defined(_WIN32)
  899. OutputDebugStringA("MEM: realloc failed\n");
  900. #else
  901. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  902. #endif
  903. #endif
  904. return _realloc;
  905. }
  906. } else {
  907. /* Allocate new block */
  908. data = mg_malloc_ex(newsize, ctx, file, line);
  909. }
  910. } else {
  911. /* Free existing block */
  912. data = 0;
  913. mg_free_ex(memory, file, line);
  914. }
  915. return data;
  916. }
  917. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  918. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  919. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  920. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  921. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  922. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  923. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  924. #else /* USE_SERVER_STATS */
  925. static __inline void *
  926. mg_malloc(size_t a)
  927. {
  928. return malloc(a);
  929. }
  930. static __inline void *
  931. mg_calloc(size_t a, size_t b)
  932. {
  933. return calloc(a, b);
  934. }
  935. static __inline void *
  936. mg_realloc(void *a, size_t b)
  937. {
  938. return realloc(a, b);
  939. }
  940. static __inline void
  941. mg_free(void *a)
  942. {
  943. free(a);
  944. }
  945. #define mg_malloc_ctx(a, c) mg_malloc(a)
  946. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  947. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  948. #define mg_free_ctx(a, c) mg_free(a)
  949. #endif /* USE_SERVER_STATS */
  950. static void mg_vsnprintf(const struct mg_connection *conn,
  951. int *truncated,
  952. char *buf,
  953. size_t buflen,
  954. const char *fmt,
  955. va_list ap);
  956. static void mg_snprintf(const struct mg_connection *conn,
  957. int *truncated,
  958. char *buf,
  959. size_t buflen,
  960. PRINTF_FORMAT_STRING(const char *fmt),
  961. ...) PRINTF_ARGS(5, 6);
  962. /* This following lines are just meant as a reminder to use the mg-functions
  963. * for memory management */
  964. #ifdef malloc
  965. #undef malloc
  966. #endif
  967. #ifdef calloc
  968. #undef calloc
  969. #endif
  970. #ifdef realloc
  971. #undef realloc
  972. #endif
  973. #ifdef free
  974. #undef free
  975. #endif
  976. #ifdef snprintf
  977. #undef snprintf
  978. #endif
  979. #ifdef vsnprintf
  980. #undef vsnprintf
  981. #endif
  982. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  983. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  984. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  985. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  986. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  987. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  988. * but this define only works well for Windows. */
  989. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  990. #endif
  991. static pthread_key_t sTlsKey; /* Thread local storage index */
  992. static int sTlsInit = 0;
  993. static int thread_idx_max = 0;
  994. struct mg_workerTLS {
  995. int is_master;
  996. unsigned long thread_idx;
  997. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  998. HANDLE pthread_cond_helper_mutex;
  999. struct mg_workerTLS *next_waiting_thread;
  1000. #endif
  1001. };
  1002. #if defined(__GNUC__) || defined(__MINGW32__)
  1003. /* Show no warning in case system functions are not used. */
  1004. #if GCC_VERSION >= 40500
  1005. #pragma GCC diagnostic push
  1006. #pragma GCC diagnostic ignored "-Wunused-function"
  1007. #endif /* GCC_VERSION >= 40500 */
  1008. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1009. #if defined(__clang__)
  1010. /* Show no warning in case system functions are not used. */
  1011. #pragma clang diagnostic push
  1012. #pragma clang diagnostic ignored "-Wunused-function"
  1013. #endif
  1014. /* Get a unique thread ID as unsigned long, independent from the data type
  1015. * of thread IDs defined by the operating system API.
  1016. * If two calls to mg_current_thread_id return the same value, they calls
  1017. * are done from the same thread. If they return different values, they are
  1018. * done from different threads. (Provided this function is used in the same
  1019. * process context and threads are not repeatedly created and deleted, but
  1020. * CivetWeb does not do that).
  1021. * This function must match the signature required for SSL id callbacks:
  1022. * CRYPTO_set_id_callback
  1023. */
  1024. static unsigned long
  1025. mg_current_thread_id(void)
  1026. {
  1027. #ifdef _WIN32
  1028. return GetCurrentThreadId();
  1029. #else
  1030. #ifdef __clang__
  1031. #pragma clang diagnostic push
  1032. #pragma clang diagnostic ignored "-Wunreachable-code"
  1033. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1034. * or not, so one of the two conditions will be unreachable by construction.
  1035. * Unfortunately the C standard does not define a way to check this at
  1036. * compile time, since the #if preprocessor conditions can not use the sizeof
  1037. * operator as an argument. */
  1038. #endif
  1039. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1040. /* This is the problematic case for CRYPTO_set_id_callback:
  1041. * The OS pthread_t can not be cast to unsigned long. */
  1042. struct mg_workerTLS *tls =
  1043. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1044. if (tls == NULL) {
  1045. /* SSL called from an unknown thread: Create some thread index.
  1046. */
  1047. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1048. tls->is_master = -2; /* -2 means "3rd party thread" */
  1049. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1050. pthread_setspecific(sTlsKey, tls);
  1051. }
  1052. return tls->thread_idx;
  1053. } else {
  1054. /* pthread_t may be any data type, so a simple cast to unsigned long
  1055. * can rise a warning/error, depending on the platform.
  1056. * Here memcpy is used as an anything-to-anything cast. */
  1057. unsigned long ret = 0;
  1058. pthread_t t = pthread_self();
  1059. memcpy(&ret, &t, sizeof(pthread_t));
  1060. return ret;
  1061. }
  1062. #ifdef __clang__
  1063. #pragma clang diagnostic pop
  1064. #endif
  1065. #endif
  1066. }
  1067. static uint64_t
  1068. mg_get_current_time_ns(void)
  1069. {
  1070. struct timespec tsnow;
  1071. clock_gettime(CLOCK_REALTIME, &tsnow);
  1072. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1073. }
  1074. #if defined(__GNUC__)
  1075. /* Show no warning in case system functions are not used. */
  1076. #if GCC_VERSION >= 40500
  1077. #pragma GCC diagnostic pop
  1078. #endif /* GCC_VERSION >= 40500 */
  1079. #endif /* defined(__GNUC__) */
  1080. #if defined(__clang__)
  1081. /* Show no warning in case system functions are not used. */
  1082. #pragma clang diagnostic pop
  1083. #endif
  1084. #if !defined(DEBUG_TRACE)
  1085. #if defined(DEBUG)
  1086. static void DEBUG_TRACE_FUNC(const char *func,
  1087. unsigned line,
  1088. PRINTF_FORMAT_STRING(const char *fmt),
  1089. ...) PRINTF_ARGS(3, 4);
  1090. static void
  1091. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1092. {
  1093. va_list args;
  1094. uint64_t nsnow;
  1095. static uint64_t nslast;
  1096. struct timespec tsnow;
  1097. /* Get some operating system independent thread id */
  1098. unsigned long thread_id = mg_current_thread_id();
  1099. clock_gettime(CLOCK_REALTIME, &tsnow);
  1100. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1101. + ((uint64_t)tsnow.tv_nsec);
  1102. if (!nslast) {
  1103. nslast = nsnow;
  1104. }
  1105. flockfile(stdout);
  1106. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1107. (unsigned long)tsnow.tv_sec,
  1108. (unsigned long)tsnow.tv_nsec,
  1109. nsnow - nslast,
  1110. thread_id,
  1111. func,
  1112. line);
  1113. va_start(args, fmt);
  1114. vprintf(fmt, args);
  1115. va_end(args);
  1116. putchar('\n');
  1117. fflush(stdout);
  1118. funlockfile(stdout);
  1119. nslast = nsnow;
  1120. }
  1121. #define DEBUG_TRACE(fmt, ...) \
  1122. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1123. #else
  1124. #define DEBUG_TRACE(fmt, ...) \
  1125. do { \
  1126. } while (0)
  1127. #endif /* DEBUG */
  1128. #endif /* DEBUG_TRACE */
  1129. #define MD5_STATIC static
  1130. #include "md5.inl"
  1131. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1132. #ifdef NO_SOCKLEN_T
  1133. typedef int socklen_t;
  1134. #endif /* NO_SOCKLEN_T */
  1135. #define _DARWIN_UNLIMITED_SELECT
  1136. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1137. #if !defined(MSG_NOSIGNAL)
  1138. #define MSG_NOSIGNAL (0)
  1139. #endif
  1140. #if !defined(SOMAXCONN)
  1141. #define SOMAXCONN (100)
  1142. #endif
  1143. /* Size of the accepted socket queue */
  1144. #if !defined(MGSQLEN)
  1145. #define MGSQLEN (20)
  1146. #endif
  1147. #if defined(NO_SSL)
  1148. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1149. typedef struct SSL_CTX SSL_CTX;
  1150. #else
  1151. #if defined(NO_SSL_DL)
  1152. #include <openssl/ssl.h>
  1153. #include <openssl/err.h>
  1154. #include <openssl/crypto.h>
  1155. #include <openssl/x509.h>
  1156. #include <openssl/pem.h>
  1157. #include <openssl/engine.h>
  1158. #include <openssl/conf.h>
  1159. #include <openssl/dh.h>
  1160. #include <openssl/bn.h>
  1161. #include <openssl/opensslv.h>
  1162. #else
  1163. /* SSL loaded dynamically from DLL.
  1164. * I put the prototypes here to be independent from OpenSSL source
  1165. * installation. */
  1166. typedef struct ssl_st SSL;
  1167. typedef struct ssl_method_st SSL_METHOD;
  1168. typedef struct ssl_ctx_st SSL_CTX;
  1169. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1170. typedef struct x509_name X509_NAME;
  1171. typedef struct asn1_integer ASN1_INTEGER;
  1172. typedef struct bignum BIGNUM;
  1173. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1174. typedef struct evp_md EVP_MD;
  1175. typedef struct x509 X509;
  1176. #define SSL_CTRL_OPTIONS (32)
  1177. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1178. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1179. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1180. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1181. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1182. #define SSL_VERIFY_NONE (0)
  1183. #define SSL_VERIFY_PEER (1)
  1184. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1185. #define SSL_VERIFY_CLIENT_ONCE (4)
  1186. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1187. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1188. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1189. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1190. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1191. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1192. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1193. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1194. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1195. #define SSL_ERROR_NONE (0)
  1196. #define SSL_ERROR_SSL (1)
  1197. #define SSL_ERROR_WANT_READ (2)
  1198. #define SSL_ERROR_WANT_WRITE (3)
  1199. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1200. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1201. #define SSL_ERROR_ZERO_RETURN (6)
  1202. #define SSL_ERROR_WANT_CONNECT (7)
  1203. #define SSL_ERROR_WANT_ACCEPT (8)
  1204. struct ssl_func {
  1205. const char *name; /* SSL function name */
  1206. void (*ptr)(void); /* Function pointer */
  1207. };
  1208. #ifdef OPENSSL_API_1_1
  1209. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1210. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1211. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1212. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1213. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1214. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1215. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1216. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1217. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1218. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1219. #define OPENSSL_init_ssl \
  1220. (*(int (*)(uint64_t opts, \
  1221. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1222. #define SSL_CTX_use_PrivateKey_file \
  1223. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1224. #define SSL_CTX_use_certificate_file \
  1225. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1226. #define SSL_CTX_set_default_passwd_cb \
  1227. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1228. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1229. #define SSL_CTX_use_certificate_chain_file \
  1230. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1231. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1232. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1233. #define SSL_CTX_set_verify \
  1234. (*(void (*)(SSL_CTX *, \
  1235. int, \
  1236. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1237. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1238. #define SSL_CTX_load_verify_locations \
  1239. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1240. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1241. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1242. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1243. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1244. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1245. #define SSL_CIPHER_get_name \
  1246. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1247. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1248. #define SSL_CTX_set_session_id_context \
  1249. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1250. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1251. #define SSL_CTX_set_cipher_list \
  1252. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1253. #define SSL_CTX_set_options \
  1254. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1255. #define SSL_CTX_clear_options(ctx, op) \
  1256. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1257. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1258. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1259. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1260. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1261. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1262. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1263. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1264. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1265. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1266. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1267. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1268. #define X509_NAME_oneline \
  1269. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1270. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1271. #define EVP_get_digestbyname \
  1272. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1273. #define EVP_Digest \
  1274. (*(int (*)( \
  1275. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1276. crypto_sw[10].ptr)
  1277. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1278. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1279. #define ASN1_INTEGER_to_BN \
  1280. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1281. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1282. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1283. #define OPENSSL_free(a) CRYPTO_free(a)
  1284. /* set_ssl_option() function updates this array.
  1285. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1286. * of respective functions. The macros above (like SSL_connect()) are really
  1287. * just calling these functions indirectly via the pointer. */
  1288. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1289. {"SSL_accept", NULL},
  1290. {"SSL_connect", NULL},
  1291. {"SSL_read", NULL},
  1292. {"SSL_write", NULL},
  1293. {"SSL_get_error", NULL},
  1294. {"SSL_set_fd", NULL},
  1295. {"SSL_new", NULL},
  1296. {"SSL_CTX_new", NULL},
  1297. {"TLS_server_method", NULL},
  1298. {"OPENSSL_init_ssl", NULL},
  1299. {"SSL_CTX_use_PrivateKey_file", NULL},
  1300. {"SSL_CTX_use_certificate_file", NULL},
  1301. {"SSL_CTX_set_default_passwd_cb", NULL},
  1302. {"SSL_CTX_free", NULL},
  1303. {"SSL_CTX_use_certificate_chain_file", NULL},
  1304. {"TLS_client_method", NULL},
  1305. {"SSL_pending", NULL},
  1306. {"SSL_CTX_set_verify", NULL},
  1307. {"SSL_shutdown", NULL},
  1308. {"SSL_CTX_load_verify_locations", NULL},
  1309. {"SSL_CTX_set_default_verify_paths", NULL},
  1310. {"SSL_CTX_set_verify_depth", NULL},
  1311. {"SSL_get_peer_certificate", NULL},
  1312. {"SSL_get_version", NULL},
  1313. {"SSL_get_current_cipher", NULL},
  1314. {"SSL_CIPHER_get_name", NULL},
  1315. {"SSL_CTX_check_private_key", NULL},
  1316. {"SSL_CTX_set_session_id_context", NULL},
  1317. {"SSL_CTX_ctrl", NULL},
  1318. {"SSL_CTX_set_cipher_list", NULL},
  1319. {"SSL_CTX_set_options", NULL},
  1320. {NULL, NULL}};
  1321. /* Similar array as ssl_sw. These functions could be located in different
  1322. * lib. */
  1323. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1324. {"ERR_error_string", NULL},
  1325. {"ERR_remove_state", NULL},
  1326. {"CONF_modules_unload", NULL},
  1327. {"X509_free", NULL},
  1328. {"X509_get_subject_name", NULL},
  1329. {"X509_get_issuer_name", NULL},
  1330. {"X509_NAME_oneline", NULL},
  1331. {"X509_get_serialNumber", NULL},
  1332. {"EVP_get_digestbyname", NULL},
  1333. {"EVP_Digest", NULL},
  1334. {"i2d_X509", NULL},
  1335. {"BN_bn2hex", NULL},
  1336. {"ASN1_INTEGER_to_BN", NULL},
  1337. {"BN_free", NULL},
  1338. {"CRYPTO_free", NULL},
  1339. {NULL, NULL}};
  1340. #else
  1341. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1342. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1343. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1344. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1345. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1346. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1347. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1348. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1349. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1350. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1351. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1352. #define SSL_CTX_use_PrivateKey_file \
  1353. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1354. #define SSL_CTX_use_certificate_file \
  1355. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1356. #define SSL_CTX_set_default_passwd_cb \
  1357. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1358. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1359. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1360. #define SSL_CTX_use_certificate_chain_file \
  1361. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1362. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1363. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1364. #define SSL_CTX_set_verify \
  1365. (*(void (*)(SSL_CTX *, \
  1366. int, \
  1367. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1368. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1369. #define SSL_CTX_load_verify_locations \
  1370. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1371. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1372. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1373. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1374. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1375. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1376. #define SSL_CIPHER_get_name \
  1377. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1378. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1379. #define SSL_CTX_set_session_id_context \
  1380. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1381. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1382. #define SSL_CTX_set_cipher_list \
  1383. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1384. #define SSL_CTX_set_options(ctx, op) \
  1385. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1386. #define SSL_CTX_clear_options(ctx, op) \
  1387. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1388. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1389. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1390. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1391. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1392. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1393. #define CRYPTO_set_locking_callback \
  1394. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1395. #define CRYPTO_set_id_callback \
  1396. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1397. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1398. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1399. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1400. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1401. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1402. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1403. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1404. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1405. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1406. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1407. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1408. #define X509_NAME_oneline \
  1409. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1410. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1411. #define i2c_ASN1_INTEGER \
  1412. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1413. #define EVP_get_digestbyname \
  1414. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1415. #define EVP_Digest \
  1416. (*(int (*)( \
  1417. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1418. crypto_sw[18].ptr)
  1419. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1420. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1421. #define ASN1_INTEGER_to_BN \
  1422. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1423. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1424. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1425. #define OPENSSL_free(a) CRYPTO_free(a)
  1426. /* set_ssl_option() function updates this array.
  1427. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1428. * of respective functions. The macros above (like SSL_connect()) are really
  1429. * just calling these functions indirectly via the pointer. */
  1430. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1431. {"SSL_accept", NULL},
  1432. {"SSL_connect", NULL},
  1433. {"SSL_read", NULL},
  1434. {"SSL_write", NULL},
  1435. {"SSL_get_error", NULL},
  1436. {"SSL_set_fd", NULL},
  1437. {"SSL_new", NULL},
  1438. {"SSL_CTX_new", NULL},
  1439. {"SSLv23_server_method", NULL},
  1440. {"SSL_library_init", NULL},
  1441. {"SSL_CTX_use_PrivateKey_file", NULL},
  1442. {"SSL_CTX_use_certificate_file", NULL},
  1443. {"SSL_CTX_set_default_passwd_cb", NULL},
  1444. {"SSL_CTX_free", NULL},
  1445. {"SSL_load_error_strings", NULL},
  1446. {"SSL_CTX_use_certificate_chain_file", NULL},
  1447. {"SSLv23_client_method", NULL},
  1448. {"SSL_pending", NULL},
  1449. {"SSL_CTX_set_verify", NULL},
  1450. {"SSL_shutdown", NULL},
  1451. {"SSL_CTX_load_verify_locations", NULL},
  1452. {"SSL_CTX_set_default_verify_paths", NULL},
  1453. {"SSL_CTX_set_verify_depth", NULL},
  1454. {"SSL_get_peer_certificate", NULL},
  1455. {"SSL_get_version", NULL},
  1456. {"SSL_get_current_cipher", NULL},
  1457. {"SSL_CIPHER_get_name", NULL},
  1458. {"SSL_CTX_check_private_key", NULL},
  1459. {"SSL_CTX_set_session_id_context", NULL},
  1460. {"SSL_CTX_ctrl", NULL},
  1461. {"SSL_CTX_set_cipher_list", NULL},
  1462. {NULL, NULL}};
  1463. /* Similar array as ssl_sw. These functions could be located in different
  1464. * lib. */
  1465. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1466. {"CRYPTO_set_locking_callback", NULL},
  1467. {"CRYPTO_set_id_callback", NULL},
  1468. {"ERR_get_error", NULL},
  1469. {"ERR_error_string", NULL},
  1470. {"ERR_remove_state", NULL},
  1471. {"ERR_free_strings", NULL},
  1472. {"ENGINE_cleanup", NULL},
  1473. {"CONF_modules_unload", NULL},
  1474. {"CRYPTO_cleanup_all_ex_data", NULL},
  1475. {"EVP_cleanup", NULL},
  1476. {"X509_free", NULL},
  1477. {"X509_get_subject_name", NULL},
  1478. {"X509_get_issuer_name", NULL},
  1479. {"X509_NAME_oneline", NULL},
  1480. {"X509_get_serialNumber", NULL},
  1481. {"i2c_ASN1_INTEGER", NULL},
  1482. {"EVP_get_digestbyname", NULL},
  1483. {"EVP_Digest", NULL},
  1484. {"i2d_X509", NULL},
  1485. {"BN_bn2hex", NULL},
  1486. {"ASN1_INTEGER_to_BN", NULL},
  1487. {"BN_free", NULL},
  1488. {"CRYPTO_free", NULL},
  1489. {NULL, NULL}};
  1490. #endif /* OPENSSL_API_1_1 */
  1491. #endif /* NO_SSL_DL */
  1492. #endif /* NO_SSL */
  1493. #if !defined(NO_CACHING)
  1494. static const char *month_names[] = {"Jan",
  1495. "Feb",
  1496. "Mar",
  1497. "Apr",
  1498. "May",
  1499. "Jun",
  1500. "Jul",
  1501. "Aug",
  1502. "Sep",
  1503. "Oct",
  1504. "Nov",
  1505. "Dec"};
  1506. #endif /* !NO_CACHING */
  1507. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1508. * union u. */
  1509. union usa {
  1510. struct sockaddr sa;
  1511. struct sockaddr_in sin;
  1512. #if defined(USE_IPV6)
  1513. struct sockaddr_in6 sin6;
  1514. #endif
  1515. };
  1516. /* Describes a string (chunk of memory). */
  1517. struct vec {
  1518. const char *ptr;
  1519. size_t len;
  1520. };
  1521. struct mg_file_stat {
  1522. /* File properties filled by mg_stat: */
  1523. uint64_t size;
  1524. time_t last_modified;
  1525. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1526. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1527. * case we need a "Content-Eencoding: gzip" header */
  1528. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1529. };
  1530. struct mg_file_in_memory {
  1531. char *p;
  1532. uint32_t pos;
  1533. char mode;
  1534. };
  1535. struct mg_file_access {
  1536. /* File properties filled by mg_fopen: */
  1537. FILE *fp;
  1538. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1539. * support library. Use some struct mg_file_in_memory *mf; instead of
  1540. * membuf char pointer. */
  1541. const char *membuf;
  1542. };
  1543. struct mg_file {
  1544. struct mg_file_stat stat;
  1545. struct mg_file_access access;
  1546. };
  1547. #define STRUCT_FILE_INITIALIZER \
  1548. { \
  1549. { \
  1550. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1551. } \
  1552. , \
  1553. { \
  1554. (FILE *) NULL, (const char *)NULL \
  1555. } \
  1556. }
  1557. /* Describes listening socket, or socket which was accept()-ed by the master
  1558. * thread and queued for future handling by the worker thread. */
  1559. struct socket {
  1560. SOCKET sock; /* Listening socket */
  1561. union usa lsa; /* Local socket address */
  1562. union usa rsa; /* Remote socket address */
  1563. unsigned char is_ssl; /* Is port SSL-ed */
  1564. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1565. * port */
  1566. unsigned char in_use; /* Is valid */
  1567. };
  1568. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1569. enum {
  1570. CGI_EXTENSIONS,
  1571. CGI_ENVIRONMENT,
  1572. PUT_DELETE_PASSWORDS_FILE,
  1573. CGI_INTERPRETER,
  1574. PROTECT_URI,
  1575. AUTHENTICATION_DOMAIN,
  1576. ENABLE_AUTH_DOMAIN_CHECK,
  1577. SSI_EXTENSIONS,
  1578. THROTTLE,
  1579. ACCESS_LOG_FILE,
  1580. ENABLE_DIRECTORY_LISTING,
  1581. ERROR_LOG_FILE,
  1582. GLOBAL_PASSWORDS_FILE,
  1583. INDEX_FILES,
  1584. ENABLE_KEEP_ALIVE,
  1585. ACCESS_CONTROL_LIST,
  1586. EXTRA_MIME_TYPES,
  1587. LISTENING_PORTS,
  1588. DOCUMENT_ROOT,
  1589. SSL_CERTIFICATE,
  1590. SSL_CERTIFICATE_CHAIN,
  1591. NUM_THREADS,
  1592. RUN_AS_USER,
  1593. URL_REWRITE_PATTERN,
  1594. HIDE_FILES,
  1595. REQUEST_TIMEOUT,
  1596. KEEP_ALIVE_TIMEOUT,
  1597. LINGER_TIMEOUT,
  1598. SSL_DO_VERIFY_PEER,
  1599. SSL_CA_PATH,
  1600. SSL_CA_FILE,
  1601. SSL_VERIFY_DEPTH,
  1602. SSL_DEFAULT_VERIFY_PATHS,
  1603. SSL_CIPHER_LIST,
  1604. SSL_PROTOCOL_VERSION,
  1605. SSL_SHORT_TRUST,
  1606. #if defined(USE_WEBSOCKET)
  1607. WEBSOCKET_TIMEOUT,
  1608. #endif
  1609. DECODE_URL,
  1610. #if defined(USE_LUA)
  1611. LUA_PRELOAD_FILE,
  1612. LUA_SCRIPT_EXTENSIONS,
  1613. LUA_SERVER_PAGE_EXTENSIONS,
  1614. #endif
  1615. #if defined(USE_DUKTAPE)
  1616. DUKTAPE_SCRIPT_EXTENSIONS,
  1617. #endif
  1618. #if defined(USE_WEBSOCKET)
  1619. WEBSOCKET_ROOT,
  1620. #endif
  1621. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1622. LUA_WEBSOCKET_EXTENSIONS,
  1623. #endif
  1624. ACCESS_CONTROL_ALLOW_ORIGIN,
  1625. ACCESS_CONTROL_ALLOW_METHODS,
  1626. ACCESS_CONTROL_ALLOW_HEADERS,
  1627. ERROR_PAGES,
  1628. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1629. * socket option typedef TCP_NODELAY. */
  1630. #if !defined(NO_CACHING)
  1631. STATIC_FILE_MAX_AGE,
  1632. #endif
  1633. #if !defined(NO_SSL)
  1634. STRICT_HTTPS_MAX_AGE,
  1635. #endif
  1636. #if defined(__linux__)
  1637. ALLOW_SENDFILE_CALL,
  1638. #endif
  1639. #if defined(_WIN32)
  1640. CASE_SENSITIVE_FILES,
  1641. #endif
  1642. #if defined(USE_LUA)
  1643. LUA_BACKGROUND_SCRIPT,
  1644. #endif
  1645. ADDITIONAL_HEADER,
  1646. MAX_REQUEST_SIZE,
  1647. NUM_OPTIONS
  1648. };
  1649. /* Config option name, config types, default value */
  1650. static struct mg_option config_options[] = {
  1651. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1652. {"cgi_environment", CONFIG_TYPE_STRING_LIST, NULL},
  1653. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1654. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1655. {"protect_uri", CONFIG_TYPE_STRING_LIST, NULL},
  1656. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1657. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1658. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1659. {"throttle", CONFIG_TYPE_STRING_LIST, NULL},
  1660. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1661. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1662. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1663. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1664. {"index_files",
  1665. CONFIG_TYPE_STRING_LIST,
  1666. #ifdef USE_LUA
  1667. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1668. "index.shtml,index.php"},
  1669. #else
  1670. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1671. #endif
  1672. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1673. {"access_control_list", CONFIG_TYPE_STRING_LIST, NULL},
  1674. {"extra_mime_types", CONFIG_TYPE_STRING_LIST, NULL},
  1675. {"listening_ports", CONFIG_TYPE_STRING_LIST, "8080"},
  1676. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1677. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1678. {"ssl_certificate_chain", CONFIG_TYPE_FILE, NULL},
  1679. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1680. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1681. {"url_rewrite_patterns", CONFIG_TYPE_STRING_LIST, NULL},
  1682. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1683. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1684. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1685. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1686. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1687. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1688. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1689. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1690. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1691. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1692. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1693. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1694. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1695. #if defined(USE_WEBSOCKET)
  1696. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1697. #endif
  1698. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1699. #if defined(USE_LUA)
  1700. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1701. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1702. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1703. #endif
  1704. #if defined(USE_DUKTAPE)
  1705. /* The support for duktape is still in alpha version state.
  1706. * The name of this config option might change. */
  1707. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1708. #endif
  1709. #if defined(USE_WEBSOCKET)
  1710. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1711. #endif
  1712. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1713. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1714. #endif
  1715. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1716. {"access_control_allow_methods", CONFIG_TYPE_STRING, "*"},
  1717. {"access_control_allow_headers", CONFIG_TYPE_STRING, "*"},
  1718. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1719. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1720. #if !defined(NO_CACHING)
  1721. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1722. #endif
  1723. #if !defined(NO_SSL)
  1724. {"strict_transport_security_max_age", CONFIG_TYPE_NUMBER, NULL},
  1725. #endif
  1726. #if defined(__linux__)
  1727. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1728. #endif
  1729. #if defined(_WIN32)
  1730. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1731. #endif
  1732. #if defined(USE_LUA)
  1733. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1734. #endif
  1735. {"additional_header", CONFIG_TYPE_STRING_MULTILINE, NULL},
  1736. {"max_request_size", CONFIG_TYPE_NUMBER, "16384"},
  1737. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1738. /* Check if the config_options and the corresponding enum have compatible
  1739. * sizes. */
  1740. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1741. == (NUM_OPTIONS + 1),
  1742. "config_options and enum not sync");
  1743. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1744. struct mg_handler_info {
  1745. /* Name/Pattern of the URI. */
  1746. char *uri;
  1747. size_t uri_len;
  1748. /* handler type */
  1749. int handler_type;
  1750. /* Handler for http/https or authorization requests. */
  1751. mg_request_handler handler;
  1752. /* Handler for ws/wss (websocket) requests. */
  1753. mg_websocket_connect_handler connect_handler;
  1754. mg_websocket_ready_handler ready_handler;
  1755. mg_websocket_data_handler data_handler;
  1756. mg_websocket_close_handler close_handler;
  1757. /* accepted subprotocols for ws/wss requests. */
  1758. struct mg_websocket_subprotocols *subprotocols;
  1759. /* Handler for authorization requests */
  1760. mg_authorization_handler auth_handler;
  1761. /* User supplied argument for the handler function. */
  1762. void *cbdata;
  1763. /* next handler in a linked list */
  1764. struct mg_handler_info *next;
  1765. };
  1766. struct mg_context {
  1767. volatile int stop_flag; /* Should we stop event loop */
  1768. SSL_CTX *ssl_ctx; /* SSL context */
  1769. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1770. struct mg_callbacks callbacks; /* User-defined callback function */
  1771. void *user_data; /* User-defined data */
  1772. int context_type; /* 1 = server context,
  1773. * 2 = ws/wss client context,
  1774. */
  1775. struct socket *listening_sockets;
  1776. struct pollfd *listening_socket_fds;
  1777. unsigned int num_listening_sockets;
  1778. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1779. #ifdef ALTERNATIVE_QUEUE
  1780. struct socket *client_socks;
  1781. void **client_wait_events;
  1782. #else
  1783. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1784. volatile int sq_head; /* Head of the socket queue */
  1785. volatile int sq_tail; /* Tail of the socket queue */
  1786. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1787. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1788. #endif
  1789. unsigned int max_request_size; /* The max request size */
  1790. pthread_t masterthreadid; /* The master thread ID */
  1791. unsigned int
  1792. cfg_worker_threads; /* The number of configured worker threads. */
  1793. pthread_t *worker_threadids; /* The worker thread IDs */
  1794. struct mg_connection *worker_connections; /* The connection struct, pre-
  1795. * allocated for each worker */
  1796. time_t start_time; /* Server start time, used for authentication */
  1797. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1798. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1799. unsigned long nonce_count; /* Used nonces, used for authentication */
  1800. char *systemName; /* What operating system is running */
  1801. /* linked list of uri handlers */
  1802. struct mg_handler_info *handlers;
  1803. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1804. /* linked list of shared lua websockets */
  1805. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1806. #endif
  1807. #if defined(USE_TIMERS)
  1808. struct ttimers *timers;
  1809. #endif
  1810. #if defined(USE_LUA)
  1811. void *lua_background_state;
  1812. #endif
  1813. #if defined(USE_SERVER_STATS)
  1814. int active_connections;
  1815. int max_connections;
  1816. int64_t total_connections;
  1817. int64_t total_requests;
  1818. struct mg_memory_stat ctx_memory;
  1819. #endif
  1820. };
  1821. #if defined(USE_SERVER_STATS)
  1822. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  1823. static struct mg_memory_stat *
  1824. get_memory_stat(struct mg_context *ctx)
  1825. {
  1826. if (ctx) {
  1827. return &(ctx->ctx_memory);
  1828. }
  1829. return &mg_common_memory;
  1830. }
  1831. #endif
  1832. struct mg_connection {
  1833. int connection_type; /* 0 none
  1834. * 1 request (we are server, mg_request_info valid)
  1835. * 2 response (we are client, response_info valid)
  1836. */
  1837. struct mg_request_info request_info;
  1838. struct mg_response_info response_info;
  1839. struct mg_context *ctx;
  1840. SSL *ssl; /* SSL descriptor */
  1841. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1842. struct socket client; /* Connected client */
  1843. time_t conn_birth_time; /* Time (wall clock) when connection was
  1844. * established */
  1845. struct timespec req_time; /* Time (since system start) when the request
  1846. * was received */
  1847. int64_t num_bytes_sent; /* Total bytes sent to client */
  1848. int64_t content_len; /* Content-Length header value */
  1849. int64_t consumed_content; /* How many bytes of content have been read */
  1850. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1851. * data available, 2: all data read */
  1852. size_t chunk_remainder; /* Unread data from the last chunk */
  1853. char *buf; /* Buffer for received data */
  1854. char *path_info; /* PATH_INFO part of the URL */
  1855. int must_close; /* 1 if connection must be closed */
  1856. int in_error_handler; /* 1 if in handler for user defined error
  1857. * pages */
  1858. int handled_requests; /* Number of requests handled by this connection */
  1859. int buf_size; /* Buffer size */
  1860. int request_len; /* Size of the request + headers in a buffer */
  1861. int data_len; /* Total size of data in a buffer */
  1862. int status_code; /* HTTP reply status code, e.g. 200 */
  1863. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1864. * throttle */
  1865. time_t last_throttle_time; /* Last time throttled data was sent */
  1866. int64_t last_throttle_bytes; /* Bytes sent this second */
  1867. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1868. * atomic transmissions for websockets */
  1869. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1870. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1871. #endif
  1872. int thread_index; /* Thread index within ctx */
  1873. };
  1874. /* Directory entry */
  1875. struct de {
  1876. struct mg_connection *conn;
  1877. char *file_name;
  1878. struct mg_file_stat file;
  1879. };
  1880. #if defined(USE_WEBSOCKET)
  1881. static int is_websocket_protocol(const struct mg_connection *conn);
  1882. #else
  1883. #define is_websocket_protocol(conn) (0)
  1884. #endif
  1885. #if !defined(NO_THREAD_NAME)
  1886. #if defined(_WIN32) && defined(_MSC_VER)
  1887. /* Set the thread name for debugging purposes in Visual Studio
  1888. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1889. */
  1890. #pragma pack(push, 8)
  1891. typedef struct tagTHREADNAME_INFO {
  1892. DWORD dwType; /* Must be 0x1000. */
  1893. LPCSTR szName; /* Pointer to name (in user addr space). */
  1894. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1895. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1896. } THREADNAME_INFO;
  1897. #pragma pack(pop)
  1898. #elif defined(__linux__)
  1899. #include <sys/prctl.h>
  1900. #include <sys/sendfile.h>
  1901. #ifdef ALTERNATIVE_QUEUE
  1902. #include <sys/eventfd.h>
  1903. #endif /* ALTERNATIVE_QUEUE */
  1904. #if defined(ALTERNATIVE_QUEUE)
  1905. static void *
  1906. event_create(void)
  1907. {
  1908. int ret = eventfd(0, EFD_CLOEXEC);
  1909. if (ret == -1) {
  1910. /* Linux uses -1 on error, Windows NULL. */
  1911. /* However, Linux does not return 0 on success either. */
  1912. return 0;
  1913. }
  1914. return (void *)ret;
  1915. }
  1916. static int
  1917. event_wait(void *eventhdl)
  1918. {
  1919. uint64_t u;
  1920. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1921. if (s != sizeof(uint64_t)) {
  1922. /* error */
  1923. return 0;
  1924. }
  1925. (void)u; /* the value is not required */
  1926. return 1;
  1927. }
  1928. static int
  1929. event_signal(void *eventhdl)
  1930. {
  1931. uint64_t u = 1;
  1932. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1933. if (s != sizeof(uint64_t)) {
  1934. /* error */
  1935. return 0;
  1936. }
  1937. return 1;
  1938. }
  1939. static void
  1940. event_destroy(void *eventhdl)
  1941. {
  1942. close((int)eventhdl);
  1943. }
  1944. #endif
  1945. #endif
  1946. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1947. struct posix_event {
  1948. pthread_mutex_t mutex;
  1949. pthread_cond_t cond;
  1950. };
  1951. static void *
  1952. event_create(void)
  1953. {
  1954. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1955. if (ret == 0) {
  1956. /* out of memory */
  1957. return 0;
  1958. }
  1959. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1960. /* pthread mutex not available */
  1961. mg_free(ret);
  1962. return 0;
  1963. }
  1964. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1965. /* pthread cond not available */
  1966. pthread_mutex_destroy(&(ret->mutex));
  1967. mg_free(ret);
  1968. return 0;
  1969. }
  1970. return (void *)ret;
  1971. }
  1972. static int
  1973. event_wait(void *eventhdl)
  1974. {
  1975. struct posix_event *ev = (struct posix_event *)eventhdl;
  1976. pthread_mutex_lock(&(ev->mutex));
  1977. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1978. pthread_mutex_unlock(&(ev->mutex));
  1979. return 1;
  1980. }
  1981. static int
  1982. event_signal(void *eventhdl)
  1983. {
  1984. struct posix_event *ev = (struct posix_event *)eventhdl;
  1985. pthread_mutex_lock(&(ev->mutex));
  1986. pthread_cond_signal(&(ev->cond));
  1987. pthread_mutex_unlock(&(ev->mutex));
  1988. return 1;
  1989. }
  1990. static void
  1991. event_destroy(void *eventhdl)
  1992. {
  1993. struct posix_event *ev = (struct posix_event *)eventhdl;
  1994. pthread_cond_destroy(&(ev->cond));
  1995. pthread_mutex_destroy(&(ev->mutex));
  1996. mg_free(ev);
  1997. }
  1998. #endif
  1999. static void
  2000. mg_set_thread_name(const char *name)
  2001. {
  2002. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2003. mg_snprintf(
  2004. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2005. #if defined(_WIN32)
  2006. #if defined(_MSC_VER)
  2007. /* Windows and Visual Studio Compiler */
  2008. __try
  2009. {
  2010. THREADNAME_INFO info;
  2011. info.dwType = 0x1000;
  2012. info.szName = threadName;
  2013. info.dwThreadID = ~0U;
  2014. info.dwFlags = 0;
  2015. RaiseException(0x406D1388,
  2016. 0,
  2017. sizeof(info) / sizeof(ULONG_PTR),
  2018. (ULONG_PTR *)&info);
  2019. }
  2020. __except(EXCEPTION_EXECUTE_HANDLER)
  2021. {
  2022. }
  2023. #elif defined(__MINGW32__)
  2024. /* No option known to set thread name for MinGW */
  2025. #endif
  2026. #elif defined(__GLIBC__) \
  2027. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2028. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2029. (void)pthread_setname_np(pthread_self(), threadName);
  2030. #elif defined(__linux__)
  2031. /* on linux we can use the old prctl function */
  2032. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2033. #endif
  2034. }
  2035. #else /* !defined(NO_THREAD_NAME) */
  2036. void
  2037. mg_set_thread_name(const char *threadName)
  2038. {
  2039. }
  2040. #endif
  2041. #if defined(MG_LEGACY_INTERFACE)
  2042. const char **
  2043. mg_get_valid_option_names(void)
  2044. {
  2045. /* This function is deprecated. Use mg_get_valid_options instead. */
  2046. static const char *
  2047. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2048. int i;
  2049. for (i = 0; config_options[i].name != NULL; i++) {
  2050. data[i * 2] = config_options[i].name;
  2051. data[i * 2 + 1] = config_options[i].default_value;
  2052. }
  2053. return data;
  2054. }
  2055. #endif
  2056. const struct mg_option *
  2057. mg_get_valid_options(void)
  2058. {
  2059. return config_options;
  2060. }
  2061. /* Do not open file (used in is_file_in_memory) */
  2062. #define MG_FOPEN_MODE_NONE (0)
  2063. /* Open file for read only access */
  2064. #define MG_FOPEN_MODE_READ (1)
  2065. /* Open file for writing, create and overwrite */
  2066. #define MG_FOPEN_MODE_WRITE (2)
  2067. /* Open file for writing, create and append */
  2068. #define MG_FOPEN_MODE_APPEND (4)
  2069. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2070. * output filep and return 1, otherwise return 0 and don't modify anything. */
  2071. static int
  2072. open_file_in_memory(const struct mg_connection *conn,
  2073. const char *path,
  2074. struct mg_file *filep,
  2075. int mode)
  2076. {
  2077. #if defined(MG_USE_OPEN_FILE)
  2078. size_t size = 0;
  2079. const char *buf = NULL;
  2080. if (!conn) {
  2081. return 0;
  2082. }
  2083. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2084. return 0;
  2085. }
  2086. if (conn->ctx->callbacks.open_file) {
  2087. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2088. if (buf != NULL) {
  2089. if (filep == NULL) {
  2090. /* This is a file in memory, but we cannot store the properties
  2091. * now.
  2092. * Called from "is_file_in_memory" function. */
  2093. return 1;
  2094. }
  2095. /* NOTE: override filep->size only on success. Otherwise, it might
  2096. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2097. filep->access.membuf = buf;
  2098. filep->access.fp = NULL;
  2099. /* Size was set by the callback */
  2100. filep->stat.size = size;
  2101. /* Assume the data may change during runtime by setting
  2102. * last_modified = now */
  2103. filep->stat.last_modified = time(NULL);
  2104. filep->stat.is_directory = 0;
  2105. filep->stat.is_gzipped = 0;
  2106. }
  2107. }
  2108. return (buf != NULL);
  2109. #else
  2110. (void)conn;
  2111. (void)path;
  2112. (void)filep;
  2113. (void)mode;
  2114. return 0;
  2115. #endif
  2116. }
  2117. static int
  2118. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2119. {
  2120. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2121. }
  2122. static int
  2123. is_file_opened(const struct mg_file_access *fileacc)
  2124. {
  2125. if (!fileacc) {
  2126. return 0;
  2127. }
  2128. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2129. }
  2130. static int mg_stat(const struct mg_connection *conn,
  2131. const char *path,
  2132. struct mg_file_stat *filep);
  2133. /* mg_fopen will open a file either in memory or on the disk.
  2134. * The input parameter path is a string in UTF-8 encoding.
  2135. * The input parameter mode is MG_FOPEN_MODE_*
  2136. * On success, either fp or membuf will be set in the output
  2137. * struct file. All status members will also be set.
  2138. * The function returns 1 on success, 0 on error. */
  2139. static int
  2140. mg_fopen(const struct mg_connection *conn,
  2141. const char *path,
  2142. int mode,
  2143. struct mg_file *filep)
  2144. {
  2145. int found;
  2146. if (!filep) {
  2147. return 0;
  2148. }
  2149. filep->access.fp = NULL;
  2150. filep->access.membuf = NULL;
  2151. if (!is_file_in_memory(conn, path)) {
  2152. /* filep is initialized in mg_stat: all fields with memset to,
  2153. * some fields like size and modification date with values */
  2154. found = mg_stat(conn, path, &(filep->stat));
  2155. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2156. /* file does not exist and will not be created */
  2157. return 0;
  2158. }
  2159. #ifdef _WIN32
  2160. {
  2161. wchar_t wbuf[PATH_MAX];
  2162. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2163. switch (mode) {
  2164. case MG_FOPEN_MODE_READ:
  2165. filep->access.fp = _wfopen(wbuf, L"rb");
  2166. break;
  2167. case MG_FOPEN_MODE_WRITE:
  2168. filep->access.fp = _wfopen(wbuf, L"wb");
  2169. break;
  2170. case MG_FOPEN_MODE_APPEND:
  2171. filep->access.fp = _wfopen(wbuf, L"ab");
  2172. break;
  2173. }
  2174. }
  2175. #else
  2176. /* Linux et al already use unicode. No need to convert. */
  2177. switch (mode) {
  2178. case MG_FOPEN_MODE_READ:
  2179. filep->access.fp = fopen(path, "r");
  2180. break;
  2181. case MG_FOPEN_MODE_WRITE:
  2182. filep->access.fp = fopen(path, "w");
  2183. break;
  2184. case MG_FOPEN_MODE_APPEND:
  2185. filep->access.fp = fopen(path, "a");
  2186. break;
  2187. }
  2188. #endif
  2189. if (!found) {
  2190. /* File did not exist before fopen was called.
  2191. * Maybe it has been created now. Get stat info
  2192. * like creation time now. */
  2193. found = mg_stat(conn, path, &(filep->stat));
  2194. (void)found;
  2195. }
  2196. /* file is on disk */
  2197. return (filep->access.fp != NULL);
  2198. } else {
  2199. /* is_file_in_memory returned true */
  2200. if (open_file_in_memory(conn, path, filep, mode)) {
  2201. /* file is in memory */
  2202. return (filep->access.membuf != NULL);
  2203. }
  2204. }
  2205. /* Open failed */
  2206. return 0;
  2207. }
  2208. /* return 0 on success, just like fclose */
  2209. static int
  2210. mg_fclose(struct mg_file_access *fileacc)
  2211. {
  2212. int ret = -1;
  2213. if (fileacc != NULL) {
  2214. if (fileacc->fp != NULL) {
  2215. ret = fclose(fileacc->fp);
  2216. } else if (fileacc->membuf != NULL) {
  2217. ret = 0;
  2218. }
  2219. /* reset all members of fileacc */
  2220. memset(fileacc, 0, sizeof(*fileacc));
  2221. }
  2222. return ret;
  2223. }
  2224. static void
  2225. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2226. {
  2227. for (; *src != '\0' && n > 1; n--) {
  2228. *dst++ = *src++;
  2229. }
  2230. *dst = '\0';
  2231. }
  2232. static int
  2233. lowercase(const char *s)
  2234. {
  2235. return tolower(*(const unsigned char *)s);
  2236. }
  2237. int
  2238. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2239. {
  2240. int diff = 0;
  2241. if (len > 0) {
  2242. do {
  2243. diff = lowercase(s1++) - lowercase(s2++);
  2244. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2245. }
  2246. return diff;
  2247. }
  2248. int
  2249. mg_strcasecmp(const char *s1, const char *s2)
  2250. {
  2251. int diff;
  2252. do {
  2253. diff = lowercase(s1++) - lowercase(s2++);
  2254. } while (diff == 0 && s1[-1] != '\0');
  2255. return diff;
  2256. }
  2257. static char *
  2258. mg_strndup(const char *ptr, size_t len)
  2259. {
  2260. char *p;
  2261. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2262. mg_strlcpy(p, ptr, len + 1);
  2263. }
  2264. return p;
  2265. }
  2266. static char *
  2267. mg_strdup(const char *str)
  2268. {
  2269. return mg_strndup(str, strlen(str));
  2270. }
  2271. static const char *
  2272. mg_strcasestr(const char *big_str, const char *small_str)
  2273. {
  2274. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2275. if (big_len >= small_len) {
  2276. for (i = 0; i <= (big_len - small_len); i++) {
  2277. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2278. return big_str + i;
  2279. }
  2280. }
  2281. }
  2282. return NULL;
  2283. }
  2284. /* Return null terminated string of given maximum length.
  2285. * Report errors if length is exceeded. */
  2286. static void
  2287. mg_vsnprintf(const struct mg_connection *conn,
  2288. int *truncated,
  2289. char *buf,
  2290. size_t buflen,
  2291. const char *fmt,
  2292. va_list ap)
  2293. {
  2294. int n, ok;
  2295. if (buflen == 0) {
  2296. if (truncated) {
  2297. *truncated = 1;
  2298. }
  2299. return;
  2300. }
  2301. #ifdef __clang__
  2302. #pragma clang diagnostic push
  2303. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2304. /* Using fmt as a non-literal is intended here, since it is mostly called
  2305. * indirectly by mg_snprintf */
  2306. #endif
  2307. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2308. ok = (n >= 0) && ((size_t)n < buflen);
  2309. #ifdef __clang__
  2310. #pragma clang diagnostic pop
  2311. #endif
  2312. if (ok) {
  2313. if (truncated) {
  2314. *truncated = 0;
  2315. }
  2316. } else {
  2317. if (truncated) {
  2318. *truncated = 1;
  2319. }
  2320. mg_cry(conn,
  2321. "truncating vsnprintf buffer: [%.*s]",
  2322. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2323. buf);
  2324. n = (int)buflen - 1;
  2325. }
  2326. buf[n] = '\0';
  2327. }
  2328. static void
  2329. mg_snprintf(const struct mg_connection *conn,
  2330. int *truncated,
  2331. char *buf,
  2332. size_t buflen,
  2333. const char *fmt,
  2334. ...)
  2335. {
  2336. va_list ap;
  2337. va_start(ap, fmt);
  2338. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2339. va_end(ap);
  2340. }
  2341. static int
  2342. get_option_index(const char *name)
  2343. {
  2344. int i;
  2345. for (i = 0; config_options[i].name != NULL; i++) {
  2346. if (strcmp(config_options[i].name, name) == 0) {
  2347. return i;
  2348. }
  2349. }
  2350. return -1;
  2351. }
  2352. const char *
  2353. mg_get_option(const struct mg_context *ctx, const char *name)
  2354. {
  2355. int i;
  2356. if ((i = get_option_index(name)) == -1) {
  2357. return NULL;
  2358. } else if (!ctx || ctx->config[i] == NULL) {
  2359. return "";
  2360. } else {
  2361. return ctx->config[i];
  2362. }
  2363. }
  2364. struct mg_context *
  2365. mg_get_context(const struct mg_connection *conn)
  2366. {
  2367. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2368. }
  2369. void *
  2370. mg_get_user_data(const struct mg_context *ctx)
  2371. {
  2372. return (ctx == NULL) ? NULL : ctx->user_data;
  2373. }
  2374. void
  2375. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2376. {
  2377. if (conn != NULL) {
  2378. conn->request_info.conn_data = data;
  2379. }
  2380. }
  2381. void *
  2382. mg_get_user_connection_data(const struct mg_connection *conn)
  2383. {
  2384. if (conn != NULL) {
  2385. return conn->request_info.conn_data;
  2386. }
  2387. return NULL;
  2388. }
  2389. #if defined(MG_LEGACY_INTERFACE)
  2390. /* Deprecated: Use mg_get_server_ports instead. */
  2391. size_t
  2392. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2393. {
  2394. size_t i;
  2395. if (!ctx) {
  2396. return 0;
  2397. }
  2398. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2399. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2400. ports[i] =
  2401. #if defined(USE_IPV6)
  2402. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2403. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2404. :
  2405. #endif
  2406. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2407. }
  2408. return i;
  2409. }
  2410. #endif
  2411. int
  2412. mg_get_server_ports(const struct mg_context *ctx,
  2413. int size,
  2414. struct mg_server_ports *ports)
  2415. {
  2416. int i, cnt = 0;
  2417. if (size <= 0) {
  2418. return -1;
  2419. }
  2420. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2421. if (!ctx) {
  2422. return -1;
  2423. }
  2424. if (!ctx->listening_sockets) {
  2425. return -1;
  2426. }
  2427. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2428. ports[cnt].port =
  2429. #if defined(USE_IPV6)
  2430. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2431. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2432. :
  2433. #endif
  2434. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2435. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2436. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2437. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2438. /* IPv4 */
  2439. ports[cnt].protocol = 1;
  2440. cnt++;
  2441. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2442. /* IPv6 */
  2443. ports[cnt].protocol = 3;
  2444. cnt++;
  2445. }
  2446. }
  2447. return cnt;
  2448. }
  2449. static void
  2450. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2451. {
  2452. buf[0] = '\0';
  2453. if (!usa) {
  2454. return;
  2455. }
  2456. if (usa->sa.sa_family == AF_INET) {
  2457. getnameinfo(&usa->sa,
  2458. sizeof(usa->sin),
  2459. buf,
  2460. (unsigned)len,
  2461. NULL,
  2462. 0,
  2463. NI_NUMERICHOST);
  2464. }
  2465. #if defined(USE_IPV6)
  2466. else if (usa->sa.sa_family == AF_INET6) {
  2467. getnameinfo(&usa->sa,
  2468. sizeof(usa->sin6),
  2469. buf,
  2470. (unsigned)len,
  2471. NULL,
  2472. 0,
  2473. NI_NUMERICHOST);
  2474. }
  2475. #endif
  2476. }
  2477. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2478. * included in all responses other than 100, 101, 5xx. */
  2479. static void
  2480. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2481. {
  2482. struct tm *tm;
  2483. tm = ((t != NULL) ? gmtime(t) : NULL);
  2484. if (tm != NULL) {
  2485. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2486. } else {
  2487. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2488. buf[buf_len - 1] = '\0';
  2489. }
  2490. }
  2491. /* difftime for struct timespec. Return value is in seconds. */
  2492. static double
  2493. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2494. {
  2495. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2496. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2497. }
  2498. /* Print error message to the opened error log stream. */
  2499. void
  2500. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2501. {
  2502. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2503. va_list ap;
  2504. struct mg_file fi;
  2505. time_t timestamp;
  2506. va_start(ap, fmt);
  2507. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2508. va_end(ap);
  2509. buf[sizeof(buf) - 1] = 0;
  2510. if (!conn) {
  2511. puts(buf);
  2512. return;
  2513. }
  2514. /* Do not lock when getting the callback value, here and below.
  2515. * I suppose this is fine, since function cannot disappear in the
  2516. * same way string option can. */
  2517. if ((conn->ctx->callbacks.log_message == NULL)
  2518. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2519. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2520. if (mg_fopen(conn,
  2521. conn->ctx->config[ERROR_LOG_FILE],
  2522. MG_FOPEN_MODE_APPEND,
  2523. &fi) == 0) {
  2524. fi.access.fp = NULL;
  2525. }
  2526. } else {
  2527. fi.access.fp = NULL;
  2528. }
  2529. if (fi.access.fp != NULL) {
  2530. flockfile(fi.access.fp);
  2531. timestamp = time(NULL);
  2532. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2533. fprintf(fi.access.fp,
  2534. "[%010lu] [error] [client %s] ",
  2535. (unsigned long)timestamp,
  2536. src_addr);
  2537. if (conn->request_info.request_method != NULL) {
  2538. fprintf(fi.access.fp,
  2539. "%s %s: ",
  2540. conn->request_info.request_method,
  2541. conn->request_info.request_uri
  2542. ? conn->request_info.request_uri
  2543. : "");
  2544. }
  2545. fprintf(fi.access.fp, "%s", buf);
  2546. fputc('\n', fi.access.fp);
  2547. fflush(fi.access.fp);
  2548. funlockfile(fi.access.fp);
  2549. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2550. * mg_cry here anyway ;-) */
  2551. }
  2552. }
  2553. }
  2554. /* Return fake connection structure. Used for logging, if connection
  2555. * is not applicable at the moment of logging. */
  2556. static struct mg_connection *
  2557. fc(struct mg_context *ctx)
  2558. {
  2559. static struct mg_connection fake_connection;
  2560. fake_connection.ctx = ctx;
  2561. return &fake_connection;
  2562. }
  2563. const char *
  2564. mg_version(void)
  2565. {
  2566. return CIVETWEB_VERSION;
  2567. }
  2568. const struct mg_request_info *
  2569. mg_get_request_info(const struct mg_connection *conn)
  2570. {
  2571. if (!conn) {
  2572. return NULL;
  2573. }
  2574. #if 1 /* TODO: deal with legacy */
  2575. if (conn->connection_type == 2) {
  2576. static char txt[16];
  2577. sprintf(txt, "%03i", conn->response_info.status_code);
  2578. ((struct mg_connection *)conn)->request_info.local_uri =
  2579. ((struct mg_connection *)conn)->request_info.request_uri =
  2580. txt; /* TODO: not thread safe */
  2581. ((struct mg_connection *)conn)->request_info.num_headers =
  2582. conn->response_info.num_headers;
  2583. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2584. conn->response_info.http_headers,
  2585. sizeof(conn->response_info.http_headers));
  2586. } else
  2587. #endif
  2588. if (conn->connection_type != 1) {
  2589. return NULL;
  2590. }
  2591. return &conn->request_info;
  2592. }
  2593. const struct mg_response_info *
  2594. mg_get_response_info(const struct mg_connection *conn)
  2595. {
  2596. if (!conn) {
  2597. return NULL;
  2598. }
  2599. if (conn->connection_type != 2) {
  2600. return NULL;
  2601. }
  2602. return &conn->response_info;
  2603. }
  2604. int
  2605. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2606. {
  2607. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2608. return -1;
  2609. } else {
  2610. int truncated = 0;
  2611. const struct mg_request_info *ri = &conn->request_info;
  2612. #ifdef __clang__
  2613. #pragma clang diagnostic push
  2614. #pragma clang diagnostic ignored "-Wunreachable-code"
  2615. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2616. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2617. * unreachable, but splitting into four different #ifdef clauses here is more
  2618. * complicated.
  2619. */
  2620. #endif
  2621. const char *proto =
  2622. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2623. : (ri->is_ssl ? "https" : "http"));
  2624. #ifdef __clang__
  2625. #pragma clang diagnostic pop
  2626. #endif
  2627. if (ri->local_uri == NULL) {
  2628. return -1;
  2629. }
  2630. if ((ri->request_uri != NULL)
  2631. && strcmp(ri->local_uri, ri->request_uri)) {
  2632. mg_snprintf(conn,
  2633. &truncated,
  2634. buf,
  2635. buflen,
  2636. "%s://%s",
  2637. proto,
  2638. ri->request_uri);
  2639. if (truncated) {
  2640. return -1;
  2641. }
  2642. return 0;
  2643. } else {
  2644. #if defined(USE_IPV6)
  2645. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2646. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2647. : htons(conn->client.lsa.sin.sin_port);
  2648. #else
  2649. int port = htons(conn->client.lsa.sin.sin_port);
  2650. #endif
  2651. int def_port = ri->is_ssl ? 443 : 80;
  2652. int auth_domain_check_enabled =
  2653. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2654. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2655. "yes"));
  2656. const char *server_domain =
  2657. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2658. char portstr[16];
  2659. char server_ip[48];
  2660. if (port != def_port) {
  2661. sprintf(portstr, ":%u", (unsigned)port);
  2662. } else {
  2663. portstr[0] = 0;
  2664. }
  2665. if (!auth_domain_check_enabled || !server_domain) {
  2666. sockaddr_to_string(server_ip,
  2667. sizeof(server_ip),
  2668. &conn->client.lsa);
  2669. server_domain = server_ip;
  2670. }
  2671. mg_snprintf(conn,
  2672. &truncated,
  2673. buf,
  2674. buflen,
  2675. "%s://%s%s%s",
  2676. proto,
  2677. server_domain,
  2678. portstr,
  2679. ri->local_uri);
  2680. if (truncated) {
  2681. return -1;
  2682. }
  2683. return 0;
  2684. }
  2685. }
  2686. }
  2687. /* Skip the characters until one of the delimiters characters found.
  2688. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2689. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2690. * Delimiters can be quoted with quotechar. */
  2691. static char *
  2692. skip_quoted(char **buf,
  2693. const char *delimiters,
  2694. const char *whitespace,
  2695. char quotechar)
  2696. {
  2697. char *p, *begin_word, *end_word, *end_whitespace;
  2698. begin_word = *buf;
  2699. end_word = begin_word + strcspn(begin_word, delimiters);
  2700. /* Check for quotechar */
  2701. if (end_word > begin_word) {
  2702. p = end_word - 1;
  2703. while (*p == quotechar) {
  2704. /* While the delimiter is quoted, look for the next delimiter. */
  2705. /* This happens, e.g., in calls from parse_auth_header,
  2706. * if the user name contains a " character. */
  2707. /* If there is anything beyond end_word, copy it. */
  2708. if (*end_word != '\0') {
  2709. size_t end_off = strcspn(end_word + 1, delimiters);
  2710. memmove(p, end_word, end_off + 1);
  2711. p += end_off; /* p must correspond to end_word - 1 */
  2712. end_word += end_off + 1;
  2713. } else {
  2714. *p = '\0';
  2715. break;
  2716. }
  2717. }
  2718. for (p++; p < end_word; p++) {
  2719. *p = '\0';
  2720. }
  2721. }
  2722. if (*end_word == '\0') {
  2723. *buf = end_word;
  2724. } else {
  2725. #if defined(__GNUC__) || defined(__MINGW32__)
  2726. /* Disable spurious conversion warning for GCC */
  2727. #if GCC_VERSION >= 40500
  2728. #pragma GCC diagnostic push
  2729. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2730. #endif /* GCC_VERSION >= 40500 */
  2731. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  2732. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2733. #if defined(__GNUC__) || defined(__MINGW32__)
  2734. #if GCC_VERSION >= 40500
  2735. #pragma GCC diagnostic pop
  2736. #endif /* GCC_VERSION >= 40500 */
  2737. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  2738. for (p = end_word; p < end_whitespace; p++) {
  2739. *p = '\0';
  2740. }
  2741. *buf = end_whitespace;
  2742. }
  2743. return begin_word;
  2744. }
  2745. /* Return HTTP header value, or NULL if not found. */
  2746. static const char *
  2747. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  2748. {
  2749. int i;
  2750. for (i = 0; i < num_hdr; i++) {
  2751. if (!mg_strcasecmp(name, hdr[i].name)) {
  2752. return hdr[i].value;
  2753. }
  2754. }
  2755. return NULL;
  2756. }
  2757. #if defined(USE_WEBSOCKET)
  2758. /* Retrieve requested HTTP header multiple values, and return the number of
  2759. * found occurences */
  2760. static int
  2761. get_req_headers(const struct mg_request_info *ri,
  2762. const char *name,
  2763. const char **output,
  2764. int output_max_size)
  2765. {
  2766. int i;
  2767. int cnt = 0;
  2768. if (ri) {
  2769. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  2770. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2771. output[cnt++] = ri->http_headers[i].value;
  2772. }
  2773. }
  2774. }
  2775. return cnt;
  2776. }
  2777. #endif
  2778. const char *
  2779. mg_get_header(const struct mg_connection *conn, const char *name)
  2780. {
  2781. if (!conn) {
  2782. return NULL;
  2783. }
  2784. if (conn->connection_type == 1) {
  2785. return get_header(conn->request_info.http_headers,
  2786. conn->request_info.num_headers,
  2787. name);
  2788. }
  2789. if (conn->connection_type == 2) {
  2790. return get_header(conn->response_info.http_headers,
  2791. conn->request_info.num_headers,
  2792. name);
  2793. }
  2794. return NULL;
  2795. }
  2796. static const char *
  2797. get_http_version(const struct mg_connection *conn)
  2798. {
  2799. if (!conn) {
  2800. return NULL;
  2801. }
  2802. if (conn->connection_type == 1) {
  2803. return conn->request_info.http_version;
  2804. }
  2805. if (conn->connection_type == 2) {
  2806. return conn->response_info.http_version;
  2807. }
  2808. return NULL;
  2809. }
  2810. /* A helper function for traversing a comma separated list of values.
  2811. * It returns a list pointer shifted to the next value, or NULL if the end
  2812. * of the list found.
  2813. * Value is stored in val vector. If value has form "x=y", then eq_val
  2814. * vector is initialized to point to the "y" part, and val vector length
  2815. * is adjusted to point only to "x". */
  2816. static const char *
  2817. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2818. {
  2819. int end;
  2820. reparse:
  2821. if (val == NULL || list == NULL || *list == '\0') {
  2822. /* End of the list */
  2823. list = NULL;
  2824. } else {
  2825. /* Skip over leading LWS */
  2826. while (*list == ' ' || *list == '\t')
  2827. list++;
  2828. val->ptr = list;
  2829. if ((list = strchr(val->ptr, ',')) != NULL) {
  2830. /* Comma found. Store length and shift the list ptr */
  2831. val->len = ((size_t)(list - val->ptr));
  2832. list++;
  2833. } else {
  2834. /* This value is the last one */
  2835. list = val->ptr + strlen(val->ptr);
  2836. val->len = ((size_t)(list - val->ptr));
  2837. }
  2838. /* Adjust length for trailing LWS */
  2839. end = (int)val->len - 1;
  2840. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  2841. end--;
  2842. val->len = (size_t)(end + 1);
  2843. if (val->len == 0) {
  2844. /* Ignore any empty entries. */
  2845. goto reparse;
  2846. }
  2847. if (eq_val != NULL) {
  2848. /* Value has form "x=y", adjust pointers and lengths
  2849. * so that val points to "x", and eq_val points to "y". */
  2850. eq_val->len = 0;
  2851. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2852. if (eq_val->ptr != NULL) {
  2853. eq_val->ptr++; /* Skip over '=' character */
  2854. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2855. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2856. }
  2857. }
  2858. }
  2859. return list;
  2860. }
  2861. /* A helper function for checking if a comma separated list of values contains
  2862. * the given option (case insensitvely).
  2863. * 'header' can be NULL, in which case false is returned. */
  2864. static int
  2865. header_has_option(const char *header, const char *option)
  2866. {
  2867. struct vec opt_vec;
  2868. struct vec eq_vec;
  2869. /*
  2870. assert(option != NULL);
  2871. assert(option[0] != '\0');
  2872. */
  2873. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2874. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2875. return 1;
  2876. }
  2877. return 0;
  2878. }
  2879. /* Perform case-insensitive match of string against pattern */
  2880. static int
  2881. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2882. {
  2883. const char *or_str;
  2884. size_t i;
  2885. int j, len, res;
  2886. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2887. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2888. return (res > 0) ? res : match_prefix(or_str + 1,
  2889. (size_t)((pattern + pattern_len)
  2890. - (or_str + 1)),
  2891. str);
  2892. }
  2893. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  2894. if ((pattern[i] == '?') && (str[j] != '\0')) {
  2895. continue;
  2896. } else if (pattern[i] == '$') {
  2897. return (str[j] == '\0') ? j : -1;
  2898. } else if (pattern[i] == '*') {
  2899. i++;
  2900. if (pattern[i] == '*') {
  2901. i++;
  2902. len = (int)strlen(str + j);
  2903. } else {
  2904. len = (int)strcspn(str + j, "/");
  2905. }
  2906. if (i == pattern_len) {
  2907. return j + len;
  2908. }
  2909. do {
  2910. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2911. } while (res == -1 && len-- > 0);
  2912. return (res == -1) ? -1 : j + res + len;
  2913. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2914. return -1;
  2915. }
  2916. }
  2917. return j;
  2918. }
  2919. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2920. * This function must tolerate situations when connection info is not
  2921. * set up, for example if request parsing failed. */
  2922. static int
  2923. should_keep_alive(const struct mg_connection *conn)
  2924. {
  2925. const char *http_version;
  2926. const char *header;
  2927. /* First satisfy needs of the server */
  2928. if ((conn == NULL) || conn->must_close) {
  2929. /* Close, if civetweb framework needs to close */
  2930. return 0;
  2931. }
  2932. if (mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  2933. /* Close, if keep alive is not enabled */
  2934. return 0;
  2935. }
  2936. /* Check explicit wish of the client */
  2937. header = mg_get_header(conn, "Connection");
  2938. if (header) {
  2939. /* If there is a connection header from the client, obey */
  2940. if (header_has_option(header, "keep-alive")) {
  2941. return 1;
  2942. }
  2943. return 0;
  2944. }
  2945. /* Use default of the standard */
  2946. http_version = get_http_version(conn);
  2947. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  2948. /* HTTP 1.1 default is keep alive */
  2949. return 1;
  2950. }
  2951. /* HTTP 1.0 (and earlier) default is to close the connection */
  2952. return 0;
  2953. }
  2954. static int
  2955. should_decode_url(const struct mg_connection *conn)
  2956. {
  2957. if (!conn || !conn->ctx) {
  2958. return 0;
  2959. }
  2960. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2961. }
  2962. static const char *
  2963. suggest_connection_header(const struct mg_connection *conn)
  2964. {
  2965. return should_keep_alive(conn) ? "keep-alive" : "close";
  2966. }
  2967. static int
  2968. send_no_cache_header(struct mg_connection *conn)
  2969. {
  2970. /* Send all current and obsolete cache opt-out directives. */
  2971. return mg_printf(conn,
  2972. "Cache-Control: no-cache, no-store, "
  2973. "must-revalidate, private, max-age=0\r\n"
  2974. "Pragma: no-cache\r\n"
  2975. "Expires: 0\r\n");
  2976. }
  2977. static int
  2978. send_static_cache_header(struct mg_connection *conn)
  2979. {
  2980. #if !defined(NO_CACHING)
  2981. /* Read the server config to check how long a file may be cached.
  2982. * The configuration is in seconds. */
  2983. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2984. if (max_age <= 0) {
  2985. /* 0 means "do not cache". All values <0 are reserved
  2986. * and may be used differently in the future. */
  2987. /* If a file should not be cached, do not only send
  2988. * max-age=0, but also pragmas and Expires headers. */
  2989. return send_no_cache_header(conn);
  2990. }
  2991. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2992. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2993. /* See also https://www.mnot.net/cache_docs/ */
  2994. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2995. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2996. * year to 31622400 seconds. For the moment, we just send whatever has
  2997. * been configured, still the behavior for >1 year should be considered
  2998. * as undefined. */
  2999. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3000. #else /* NO_CACHING */
  3001. return send_no_cache_header(conn);
  3002. #endif /* !NO_CACHING */
  3003. }
  3004. static int
  3005. send_additional_header(struct mg_connection *conn)
  3006. {
  3007. int i = 0;
  3008. const char *header = conn->ctx->config[ADDITIONAL_HEADER];
  3009. #if !defined(NO_SSL)
  3010. if (conn->ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3011. int max_age = atoi(conn->ctx->config[STRICT_HTTPS_MAX_AGE]);
  3012. if (max_age >= 0) {
  3013. i += mg_printf(conn,
  3014. "Strict-Transport-Security: max-age=%u\r\n",
  3015. (unsigned)max_age);
  3016. }
  3017. }
  3018. #endif
  3019. if (header && header[0]) {
  3020. i += mg_printf(conn, "%s\r\n", header);
  3021. }
  3022. return i;
  3023. }
  3024. static void handle_file_based_request(struct mg_connection *conn,
  3025. const char *path,
  3026. struct mg_file *filep);
  3027. const char *
  3028. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3029. {
  3030. /* See IANA HTTP status code assignment:
  3031. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3032. */
  3033. switch (response_code) {
  3034. /* RFC2616 Section 10.1 - Informational 1xx */
  3035. case 100:
  3036. return "Continue"; /* RFC2616 Section 10.1.1 */
  3037. case 101:
  3038. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3039. case 102:
  3040. return "Processing"; /* RFC2518 Section 10.1 */
  3041. /* RFC2616 Section 10.2 - Successful 2xx */
  3042. case 200:
  3043. return "OK"; /* RFC2616 Section 10.2.1 */
  3044. case 201:
  3045. return "Created"; /* RFC2616 Section 10.2.2 */
  3046. case 202:
  3047. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3048. case 203:
  3049. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3050. case 204:
  3051. return "No Content"; /* RFC2616 Section 10.2.5 */
  3052. case 205:
  3053. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3054. case 206:
  3055. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3056. case 207:
  3057. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  3058. case 208:
  3059. return "Already Reported"; /* RFC5842 Section 7.1 */
  3060. case 226:
  3061. return "IM used"; /* RFC3229 Section 10.4.1 */
  3062. /* RFC2616 Section 10.3 - Redirection 3xx */
  3063. case 300:
  3064. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3065. case 301:
  3066. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3067. case 302:
  3068. return "Found"; /* RFC2616 Section 10.3.3 */
  3069. case 303:
  3070. return "See Other"; /* RFC2616 Section 10.3.4 */
  3071. case 304:
  3072. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3073. case 305:
  3074. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3075. case 307:
  3076. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3077. case 308:
  3078. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3079. /* RFC2616 Section 10.4 - Client Error 4xx */
  3080. case 400:
  3081. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3082. case 401:
  3083. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3084. case 402:
  3085. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3086. case 403:
  3087. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3088. case 404:
  3089. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3090. case 405:
  3091. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3092. case 406:
  3093. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3094. case 407:
  3095. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3096. case 408:
  3097. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3098. case 409:
  3099. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3100. case 410:
  3101. return "Gone"; /* RFC2616 Section 10.4.11 */
  3102. case 411:
  3103. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3104. case 412:
  3105. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3106. case 413:
  3107. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3108. case 414:
  3109. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3110. case 415:
  3111. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3112. case 416:
  3113. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  3114. case 417:
  3115. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3116. case 421:
  3117. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3118. case 422:
  3119. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3120. * Section 11.2 */
  3121. case 423:
  3122. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3123. case 424:
  3124. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3125. * Section 11.4 */
  3126. case 426:
  3127. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3128. case 428:
  3129. return "Precondition Required"; /* RFC 6585, Section 3 */
  3130. case 429:
  3131. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3132. case 431:
  3133. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3134. case 451:
  3135. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3136. * Section 3 */
  3137. /* RFC2616 Section 10.5 - Server Error 5xx */
  3138. case 500:
  3139. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3140. case 501:
  3141. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3142. case 502:
  3143. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3144. case 503:
  3145. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3146. case 504:
  3147. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3148. case 505:
  3149. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3150. case 506:
  3151. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3152. case 507:
  3153. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3154. * Section 11.5 */
  3155. case 508:
  3156. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3157. case 510:
  3158. return "Not Extended"; /* RFC 2774, Section 7 */
  3159. case 511:
  3160. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3161. /* Other status codes, not shown in the IANA HTTP status code assignment.
  3162. * E.g., "de facto" standards due to common use, ... */
  3163. case 418:
  3164. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3165. case 419:
  3166. return "Authentication Timeout"; /* common use */
  3167. case 420:
  3168. return "Enhance Your Calm"; /* common use */
  3169. case 440:
  3170. return "Login Timeout"; /* common use */
  3171. case 509:
  3172. return "Bandwidth Limit Exceeded"; /* common use */
  3173. default:
  3174. /* This error code is unknown. This should not happen. */
  3175. if (conn) {
  3176. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3177. }
  3178. /* Return at least a category according to RFC 2616 Section 10. */
  3179. if (response_code >= 100 && response_code < 200) {
  3180. /* Unknown informational status code */
  3181. return "Information";
  3182. }
  3183. if (response_code >= 200 && response_code < 300) {
  3184. /* Unknown success code */
  3185. return "Success";
  3186. }
  3187. if (response_code >= 300 && response_code < 400) {
  3188. /* Unknown redirection code */
  3189. return "Redirection";
  3190. }
  3191. if (response_code >= 400 && response_code < 500) {
  3192. /* Unknown request error code */
  3193. return "Client Error";
  3194. }
  3195. if (response_code >= 500 && response_code < 600) {
  3196. /* Unknown server error code */
  3197. return "Server Error";
  3198. }
  3199. /* Response code not even within reasonable range */
  3200. return "";
  3201. }
  3202. }
  3203. void
  3204. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3205. {
  3206. char buf[MG_BUF_LEN];
  3207. va_list ap;
  3208. int len, i, page_handler_found, scope, truncated, has_body;
  3209. char date[64];
  3210. time_t curtime = time(NULL);
  3211. const char *error_handler = NULL;
  3212. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3213. const char *error_page_file_ext, *tstr;
  3214. const char *status_text = mg_get_response_code_text(conn, status);
  3215. if (conn == NULL) {
  3216. return;
  3217. }
  3218. conn->status_code = status;
  3219. if (conn->in_error_handler || (conn->ctx->callbacks.http_error == NULL)
  3220. || conn->ctx->callbacks.http_error(conn, status)) {
  3221. if (!conn->in_error_handler) {
  3222. /* Send user defined error pages, if defined */
  3223. error_handler = conn->ctx->config[ERROR_PAGES];
  3224. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3225. page_handler_found = 0;
  3226. if (error_handler != NULL) {
  3227. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3228. switch (scope) {
  3229. case 1: /* Handler for specific error, e.g. 404 error */
  3230. mg_snprintf(conn,
  3231. &truncated,
  3232. buf,
  3233. sizeof(buf) - 32,
  3234. "%serror%03u.",
  3235. error_handler,
  3236. status);
  3237. break;
  3238. case 2: /* Handler for error group, e.g., 5xx error handler
  3239. * for all server errors (500-599) */
  3240. mg_snprintf(conn,
  3241. &truncated,
  3242. buf,
  3243. sizeof(buf) - 32,
  3244. "%serror%01uxx.",
  3245. error_handler,
  3246. status / 100);
  3247. break;
  3248. default: /* Handler for all errors */
  3249. mg_snprintf(conn,
  3250. &truncated,
  3251. buf,
  3252. sizeof(buf) - 32,
  3253. "%serror.",
  3254. error_handler);
  3255. break;
  3256. }
  3257. /* String truncation in buf may only occur if error_handler
  3258. * is too long. This string is from the config, not from a
  3259. * client. */
  3260. (void)truncated;
  3261. len = (int)strlen(buf);
  3262. tstr = strchr(error_page_file_ext, '.');
  3263. while (tstr) {
  3264. for (i = 1;
  3265. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3266. i++)
  3267. buf[len + i - 1] = tstr[i];
  3268. buf[len + i - 1] = 0;
  3269. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3270. page_handler_found = 1;
  3271. break;
  3272. }
  3273. tstr = strchr(tstr + i, '.');
  3274. }
  3275. }
  3276. }
  3277. if (page_handler_found) {
  3278. conn->in_error_handler = 1;
  3279. handle_file_based_request(conn, buf, &error_page_file);
  3280. conn->in_error_handler = 0;
  3281. return;
  3282. }
  3283. }
  3284. /* No custom error page. Send default error page. */
  3285. gmt_time_string(date, sizeof(date), &curtime);
  3286. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3287. has_body = ((status > 199) && (status != 204) && (status != 304));
  3288. conn->must_close = 1;
  3289. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3290. send_no_cache_header(conn);
  3291. send_additional_header(conn);
  3292. if (has_body) {
  3293. mg_printf(conn,
  3294. "%s",
  3295. "Content-Type: text/plain; charset=utf-8\r\n");
  3296. }
  3297. mg_printf(conn,
  3298. "Date: %s\r\n"
  3299. "Connection: close\r\n\r\n",
  3300. date);
  3301. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3302. if (has_body) {
  3303. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3304. if (fmt != NULL) {
  3305. va_start(ap, fmt);
  3306. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3307. va_end(ap);
  3308. mg_write(conn, buf, strlen(buf));
  3309. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3310. }
  3311. } else {
  3312. /* No body allowed. Close the connection. */
  3313. DEBUG_TRACE("Error %i", status);
  3314. }
  3315. }
  3316. }
  3317. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3318. /* Create substitutes for POSIX functions in Win32. */
  3319. #if defined(__MINGW32__)
  3320. /* Show no warning in case system functions are not used. */
  3321. #pragma GCC diagnostic push
  3322. #pragma GCC diagnostic ignored "-Wunused-function"
  3323. #endif
  3324. static int
  3325. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3326. {
  3327. (void)unused;
  3328. *mutex = CreateMutex(NULL, FALSE, NULL);
  3329. return (*mutex == NULL) ? -1 : 0;
  3330. }
  3331. static int
  3332. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3333. {
  3334. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3335. }
  3336. static int
  3337. pthread_mutex_lock(pthread_mutex_t *mutex)
  3338. {
  3339. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3340. }
  3341. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3342. static int
  3343. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3344. {
  3345. switch (WaitForSingleObject(*mutex, 0)) {
  3346. case WAIT_OBJECT_0:
  3347. return 0;
  3348. case WAIT_TIMEOUT:
  3349. return -2; /* EBUSY */
  3350. }
  3351. return -1;
  3352. }
  3353. #endif
  3354. static int
  3355. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3356. {
  3357. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3358. }
  3359. static int
  3360. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3361. {
  3362. (void)unused;
  3363. InitializeCriticalSection(&cv->threadIdSec);
  3364. cv->waiting_thread = NULL;
  3365. return 0;
  3366. }
  3367. static int
  3368. pthread_cond_timedwait(pthread_cond_t *cv,
  3369. pthread_mutex_t *mutex,
  3370. const struct timespec *abstime)
  3371. {
  3372. struct mg_workerTLS **ptls,
  3373. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3374. int ok;
  3375. int64_t nsnow, nswaitabs, nswaitrel;
  3376. DWORD mswaitrel;
  3377. EnterCriticalSection(&cv->threadIdSec);
  3378. /* Add this thread to cv's waiting list */
  3379. ptls = &cv->waiting_thread;
  3380. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3381. ;
  3382. tls->next_waiting_thread = NULL;
  3383. *ptls = tls;
  3384. LeaveCriticalSection(&cv->threadIdSec);
  3385. if (abstime) {
  3386. nsnow = mg_get_current_time_ns();
  3387. nswaitabs =
  3388. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3389. nswaitrel = nswaitabs - nsnow;
  3390. if (nswaitrel < 0) {
  3391. nswaitrel = 0;
  3392. }
  3393. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3394. } else {
  3395. mswaitrel = INFINITE;
  3396. }
  3397. pthread_mutex_unlock(mutex);
  3398. ok = (WAIT_OBJECT_0
  3399. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3400. if (!ok) {
  3401. ok = 1;
  3402. EnterCriticalSection(&cv->threadIdSec);
  3403. ptls = &cv->waiting_thread;
  3404. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3405. if (*ptls == tls) {
  3406. *ptls = tls->next_waiting_thread;
  3407. ok = 0;
  3408. break;
  3409. }
  3410. }
  3411. LeaveCriticalSection(&cv->threadIdSec);
  3412. if (ok) {
  3413. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3414. }
  3415. }
  3416. /* This thread has been removed from cv's waiting list */
  3417. pthread_mutex_lock(mutex);
  3418. return ok ? 0 : -1;
  3419. }
  3420. static int
  3421. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3422. {
  3423. return pthread_cond_timedwait(cv, mutex, NULL);
  3424. }
  3425. static int
  3426. pthread_cond_signal(pthread_cond_t *cv)
  3427. {
  3428. HANDLE wkup = NULL;
  3429. BOOL ok = FALSE;
  3430. EnterCriticalSection(&cv->threadIdSec);
  3431. if (cv->waiting_thread) {
  3432. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3433. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3434. ok = SetEvent(wkup);
  3435. assert(ok);
  3436. }
  3437. LeaveCriticalSection(&cv->threadIdSec);
  3438. return ok ? 0 : 1;
  3439. }
  3440. static int
  3441. pthread_cond_broadcast(pthread_cond_t *cv)
  3442. {
  3443. EnterCriticalSection(&cv->threadIdSec);
  3444. while (cv->waiting_thread) {
  3445. pthread_cond_signal(cv);
  3446. }
  3447. LeaveCriticalSection(&cv->threadIdSec);
  3448. return 0;
  3449. }
  3450. static int
  3451. pthread_cond_destroy(pthread_cond_t *cv)
  3452. {
  3453. EnterCriticalSection(&cv->threadIdSec);
  3454. assert(cv->waiting_thread == NULL);
  3455. LeaveCriticalSection(&cv->threadIdSec);
  3456. DeleteCriticalSection(&cv->threadIdSec);
  3457. return 0;
  3458. }
  3459. #ifdef ALTERNATIVE_QUEUE
  3460. static void *
  3461. event_create(void)
  3462. {
  3463. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3464. }
  3465. static int
  3466. event_wait(void *eventhdl)
  3467. {
  3468. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3469. return (res == WAIT_OBJECT_0);
  3470. }
  3471. static int
  3472. event_signal(void *eventhdl)
  3473. {
  3474. return (int)SetEvent((HANDLE)eventhdl);
  3475. }
  3476. static void
  3477. event_destroy(void *eventhdl)
  3478. {
  3479. CloseHandle((HANDLE)eventhdl);
  3480. }
  3481. #endif
  3482. #if defined(__MINGW32__)
  3483. /* Enable unused function warning again */
  3484. #pragma GCC diagnostic pop
  3485. #endif
  3486. /* For Windows, change all slashes to backslashes in path names. */
  3487. static void
  3488. change_slashes_to_backslashes(char *path)
  3489. {
  3490. int i;
  3491. for (i = 0; path[i] != '\0'; i++) {
  3492. if (path[i] == '/') {
  3493. path[i] = '\\';
  3494. }
  3495. /* remove double backslash (check i > 0 to preserve UNC paths,
  3496. * like \\server\file.txt) */
  3497. if ((path[i] == '\\') && (i > 0)) {
  3498. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3499. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3500. }
  3501. }
  3502. }
  3503. }
  3504. static int
  3505. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3506. {
  3507. int diff;
  3508. do {
  3509. diff = tolower(*s1) - tolower(*s2);
  3510. s1++;
  3511. s2++;
  3512. } while ((diff == 0) && (s1[-1] != '\0'));
  3513. return diff;
  3514. }
  3515. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3516. * wbuf and wbuf_len is a target buffer and its length. */
  3517. static void
  3518. path_to_unicode(const struct mg_connection *conn,
  3519. const char *path,
  3520. wchar_t *wbuf,
  3521. size_t wbuf_len)
  3522. {
  3523. char buf[PATH_MAX], buf2[PATH_MAX];
  3524. wchar_t wbuf2[MAX_PATH + 1];
  3525. DWORD long_len, err;
  3526. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3527. mg_strlcpy(buf, path, sizeof(buf));
  3528. change_slashes_to_backslashes(buf);
  3529. /* Convert to Unicode and back. If doubly-converted string does not
  3530. * match the original, something is fishy, reject. */
  3531. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3532. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3533. WideCharToMultiByte(
  3534. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3535. if (strcmp(buf, buf2) != 0) {
  3536. wbuf[0] = L'\0';
  3537. }
  3538. /* Windows file systems are not case sensitive, but you can still use
  3539. * uppercase and lowercase letters (on all modern file systems).
  3540. * The server can check if the URI uses the same upper/lowercase
  3541. * letters an the file system, effectively making Windows servers
  3542. * case sensitive (like Linux servers are). It is still not possible
  3543. * to use two files with the same name in different cases on Windows
  3544. * (like /a and /A) - this would be possible in Linux.
  3545. * As a default, Windows is not case sensitive, but the case sensitive
  3546. * file name check can be activated by an additional configuration. */
  3547. if (conn) {
  3548. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3549. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3550. /* Use case sensitive compare function */
  3551. fcompare = wcscmp;
  3552. }
  3553. }
  3554. (void)conn; /* conn is currently unused */
  3555. #if !defined(_WIN32_WCE)
  3556. /* Only accept a full file path, not a Windows short (8.3) path. */
  3557. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3558. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3559. if (long_len == 0) {
  3560. err = GetLastError();
  3561. if (err == ERROR_FILE_NOT_FOUND) {
  3562. /* File does not exist. This is not always a problem here. */
  3563. return;
  3564. }
  3565. }
  3566. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3567. /* Short name is used. */
  3568. wbuf[0] = L'\0';
  3569. }
  3570. #else
  3571. (void)long_len;
  3572. (void)wbuf2;
  3573. (void)err;
  3574. if (strchr(path, '~')) {
  3575. wbuf[0] = L'\0';
  3576. }
  3577. #endif
  3578. }
  3579. /* Windows happily opens files with some garbage at the end of file name.
  3580. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3581. * "a.cgi", despite one would expect an error back.
  3582. * This function returns non-0 if path ends with some garbage. */
  3583. static int
  3584. path_cannot_disclose_cgi(const char *path)
  3585. {
  3586. static const char *allowed_last_characters = "_-";
  3587. int last = path[strlen(path) - 1];
  3588. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3589. }
  3590. static int
  3591. mg_stat(const struct mg_connection *conn,
  3592. const char *path,
  3593. struct mg_file_stat *filep)
  3594. {
  3595. wchar_t wbuf[PATH_MAX];
  3596. WIN32_FILE_ATTRIBUTE_DATA info;
  3597. time_t creation_time;
  3598. if (!filep) {
  3599. return 0;
  3600. }
  3601. memset(filep, 0, sizeof(*filep));
  3602. if (conn && is_file_in_memory(conn, path)) {
  3603. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3604. * memset */
  3605. /* Quick fix (for 1.9.x): */
  3606. /* mg_stat must fill all fields, also for files in memory */
  3607. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3608. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3609. filep->size = tmp_file.stat.size;
  3610. filep->location = 2;
  3611. /* TODO: for 1.10: restructure how files in memory are handled */
  3612. /* The "file in memory" feature is a candidate for deletion.
  3613. * Please join the discussion at
  3614. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3615. */
  3616. filep->last_modified = time(NULL); /* TODO */
  3617. /* last_modified = now ... assumes the file may change during runtime,
  3618. * so every mg_fopen call may return different data */
  3619. /* last_modified = conn->ctx.start_time;
  3620. * May be used it the data does not change during runtime. This allows
  3621. * browser caching. Since we do not know, we have to assume the file
  3622. * in memory may change. */
  3623. return 1;
  3624. }
  3625. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3626. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3627. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3628. filep->last_modified =
  3629. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3630. info.ftLastWriteTime.dwHighDateTime);
  3631. /* On Windows, the file creation time can be higher than the
  3632. * modification time, e.g. when a file is copied.
  3633. * Since the Last-Modified timestamp is used for caching
  3634. * it should be based on the most recent timestamp. */
  3635. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3636. info.ftCreationTime.dwHighDateTime);
  3637. if (creation_time > filep->last_modified) {
  3638. filep->last_modified = creation_time;
  3639. }
  3640. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3641. /* If file name is fishy, reset the file structure and return
  3642. * error.
  3643. * Note it is important to reset, not just return the error, cause
  3644. * functions like is_file_opened() check the struct. */
  3645. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3646. memset(filep, 0, sizeof(*filep));
  3647. return 0;
  3648. }
  3649. return 1;
  3650. }
  3651. return 0;
  3652. }
  3653. static int
  3654. mg_remove(const struct mg_connection *conn, const char *path)
  3655. {
  3656. wchar_t wbuf[PATH_MAX];
  3657. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3658. return DeleteFileW(wbuf) ? 0 : -1;
  3659. }
  3660. static int
  3661. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3662. {
  3663. wchar_t wbuf[PATH_MAX];
  3664. (void)mode;
  3665. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3666. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3667. }
  3668. /* Create substitutes for POSIX functions in Win32. */
  3669. #if defined(__MINGW32__)
  3670. /* Show no warning in case system functions are not used. */
  3671. #pragma GCC diagnostic push
  3672. #pragma GCC diagnostic ignored "-Wunused-function"
  3673. #endif
  3674. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3675. static DIR *
  3676. mg_opendir(const struct mg_connection *conn, const char *name)
  3677. {
  3678. DIR *dir = NULL;
  3679. wchar_t wpath[PATH_MAX];
  3680. DWORD attrs;
  3681. if (name == NULL) {
  3682. SetLastError(ERROR_BAD_ARGUMENTS);
  3683. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3684. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3685. } else {
  3686. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3687. attrs = GetFileAttributesW(wpath);
  3688. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3689. == FILE_ATTRIBUTE_DIRECTORY)) {
  3690. (void)wcscat(wpath, L"\\*");
  3691. dir->handle = FindFirstFileW(wpath, &dir->info);
  3692. dir->result.d_name[0] = '\0';
  3693. } else {
  3694. mg_free(dir);
  3695. dir = NULL;
  3696. }
  3697. }
  3698. return dir;
  3699. }
  3700. static int
  3701. mg_closedir(DIR *dir)
  3702. {
  3703. int result = 0;
  3704. if (dir != NULL) {
  3705. if (dir->handle != INVALID_HANDLE_VALUE)
  3706. result = FindClose(dir->handle) ? 0 : -1;
  3707. mg_free(dir);
  3708. } else {
  3709. result = -1;
  3710. SetLastError(ERROR_BAD_ARGUMENTS);
  3711. }
  3712. return result;
  3713. }
  3714. static struct dirent *
  3715. mg_readdir(DIR *dir)
  3716. {
  3717. struct dirent *result = 0;
  3718. if (dir) {
  3719. if (dir->handle != INVALID_HANDLE_VALUE) {
  3720. result = &dir->result;
  3721. (void)WideCharToMultiByte(CP_UTF8,
  3722. 0,
  3723. dir->info.cFileName,
  3724. -1,
  3725. result->d_name,
  3726. sizeof(result->d_name),
  3727. NULL,
  3728. NULL);
  3729. if (!FindNextFileW(dir->handle, &dir->info)) {
  3730. (void)FindClose(dir->handle);
  3731. dir->handle = INVALID_HANDLE_VALUE;
  3732. }
  3733. } else {
  3734. SetLastError(ERROR_FILE_NOT_FOUND);
  3735. }
  3736. } else {
  3737. SetLastError(ERROR_BAD_ARGUMENTS);
  3738. }
  3739. return result;
  3740. }
  3741. #ifndef HAVE_POLL
  3742. static int
  3743. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3744. {
  3745. struct timeval tv;
  3746. fd_set set;
  3747. unsigned int i;
  3748. int result;
  3749. SOCKET maxfd = 0;
  3750. memset(&tv, 0, sizeof(tv));
  3751. tv.tv_sec = milliseconds / 1000;
  3752. tv.tv_usec = (milliseconds % 1000) * 1000;
  3753. FD_ZERO(&set);
  3754. for (i = 0; i < n; i++) {
  3755. FD_SET((SOCKET)pfd[i].fd, &set);
  3756. pfd[i].revents = 0;
  3757. if (pfd[i].fd > maxfd) {
  3758. maxfd = pfd[i].fd;
  3759. }
  3760. }
  3761. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3762. for (i = 0; i < n; i++) {
  3763. if (FD_ISSET(pfd[i].fd, &set)) {
  3764. pfd[i].revents = POLLIN;
  3765. }
  3766. }
  3767. }
  3768. /* We should subtract the time used in select from remaining
  3769. * "milliseconds", in particular if called from mg_poll with a
  3770. * timeout quantum.
  3771. * Unfortunately, the remaining time is not stored in "tv" in all
  3772. * implementations, so the result in "tv" must be considered undefined.
  3773. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3774. return result;
  3775. }
  3776. #endif /* HAVE_POLL */
  3777. #if defined(__MINGW32__)
  3778. /* Enable unused function warning again */
  3779. #pragma GCC diagnostic pop
  3780. #endif
  3781. static void
  3782. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3783. {
  3784. (void)conn; /* Unused. */
  3785. #if defined(_WIN32_WCE)
  3786. (void)sock;
  3787. #else
  3788. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3789. #endif
  3790. }
  3791. int
  3792. mg_start_thread(mg_thread_func_t f, void *p)
  3793. {
  3794. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3795. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3796. */
  3797. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3798. == ((uintptr_t)(-1L)))
  3799. ? -1
  3800. : 0);
  3801. #else
  3802. return (
  3803. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3804. ? -1
  3805. : 0);
  3806. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3807. }
  3808. /* Start a thread storing the thread context. */
  3809. static int
  3810. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3811. void *p,
  3812. pthread_t *threadidptr)
  3813. {
  3814. uintptr_t uip;
  3815. HANDLE threadhandle;
  3816. int result = -1;
  3817. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3818. threadhandle = (HANDLE)uip;
  3819. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3820. *threadidptr = threadhandle;
  3821. result = 0;
  3822. }
  3823. return result;
  3824. }
  3825. /* Wait for a thread to finish. */
  3826. static int
  3827. mg_join_thread(pthread_t threadid)
  3828. {
  3829. int result;
  3830. DWORD dwevent;
  3831. result = -1;
  3832. dwevent = WaitForSingleObject(threadid, INFINITE);
  3833. if (dwevent == WAIT_FAILED) {
  3834. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3835. } else {
  3836. if (dwevent == WAIT_OBJECT_0) {
  3837. CloseHandle(threadid);
  3838. result = 0;
  3839. }
  3840. }
  3841. return result;
  3842. }
  3843. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3844. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3845. /* Create substitutes for POSIX functions in Win32. */
  3846. #if defined(__MINGW32__)
  3847. /* Show no warning in case system functions are not used. */
  3848. #pragma GCC diagnostic push
  3849. #pragma GCC diagnostic ignored "-Wunused-function"
  3850. #endif
  3851. static HANDLE
  3852. dlopen(const char *dll_name, int flags)
  3853. {
  3854. wchar_t wbuf[PATH_MAX];
  3855. (void)flags;
  3856. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3857. return LoadLibraryW(wbuf);
  3858. }
  3859. static int
  3860. dlclose(void *handle)
  3861. {
  3862. int result;
  3863. if (FreeLibrary((HMODULE)handle) != 0) {
  3864. result = 0;
  3865. } else {
  3866. result = -1;
  3867. }
  3868. return result;
  3869. }
  3870. #if defined(__MINGW32__)
  3871. /* Enable unused function warning again */
  3872. #pragma GCC diagnostic pop
  3873. #endif
  3874. #endif
  3875. #if !defined(NO_CGI)
  3876. #define SIGKILL (0)
  3877. static int
  3878. kill(pid_t pid, int sig_num)
  3879. {
  3880. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3881. (void)CloseHandle((HANDLE)pid);
  3882. return 0;
  3883. }
  3884. static void
  3885. trim_trailing_whitespaces(char *s)
  3886. {
  3887. char *e = s + strlen(s) - 1;
  3888. while ((e > s) && isspace(*(unsigned char *)e)) {
  3889. *e-- = '\0';
  3890. }
  3891. }
  3892. static pid_t
  3893. spawn_process(struct mg_connection *conn,
  3894. const char *prog,
  3895. char *envblk,
  3896. char *envp[],
  3897. int fdin[2],
  3898. int fdout[2],
  3899. int fderr[2],
  3900. const char *dir)
  3901. {
  3902. HANDLE me;
  3903. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3904. cmdline[PATH_MAX], buf[PATH_MAX];
  3905. int truncated;
  3906. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3907. STARTUPINFOA si;
  3908. PROCESS_INFORMATION pi = {0};
  3909. (void)envp;
  3910. memset(&si, 0, sizeof(si));
  3911. si.cb = sizeof(si);
  3912. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3913. si.wShowWindow = SW_HIDE;
  3914. me = GetCurrentProcess();
  3915. DuplicateHandle(me,
  3916. (HANDLE)_get_osfhandle(fdin[0]),
  3917. me,
  3918. &si.hStdInput,
  3919. 0,
  3920. TRUE,
  3921. DUPLICATE_SAME_ACCESS);
  3922. DuplicateHandle(me,
  3923. (HANDLE)_get_osfhandle(fdout[1]),
  3924. me,
  3925. &si.hStdOutput,
  3926. 0,
  3927. TRUE,
  3928. DUPLICATE_SAME_ACCESS);
  3929. DuplicateHandle(me,
  3930. (HANDLE)_get_osfhandle(fderr[1]),
  3931. me,
  3932. &si.hStdError,
  3933. 0,
  3934. TRUE,
  3935. DUPLICATE_SAME_ACCESS);
  3936. /* Mark handles that should not be inherited. See
  3937. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3938. */
  3939. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3940. HANDLE_FLAG_INHERIT,
  3941. 0);
  3942. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3943. HANDLE_FLAG_INHERIT,
  3944. 0);
  3945. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3946. HANDLE_FLAG_INHERIT,
  3947. 0);
  3948. /* If CGI file is a script, try to read the interpreter line */
  3949. interp = conn->ctx->config[CGI_INTERPRETER];
  3950. if (interp == NULL) {
  3951. buf[0] = buf[1] = '\0';
  3952. /* Read the first line of the script into the buffer */
  3953. mg_snprintf(
  3954. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3955. if (truncated) {
  3956. pi.hProcess = (pid_t)-1;
  3957. goto spawn_cleanup;
  3958. }
  3959. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3960. p = (char *)file.access.membuf;
  3961. mg_fgets(buf, sizeof(buf), &file, &p);
  3962. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3963. buf[sizeof(buf) - 1] = '\0';
  3964. }
  3965. if ((buf[0] == '#') && (buf[1] == '!')) {
  3966. trim_trailing_whitespaces(buf + 2);
  3967. } else {
  3968. buf[2] = '\0';
  3969. }
  3970. interp = buf + 2;
  3971. }
  3972. if (interp[0] != '\0') {
  3973. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3974. interp = full_interp;
  3975. }
  3976. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3977. if (interp[0] != '\0') {
  3978. mg_snprintf(conn,
  3979. &truncated,
  3980. cmdline,
  3981. sizeof(cmdline),
  3982. "\"%s\" \"%s\\%s\"",
  3983. interp,
  3984. full_dir,
  3985. prog);
  3986. } else {
  3987. mg_snprintf(conn,
  3988. &truncated,
  3989. cmdline,
  3990. sizeof(cmdline),
  3991. "\"%s\\%s\"",
  3992. full_dir,
  3993. prog);
  3994. }
  3995. if (truncated) {
  3996. pi.hProcess = (pid_t)-1;
  3997. goto spawn_cleanup;
  3998. }
  3999. DEBUG_TRACE("Running [%s]", cmdline);
  4000. if (CreateProcessA(NULL,
  4001. cmdline,
  4002. NULL,
  4003. NULL,
  4004. TRUE,
  4005. CREATE_NEW_PROCESS_GROUP,
  4006. envblk,
  4007. NULL,
  4008. &si,
  4009. &pi) == 0) {
  4010. mg_cry(
  4011. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4012. pi.hProcess = (pid_t)-1;
  4013. /* goto spawn_cleanup; */
  4014. }
  4015. spawn_cleanup:
  4016. (void)CloseHandle(si.hStdOutput);
  4017. (void)CloseHandle(si.hStdError);
  4018. (void)CloseHandle(si.hStdInput);
  4019. if (pi.hThread != NULL) {
  4020. (void)CloseHandle(pi.hThread);
  4021. }
  4022. return (pid_t)pi.hProcess;
  4023. }
  4024. #endif /* !NO_CGI */
  4025. static int
  4026. set_blocking_mode(SOCKET sock, int blocking)
  4027. {
  4028. unsigned long non_blocking = !blocking;
  4029. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4030. }
  4031. #else
  4032. static int
  4033. mg_stat(const struct mg_connection *conn,
  4034. const char *path,
  4035. struct mg_file_stat *filep)
  4036. {
  4037. struct stat st;
  4038. if (!filep) {
  4039. return 0;
  4040. }
  4041. memset(filep, 0, sizeof(*filep));
  4042. if (conn && is_file_in_memory(conn, path)) {
  4043. /* Quick fix (for 1.9.x): */
  4044. /* mg_stat must fill all fields, also for files in memory */
  4045. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4046. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4047. filep->size = tmp_file.stat.size;
  4048. filep->last_modified = time(NULL);
  4049. filep->location = 2;
  4050. /* TODO: for 1.10: restructure how files in memory are handled */
  4051. return 1;
  4052. }
  4053. if (0 == stat(path, &st)) {
  4054. filep->size = (uint64_t)(st.st_size);
  4055. filep->last_modified = st.st_mtime;
  4056. filep->is_directory = S_ISDIR(st.st_mode);
  4057. return 1;
  4058. }
  4059. return 0;
  4060. }
  4061. static void
  4062. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4063. {
  4064. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4065. if (conn) {
  4066. mg_cry(conn,
  4067. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4068. __func__,
  4069. strerror(ERRNO));
  4070. }
  4071. }
  4072. }
  4073. int
  4074. mg_start_thread(mg_thread_func_t func, void *param)
  4075. {
  4076. pthread_t thread_id;
  4077. pthread_attr_t attr;
  4078. int result;
  4079. (void)pthread_attr_init(&attr);
  4080. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4081. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4082. /* Compile-time option to control stack size,
  4083. * e.g. -DUSE_STACK_SIZE=16384 */
  4084. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4085. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4086. result = pthread_create(&thread_id, &attr, func, param);
  4087. pthread_attr_destroy(&attr);
  4088. return result;
  4089. }
  4090. /* Start a thread storing the thread context. */
  4091. static int
  4092. mg_start_thread_with_id(mg_thread_func_t func,
  4093. void *param,
  4094. pthread_t *threadidptr)
  4095. {
  4096. pthread_t thread_id;
  4097. pthread_attr_t attr;
  4098. int result;
  4099. (void)pthread_attr_init(&attr);
  4100. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4101. /* Compile-time option to control stack size,
  4102. * e.g. -DUSE_STACK_SIZE=16384 */
  4103. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4104. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4105. result = pthread_create(&thread_id, &attr, func, param);
  4106. pthread_attr_destroy(&attr);
  4107. if ((result == 0) && (threadidptr != NULL)) {
  4108. *threadidptr = thread_id;
  4109. }
  4110. return result;
  4111. }
  4112. /* Wait for a thread to finish. */
  4113. static int
  4114. mg_join_thread(pthread_t threadid)
  4115. {
  4116. int result;
  4117. result = pthread_join(threadid, NULL);
  4118. return result;
  4119. }
  4120. #ifndef NO_CGI
  4121. static pid_t
  4122. spawn_process(struct mg_connection *conn,
  4123. const char *prog,
  4124. char *envblk,
  4125. char *envp[],
  4126. int fdin[2],
  4127. int fdout[2],
  4128. int fderr[2],
  4129. const char *dir)
  4130. {
  4131. pid_t pid;
  4132. const char *interp;
  4133. (void)envblk;
  4134. if (conn == NULL) {
  4135. return 0;
  4136. }
  4137. if ((pid = fork()) == -1) {
  4138. /* Parent */
  4139. mg_send_http_error(conn,
  4140. 500,
  4141. "Error: Creating CGI process\nfork(): %s",
  4142. strerror(ERRNO));
  4143. } else if (pid == 0) {
  4144. /* Child */
  4145. if (chdir(dir) != 0) {
  4146. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4147. } else if (dup2(fdin[0], 0) == -1) {
  4148. mg_cry(conn,
  4149. "%s: dup2(%d, 0): %s",
  4150. __func__,
  4151. fdin[0],
  4152. strerror(ERRNO));
  4153. } else if (dup2(fdout[1], 1) == -1) {
  4154. mg_cry(conn,
  4155. "%s: dup2(%d, 1): %s",
  4156. __func__,
  4157. fdout[1],
  4158. strerror(ERRNO));
  4159. } else if (dup2(fderr[1], 2) == -1) {
  4160. mg_cry(conn,
  4161. "%s: dup2(%d, 2): %s",
  4162. __func__,
  4163. fderr[1],
  4164. strerror(ERRNO));
  4165. } else {
  4166. /* Keep stderr and stdout in two different pipes.
  4167. * Stdout will be sent back to the client,
  4168. * stderr should go into a server error log. */
  4169. (void)close(fdin[0]);
  4170. (void)close(fdout[1]);
  4171. (void)close(fderr[1]);
  4172. /* Close write end fdin and read end fdout and fderr */
  4173. (void)close(fdin[1]);
  4174. (void)close(fdout[0]);
  4175. (void)close(fderr[0]);
  4176. /* After exec, all signal handlers are restored to their default
  4177. * values, with one exception of SIGCHLD. According to
  4178. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4179. * leave unchanged after exec if it was set to be ignored. Restore
  4180. * it to default action. */
  4181. signal(SIGCHLD, SIG_DFL);
  4182. interp = conn->ctx->config[CGI_INTERPRETER];
  4183. if (interp == NULL) {
  4184. (void)execle(prog, prog, NULL, envp);
  4185. mg_cry(conn,
  4186. "%s: execle(%s): %s",
  4187. __func__,
  4188. prog,
  4189. strerror(ERRNO));
  4190. } else {
  4191. (void)execle(interp, interp, prog, NULL, envp);
  4192. mg_cry(conn,
  4193. "%s: execle(%s %s): %s",
  4194. __func__,
  4195. interp,
  4196. prog,
  4197. strerror(ERRNO));
  4198. }
  4199. }
  4200. exit(EXIT_FAILURE);
  4201. }
  4202. return pid;
  4203. }
  4204. #endif /* !NO_CGI */
  4205. static int
  4206. set_blocking_mode(SOCKET sock, int blocking)
  4207. {
  4208. int flags;
  4209. flags = fcntl(sock, F_GETFL, 0);
  4210. if (blocking) {
  4211. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  4212. } else {
  4213. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  4214. }
  4215. return 0;
  4216. }
  4217. #endif /* _WIN32 */
  4218. /* End of initial operating system specific define block. */
  4219. /* Get a random number (independent of C rand function) */
  4220. static uint64_t
  4221. get_random(void)
  4222. {
  4223. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4224. static uint64_t lcg = 0; /* Linear congruential generator */
  4225. uint64_t now = mg_get_current_time_ns();
  4226. if (lfsr == 0) {
  4227. /* lfsr will be only 0 if has not been initialized,
  4228. * so this code is called only once. */
  4229. lfsr = mg_get_current_time_ns();
  4230. lcg = mg_get_current_time_ns();
  4231. } else {
  4232. /* Get the next step of both random number generators. */
  4233. lfsr = (lfsr >> 1)
  4234. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4235. << 63);
  4236. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4237. }
  4238. /* Combining two pseudo-random number generators and a high resolution part
  4239. * of the current server time will make it hard (impossible?) to guess the
  4240. * next number. */
  4241. return (lfsr ^ lcg ^ now);
  4242. }
  4243. static int
  4244. mg_poll(struct pollfd *pfd,
  4245. unsigned int n,
  4246. int milliseconds,
  4247. volatile int *stop_server)
  4248. {
  4249. int ms_now, result;
  4250. /* Call poll, but only for a maximum time of a few seconds.
  4251. * This will allow to stop the server after some seconds, instead
  4252. * of having to wait for a long socket timeout. */
  4253. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4254. do {
  4255. if (*stop_server) {
  4256. /* Shut down signal */
  4257. return -2;
  4258. }
  4259. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4260. ms_now = milliseconds;
  4261. }
  4262. result = poll(pfd, n, ms_now);
  4263. if (result != 0) {
  4264. /* Poll returned either success (1) or error (-1).
  4265. * Forward both to the caller. */
  4266. return result;
  4267. }
  4268. /* Poll returned timeout (0). */
  4269. if (milliseconds > 0) {
  4270. milliseconds -= ms_now;
  4271. }
  4272. } while (milliseconds != 0);
  4273. return result;
  4274. }
  4275. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4276. * descriptor.
  4277. * Return value:
  4278. * >=0 .. number of bytes successfully written
  4279. * -1 .. timeout
  4280. * -2 .. error
  4281. */
  4282. static int
  4283. push_inner(struct mg_context *ctx,
  4284. FILE *fp,
  4285. SOCKET sock,
  4286. SSL *ssl,
  4287. const char *buf,
  4288. int len,
  4289. double timeout)
  4290. {
  4291. uint64_t start = 0, now = 0, timeout_ns = 0;
  4292. int n, err;
  4293. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4294. #ifdef _WIN32
  4295. typedef int len_t;
  4296. #else
  4297. typedef size_t len_t;
  4298. #endif
  4299. if (timeout > 0) {
  4300. start = mg_get_current_time_ns();
  4301. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4302. }
  4303. if (ctx == NULL) {
  4304. return -2;
  4305. }
  4306. #ifdef NO_SSL
  4307. if (ssl) {
  4308. return -2;
  4309. }
  4310. #endif
  4311. do {
  4312. #ifndef NO_SSL
  4313. if (ssl != NULL) {
  4314. n = SSL_write(ssl, buf, len);
  4315. if (n <= 0) {
  4316. err = SSL_get_error(ssl, n);
  4317. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4318. err = ERRNO;
  4319. } else if ((err == SSL_ERROR_WANT_READ)
  4320. || (err == SSL_ERROR_WANT_WRITE)) {
  4321. n = 0;
  4322. } else {
  4323. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4324. return -2;
  4325. }
  4326. } else {
  4327. err = 0;
  4328. }
  4329. } else
  4330. #endif
  4331. if (fp != NULL) {
  4332. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4333. if (ferror(fp)) {
  4334. n = -1;
  4335. err = ERRNO;
  4336. } else {
  4337. err = 0;
  4338. }
  4339. } else {
  4340. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4341. err = (n < 0) ? ERRNO : 0;
  4342. #ifdef _WIN32
  4343. if (err == WSAEWOULDBLOCK) {
  4344. err = 0;
  4345. n = 0;
  4346. }
  4347. #else
  4348. if (err == EWOULDBLOCK) {
  4349. err = 0;
  4350. n = 0;
  4351. }
  4352. #endif
  4353. if (n < 0) {
  4354. /* shutdown of the socket at client side */
  4355. return -2;
  4356. }
  4357. }
  4358. if (ctx->stop_flag) {
  4359. return -2;
  4360. }
  4361. if ((n > 0) || ((n == 0) && (len == 0))) {
  4362. /* some data has been read, or no data was requested */
  4363. return n;
  4364. }
  4365. if (n < 0) {
  4366. /* socket error - check errno */
  4367. DEBUG_TRACE("send() failed, error %d", err);
  4368. /* TODO (mid): error handling depending on the error code.
  4369. * These codes are different between Windows and Linux.
  4370. * Currently there is no problem with failing send calls,
  4371. * if there is a reproducible situation, it should be
  4372. * investigated in detail.
  4373. */
  4374. return -2;
  4375. }
  4376. /* Only in case n=0 (timeout), repeat calling the write function */
  4377. /* If send failed, wait before retry */
  4378. if (fp != NULL) {
  4379. /* For files, just wait a fixed time,
  4380. * maybe an average disk seek time. */
  4381. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4382. } else {
  4383. /* For sockets, wait for the socket using select */
  4384. fd_set wfds;
  4385. struct timeval tv;
  4386. int sret;
  4387. #if defined(__GNUC__) || defined(__MINGW32__)
  4388. /* GCC seems to have a flaw with it's own socket macros:
  4389. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4390. */
  4391. #pragma GCC diagnostic push
  4392. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4393. #endif
  4394. FD_ZERO(&wfds);
  4395. FD_SET(sock, &wfds);
  4396. tv.tv_sec = (time_t)(ms_wait / 1000);
  4397. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4398. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4399. #if defined(__GNUC__) || defined(__MINGW32__)
  4400. #pragma GCC diagnostic pop
  4401. #endif
  4402. if (sret > 0) {
  4403. /* We got ready to write. Don't check the timeout
  4404. * but directly go back to write again. */
  4405. continue;
  4406. }
  4407. }
  4408. if (timeout >= 0) {
  4409. now = mg_get_current_time_ns();
  4410. }
  4411. } while ((timeout <= 0) || ((now - start) <= timeout_ns));
  4412. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4413. used */
  4414. return -1;
  4415. }
  4416. static int64_t
  4417. push_all(struct mg_context *ctx,
  4418. FILE *fp,
  4419. SOCKET sock,
  4420. SSL *ssl,
  4421. const char *buf,
  4422. int64_t len)
  4423. {
  4424. double timeout = -1.0;
  4425. int64_t n, nwritten = 0;
  4426. if (ctx == NULL) {
  4427. return -1;
  4428. }
  4429. if (ctx->config[REQUEST_TIMEOUT]) {
  4430. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4431. }
  4432. while ((len > 0) && (ctx->stop_flag == 0)) {
  4433. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4434. if (n < 0) {
  4435. if (nwritten == 0) {
  4436. nwritten = n; /* Propagate the error */
  4437. }
  4438. break;
  4439. } else if (n == 0) {
  4440. break; /* No more data to write */
  4441. } else {
  4442. nwritten += n;
  4443. len -= n;
  4444. }
  4445. }
  4446. return nwritten;
  4447. }
  4448. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4449. * Return value:
  4450. * >=0 .. number of bytes successfully read
  4451. * -1 .. timeout
  4452. * -2 .. error
  4453. */
  4454. static int
  4455. pull_inner(FILE *fp,
  4456. struct mg_connection *conn,
  4457. char *buf,
  4458. int len,
  4459. double timeout)
  4460. {
  4461. int nread, err = 0;
  4462. #ifdef _WIN32
  4463. typedef int len_t;
  4464. #else
  4465. typedef size_t len_t;
  4466. #endif
  4467. #ifndef NO_SSL
  4468. int ssl_pending;
  4469. #endif
  4470. /* We need an additional wait loop around this, because in some cases
  4471. * with TLSwe may get data from the socket but not from SSL_read.
  4472. * In this case we need to repeat at least once.
  4473. */
  4474. if (fp != NULL) {
  4475. #if !defined(_WIN32_WCE)
  4476. /* Use read() instead of fread(), because if we're reading from the
  4477. * CGI pipe, fread() may block until IO buffer is filled up. We
  4478. * cannot afford to block and must pass all read bytes immediately
  4479. * to the client. */
  4480. nread = (int)read(fileno(fp), buf, (size_t)len);
  4481. #else
  4482. /* WinCE does not support CGI pipes */
  4483. nread = (int)fread(buf, 1, (size_t)len, fp);
  4484. #endif
  4485. err = (nread < 0) ? ERRNO : 0;
  4486. #ifndef NO_SSL
  4487. } else if ((conn->ssl != NULL)
  4488. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4489. /* We already know there is no more data buffered in conn->buf
  4490. * but there is more available in the SSL layer. So don't poll
  4491. * conn->client.sock yet. */
  4492. if (ssl_pending > len) {
  4493. ssl_pending = len;
  4494. }
  4495. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4496. if (nread <= 0) {
  4497. err = SSL_get_error(conn->ssl, nread);
  4498. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4499. err = ERRNO;
  4500. } else if ((err == SSL_ERROR_WANT_READ)
  4501. || (err == SSL_ERROR_WANT_WRITE)) {
  4502. nread = 0;
  4503. } else {
  4504. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4505. return -1;
  4506. }
  4507. } else {
  4508. err = 0;
  4509. }
  4510. } else if (conn->ssl != NULL) {
  4511. struct pollfd pfd[1];
  4512. int pollres;
  4513. pfd[0].fd = conn->client.sock;
  4514. pfd[0].events = POLLIN;
  4515. pollres =
  4516. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4517. if (conn->ctx->stop_flag) {
  4518. return -2;
  4519. }
  4520. if (pollres > 0) {
  4521. nread = SSL_read(conn->ssl, buf, len);
  4522. if (nread <= 0) {
  4523. err = SSL_get_error(conn->ssl, nread);
  4524. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4525. err = ERRNO;
  4526. } else if ((err == SSL_ERROR_WANT_READ)
  4527. || (err == SSL_ERROR_WANT_WRITE)) {
  4528. nread = 0;
  4529. } else {
  4530. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4531. return -2;
  4532. }
  4533. } else {
  4534. err = 0;
  4535. }
  4536. } else if (pollres < 0) {
  4537. /* Error */
  4538. return -2;
  4539. } else {
  4540. /* pollres = 0 means timeout */
  4541. nread = 0;
  4542. }
  4543. #endif
  4544. } else {
  4545. struct pollfd pfd[1];
  4546. int pollres;
  4547. pfd[0].fd = conn->client.sock;
  4548. pfd[0].events = POLLIN;
  4549. pollres =
  4550. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4551. if (conn->ctx->stop_flag) {
  4552. return -2;
  4553. }
  4554. if (pollres > 0) {
  4555. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4556. err = (nread < 0) ? ERRNO : 0;
  4557. if (nread <= 0) {
  4558. /* shutdown of the socket at client side */
  4559. return -2;
  4560. }
  4561. } else if (pollres < 0) {
  4562. /* error callint poll */
  4563. return -2;
  4564. } else {
  4565. /* pollres = 0 means timeout */
  4566. nread = 0;
  4567. }
  4568. }
  4569. if (conn->ctx->stop_flag) {
  4570. return -2;
  4571. }
  4572. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  4573. /* some data has been read, or no data was requested */
  4574. return nread;
  4575. }
  4576. if (nread < 0) {
  4577. /* socket error - check errno */
  4578. #ifdef _WIN32
  4579. if (err == WSAEWOULDBLOCK) {
  4580. /* TODO (low): check if this is still required */
  4581. /* standard case if called from close_socket_gracefully */
  4582. return -2;
  4583. } else if (err == WSAETIMEDOUT) {
  4584. /* TODO (low): check if this is still required */
  4585. /* timeout is handled by the while loop */
  4586. return 0;
  4587. } else if (err == WSAECONNABORTED) {
  4588. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4589. return -2;
  4590. } else {
  4591. DEBUG_TRACE("recv() failed, error %d", err);
  4592. return -2;
  4593. }
  4594. #else
  4595. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4596. * if the timeout is reached and if the socket was set to non-
  4597. * blocking in close_socket_gracefully, so we can not distinguish
  4598. * here. We have to wait for the timeout in both cases for now.
  4599. */
  4600. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  4601. /* TODO (low): check if this is still required */
  4602. /* EAGAIN/EWOULDBLOCK:
  4603. * standard case if called from close_socket_gracefully
  4604. * => should return -1 */
  4605. /* or timeout occured
  4606. * => the code must stay in the while loop */
  4607. /* EINTR can be generated on a socket with a timeout set even
  4608. * when SA_RESTART is effective for all relevant signals
  4609. * (see signal(7)).
  4610. * => stay in the while loop */
  4611. } else {
  4612. DEBUG_TRACE("recv() failed, error %d", err);
  4613. return -2;
  4614. }
  4615. #endif
  4616. }
  4617. /* Timeout occured, but no data available. */
  4618. return -1;
  4619. }
  4620. static int
  4621. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4622. {
  4623. int n, nread = 0;
  4624. double timeout = -1.0;
  4625. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4626. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4627. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4628. }
  4629. if (timeout >= 0.0) {
  4630. start_time = mg_get_current_time_ns();
  4631. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4632. }
  4633. while ((len > 0) && (conn->ctx->stop_flag == 0)) {
  4634. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4635. if (n == -2) {
  4636. if (nread == 0) {
  4637. nread = -1; /* Propagate the error */
  4638. }
  4639. break;
  4640. } else if (n == -1) {
  4641. /* timeout */
  4642. if (timeout >= 0.0) {
  4643. now = mg_get_current_time_ns();
  4644. if ((now - start_time) <= timeout_ns) {
  4645. continue;
  4646. }
  4647. }
  4648. break;
  4649. } else if (n == 0) {
  4650. break; /* No more data to read */
  4651. } else {
  4652. conn->consumed_content += n;
  4653. nread += n;
  4654. len -= n;
  4655. }
  4656. }
  4657. return nread;
  4658. }
  4659. static void
  4660. discard_unread_request_data(struct mg_connection *conn)
  4661. {
  4662. char buf[MG_BUF_LEN];
  4663. size_t to_read;
  4664. int nread;
  4665. if (conn == NULL) {
  4666. return;
  4667. }
  4668. to_read = sizeof(buf);
  4669. if (conn->is_chunked) {
  4670. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4671. * completely */
  4672. while (conn->is_chunked == 1) {
  4673. nread = mg_read(conn, buf, to_read);
  4674. if (nread <= 0) {
  4675. break;
  4676. }
  4677. }
  4678. } else {
  4679. /* Not chunked: content length is known */
  4680. while (conn->consumed_content < conn->content_len) {
  4681. if (to_read
  4682. > (size_t)(conn->content_len - conn->consumed_content)) {
  4683. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4684. }
  4685. nread = mg_read(conn, buf, to_read);
  4686. if (nread <= 0) {
  4687. break;
  4688. }
  4689. }
  4690. }
  4691. }
  4692. static int
  4693. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4694. {
  4695. int64_t n, buffered_len, nread;
  4696. int64_t len64 =
  4697. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4698. * int, we may not read more
  4699. * bytes */
  4700. const char *body;
  4701. if (conn == NULL) {
  4702. return 0;
  4703. }
  4704. /* If Content-Length is not set for a PUT or POST request, read until
  4705. * socket is closed */
  4706. if ((conn->consumed_content) == 0 && (conn->content_len == -1)) {
  4707. conn->content_len = INT64_MAX;
  4708. conn->must_close = 1;
  4709. }
  4710. nread = 0;
  4711. if (conn->consumed_content < conn->content_len) {
  4712. /* Adjust number of bytes to read. */
  4713. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4714. if (left_to_read < len64) {
  4715. /* Do not read more than the total content length of the request.
  4716. */
  4717. len64 = left_to_read;
  4718. }
  4719. /* Return buffered data */
  4720. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4721. - conn->consumed_content;
  4722. if (buffered_len > 0) {
  4723. if (len64 < buffered_len) {
  4724. buffered_len = len64;
  4725. }
  4726. body = conn->buf + conn->request_len + conn->consumed_content;
  4727. memcpy(buf, body, (size_t)buffered_len);
  4728. len64 -= buffered_len;
  4729. conn->consumed_content += buffered_len;
  4730. nread += buffered_len;
  4731. buf = (char *)buf + buffered_len;
  4732. }
  4733. /* We have returned all buffered data. Read new data from the remote
  4734. * socket.
  4735. */
  4736. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4737. nread += n;
  4738. } else {
  4739. nread = ((nread > 0) ? nread : n);
  4740. }
  4741. }
  4742. return (int)nread;
  4743. }
  4744. static char
  4745. mg_getc(struct mg_connection *conn)
  4746. {
  4747. char c;
  4748. if (conn == NULL) {
  4749. return 0;
  4750. }
  4751. conn->content_len++;
  4752. if (mg_read_inner(conn, &c, 1) <= 0) {
  4753. return (char)0;
  4754. }
  4755. return c;
  4756. }
  4757. int
  4758. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4759. {
  4760. if (len > INT_MAX) {
  4761. len = INT_MAX;
  4762. }
  4763. if (conn == NULL) {
  4764. return 0;
  4765. }
  4766. if (conn->is_chunked) {
  4767. size_t all_read = 0;
  4768. while (len > 0) {
  4769. if (conn->is_chunked == 2) {
  4770. /* No more data left to read */
  4771. return 0;
  4772. }
  4773. if (conn->chunk_remainder) {
  4774. /* copy from the remainder of the last received chunk */
  4775. long read_ret;
  4776. size_t read_now =
  4777. ((conn->chunk_remainder > len) ? (len)
  4778. : (conn->chunk_remainder));
  4779. conn->content_len += (int)read_now;
  4780. read_ret =
  4781. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4782. if (read_ret < 1) {
  4783. /* read error */
  4784. return -1;
  4785. }
  4786. all_read += (size_t)read_ret;
  4787. conn->chunk_remainder -= (size_t)read_ret;
  4788. len -= (size_t)read_ret;
  4789. if (conn->chunk_remainder == 0) {
  4790. /* Add data bytes in the current chunk have been read,
  4791. * so we are expecting \r\n now. */
  4792. char x1 = mg_getc(conn);
  4793. char x2 = mg_getc(conn);
  4794. if ((x1 != '\r') || (x2 != '\n')) {
  4795. /* Protocol violation */
  4796. return -1;
  4797. }
  4798. }
  4799. } else {
  4800. /* fetch a new chunk */
  4801. int i = 0;
  4802. char lenbuf[64];
  4803. char *end = 0;
  4804. unsigned long chunkSize = 0;
  4805. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4806. lenbuf[i] = mg_getc(conn);
  4807. if ((i > 0) && (lenbuf[i] == '\r')
  4808. && (lenbuf[i - 1] != '\r')) {
  4809. continue;
  4810. }
  4811. if ((i > 1) && (lenbuf[i] == '\n')
  4812. && (lenbuf[i - 1] == '\r')) {
  4813. lenbuf[i + 1] = 0;
  4814. chunkSize = strtoul(lenbuf, &end, 16);
  4815. if (chunkSize == 0) {
  4816. /* regular end of content */
  4817. conn->is_chunked = 2;
  4818. }
  4819. break;
  4820. }
  4821. if (!isxdigit(lenbuf[i])) {
  4822. /* illegal character for chunk length */
  4823. return -1;
  4824. }
  4825. }
  4826. if ((end == NULL) || (*end != '\r')) {
  4827. /* chunksize not set correctly */
  4828. return -1;
  4829. }
  4830. if (chunkSize == 0) {
  4831. break;
  4832. }
  4833. conn->chunk_remainder = chunkSize;
  4834. }
  4835. }
  4836. return (int)all_read;
  4837. }
  4838. return mg_read_inner(conn, buf, len);
  4839. }
  4840. int
  4841. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4842. {
  4843. time_t now;
  4844. int64_t n, total, allowed;
  4845. if (conn == NULL) {
  4846. return 0;
  4847. }
  4848. if (conn->throttle > 0) {
  4849. if ((now = time(NULL)) != conn->last_throttle_time) {
  4850. conn->last_throttle_time = now;
  4851. conn->last_throttle_bytes = 0;
  4852. }
  4853. allowed = conn->throttle - conn->last_throttle_bytes;
  4854. if (allowed > (int64_t)len) {
  4855. allowed = (int64_t)len;
  4856. }
  4857. if ((total = push_all(conn->ctx,
  4858. NULL,
  4859. conn->client.sock,
  4860. conn->ssl,
  4861. (const char *)buf,
  4862. (int64_t)allowed)) == allowed) {
  4863. buf = (const char *)buf + total;
  4864. conn->last_throttle_bytes += total;
  4865. while ((total < (int64_t)len) && (conn->ctx->stop_flag == 0)) {
  4866. allowed = (conn->throttle > ((int64_t)len - total))
  4867. ? (int64_t)len - total
  4868. : conn->throttle;
  4869. if ((n = push_all(conn->ctx,
  4870. NULL,
  4871. conn->client.sock,
  4872. conn->ssl,
  4873. (const char *)buf,
  4874. (int64_t)allowed)) != allowed) {
  4875. break;
  4876. }
  4877. sleep(1);
  4878. conn->last_throttle_bytes = allowed;
  4879. conn->last_throttle_time = time(NULL);
  4880. buf = (const char *)buf + n;
  4881. total += n;
  4882. }
  4883. }
  4884. } else {
  4885. total = push_all(conn->ctx,
  4886. NULL,
  4887. conn->client.sock,
  4888. conn->ssl,
  4889. (const char *)buf,
  4890. (int64_t)len);
  4891. }
  4892. if (total > 0) {
  4893. conn->num_bytes_sent += total;
  4894. }
  4895. return (int)total;
  4896. }
  4897. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  4898. int
  4899. mg_send_chunk(struct mg_connection *conn,
  4900. const char *chunk,
  4901. unsigned int chunk_len)
  4902. {
  4903. char lenbuf[16];
  4904. size_t lenbuf_len;
  4905. int ret;
  4906. int t;
  4907. /* First store the length information in a text buffer. */
  4908. sprintf(lenbuf, "%x\r\n", chunk_len);
  4909. lenbuf_len = strlen(lenbuf);
  4910. /* Then send length information, chunk and terminating \r\n. */
  4911. ret = mg_write(conn, lenbuf, lenbuf_len);
  4912. if (ret != (int)lenbuf_len) {
  4913. return -1;
  4914. }
  4915. t = ret;
  4916. ret = mg_write(conn, chunk, chunk_len);
  4917. if (ret != (int)chunk_len) {
  4918. return -1;
  4919. }
  4920. t += ret;
  4921. ret = mg_write(conn, "\r\n", 2);
  4922. if (ret != 2) {
  4923. return -1;
  4924. }
  4925. t += ret;
  4926. return t;
  4927. }
  4928. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4929. static int
  4930. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4931. {
  4932. va_list ap_copy;
  4933. size_t size = MG_BUF_LEN / 4;
  4934. int len = -1;
  4935. *buf = NULL;
  4936. while (len < 0) {
  4937. if (*buf) {
  4938. mg_free(*buf);
  4939. }
  4940. size *= 4;
  4941. *buf = (char *)mg_malloc(size);
  4942. if (!*buf) {
  4943. break;
  4944. }
  4945. va_copy(ap_copy, ap);
  4946. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4947. va_end(ap_copy);
  4948. (*buf)[size - 1] = 0;
  4949. }
  4950. return len;
  4951. }
  4952. /* Print message to buffer. If buffer is large enough to hold the message,
  4953. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4954. * and return allocated buffer. */
  4955. static int
  4956. alloc_vprintf(char **out_buf,
  4957. char *prealloc_buf,
  4958. size_t prealloc_size,
  4959. const char *fmt,
  4960. va_list ap)
  4961. {
  4962. va_list ap_copy;
  4963. int len;
  4964. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4965. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4966. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4967. * Therefore, we make two passes: on first pass, get required message
  4968. * length.
  4969. * On second pass, actually print the message. */
  4970. va_copy(ap_copy, ap);
  4971. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4972. va_end(ap_copy);
  4973. if (len < 0) {
  4974. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4975. * Switch to alternative code path that uses incremental allocations.
  4976. */
  4977. va_copy(ap_copy, ap);
  4978. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4979. va_end(ap_copy);
  4980. } else if ((size_t)(len) >= prealloc_size) {
  4981. /* The pre-allocated buffer not large enough. */
  4982. /* Allocate a new buffer. */
  4983. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4984. if (!*out_buf) {
  4985. /* Allocation failed. Return -1 as "out of memory" error. */
  4986. return -1;
  4987. }
  4988. /* Buffer allocation successful. Store the string there. */
  4989. va_copy(ap_copy, ap);
  4990. IGNORE_UNUSED_RESULT(
  4991. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4992. va_end(ap_copy);
  4993. } else {
  4994. /* The pre-allocated buffer is large enough.
  4995. * Use it to store the string and return the address. */
  4996. va_copy(ap_copy, ap);
  4997. IGNORE_UNUSED_RESULT(
  4998. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4999. va_end(ap_copy);
  5000. *out_buf = prealloc_buf;
  5001. }
  5002. return len;
  5003. }
  5004. static int
  5005. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5006. {
  5007. char mem[MG_BUF_LEN];
  5008. char *buf = NULL;
  5009. int len;
  5010. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5011. len = mg_write(conn, buf, (size_t)len);
  5012. }
  5013. if ((buf != mem) && (buf != NULL)) {
  5014. mg_free(buf);
  5015. }
  5016. return len;
  5017. }
  5018. int
  5019. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5020. {
  5021. va_list ap;
  5022. int result;
  5023. va_start(ap, fmt);
  5024. result = mg_vprintf(conn, fmt, ap);
  5025. va_end(ap);
  5026. return result;
  5027. }
  5028. int
  5029. mg_url_decode(const char *src,
  5030. int src_len,
  5031. char *dst,
  5032. int dst_len,
  5033. int is_form_url_encoded)
  5034. {
  5035. int i, j, a, b;
  5036. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5037. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5038. if ((i < src_len - 2) && (src[i] == '%')
  5039. && isxdigit(*(const unsigned char *)(src + i + 1))
  5040. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5041. a = tolower(*(const unsigned char *)(src + i + 1));
  5042. b = tolower(*(const unsigned char *)(src + i + 2));
  5043. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5044. i += 2;
  5045. } else if (is_form_url_encoded && (src[i] == '+')) {
  5046. dst[j] = ' ';
  5047. } else {
  5048. dst[j] = src[i];
  5049. }
  5050. }
  5051. dst[j] = '\0'; /* Null-terminate the destination */
  5052. return (i >= src_len) ? j : -1;
  5053. }
  5054. int
  5055. mg_get_var(const char *data,
  5056. size_t data_len,
  5057. const char *name,
  5058. char *dst,
  5059. size_t dst_len)
  5060. {
  5061. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5062. }
  5063. int
  5064. mg_get_var2(const char *data,
  5065. size_t data_len,
  5066. const char *name,
  5067. char *dst,
  5068. size_t dst_len,
  5069. size_t occurrence)
  5070. {
  5071. const char *p, *e, *s;
  5072. size_t name_len;
  5073. int len;
  5074. if ((dst == NULL) || (dst_len == 0)) {
  5075. len = -2;
  5076. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5077. len = -1;
  5078. dst[0] = '\0';
  5079. } else {
  5080. name_len = strlen(name);
  5081. e = data + data_len;
  5082. len = -1;
  5083. dst[0] = '\0';
  5084. /* data is "var1=val1&var2=val2...". Find variable first */
  5085. for (p = data; p + name_len < e; p++) {
  5086. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5087. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5088. /* Point p to variable value */
  5089. p += name_len + 1;
  5090. /* Point s to the end of the value */
  5091. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5092. if (s == NULL) {
  5093. s = e;
  5094. }
  5095. /* assert(s >= p); */
  5096. if (s < p) {
  5097. return -3;
  5098. }
  5099. /* Decode variable into destination buffer */
  5100. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5101. /* Redirect error code from -1 to -2 (destination buffer too
  5102. * small). */
  5103. if (len == -1) {
  5104. len = -2;
  5105. }
  5106. break;
  5107. }
  5108. }
  5109. }
  5110. return len;
  5111. }
  5112. /* HCP24: some changes to compare hole var_name */
  5113. int
  5114. mg_get_cookie(const char *cookie_header,
  5115. const char *var_name,
  5116. char *dst,
  5117. size_t dst_size)
  5118. {
  5119. const char *s, *p, *end;
  5120. int name_len, len = -1;
  5121. if ((dst == NULL) || (dst_size == 0)) {
  5122. return -2;
  5123. }
  5124. dst[0] = '\0';
  5125. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5126. return -1;
  5127. }
  5128. name_len = (int)strlen(var_name);
  5129. end = s + strlen(s);
  5130. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5131. if (s[name_len] == '=') {
  5132. /* HCP24: now check is it a substring or a full cookie name */
  5133. if ((s == cookie_header) || (s[-1] == ' ')) {
  5134. s += name_len + 1;
  5135. if ((p = strchr(s, ' ')) == NULL) {
  5136. p = end;
  5137. }
  5138. if (p[-1] == ';') {
  5139. p--;
  5140. }
  5141. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5142. s++;
  5143. p--;
  5144. }
  5145. if ((size_t)(p - s) < dst_size) {
  5146. len = (int)(p - s);
  5147. mg_strlcpy(dst, s, (size_t)len + 1);
  5148. } else {
  5149. len = -3;
  5150. }
  5151. break;
  5152. }
  5153. }
  5154. }
  5155. return len;
  5156. }
  5157. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5158. static void
  5159. base64_encode(const unsigned char *src, int src_len, char *dst)
  5160. {
  5161. static const char *b64 =
  5162. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5163. int i, j, a, b, c;
  5164. for (i = j = 0; i < src_len; i += 3) {
  5165. a = src[i];
  5166. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5167. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5168. dst[j++] = b64[a >> 2];
  5169. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5170. if (i + 1 < src_len) {
  5171. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5172. }
  5173. if (i + 2 < src_len) {
  5174. dst[j++] = b64[c & 63];
  5175. }
  5176. }
  5177. while (j % 4 != 0) {
  5178. dst[j++] = '=';
  5179. }
  5180. dst[j++] = '\0';
  5181. }
  5182. #endif
  5183. #if defined(USE_LUA)
  5184. static unsigned char
  5185. b64reverse(char letter)
  5186. {
  5187. if ((letter >= 'A') && (letter <= 'Z')) {
  5188. return letter - 'A';
  5189. }
  5190. if ((letter >= 'a') && (letter <= 'z')) {
  5191. return letter - 'a' + 26;
  5192. }
  5193. if ((letter >= '0') && (letter <= '9')) {
  5194. return letter - '0' + 52;
  5195. }
  5196. if (letter == '+') {
  5197. return 62;
  5198. }
  5199. if (letter == '/') {
  5200. return 63;
  5201. }
  5202. if (letter == '=') {
  5203. return 255; /* normal end */
  5204. }
  5205. return 254; /* error */
  5206. }
  5207. static int
  5208. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5209. {
  5210. int i;
  5211. unsigned char a, b, c, d;
  5212. *dst_len = 0;
  5213. for (i = 0; i < src_len; i += 4) {
  5214. a = b64reverse(src[i]);
  5215. if (a >= 254) {
  5216. return i;
  5217. }
  5218. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5219. if (b >= 254) {
  5220. return i + 1;
  5221. }
  5222. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5223. if (c == 254) {
  5224. return i + 2;
  5225. }
  5226. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5227. if (d == 254) {
  5228. return i + 3;
  5229. }
  5230. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5231. if (c != 255) {
  5232. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5233. if (d != 255) {
  5234. dst[(*dst_len)++] = (c << 6) + d;
  5235. }
  5236. }
  5237. }
  5238. return -1;
  5239. }
  5240. #endif
  5241. static int
  5242. is_put_or_delete_method(const struct mg_connection *conn)
  5243. {
  5244. if (conn) {
  5245. const char *s = conn->request_info.request_method;
  5246. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5247. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5248. }
  5249. return 0;
  5250. }
  5251. #if !defined(NO_FILES)
  5252. static int
  5253. extention_matches_script(
  5254. struct mg_connection *conn, /* in: request (must be valid) */
  5255. const char *filename /* in: filename (must be valid) */
  5256. )
  5257. {
  5258. #if !defined(NO_CGI)
  5259. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5260. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5261. filename) > 0) {
  5262. return 1;
  5263. }
  5264. #endif
  5265. #if defined(USE_LUA)
  5266. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5267. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5268. filename) > 0) {
  5269. return 1;
  5270. }
  5271. #endif
  5272. #if defined(USE_DUKTAPE)
  5273. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5274. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5275. filename) > 0) {
  5276. return 1;
  5277. }
  5278. #endif
  5279. /* filename and conn could be unused, if all preocessor conditions
  5280. * are false (no script language supported). */
  5281. (void)filename;
  5282. (void)conn;
  5283. return 0;
  5284. }
  5285. /* For given directory path, substitute it to valid index file.
  5286. * Return 1 if index file has been found, 0 if not found.
  5287. * If the file is found, it's stats is returned in stp. */
  5288. static int
  5289. substitute_index_file(struct mg_connection *conn,
  5290. char *path,
  5291. size_t path_len,
  5292. struct mg_file_stat *filestat)
  5293. {
  5294. const char *list = conn->ctx->config[INDEX_FILES];
  5295. struct vec filename_vec;
  5296. size_t n = strlen(path);
  5297. int found = 0;
  5298. /* The 'path' given to us points to the directory. Remove all trailing
  5299. * directory separator characters from the end of the path, and
  5300. * then append single directory separator character. */
  5301. while ((n > 0) && (path[n - 1] == '/')) {
  5302. n--;
  5303. }
  5304. path[n] = '/';
  5305. /* Traverse index files list. For each entry, append it to the given
  5306. * path and see if the file exists. If it exists, break the loop */
  5307. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5308. /* Ignore too long entries that may overflow path buffer */
  5309. if (filename_vec.len > (path_len - (n + 2))) {
  5310. continue;
  5311. }
  5312. /* Prepare full path to the index file */
  5313. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5314. /* Does it exist? */
  5315. if (mg_stat(conn, path, filestat)) {
  5316. /* Yes it does, break the loop */
  5317. found = 1;
  5318. break;
  5319. }
  5320. }
  5321. /* If no index file exists, restore directory path */
  5322. if (!found) {
  5323. path[n] = '\0';
  5324. }
  5325. return found;
  5326. }
  5327. #endif
  5328. static void
  5329. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5330. char *filename, /* out: filename */
  5331. size_t filename_buf_len, /* in: size of filename buffer */
  5332. struct mg_file_stat *filestat, /* out: file status structure */
  5333. int *is_found, /* out: file found (directly) */
  5334. int *is_script_resource, /* out: handled by a script? */
  5335. int *is_websocket_request, /* out: websocket connetion? */
  5336. int *is_put_or_delete_request /* out: put/delete a file? */
  5337. )
  5338. {
  5339. #if !defined(NO_FILES)
  5340. const char *uri = conn->request_info.local_uri;
  5341. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5342. const char *rewrite;
  5343. struct vec a, b;
  5344. int match_len;
  5345. char gz_path[PATH_MAX];
  5346. char const *accept_encoding;
  5347. int truncated;
  5348. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5349. char *tmp_str;
  5350. size_t tmp_str_len, sep_pos;
  5351. #endif
  5352. #else
  5353. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5354. #endif
  5355. /* Step 1: Set all initially unknown outputs to zero */
  5356. memset(filestat, 0, sizeof(*filestat));
  5357. *filename = 0;
  5358. *is_found = 0;
  5359. *is_script_resource = 0;
  5360. /* Step 2: Check if the request attempts to modify the file system */
  5361. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5362. /* Step 3: Check if it is a websocket request, and modify the document
  5363. * root if required */
  5364. #if defined(USE_WEBSOCKET)
  5365. *is_websocket_request = is_websocket_protocol(conn);
  5366. #if !defined(NO_FILES)
  5367. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5368. root = conn->ctx->config[WEBSOCKET_ROOT];
  5369. }
  5370. #endif /* !NO_FILES */
  5371. #else /* USE_WEBSOCKET */
  5372. *is_websocket_request = 0;
  5373. #endif /* USE_WEBSOCKET */
  5374. #if !defined(NO_FILES)
  5375. /* Step 4: If there is no root directory, don't look for files. */
  5376. /* Note that root == NULL is a regular use case here. This occurs,
  5377. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5378. * config is not required. */
  5379. if (root == NULL) {
  5380. /* all file related outputs have already been set to 0, just return
  5381. */
  5382. return;
  5383. }
  5384. /* Step 5: Determine the local file path from the root path and the
  5385. * request uri. */
  5386. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5387. * part of the path one byte on the right. */
  5388. mg_snprintf(
  5389. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5390. if (truncated) {
  5391. goto interpret_cleanup;
  5392. }
  5393. /* Step 6: URI rewriting */
  5394. rewrite = conn->ctx->config[URL_REWRITE_PATTERN];
  5395. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5396. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5397. mg_snprintf(conn,
  5398. &truncated,
  5399. filename,
  5400. filename_buf_len - 1,
  5401. "%.*s%s",
  5402. (int)b.len,
  5403. b.ptr,
  5404. uri + match_len);
  5405. break;
  5406. }
  5407. }
  5408. if (truncated) {
  5409. goto interpret_cleanup;
  5410. }
  5411. /* Step 7: Check if the file exists at the server */
  5412. /* Local file path and name, corresponding to requested URI
  5413. * is now stored in "filename" variable. */
  5414. if (mg_stat(conn, filename, filestat)) {
  5415. /* 7.1: File exists. */
  5416. *is_found = 1;
  5417. /* 7.2: Check if it is a script type. */
  5418. if (extention_matches_script(conn, filename)) {
  5419. /* The request addresses a CGI resource, Lua script or
  5420. * server-side javascript.
  5421. * The URI corresponds to the script itself (like
  5422. * /path/script.cgi), and there is no additional resource
  5423. * path (like /path/script.cgi/something).
  5424. * Requests that modify (replace or delete) a resource, like
  5425. * PUT and DELETE requests, should replace/delete the script
  5426. * file.
  5427. * Requests that read or write from/to a resource, like GET and
  5428. * POST requests, should call the script and return the
  5429. * generated response. */
  5430. *is_script_resource = (!*is_put_or_delete_request);
  5431. }
  5432. /* 7.3: If the request target is a directory, there could be
  5433. * a substitute file (index.html, index.cgi, ...). */
  5434. if (filestat->is_directory) {
  5435. /* Use a local copy here, since substitute_index_file will
  5436. * change the content of the file status */
  5437. struct mg_file_stat tmp_filestat;
  5438. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5439. if (substitute_index_file(
  5440. conn, filename, filename_buf_len, &tmp_filestat)) {
  5441. /* Substitute file found. Copy stat to the output, then
  5442. * check if the file is a script file */
  5443. *filestat = tmp_filestat;
  5444. if (extention_matches_script(conn, filename)) {
  5445. /* Substitute file is a script file */
  5446. *is_script_resource = 1;
  5447. } else {
  5448. /* Substitute file is a regular file */
  5449. *is_script_resource = 0;
  5450. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5451. }
  5452. }
  5453. /* If there is no substitute file, the server could return
  5454. * a directory listing in a later step */
  5455. }
  5456. return;
  5457. }
  5458. /* Step 8: Check for zipped files: */
  5459. /* If we can't find the actual file, look for the file
  5460. * with the same name but a .gz extension. If we find it,
  5461. * use that and set the gzipped flag in the file struct
  5462. * to indicate that the response need to have the content-
  5463. * encoding: gzip header.
  5464. * We can only do this if the browser declares support. */
  5465. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5466. if (strstr(accept_encoding, "gzip") != NULL) {
  5467. mg_snprintf(
  5468. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5469. if (truncated) {
  5470. goto interpret_cleanup;
  5471. }
  5472. if (mg_stat(conn, gz_path, filestat)) {
  5473. if (filestat) {
  5474. filestat->is_gzipped = 1;
  5475. *is_found = 1;
  5476. }
  5477. /* Currently gz files can not be scripts. */
  5478. return;
  5479. }
  5480. }
  5481. }
  5482. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5483. /* Step 9: Script resources may handle sub-resources */
  5484. /* Support PATH_INFO for CGI scripts. */
  5485. tmp_str_len = strlen(filename);
  5486. tmp_str = mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->ctx);
  5487. if (!tmp_str) {
  5488. /* Out of memory */
  5489. goto interpret_cleanup;
  5490. }
  5491. memcpy(tmp_str, filename, tmp_str_len + 1);
  5492. sep_pos = tmp_str_len;
  5493. while (sep_pos > 0) {
  5494. sep_pos--;
  5495. if (tmp_str[sep_pos] == '/') {
  5496. int is_script = 0, does_exist = 0;
  5497. tmp_str[sep_pos] = 0;
  5498. if (tmp_str[0]) {
  5499. is_script = extention_matches_script(conn, tmp_str);
  5500. does_exist = mg_stat(conn, tmp_str, filestat);
  5501. }
  5502. if (does_exist && is_script) {
  5503. filename[sep_pos] = 0;
  5504. memmove(filename + sep_pos + 2,
  5505. filename + sep_pos + 1,
  5506. strlen(filename + sep_pos + 1) + 1);
  5507. conn->path_info = filename + sep_pos + 1;
  5508. filename[sep_pos + 1] = '/';
  5509. *is_script_resource = 1;
  5510. *is_found = 1;
  5511. break;
  5512. }
  5513. if (substitute_index_file(
  5514. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5515. /* some intermediate directory has an index file */
  5516. if (extention_matches_script(conn, tmp_str)) {
  5517. /* this index file is a script */
  5518. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5519. mg_snprintf(conn,
  5520. &truncated,
  5521. filename,
  5522. filename_buf_len,
  5523. "%s//%s",
  5524. tmp_str,
  5525. tmp_str2);
  5526. mg_free(tmp_str2);
  5527. if (truncated) {
  5528. mg_free(tmp_str);
  5529. goto interpret_cleanup;
  5530. }
  5531. sep_pos = strlen(tmp_str);
  5532. filename[sep_pos] = 0;
  5533. conn->path_info = filename + sep_pos + 1;
  5534. *is_script_resource = 1;
  5535. *is_found = 1;
  5536. break;
  5537. } else {
  5538. /* non-script files will not have sub-resources */
  5539. filename[sep_pos] = 0;
  5540. conn->path_info = 0;
  5541. *is_script_resource = 0;
  5542. *is_found = 0;
  5543. break;
  5544. }
  5545. }
  5546. tmp_str[sep_pos] = '/';
  5547. }
  5548. }
  5549. mg_free(tmp_str);
  5550. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5551. #endif /* !defined(NO_FILES) */
  5552. return;
  5553. #if !defined(NO_FILES)
  5554. /* Reset all outputs */
  5555. interpret_cleanup:
  5556. memset(filestat, 0, sizeof(*filestat));
  5557. *filename = 0;
  5558. *is_found = 0;
  5559. *is_script_resource = 0;
  5560. *is_websocket_request = 0;
  5561. *is_put_or_delete_request = 0;
  5562. #endif /* !defined(NO_FILES) */
  5563. }
  5564. /* Check whether full request is buffered. Return:
  5565. * -1 if request or response is malformed
  5566. * 0 if request or response is not yet fully buffered
  5567. * >0 actual request length, including last \r\n\r\n */
  5568. static int
  5569. get_http_header_len(const char *buf, int buflen)
  5570. {
  5571. int i;
  5572. for (i = 0; i < buflen; i++) {
  5573. /* Do an unsigned comparison in some conditions below */
  5574. const unsigned char c = ((const unsigned char *)buf)[i];
  5575. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  5576. && !isprint(c)) {
  5577. /* abort scan as soon as one malformed character is found */
  5578. return -1;
  5579. }
  5580. if (i < buflen - 1) {
  5581. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  5582. /* Two newline, no carriage return - not standard compliant, but
  5583. * it
  5584. * should be accepted */
  5585. return i + 2;
  5586. }
  5587. }
  5588. if (i < buflen - 3) {
  5589. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  5590. && (buf[i + 3] == '\n')) {
  5591. /* Two \r\n - standard compliant */
  5592. return i + 4;
  5593. }
  5594. }
  5595. }
  5596. return 0;
  5597. }
  5598. #if !defined(NO_CACHING)
  5599. /* Convert month to the month number. Return -1 on error, or month number */
  5600. static int
  5601. get_month_index(const char *s)
  5602. {
  5603. size_t i;
  5604. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5605. if (!strcmp(s, month_names[i])) {
  5606. return (int)i;
  5607. }
  5608. }
  5609. return -1;
  5610. }
  5611. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5612. static time_t
  5613. parse_date_string(const char *datetime)
  5614. {
  5615. char month_str[32] = {0};
  5616. int second, minute, hour, day, month, year;
  5617. time_t result = (time_t)0;
  5618. struct tm tm;
  5619. if ((sscanf(datetime,
  5620. "%d/%3s/%d %d:%d:%d",
  5621. &day,
  5622. month_str,
  5623. &year,
  5624. &hour,
  5625. &minute,
  5626. &second) == 6) || (sscanf(datetime,
  5627. "%d %3s %d %d:%d:%d",
  5628. &day,
  5629. month_str,
  5630. &year,
  5631. &hour,
  5632. &minute,
  5633. &second) == 6)
  5634. || (sscanf(datetime,
  5635. "%*3s, %d %3s %d %d:%d:%d",
  5636. &day,
  5637. month_str,
  5638. &year,
  5639. &hour,
  5640. &minute,
  5641. &second) == 6) || (sscanf(datetime,
  5642. "%d-%3s-%d %d:%d:%d",
  5643. &day,
  5644. month_str,
  5645. &year,
  5646. &hour,
  5647. &minute,
  5648. &second) == 6)) {
  5649. month = get_month_index(month_str);
  5650. if ((month >= 0) && (year >= 1970)) {
  5651. memset(&tm, 0, sizeof(tm));
  5652. tm.tm_year = year - 1900;
  5653. tm.tm_mon = month;
  5654. tm.tm_mday = day;
  5655. tm.tm_hour = hour;
  5656. tm.tm_min = minute;
  5657. tm.tm_sec = second;
  5658. result = timegm(&tm);
  5659. }
  5660. }
  5661. return result;
  5662. }
  5663. #endif /* !NO_CACHING */
  5664. /* Protect against directory disclosure attack by removing '..',
  5665. * excessive '/' and '\' characters */
  5666. static void
  5667. remove_double_dots_and_double_slashes(char *s)
  5668. {
  5669. char *p = s;
  5670. while ((s[0] == '.') && (s[1] == '.')) {
  5671. s++;
  5672. }
  5673. while (*s != '\0') {
  5674. *p++ = *s++;
  5675. if ((s[-1] == '/') || (s[-1] == '\\')) {
  5676. /* Skip all following slashes, backslashes and double-dots */
  5677. while (s[0] != '\0') {
  5678. if ((s[0] == '/') || (s[0] == '\\')) {
  5679. s++;
  5680. } else if ((s[0] == '.') && (s[1] == '.')) {
  5681. s += 2;
  5682. } else {
  5683. break;
  5684. }
  5685. }
  5686. }
  5687. }
  5688. *p = '\0';
  5689. }
  5690. static const struct {
  5691. const char *extension;
  5692. size_t ext_len;
  5693. const char *mime_type;
  5694. } builtin_mime_types[] = {
  5695. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5696. * application types */
  5697. {".doc", 4, "application/msword"},
  5698. {".eps", 4, "application/postscript"},
  5699. {".exe", 4, "application/octet-stream"},
  5700. {".js", 3, "application/javascript"},
  5701. {".json", 5, "application/json"},
  5702. {".pdf", 4, "application/pdf"},
  5703. {".ps", 3, "application/postscript"},
  5704. {".rtf", 4, "application/rtf"},
  5705. {".xhtml", 6, "application/xhtml+xml"},
  5706. {".xsl", 4, "application/xml"},
  5707. {".xslt", 5, "application/xml"},
  5708. /* fonts */
  5709. {".ttf", 4, "application/font-sfnt"},
  5710. {".cff", 4, "application/font-sfnt"},
  5711. {".otf", 4, "application/font-sfnt"},
  5712. {".aat", 4, "application/font-sfnt"},
  5713. {".sil", 4, "application/font-sfnt"},
  5714. {".pfr", 4, "application/font-tdpfr"},
  5715. {".woff", 5, "application/font-woff"},
  5716. /* audio */
  5717. {".mp3", 4, "audio/mpeg"},
  5718. {".oga", 4, "audio/ogg"},
  5719. {".ogg", 4, "audio/ogg"},
  5720. /* image */
  5721. {".gif", 4, "image/gif"},
  5722. {".ief", 4, "image/ief"},
  5723. {".jpeg", 5, "image/jpeg"},
  5724. {".jpg", 4, "image/jpeg"},
  5725. {".jpm", 4, "image/jpm"},
  5726. {".jpx", 4, "image/jpx"},
  5727. {".png", 4, "image/png"},
  5728. {".svg", 4, "image/svg+xml"},
  5729. {".tif", 4, "image/tiff"},
  5730. {".tiff", 5, "image/tiff"},
  5731. /* model */
  5732. {".wrl", 4, "model/vrml"},
  5733. /* text */
  5734. {".css", 4, "text/css"},
  5735. {".csv", 4, "text/csv"},
  5736. {".htm", 4, "text/html"},
  5737. {".html", 5, "text/html"},
  5738. {".sgm", 4, "text/sgml"},
  5739. {".shtm", 5, "text/html"},
  5740. {".shtml", 6, "text/html"},
  5741. {".txt", 4, "text/plain"},
  5742. {".xml", 4, "text/xml"},
  5743. /* video */
  5744. {".mov", 4, "video/quicktime"},
  5745. {".mp4", 4, "video/mp4"},
  5746. {".mpeg", 5, "video/mpeg"},
  5747. {".mpg", 4, "video/mpeg"},
  5748. {".ogv", 4, "video/ogg"},
  5749. {".qt", 3, "video/quicktime"},
  5750. /* not registered types
  5751. * (http://reference.sitepoint.com/html/mime-types-full,
  5752. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5753. {".arj", 4, "application/x-arj-compressed"},
  5754. {".gz", 3, "application/x-gunzip"},
  5755. {".rar", 4, "application/x-arj-compressed"},
  5756. {".swf", 4, "application/x-shockwave-flash"},
  5757. {".tar", 4, "application/x-tar"},
  5758. {".tgz", 4, "application/x-tar-gz"},
  5759. {".torrent", 8, "application/x-bittorrent"},
  5760. {".ppt", 4, "application/x-mspowerpoint"},
  5761. {".xls", 4, "application/x-msexcel"},
  5762. {".zip", 4, "application/x-zip-compressed"},
  5763. {".aac",
  5764. 4,
  5765. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5766. {".aif", 4, "audio/x-aif"},
  5767. {".m3u", 4, "audio/x-mpegurl"},
  5768. {".mid", 4, "audio/x-midi"},
  5769. {".ra", 3, "audio/x-pn-realaudio"},
  5770. {".ram", 4, "audio/x-pn-realaudio"},
  5771. {".wav", 4, "audio/x-wav"},
  5772. {".bmp", 4, "image/bmp"},
  5773. {".ico", 4, "image/x-icon"},
  5774. {".pct", 4, "image/x-pct"},
  5775. {".pict", 5, "image/pict"},
  5776. {".rgb", 4, "image/x-rgb"},
  5777. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5778. {".asf", 4, "video/x-ms-asf"},
  5779. {".avi", 4, "video/x-msvideo"},
  5780. {".m4v", 4, "video/x-m4v"},
  5781. {NULL, 0, NULL}};
  5782. const char *
  5783. mg_get_builtin_mime_type(const char *path)
  5784. {
  5785. const char *ext;
  5786. size_t i, path_len;
  5787. path_len = strlen(path);
  5788. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5789. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5790. if ((path_len > builtin_mime_types[i].ext_len)
  5791. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  5792. return builtin_mime_types[i].mime_type;
  5793. }
  5794. }
  5795. return "text/plain";
  5796. }
  5797. /* Look at the "path" extension and figure what mime type it has.
  5798. * Store mime type in the vector. */
  5799. static void
  5800. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5801. {
  5802. struct vec ext_vec, mime_vec;
  5803. const char *list, *ext;
  5804. size_t path_len;
  5805. path_len = strlen(path);
  5806. if ((ctx == NULL) || (vec == NULL)) {
  5807. if (vec != NULL) {
  5808. memset(vec, '\0', sizeof(struct vec));
  5809. }
  5810. return;
  5811. }
  5812. /* Scan user-defined mime types first, in case user wants to
  5813. * override default mime types. */
  5814. list = ctx->config[EXTRA_MIME_TYPES];
  5815. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5816. /* ext now points to the path suffix */
  5817. ext = path + path_len - ext_vec.len;
  5818. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5819. *vec = mime_vec;
  5820. return;
  5821. }
  5822. }
  5823. vec->ptr = mg_get_builtin_mime_type(path);
  5824. vec->len = strlen(vec->ptr);
  5825. }
  5826. /* Stringify binary data. Output buffer must be twice as big as input,
  5827. * because each byte takes 2 bytes in string representation */
  5828. static void
  5829. bin2str(char *to, const unsigned char *p, size_t len)
  5830. {
  5831. static const char *hex = "0123456789abcdef";
  5832. for (; len--; p++) {
  5833. *to++ = hex[p[0] >> 4];
  5834. *to++ = hex[p[0] & 0x0f];
  5835. }
  5836. *to = '\0';
  5837. }
  5838. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5839. char *
  5840. mg_md5(char buf[33], ...)
  5841. {
  5842. md5_byte_t hash[16];
  5843. const char *p;
  5844. va_list ap;
  5845. md5_state_t ctx;
  5846. md5_init(&ctx);
  5847. va_start(ap, buf);
  5848. while ((p = va_arg(ap, const char *)) != NULL) {
  5849. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5850. }
  5851. va_end(ap);
  5852. md5_finish(&ctx, hash);
  5853. bin2str(buf, hash, sizeof(hash));
  5854. return buf;
  5855. }
  5856. /* Check the user's password, return 1 if OK */
  5857. static int
  5858. check_password(const char *method,
  5859. const char *ha1,
  5860. const char *uri,
  5861. const char *nonce,
  5862. const char *nc,
  5863. const char *cnonce,
  5864. const char *qop,
  5865. const char *response)
  5866. {
  5867. char ha2[32 + 1], expected_response[32 + 1];
  5868. /* Some of the parameters may be NULL */
  5869. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  5870. || (qop == NULL) || (response == NULL)) {
  5871. return 0;
  5872. }
  5873. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5874. if (strlen(response) != 32) {
  5875. return 0;
  5876. }
  5877. mg_md5(ha2, method, ":", uri, NULL);
  5878. mg_md5(expected_response,
  5879. ha1,
  5880. ":",
  5881. nonce,
  5882. ":",
  5883. nc,
  5884. ":",
  5885. cnonce,
  5886. ":",
  5887. qop,
  5888. ":",
  5889. ha2,
  5890. NULL);
  5891. return mg_strcasecmp(response, expected_response) == 0;
  5892. }
  5893. /* Use the global passwords file, if specified by auth_gpass option,
  5894. * or search for .htpasswd in the requested directory. */
  5895. static void
  5896. open_auth_file(struct mg_connection *conn,
  5897. const char *path,
  5898. struct mg_file *filep)
  5899. {
  5900. if ((conn != NULL) && (conn->ctx != NULL)) {
  5901. char name[PATH_MAX];
  5902. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5903. int truncated;
  5904. if (gpass != NULL) {
  5905. /* Use global passwords file */
  5906. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5907. #ifdef DEBUG
  5908. /* Use mg_cry here, since gpass has been configured. */
  5909. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5910. #endif
  5911. }
  5912. /* Important: using local struct mg_file to test path for
  5913. * is_directory flag. If filep is used, mg_stat() makes it
  5914. * appear as if auth file was opened.
  5915. * TODO(mid): Check if this is still required after rewriting
  5916. * mg_stat */
  5917. } else if (mg_stat(conn, path, &filep->stat)
  5918. && filep->stat.is_directory) {
  5919. mg_snprintf(conn,
  5920. &truncated,
  5921. name,
  5922. sizeof(name),
  5923. "%s/%s",
  5924. path,
  5925. PASSWORDS_FILE_NAME);
  5926. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5927. #ifdef DEBUG
  5928. /* Don't use mg_cry here, but only a trace, since this is
  5929. * a typical case. It will occur for every directory
  5930. * without a password file. */
  5931. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5932. #endif
  5933. }
  5934. } else {
  5935. /* Try to find .htpasswd in requested directory. */
  5936. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5937. if (e[0] == '/') {
  5938. break;
  5939. }
  5940. }
  5941. mg_snprintf(conn,
  5942. &truncated,
  5943. name,
  5944. sizeof(name),
  5945. "%.*s/%s",
  5946. (int)(e - p),
  5947. p,
  5948. PASSWORDS_FILE_NAME);
  5949. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5950. #ifdef DEBUG
  5951. /* Don't use mg_cry here, but only a trace, since this is
  5952. * a typical case. It will occur for every directory
  5953. * without a password file. */
  5954. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5955. #endif
  5956. }
  5957. }
  5958. }
  5959. }
  5960. /* Parsed Authorization header */
  5961. struct ah {
  5962. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5963. };
  5964. /* Return 1 on success. Always initializes the ah structure. */
  5965. static int
  5966. parse_auth_header(struct mg_connection *conn,
  5967. char *buf,
  5968. size_t buf_size,
  5969. struct ah *ah)
  5970. {
  5971. char *name, *value, *s;
  5972. const char *auth_header;
  5973. uint64_t nonce;
  5974. if (!ah || !conn) {
  5975. return 0;
  5976. }
  5977. (void)memset(ah, 0, sizeof(*ah));
  5978. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  5979. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5980. return 0;
  5981. }
  5982. /* Make modifiable copy of the auth header */
  5983. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5984. s = buf;
  5985. /* Parse authorization header */
  5986. for (;;) {
  5987. /* Gobble initial spaces */
  5988. while (isspace(*(unsigned char *)s)) {
  5989. s++;
  5990. }
  5991. name = skip_quoted(&s, "=", " ", 0);
  5992. /* Value is either quote-delimited, or ends at first comma or space. */
  5993. if (s[0] == '\"') {
  5994. s++;
  5995. value = skip_quoted(&s, "\"", " ", '\\');
  5996. if (s[0] == ',') {
  5997. s++;
  5998. }
  5999. } else {
  6000. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6001. * spaces */
  6002. }
  6003. if (*name == '\0') {
  6004. break;
  6005. }
  6006. if (!strcmp(name, "username")) {
  6007. ah->user = value;
  6008. } else if (!strcmp(name, "cnonce")) {
  6009. ah->cnonce = value;
  6010. } else if (!strcmp(name, "response")) {
  6011. ah->response = value;
  6012. } else if (!strcmp(name, "uri")) {
  6013. ah->uri = value;
  6014. } else if (!strcmp(name, "qop")) {
  6015. ah->qop = value;
  6016. } else if (!strcmp(name, "nc")) {
  6017. ah->nc = value;
  6018. } else if (!strcmp(name, "nonce")) {
  6019. ah->nonce = value;
  6020. }
  6021. }
  6022. #ifndef NO_NONCE_CHECK
  6023. /* Read the nonce from the response. */
  6024. if (ah->nonce == NULL) {
  6025. return 0;
  6026. }
  6027. s = NULL;
  6028. nonce = strtoull(ah->nonce, &s, 10);
  6029. if ((s == NULL) || (*s != 0)) {
  6030. return 0;
  6031. }
  6032. /* Convert the nonce from the client to a number. */
  6033. nonce ^= conn->ctx->auth_nonce_mask;
  6034. /* The converted number corresponds to the time the nounce has been
  6035. * created. This should not be earlier than the server start. */
  6036. /* Server side nonce check is valuable in all situations but one:
  6037. * if the server restarts frequently, but the client should not see
  6038. * that, so the server should accept nonces from previous starts. */
  6039. /* However, the reasonable default is to not accept a nonce from a
  6040. * previous start, so if anyone changed the access rights between
  6041. * two restarts, a new login is required. */
  6042. if (nonce < (uint64_t)conn->ctx->start_time) {
  6043. /* nonce is from a previous start of the server and no longer valid
  6044. * (replay attack?) */
  6045. return 0;
  6046. }
  6047. /* Check if the nonce is too high, so it has not (yet) been used by the
  6048. * server. */
  6049. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  6050. return 0;
  6051. }
  6052. #else
  6053. (void)nonce;
  6054. #endif
  6055. /* CGI needs it as REMOTE_USER */
  6056. if (ah->user != NULL) {
  6057. conn->request_info.remote_user = mg_strdup(ah->user);
  6058. } else {
  6059. return 0;
  6060. }
  6061. return 1;
  6062. }
  6063. static const char *
  6064. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6065. {
  6066. const char *eof;
  6067. size_t len;
  6068. const char *memend;
  6069. if (!filep) {
  6070. return NULL;
  6071. }
  6072. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6073. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6074. /* Search for \n from p till the end of stream */
  6075. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6076. if (eof != NULL) {
  6077. eof += 1; /* Include \n */
  6078. } else {
  6079. eof = memend; /* Copy remaining data */
  6080. }
  6081. len =
  6082. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6083. memcpy(buf, *p, len);
  6084. buf[len] = '\0';
  6085. *p += len;
  6086. return len ? eof : NULL;
  6087. } else if (filep->access.fp != NULL) {
  6088. return fgets(buf, (int)size, filep->access.fp);
  6089. } else {
  6090. return NULL;
  6091. }
  6092. }
  6093. /* Define the initial recursion depth for procesesing htpasswd files that
  6094. * include other htpasswd
  6095. * (or even the same) files. It is not difficult to provide a file or files
  6096. * s.t. they force civetweb
  6097. * to infinitely recurse and then crash.
  6098. */
  6099. #define INITIAL_DEPTH 9
  6100. #if INITIAL_DEPTH <= 0
  6101. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6102. #endif
  6103. struct read_auth_file_struct {
  6104. struct mg_connection *conn;
  6105. struct ah ah;
  6106. char *domain;
  6107. char buf[256 + 256 + 40];
  6108. char *f_user;
  6109. char *f_domain;
  6110. char *f_ha1;
  6111. };
  6112. static int
  6113. read_auth_file(struct mg_file *filep,
  6114. struct read_auth_file_struct *workdata,
  6115. int depth)
  6116. {
  6117. char *p;
  6118. int is_authorized = 0;
  6119. struct mg_file fp;
  6120. size_t l;
  6121. if (!filep || !workdata || (0 == depth)) {
  6122. return 0;
  6123. }
  6124. /* Loop over passwords file */
  6125. p = (char *)filep->access.membuf;
  6126. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6127. l = strlen(workdata->buf);
  6128. while (l > 0) {
  6129. if (isspace(workdata->buf[l - 1])
  6130. || iscntrl(workdata->buf[l - 1])) {
  6131. l--;
  6132. workdata->buf[l] = 0;
  6133. } else
  6134. break;
  6135. }
  6136. if (l < 1) {
  6137. continue;
  6138. }
  6139. workdata->f_user = workdata->buf;
  6140. if (workdata->f_user[0] == ':') {
  6141. /* user names may not contain a ':' and may not be empty,
  6142. * so lines starting with ':' may be used for a special purpose */
  6143. if (workdata->f_user[1] == '#') {
  6144. /* :# is a comment */
  6145. continue;
  6146. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6147. if (mg_fopen(workdata->conn,
  6148. workdata->f_user + 9,
  6149. MG_FOPEN_MODE_READ,
  6150. &fp)) {
  6151. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6152. (void)mg_fclose(
  6153. &fp.access); /* ignore error on read only file */
  6154. /* No need to continue processing files once we have a
  6155. * match, since nothing will reset it back
  6156. * to 0.
  6157. */
  6158. if (is_authorized) {
  6159. return is_authorized;
  6160. }
  6161. } else {
  6162. mg_cry(workdata->conn,
  6163. "%s: cannot open authorization file: %s",
  6164. __func__,
  6165. workdata->buf);
  6166. }
  6167. continue;
  6168. }
  6169. /* everything is invalid for the moment (might change in the
  6170. * future) */
  6171. mg_cry(workdata->conn,
  6172. "%s: syntax error in authorization file: %s",
  6173. __func__,
  6174. workdata->buf);
  6175. continue;
  6176. }
  6177. workdata->f_domain = strchr(workdata->f_user, ':');
  6178. if (workdata->f_domain == NULL) {
  6179. mg_cry(workdata->conn,
  6180. "%s: syntax error in authorization file: %s",
  6181. __func__,
  6182. workdata->buf);
  6183. continue;
  6184. }
  6185. *(workdata->f_domain) = 0;
  6186. (workdata->f_domain)++;
  6187. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6188. if (workdata->f_ha1 == NULL) {
  6189. mg_cry(workdata->conn,
  6190. "%s: syntax error in authorization file: %s",
  6191. __func__,
  6192. workdata->buf);
  6193. continue;
  6194. }
  6195. *(workdata->f_ha1) = 0;
  6196. (workdata->f_ha1)++;
  6197. if (!strcmp(workdata->ah.user, workdata->f_user)
  6198. && !strcmp(workdata->domain, workdata->f_domain)) {
  6199. return check_password(workdata->conn->request_info.request_method,
  6200. workdata->f_ha1,
  6201. workdata->ah.uri,
  6202. workdata->ah.nonce,
  6203. workdata->ah.nc,
  6204. workdata->ah.cnonce,
  6205. workdata->ah.qop,
  6206. workdata->ah.response);
  6207. }
  6208. }
  6209. return is_authorized;
  6210. }
  6211. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6212. static int
  6213. authorize(struct mg_connection *conn, struct mg_file *filep)
  6214. {
  6215. struct read_auth_file_struct workdata;
  6216. char buf[MG_BUF_LEN];
  6217. if (!conn || !conn->ctx) {
  6218. return 0;
  6219. }
  6220. memset(&workdata, 0, sizeof(workdata));
  6221. workdata.conn = conn;
  6222. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6223. return 0;
  6224. }
  6225. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6226. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6227. }
  6228. /* Return 1 if request is authorised, 0 otherwise. */
  6229. static int
  6230. check_authorization(struct mg_connection *conn, const char *path)
  6231. {
  6232. char fname[PATH_MAX];
  6233. struct vec uri_vec, filename_vec;
  6234. const char *list;
  6235. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6236. int authorized = 1, truncated;
  6237. if (!conn || !conn->ctx) {
  6238. return 0;
  6239. }
  6240. list = conn->ctx->config[PROTECT_URI];
  6241. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6242. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6243. mg_snprintf(conn,
  6244. &truncated,
  6245. fname,
  6246. sizeof(fname),
  6247. "%.*s",
  6248. (int)filename_vec.len,
  6249. filename_vec.ptr);
  6250. if (truncated
  6251. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6252. mg_cry(conn,
  6253. "%s: cannot open %s: %s",
  6254. __func__,
  6255. fname,
  6256. strerror(errno));
  6257. }
  6258. break;
  6259. }
  6260. }
  6261. if (!is_file_opened(&file.access)) {
  6262. open_auth_file(conn, path, &file);
  6263. }
  6264. if (is_file_opened(&file.access)) {
  6265. authorized = authorize(conn, &file);
  6266. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6267. }
  6268. return authorized;
  6269. }
  6270. static void
  6271. send_authorization_request(struct mg_connection *conn)
  6272. {
  6273. char date[64];
  6274. time_t curtime = time(NULL);
  6275. if (conn && conn->ctx) {
  6276. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6277. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6278. nonce += conn->ctx->nonce_count;
  6279. ++conn->ctx->nonce_count;
  6280. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6281. nonce ^= conn->ctx->auth_nonce_mask;
  6282. conn->status_code = 401;
  6283. conn->must_close = 1;
  6284. gmt_time_string(date, sizeof(date), &curtime);
  6285. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6286. send_no_cache_header(conn);
  6287. send_additional_header(conn);
  6288. mg_printf(conn,
  6289. "Date: %s\r\n"
  6290. "Connection: %s\r\n"
  6291. "Content-Length: 0\r\n"
  6292. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6293. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6294. date,
  6295. suggest_connection_header(conn),
  6296. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6297. nonce);
  6298. }
  6299. }
  6300. #if !defined(NO_FILES)
  6301. static int
  6302. is_authorized_for_put(struct mg_connection *conn)
  6303. {
  6304. if (conn) {
  6305. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6306. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6307. int ret = 0;
  6308. if (passfile != NULL
  6309. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6310. ret = authorize(conn, &file);
  6311. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6312. }
  6313. return ret;
  6314. }
  6315. return 0;
  6316. }
  6317. #endif
  6318. int
  6319. mg_modify_passwords_file(const char *fname,
  6320. const char *domain,
  6321. const char *user,
  6322. const char *pass)
  6323. {
  6324. int found, i;
  6325. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6326. FILE *fp, *fp2;
  6327. found = 0;
  6328. fp = fp2 = NULL;
  6329. /* Regard empty password as no password - remove user record. */
  6330. if ((pass != NULL) && (pass[0] == '\0')) {
  6331. pass = NULL;
  6332. }
  6333. /* Other arguments must not be empty */
  6334. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6335. return 0;
  6336. }
  6337. /* Using the given file format, user name and domain must not contain ':'
  6338. */
  6339. if (strchr(user, ':') != NULL) {
  6340. return 0;
  6341. }
  6342. if (strchr(domain, ':') != NULL) {
  6343. return 0;
  6344. }
  6345. /* Do not allow control characters like newline in user name and domain.
  6346. * Do not allow excessively long names either. */
  6347. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6348. if (iscntrl(user[i])) {
  6349. return 0;
  6350. }
  6351. }
  6352. if (user[i]) {
  6353. return 0;
  6354. }
  6355. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6356. if (iscntrl(domain[i])) {
  6357. return 0;
  6358. }
  6359. }
  6360. if (domain[i]) {
  6361. return 0;
  6362. }
  6363. /* The maximum length of the path to the password file is limited */
  6364. if ((strlen(fname) + 4) >= PATH_MAX) {
  6365. return 0;
  6366. }
  6367. /* Create a temporary file name. Length has been checked before. */
  6368. strcpy(tmp, fname);
  6369. strcat(tmp, ".tmp");
  6370. /* Create the file if does not exist */
  6371. /* Use of fopen here is OK, since fname is only ASCII */
  6372. if ((fp = fopen(fname, "a+")) != NULL) {
  6373. (void)fclose(fp);
  6374. }
  6375. /* Open the given file and temporary file */
  6376. if ((fp = fopen(fname, "r")) == NULL) {
  6377. return 0;
  6378. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6379. fclose(fp);
  6380. return 0;
  6381. }
  6382. /* Copy the stuff to temporary file */
  6383. while (fgets(line, sizeof(line), fp) != NULL) {
  6384. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6385. continue;
  6386. }
  6387. u[255] = 0;
  6388. d[255] = 0;
  6389. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6390. found++;
  6391. if (pass != NULL) {
  6392. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6393. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6394. }
  6395. } else {
  6396. fprintf(fp2, "%s", line);
  6397. }
  6398. }
  6399. /* If new user, just add it */
  6400. if (!found && (pass != NULL)) {
  6401. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6402. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6403. }
  6404. /* Close files */
  6405. fclose(fp);
  6406. fclose(fp2);
  6407. /* Put the temp file in place of real file */
  6408. IGNORE_UNUSED_RESULT(remove(fname));
  6409. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6410. return 1;
  6411. }
  6412. static int
  6413. is_valid_port(unsigned long port)
  6414. {
  6415. return (port <= 0xffff);
  6416. }
  6417. static int
  6418. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6419. {
  6420. struct addrinfo hints, *res, *ressave;
  6421. int func_ret = 0;
  6422. int gai_ret;
  6423. memset(&hints, 0, sizeof(struct addrinfo));
  6424. hints.ai_family = af;
  6425. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6426. if (gai_ret != 0) {
  6427. /* gai_strerror could be used to convert gai_ret to a string */
  6428. /* POSIX return values: see
  6429. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6430. */
  6431. /* Windows return values: see
  6432. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6433. */
  6434. return 0;
  6435. }
  6436. ressave = res;
  6437. while (res) {
  6438. if (dstlen >= (size_t)res->ai_addrlen) {
  6439. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6440. func_ret = 1;
  6441. }
  6442. res = res->ai_next;
  6443. }
  6444. freeaddrinfo(ressave);
  6445. return func_ret;
  6446. }
  6447. static int
  6448. connect_socket(struct mg_context *ctx /* may be NULL */,
  6449. const char *host,
  6450. int port,
  6451. int use_ssl,
  6452. char *ebuf,
  6453. size_t ebuf_len,
  6454. SOCKET *sock /* output: socket, must not be NULL */,
  6455. union usa *sa /* output: socket address, must not be NULL */
  6456. )
  6457. {
  6458. int ip_ver = 0;
  6459. *sock = INVALID_SOCKET;
  6460. memset(sa, 0, sizeof(*sa));
  6461. if (ebuf_len > 0) {
  6462. *ebuf = 0;
  6463. }
  6464. if (host == NULL) {
  6465. mg_snprintf(NULL,
  6466. NULL, /* No truncation check for ebuf */
  6467. ebuf,
  6468. ebuf_len,
  6469. "%s",
  6470. "NULL host");
  6471. return 0;
  6472. }
  6473. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  6474. mg_snprintf(NULL,
  6475. NULL, /* No truncation check for ebuf */
  6476. ebuf,
  6477. ebuf_len,
  6478. "%s",
  6479. "invalid port");
  6480. return 0;
  6481. }
  6482. #if !defined(NO_SSL)
  6483. #if !defined(NO_SSL_DL)
  6484. #ifdef OPENSSL_API_1_1
  6485. if (use_ssl && (TLS_client_method == NULL)) {
  6486. mg_snprintf(NULL,
  6487. NULL, /* No truncation check for ebuf */
  6488. ebuf,
  6489. ebuf_len,
  6490. "%s",
  6491. "SSL is not initialized");
  6492. return 0;
  6493. }
  6494. #else
  6495. if (use_ssl && (SSLv23_client_method == NULL)) {
  6496. mg_snprintf(NULL,
  6497. NULL, /* No truncation check for ebuf */
  6498. ebuf,
  6499. ebuf_len,
  6500. "%s",
  6501. "SSL is not initialized");
  6502. return 0;
  6503. }
  6504. #endif /* OPENSSL_API_1_1 */
  6505. #else
  6506. (void)use_ssl;
  6507. #endif /* NO_SSL_DL */
  6508. #else
  6509. (void)use_ssl;
  6510. #endif /* !defined(NO_SSL) */
  6511. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6512. sa->sin.sin_family = AF_INET;
  6513. sa->sin.sin_port = htons((uint16_t)port);
  6514. ip_ver = 4;
  6515. #ifdef USE_IPV6
  6516. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6517. sa->sin6.sin6_family = AF_INET6;
  6518. sa->sin6.sin6_port = htons((uint16_t)port);
  6519. ip_ver = 6;
  6520. } else if (host[0] == '[') {
  6521. /* While getaddrinfo on Windows will work with [::1],
  6522. * getaddrinfo on Linux only works with ::1 (without []). */
  6523. size_t l = strlen(host + 1);
  6524. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6525. if (h) {
  6526. h[l - 1] = 0;
  6527. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6528. sa->sin6.sin6_family = AF_INET6;
  6529. sa->sin6.sin6_port = htons((uint16_t)port);
  6530. ip_ver = 6;
  6531. }
  6532. mg_free(h);
  6533. }
  6534. #endif
  6535. }
  6536. if (ip_ver == 0) {
  6537. mg_snprintf(NULL,
  6538. NULL, /* No truncation check for ebuf */
  6539. ebuf,
  6540. ebuf_len,
  6541. "%s",
  6542. "host not found");
  6543. return 0;
  6544. }
  6545. if (ip_ver == 4) {
  6546. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6547. }
  6548. #ifdef USE_IPV6
  6549. else if (ip_ver == 6) {
  6550. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6551. }
  6552. #endif
  6553. if (*sock == INVALID_SOCKET) {
  6554. mg_snprintf(NULL,
  6555. NULL, /* No truncation check for ebuf */
  6556. ebuf,
  6557. ebuf_len,
  6558. "socket(): %s",
  6559. strerror(ERRNO));
  6560. return 0;
  6561. }
  6562. set_close_on_exec(*sock, fc(ctx));
  6563. if ((ip_ver == 4)
  6564. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6565. == 0)) {
  6566. /* connected with IPv4 */
  6567. set_blocking_mode(*sock, 0);
  6568. return 1;
  6569. }
  6570. #ifdef USE_IPV6
  6571. if ((ip_ver == 6)
  6572. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6573. == 0)) {
  6574. /* connected with IPv6 */
  6575. set_blocking_mode(*sock, 0);
  6576. return 1;
  6577. }
  6578. #endif
  6579. /* Not connected */
  6580. mg_snprintf(NULL,
  6581. NULL, /* No truncation check for ebuf */
  6582. ebuf,
  6583. ebuf_len,
  6584. "connect(%s:%d): %s",
  6585. host,
  6586. port,
  6587. strerror(ERRNO));
  6588. closesocket(*sock);
  6589. *sock = INVALID_SOCKET;
  6590. return 0;
  6591. }
  6592. int
  6593. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6594. {
  6595. static const char *dont_escape = "._-$,;~()";
  6596. static const char *hex = "0123456789abcdef";
  6597. char *pos = dst;
  6598. const char *end = dst + dst_len - 1;
  6599. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  6600. if (isalnum(*(const unsigned char *)src)
  6601. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  6602. *pos = *src;
  6603. } else if (pos + 2 < end) {
  6604. pos[0] = '%';
  6605. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6606. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6607. pos += 2;
  6608. } else {
  6609. break;
  6610. }
  6611. }
  6612. *pos = '\0';
  6613. return (*src == '\0') ? (int)(pos - dst) : -1;
  6614. }
  6615. /* Return 0 on success, non-zero if an error occurs. */
  6616. static int
  6617. print_dir_entry(struct de *de)
  6618. {
  6619. size_t hrefsize;
  6620. char *href;
  6621. char size[64], mod[64];
  6622. struct tm *tm;
  6623. hrefsize = PATH_MAX * 3; /* worst case */
  6624. href = mg_malloc(hrefsize);
  6625. if (href == NULL) {
  6626. return -1;
  6627. }
  6628. if (de->file.is_directory) {
  6629. mg_snprintf(de->conn,
  6630. NULL, /* Buffer is big enough */
  6631. size,
  6632. sizeof(size),
  6633. "%s",
  6634. "[DIRECTORY]");
  6635. } else {
  6636. /* We use (signed) cast below because MSVC 6 compiler cannot
  6637. * convert unsigned __int64 to double. Sigh. */
  6638. if (de->file.size < 1024) {
  6639. mg_snprintf(de->conn,
  6640. NULL, /* Buffer is big enough */
  6641. size,
  6642. sizeof(size),
  6643. "%d",
  6644. (int)de->file.size);
  6645. } else if (de->file.size < 0x100000) {
  6646. mg_snprintf(de->conn,
  6647. NULL, /* Buffer is big enough */
  6648. size,
  6649. sizeof(size),
  6650. "%.1fk",
  6651. (double)de->file.size / 1024.0);
  6652. } else if (de->file.size < 0x40000000) {
  6653. mg_snprintf(de->conn,
  6654. NULL, /* Buffer is big enough */
  6655. size,
  6656. sizeof(size),
  6657. "%.1fM",
  6658. (double)de->file.size / 1048576);
  6659. } else {
  6660. mg_snprintf(de->conn,
  6661. NULL, /* Buffer is big enough */
  6662. size,
  6663. sizeof(size),
  6664. "%.1fG",
  6665. (double)de->file.size / 1073741824);
  6666. }
  6667. }
  6668. /* Note: mg_snprintf will not cause a buffer overflow above.
  6669. * So, string truncation checks are not required here. */
  6670. tm = localtime(&de->file.last_modified);
  6671. if (tm != NULL) {
  6672. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6673. } else {
  6674. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6675. mod[sizeof(mod) - 1] = '\0';
  6676. }
  6677. mg_url_encode(de->file_name, href, hrefsize);
  6678. mg_printf(de->conn,
  6679. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6680. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6681. de->conn->request_info.local_uri,
  6682. href,
  6683. de->file.is_directory ? "/" : "",
  6684. de->file_name,
  6685. de->file.is_directory ? "/" : "",
  6686. mod,
  6687. size);
  6688. mg_free(href);
  6689. return 0;
  6690. }
  6691. /* This function is called from send_directory() and used for
  6692. * sorting directory entries by size, or name, or modification time.
  6693. * On windows, __cdecl specification is needed in case if project is built
  6694. * with __stdcall convention. qsort always requires __cdels callback. */
  6695. static int WINCDECL
  6696. compare_dir_entries(const void *p1, const void *p2)
  6697. {
  6698. if (p1 && p2) {
  6699. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6700. const char *query_string = a->conn->request_info.query_string;
  6701. int cmp_result = 0;
  6702. if (query_string == NULL) {
  6703. query_string = "na";
  6704. }
  6705. if (a->file.is_directory && !b->file.is_directory) {
  6706. return -1; /* Always put directories on top */
  6707. } else if (!a->file.is_directory && b->file.is_directory) {
  6708. return 1; /* Always put directories on top */
  6709. } else if (*query_string == 'n') {
  6710. cmp_result = strcmp(a->file_name, b->file_name);
  6711. } else if (*query_string == 's') {
  6712. cmp_result = (a->file.size == b->file.size)
  6713. ? 0
  6714. : ((a->file.size > b->file.size) ? 1 : -1);
  6715. } else if (*query_string == 'd') {
  6716. cmp_result =
  6717. (a->file.last_modified == b->file.last_modified)
  6718. ? 0
  6719. : ((a->file.last_modified > b->file.last_modified) ? 1
  6720. : -1);
  6721. }
  6722. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6723. }
  6724. return 0;
  6725. }
  6726. static int
  6727. must_hide_file(struct mg_connection *conn, const char *path)
  6728. {
  6729. if (conn && conn->ctx) {
  6730. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6731. const char *pattern = conn->ctx->config[HIDE_FILES];
  6732. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  6733. || ((pattern != NULL)
  6734. && (match_prefix(pattern, strlen(pattern), path) > 0));
  6735. }
  6736. return 0;
  6737. }
  6738. static int
  6739. scan_directory(struct mg_connection *conn,
  6740. const char *dir,
  6741. void *data,
  6742. int (*cb)(struct de *, void *))
  6743. {
  6744. char path[PATH_MAX];
  6745. struct dirent *dp;
  6746. DIR *dirp;
  6747. struct de de;
  6748. int truncated;
  6749. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6750. return 0;
  6751. } else {
  6752. de.conn = conn;
  6753. while ((dp = mg_readdir(dirp)) != NULL) {
  6754. /* Do not show current dir and hidden files */
  6755. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6756. || must_hide_file(conn, dp->d_name)) {
  6757. continue;
  6758. }
  6759. mg_snprintf(
  6760. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6761. /* If we don't memset stat structure to zero, mtime will have
  6762. * garbage and strftime() will segfault later on in
  6763. * print_dir_entry(). memset is required only if mg_stat()
  6764. * fails. For more details, see
  6765. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6766. memset(&de.file, 0, sizeof(de.file));
  6767. if (truncated) {
  6768. /* If the path is not complete, skip processing. */
  6769. continue;
  6770. }
  6771. if (!mg_stat(conn, path, &de.file)) {
  6772. mg_cry(conn,
  6773. "%s: mg_stat(%s) failed: %s",
  6774. __func__,
  6775. path,
  6776. strerror(ERRNO));
  6777. }
  6778. de.file_name = dp->d_name;
  6779. cb(&de, data);
  6780. }
  6781. (void)mg_closedir(dirp);
  6782. }
  6783. return 1;
  6784. }
  6785. #if !defined(NO_FILES)
  6786. static int
  6787. remove_directory(struct mg_connection *conn, const char *dir)
  6788. {
  6789. char path[PATH_MAX];
  6790. struct dirent *dp;
  6791. DIR *dirp;
  6792. struct de de;
  6793. int truncated;
  6794. int ok = 1;
  6795. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6796. return 0;
  6797. } else {
  6798. de.conn = conn;
  6799. while ((dp = mg_readdir(dirp)) != NULL) {
  6800. /* Do not show current dir (but show hidden files as they will
  6801. * also be removed) */
  6802. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6803. continue;
  6804. }
  6805. mg_snprintf(
  6806. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6807. /* If we don't memset stat structure to zero, mtime will have
  6808. * garbage and strftime() will segfault later on in
  6809. * print_dir_entry(). memset is required only if mg_stat()
  6810. * fails. For more details, see
  6811. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6812. memset(&de.file, 0, sizeof(de.file));
  6813. if (truncated) {
  6814. /* Do not delete anything shorter */
  6815. ok = 0;
  6816. continue;
  6817. }
  6818. if (!mg_stat(conn, path, &de.file)) {
  6819. mg_cry(conn,
  6820. "%s: mg_stat(%s) failed: %s",
  6821. __func__,
  6822. path,
  6823. strerror(ERRNO));
  6824. ok = 0;
  6825. }
  6826. if (de.file.is_directory) {
  6827. if (remove_directory(conn, path) == 0) {
  6828. ok = 0;
  6829. }
  6830. } else {
  6831. /* This will fail file is the file is in memory */
  6832. if (mg_remove(conn, path) == 0) {
  6833. ok = 0;
  6834. }
  6835. }
  6836. }
  6837. (void)mg_closedir(dirp);
  6838. IGNORE_UNUSED_RESULT(rmdir(dir));
  6839. }
  6840. return ok;
  6841. }
  6842. #endif
  6843. struct dir_scan_data {
  6844. struct de *entries;
  6845. unsigned int num_entries;
  6846. unsigned int arr_size;
  6847. };
  6848. /* Behaves like realloc(), but frees original pointer on failure */
  6849. static void *
  6850. realloc2(void *ptr, size_t size)
  6851. {
  6852. void *new_ptr = mg_realloc(ptr, size);
  6853. if (new_ptr == NULL) {
  6854. mg_free(ptr);
  6855. }
  6856. return new_ptr;
  6857. }
  6858. static int
  6859. dir_scan_callback(struct de *de, void *data)
  6860. {
  6861. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6862. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  6863. dsd->arr_size *= 2;
  6864. dsd->entries =
  6865. (struct de *)realloc2(dsd->entries,
  6866. dsd->arr_size * sizeof(dsd->entries[0]));
  6867. }
  6868. if (dsd->entries == NULL) {
  6869. /* TODO(lsm, low): propagate an error to the caller */
  6870. dsd->num_entries = 0;
  6871. } else {
  6872. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6873. dsd->entries[dsd->num_entries].file = de->file;
  6874. dsd->entries[dsd->num_entries].conn = de->conn;
  6875. dsd->num_entries++;
  6876. }
  6877. return 0;
  6878. }
  6879. static void
  6880. handle_directory_request(struct mg_connection *conn, const char *dir)
  6881. {
  6882. unsigned int i;
  6883. int sort_direction;
  6884. struct dir_scan_data data = {NULL, 0, 128};
  6885. char date[64];
  6886. time_t curtime = time(NULL);
  6887. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6888. mg_send_http_error(conn,
  6889. 500,
  6890. "Error: Cannot open directory\nopendir(%s): %s",
  6891. dir,
  6892. strerror(ERRNO));
  6893. return;
  6894. }
  6895. gmt_time_string(date, sizeof(date), &curtime);
  6896. if (!conn) {
  6897. return;
  6898. }
  6899. sort_direction = ((conn->request_info.query_string != NULL)
  6900. && (conn->request_info.query_string[1] == 'd'))
  6901. ? 'a'
  6902. : 'd';
  6903. conn->must_close = 1;
  6904. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6905. send_static_cache_header(conn);
  6906. send_additional_header(conn);
  6907. mg_printf(conn,
  6908. "Date: %s\r\n"
  6909. "Connection: close\r\n"
  6910. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6911. date);
  6912. mg_printf(conn,
  6913. "<html><head><title>Index of %s</title>"
  6914. "<style>th {text-align: left;}</style></head>"
  6915. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6916. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6917. "<th><a href=\"?d%c\">Modified</a></th>"
  6918. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6919. "<tr><td colspan=\"3\"><hr></td></tr>",
  6920. conn->request_info.local_uri,
  6921. conn->request_info.local_uri,
  6922. sort_direction,
  6923. sort_direction,
  6924. sort_direction);
  6925. /* Print first entry - link to a parent directory */
  6926. mg_printf(conn,
  6927. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6928. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6929. conn->request_info.local_uri,
  6930. "..",
  6931. "Parent directory",
  6932. "-",
  6933. "-");
  6934. /* Sort and print directory entries */
  6935. if (data.entries != NULL) {
  6936. qsort(data.entries,
  6937. (size_t)data.num_entries,
  6938. sizeof(data.entries[0]),
  6939. compare_dir_entries);
  6940. for (i = 0; i < data.num_entries; i++) {
  6941. print_dir_entry(&data.entries[i]);
  6942. mg_free(data.entries[i].file_name);
  6943. }
  6944. mg_free(data.entries);
  6945. }
  6946. mg_printf(conn, "%s", "</table></body></html>");
  6947. conn->status_code = 200;
  6948. }
  6949. /* Send len bytes from the opened file to the client. */
  6950. static void
  6951. send_file_data(struct mg_connection *conn,
  6952. struct mg_file *filep,
  6953. int64_t offset,
  6954. int64_t len)
  6955. {
  6956. char buf[MG_BUF_LEN];
  6957. int to_read, num_read, num_written;
  6958. int64_t size;
  6959. if (!filep || !conn) {
  6960. return;
  6961. }
  6962. /* Sanity check the offset */
  6963. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6964. : (int64_t)(filep->stat.size);
  6965. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6966. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6967. /* file stored in memory */
  6968. if (len > size - offset) {
  6969. len = size - offset;
  6970. }
  6971. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6972. } else if (len > 0 && filep->access.fp != NULL) {
  6973. /* file stored on disk */
  6974. #if defined(__linux__)
  6975. /* sendfile is only available for Linux */
  6976. if ((conn->ssl == 0) && (conn->throttle == 0)
  6977. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6978. "yes"))) {
  6979. off_t sf_offs = (off_t)offset;
  6980. ssize_t sf_sent;
  6981. int sf_file = fileno(filep->access.fp);
  6982. int loop_cnt = 0;
  6983. do {
  6984. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6985. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6986. size_t sf_tosend =
  6987. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6988. sf_sent =
  6989. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6990. if (sf_sent > 0) {
  6991. len -= sf_sent;
  6992. offset += sf_sent;
  6993. } else if (loop_cnt == 0) {
  6994. /* This file can not be sent using sendfile.
  6995. * This might be the case for pseudo-files in the
  6996. * /sys/ and /proc/ file system.
  6997. * Use the regular user mode copy code instead. */
  6998. break;
  6999. } else if (sf_sent == 0) {
  7000. /* No error, but 0 bytes sent. May be EOF? */
  7001. return;
  7002. }
  7003. loop_cnt++;
  7004. } while ((len > 0) && (sf_sent >= 0));
  7005. if (sf_sent > 0) {
  7006. return; /* OK */
  7007. }
  7008. /* sf_sent<0 means error, thus fall back to the classic way */
  7009. /* This is always the case, if sf_file is not a "normal" file,
  7010. * e.g., for sending data from the output of a CGI process. */
  7011. offset = (int64_t)sf_offs;
  7012. }
  7013. #endif
  7014. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7015. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  7016. mg_send_http_error(
  7017. conn,
  7018. 500,
  7019. "%s",
  7020. "Error: Unable to access file at requested position.");
  7021. } else {
  7022. while (len > 0) {
  7023. /* Calculate how much to read from the file in the buffer */
  7024. to_read = sizeof(buf);
  7025. if ((int64_t)to_read > len) {
  7026. to_read = (int)len;
  7027. }
  7028. /* Read from file, exit the loop on error */
  7029. if ((num_read =
  7030. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7031. <= 0) {
  7032. break;
  7033. }
  7034. /* Send read bytes to the client, exit the loop on error */
  7035. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7036. != num_read) {
  7037. break;
  7038. }
  7039. /* Both read and were successful, adjust counters */
  7040. len -= num_written;
  7041. }
  7042. }
  7043. }
  7044. }
  7045. static int
  7046. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7047. {
  7048. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7049. }
  7050. static void
  7051. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7052. {
  7053. if ((filestat != NULL) && (buf != NULL)) {
  7054. mg_snprintf(NULL,
  7055. NULL, /* All calls to construct_etag use 64 byte buffer */
  7056. buf,
  7057. buf_len,
  7058. "\"%lx.%" INT64_FMT "\"",
  7059. (unsigned long)filestat->last_modified,
  7060. filestat->size);
  7061. }
  7062. }
  7063. static void
  7064. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7065. {
  7066. if (filep != NULL && filep->fp != NULL) {
  7067. #ifdef _WIN32
  7068. (void)conn; /* Unused. */
  7069. #else
  7070. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7071. mg_cry(conn,
  7072. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7073. __func__,
  7074. strerror(ERRNO));
  7075. }
  7076. #endif
  7077. }
  7078. }
  7079. static void
  7080. handle_static_file_request(struct mg_connection *conn,
  7081. const char *path,
  7082. struct mg_file *filep,
  7083. const char *mime_type,
  7084. const char *additional_headers)
  7085. {
  7086. char date[64], lm[64], etag[64];
  7087. char range[128]; /* large enough, so there will be no overflow */
  7088. const char *msg = "OK", *hdr;
  7089. time_t curtime = time(NULL);
  7090. int64_t cl, r1, r2;
  7091. struct vec mime_vec;
  7092. int n, truncated;
  7093. char gz_path[PATH_MAX];
  7094. const char *encoding = "";
  7095. const char *cors1, *cors2, *cors3;
  7096. if ((conn == NULL) || (conn->ctx == NULL) || (filep == NULL)) {
  7097. return;
  7098. }
  7099. if (mime_type == NULL) {
  7100. get_mime_type(conn->ctx, path, &mime_vec);
  7101. } else {
  7102. mime_vec.ptr = mime_type;
  7103. mime_vec.len = strlen(mime_type);
  7104. }
  7105. if (filep->stat.size > INT64_MAX) {
  7106. mg_send_http_error(conn,
  7107. 500,
  7108. "Error: File size is too large to send\n%" INT64_FMT,
  7109. filep->stat.size);
  7110. return;
  7111. }
  7112. cl = (int64_t)filep->stat.size;
  7113. conn->status_code = 200;
  7114. range[0] = '\0';
  7115. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7116. * it's important to rewrite the filename after resolving
  7117. * the mime type from it, to preserve the actual file's type */
  7118. if (filep->stat.is_gzipped) {
  7119. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7120. if (truncated) {
  7121. mg_send_http_error(conn,
  7122. 500,
  7123. "Error: Path of zipped file too long (%s)",
  7124. path);
  7125. return;
  7126. }
  7127. path = gz_path;
  7128. encoding = "Content-Encoding: gzip\r\n";
  7129. }
  7130. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7131. mg_send_http_error(conn,
  7132. 500,
  7133. "Error: Cannot open file\nfopen(%s): %s",
  7134. path,
  7135. strerror(ERRNO));
  7136. return;
  7137. }
  7138. fclose_on_exec(&filep->access, conn);
  7139. /* If Range: header specified, act accordingly */
  7140. r1 = r2 = 0;
  7141. hdr = mg_get_header(conn, "Range");
  7142. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7143. && (r1 >= 0) && (r2 >= 0)) {
  7144. /* actually, range requests don't play well with a pre-gzipped
  7145. * file (since the range is specified in the uncompressed space) */
  7146. if (filep->stat.is_gzipped) {
  7147. mg_send_http_error(
  7148. conn,
  7149. 416, /* 416 = Range Not Satisfiable */
  7150. "%s",
  7151. "Error: Range requests in gzipped files are not supported");
  7152. (void)mg_fclose(
  7153. &filep->access); /* ignore error on read only file */
  7154. return;
  7155. }
  7156. conn->status_code = 206;
  7157. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7158. mg_snprintf(conn,
  7159. NULL, /* range buffer is big enough */
  7160. range,
  7161. sizeof(range),
  7162. "Content-Range: bytes "
  7163. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7164. r1,
  7165. r1 + cl - 1,
  7166. filep->stat.size);
  7167. msg = "Partial Content";
  7168. }
  7169. hdr = mg_get_header(conn, "Origin");
  7170. if (hdr) {
  7171. /* Cross-origin resource sharing (CORS), see
  7172. * http://www.html5rocks.com/en/tutorials/cors/,
  7173. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  7174. * preflight is not supported for files. */
  7175. cors1 = "Access-Control-Allow-Origin: ";
  7176. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7177. cors3 = "\r\n";
  7178. } else {
  7179. cors1 = cors2 = cors3 = "";
  7180. }
  7181. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  7182. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7183. gmt_time_string(date, sizeof(date), &curtime);
  7184. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7185. construct_etag(etag, sizeof(etag), &filep->stat);
  7186. (void)mg_printf(conn,
  7187. "HTTP/1.1 %d %s\r\n"
  7188. "%s%s%s"
  7189. "Date: %s\r\n",
  7190. conn->status_code,
  7191. msg,
  7192. cors1,
  7193. cors2,
  7194. cors3,
  7195. date);
  7196. send_static_cache_header(conn);
  7197. send_additional_header(conn);
  7198. (void)mg_printf(conn,
  7199. "Last-Modified: %s\r\n"
  7200. "Etag: %s\r\n"
  7201. "Content-Type: %.*s\r\n"
  7202. "Content-Length: %" INT64_FMT "\r\n"
  7203. "Connection: %s\r\n"
  7204. "Accept-Ranges: bytes\r\n"
  7205. "%s%s",
  7206. lm,
  7207. etag,
  7208. (int)mime_vec.len,
  7209. mime_vec.ptr,
  7210. cl,
  7211. suggest_connection_header(conn),
  7212. range,
  7213. encoding);
  7214. /* The previous code must not add any header starting with X- to make
  7215. * sure no one of the additional_headers is included twice */
  7216. if (additional_headers != NULL) {
  7217. (void)mg_printf(conn,
  7218. "%.*s\r\n\r\n",
  7219. (int)strlen(additional_headers),
  7220. additional_headers);
  7221. } else {
  7222. (void)mg_printf(conn, "\r\n");
  7223. }
  7224. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7225. send_file_data(conn, filep, r1, cl);
  7226. }
  7227. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7228. }
  7229. #if !defined(NO_CACHING)
  7230. static void
  7231. handle_not_modified_static_file_request(struct mg_connection *conn,
  7232. struct mg_file *filep)
  7233. {
  7234. char date[64], lm[64], etag[64];
  7235. time_t curtime = time(NULL);
  7236. if ((conn == NULL) || (filep == NULL)) {
  7237. return;
  7238. }
  7239. conn->status_code = 304;
  7240. gmt_time_string(date, sizeof(date), &curtime);
  7241. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7242. construct_etag(etag, sizeof(etag), &filep->stat);
  7243. (void)mg_printf(conn,
  7244. "HTTP/1.1 %d %s\r\n"
  7245. "Date: %s\r\n",
  7246. conn->status_code,
  7247. mg_get_response_code_text(conn, conn->status_code),
  7248. date);
  7249. send_static_cache_header(conn);
  7250. send_additional_header(conn);
  7251. (void)mg_printf(conn,
  7252. "Last-Modified: %s\r\n"
  7253. "Etag: %s\r\n"
  7254. "Connection: %s\r\n"
  7255. "\r\n",
  7256. lm,
  7257. etag,
  7258. suggest_connection_header(conn));
  7259. }
  7260. #endif
  7261. void
  7262. mg_send_file(struct mg_connection *conn, const char *path)
  7263. {
  7264. mg_send_mime_file(conn, path, NULL);
  7265. }
  7266. void
  7267. mg_send_mime_file(struct mg_connection *conn,
  7268. const char *path,
  7269. const char *mime_type)
  7270. {
  7271. mg_send_mime_file2(conn, path, mime_type, NULL);
  7272. }
  7273. void
  7274. mg_send_mime_file2(struct mg_connection *conn,
  7275. const char *path,
  7276. const char *mime_type,
  7277. const char *additional_headers)
  7278. {
  7279. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7280. if (mg_stat(conn, path, &file.stat)) {
  7281. if (file.stat.is_directory) {
  7282. if (!conn) {
  7283. return;
  7284. }
  7285. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7286. "yes")) {
  7287. handle_directory_request(conn, path);
  7288. } else {
  7289. mg_send_http_error(conn,
  7290. 403,
  7291. "%s",
  7292. "Error: Directory listing denied");
  7293. }
  7294. } else {
  7295. handle_static_file_request(
  7296. conn, path, &file, mime_type, additional_headers);
  7297. }
  7298. } else {
  7299. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7300. }
  7301. }
  7302. /* For a given PUT path, create all intermediate subdirectories.
  7303. * Return 0 if the path itself is a directory.
  7304. * Return 1 if the path leads to a file.
  7305. * Return -1 for if the path is too long.
  7306. * Return -2 if path can not be created.
  7307. */
  7308. static int
  7309. put_dir(struct mg_connection *conn, const char *path)
  7310. {
  7311. char buf[PATH_MAX];
  7312. const char *s, *p;
  7313. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7314. size_t len;
  7315. int res = 1;
  7316. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7317. len = (size_t)(p - path);
  7318. if (len >= sizeof(buf)) {
  7319. /* path too long */
  7320. res = -1;
  7321. break;
  7322. }
  7323. memcpy(buf, path, len);
  7324. buf[len] = '\0';
  7325. /* Try to create intermediate directory */
  7326. DEBUG_TRACE("mkdir(%s)", buf);
  7327. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7328. /* path does not exixt and can not be created */
  7329. res = -2;
  7330. break;
  7331. }
  7332. /* Is path itself a directory? */
  7333. if (p[1] == '\0') {
  7334. res = 0;
  7335. }
  7336. }
  7337. return res;
  7338. }
  7339. static void
  7340. remove_bad_file(const struct mg_connection *conn, const char *path)
  7341. {
  7342. int r = mg_remove(conn, path);
  7343. if (r != 0) {
  7344. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7345. }
  7346. }
  7347. long long
  7348. mg_store_body(struct mg_connection *conn, const char *path)
  7349. {
  7350. char buf[MG_BUF_LEN];
  7351. long long len = 0;
  7352. int ret, n;
  7353. struct mg_file fi;
  7354. if (conn->consumed_content != 0) {
  7355. mg_cry(conn, "%s: Contents already consumed", __func__);
  7356. return -11;
  7357. }
  7358. ret = put_dir(conn, path);
  7359. if (ret < 0) {
  7360. /* -1 for path too long,
  7361. * -2 for path can not be created. */
  7362. return ret;
  7363. }
  7364. if (ret != 1) {
  7365. /* Return 0 means, path itself is a directory. */
  7366. return 0;
  7367. }
  7368. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7369. return -12;
  7370. }
  7371. ret = mg_read(conn, buf, sizeof(buf));
  7372. while (ret > 0) {
  7373. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7374. if (n != ret) {
  7375. (void)mg_fclose(
  7376. &fi.access); /* File is bad and will be removed anyway. */
  7377. remove_bad_file(conn, path);
  7378. return -13;
  7379. }
  7380. len += ret;
  7381. ret = mg_read(conn, buf, sizeof(buf));
  7382. }
  7383. /* File is open for writing. If fclose fails, there was probably an
  7384. * error flushing the buffer to disk, so the file on disk might be
  7385. * broken. Delete it and return an error to the caller. */
  7386. if (mg_fclose(&fi.access) != 0) {
  7387. remove_bad_file(conn, path);
  7388. return -14;
  7389. }
  7390. return len;
  7391. }
  7392. /* Parse a buffer:
  7393. * Forward the string pointer till the end of a word, then
  7394. * terminate it and forward till the begin of the next word.
  7395. */
  7396. static int
  7397. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  7398. {
  7399. /* Forward until a space is found - use isgraph here */
  7400. /* See http://www.cplusplus.com/reference/cctype/ */
  7401. while (isgraph(**ppw)) {
  7402. (*ppw)++;
  7403. }
  7404. /* Check end of word */
  7405. if (eol) {
  7406. /* must be a end of line */
  7407. if ((**ppw != '\r') && (**ppw != '\n')) {
  7408. return -1;
  7409. }
  7410. } else {
  7411. /* must be a end of a word, but not a line */
  7412. if (**ppw != ' ') {
  7413. return -1;
  7414. }
  7415. }
  7416. /* Terminate and forward to the next word */
  7417. do {
  7418. **ppw = 0;
  7419. (*ppw)++;
  7420. } while ((**ppw) && isspace(**ppw));
  7421. /* Check after term */
  7422. if (!eol) {
  7423. /* if it's not the end of line, there must be a next word */
  7424. if (!isgraph(**ppw)) {
  7425. return -1;
  7426. }
  7427. }
  7428. /* ok */
  7429. return 1;
  7430. }
  7431. /* Parse HTTP headers from the given buffer, advance buf pointer
  7432. * to the point where parsing stopped.
  7433. * All parameters must be valid pointers (not NULL).
  7434. * Return <0 on error. */
  7435. static int
  7436. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  7437. {
  7438. int i;
  7439. int num_headers = 0;
  7440. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  7441. char *dp = *buf;
  7442. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7443. dp++;
  7444. }
  7445. if (dp == *buf) {
  7446. /* End of headers reached. */
  7447. break;
  7448. }
  7449. if (*dp != ':') {
  7450. /* This is not a valid field. */
  7451. return -1;
  7452. }
  7453. /* End of header key (*dp == ':') */
  7454. /* Truncate here and set the key name */
  7455. *dp = 0;
  7456. hdr[i].name = *buf;
  7457. do {
  7458. dp++;
  7459. } while (*dp == ' ');
  7460. /* The rest of the line is the value */
  7461. hdr[i].value = dp;
  7462. *buf = dp + strcspn(dp, "\r\n");
  7463. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7464. *buf = NULL;
  7465. }
  7466. num_headers = i + 1;
  7467. if (*buf) {
  7468. (*buf)[0] = 0;
  7469. (*buf)[1] = 0;
  7470. *buf += 2;
  7471. } else {
  7472. *buf = dp;
  7473. break;
  7474. }
  7475. if ((*buf)[0] == '\r') {
  7476. /* This is the end of the header */
  7477. break;
  7478. }
  7479. }
  7480. return num_headers;
  7481. }
  7482. static int
  7483. is_valid_http_method(const char *method)
  7484. {
  7485. /* Check if the method is known to the server. The list of all known
  7486. * HTTP methods can be found here at
  7487. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7488. */
  7489. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7490. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7491. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7492. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7493. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7494. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7495. /* TRACE method (RFC 2616) is not supported for security reasons */
  7496. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7497. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7498. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7499. /* Unsupported WEBDAV Methods: */
  7500. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7501. /* + 11 methods from RFC 3253 */
  7502. /* ORDERPATCH (RFC 3648) */
  7503. /* ACL (RFC 3744) */
  7504. /* SEARCH (RFC 5323) */
  7505. /* + MicroSoft extensions
  7506. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7507. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7508. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7509. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7510. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7511. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7512. * to be useful for REST in case a "GET request with body" is
  7513. * required. */
  7514. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7515. ;
  7516. }
  7517. /* Parse HTTP request, fill in mg_request_info structure.
  7518. * This function modifies the buffer by NUL-terminating
  7519. * HTTP request components, header names and header values.
  7520. * Parameters:
  7521. * buf (in/out): pointer to the HTTP header to parse and split
  7522. * len (in): length of HTTP header buffer
  7523. * re (out): parsed header as mg_request_info
  7524. * buf and ri must be valid pointers (not NULL), len>0.
  7525. * Returns <0 on error. */
  7526. static int
  7527. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  7528. {
  7529. int request_length;
  7530. int init_skip = 0;
  7531. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7532. * remote_port */
  7533. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  7534. NULL;
  7535. ri->num_headers = 0;
  7536. /* RFC says that all initial whitespaces should be ingored */
  7537. /* This included all leading \r and \n (isspace) */
  7538. /* See table: http://www.cplusplus.com/reference/cctype/ */
  7539. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  7540. buf++;
  7541. len--;
  7542. init_skip++;
  7543. }
  7544. if (len == 0) {
  7545. /* Incomplete request */
  7546. return 0;
  7547. }
  7548. /* Control characters are not allowed, including zero */
  7549. if (iscntrl(*(unsigned char *)buf)) {
  7550. return -1;
  7551. }
  7552. /* Find end of HTTP header */
  7553. request_length = get_http_header_len(buf, len);
  7554. if (request_length <= 0) {
  7555. return request_length;
  7556. }
  7557. buf[request_length - 1] = '\0';
  7558. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  7559. return -1;
  7560. }
  7561. /* The first word has to be the HTTP method */
  7562. ri->request_method = buf;
  7563. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7564. return -1;
  7565. }
  7566. /* Check for a valid http method */
  7567. if (!is_valid_http_method(ri->request_method)) {
  7568. return -1;
  7569. }
  7570. /* The second word is the URI */
  7571. ri->request_uri = buf;
  7572. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7573. return -1;
  7574. }
  7575. /* Next would be the HTTP version */
  7576. ri->http_version = buf;
  7577. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  7578. return -1;
  7579. }
  7580. /* Check for a valid HTTP version key */
  7581. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  7582. /* Invalid request */
  7583. return -1;
  7584. }
  7585. ri->http_version += 5;
  7586. /* Parse all HTTP headers */
  7587. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  7588. if (ri->num_headers < 0) {
  7589. /* Error while parsing headers */
  7590. return -1;
  7591. }
  7592. return request_length + init_skip;
  7593. }
  7594. static int
  7595. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  7596. {
  7597. int response_length;
  7598. int init_skip = 0;
  7599. char *tmp, *tmp2;
  7600. long l;
  7601. /* Initialize elements. */
  7602. ri->http_version = ri->status_text = NULL;
  7603. ri->num_headers = ri->status_code = 0;
  7604. /* RFC says that all initial whitespaces should be ingored */
  7605. /* This included all leading \r and \n (isspace) */
  7606. /* See table: http://www.cplusplus.com/reference/cctype/ */
  7607. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  7608. buf++;
  7609. len--;
  7610. init_skip++;
  7611. }
  7612. if (len == 0) {
  7613. /* Incomplete request */
  7614. return 0;
  7615. }
  7616. /* Control characters are not allowed, including zero */
  7617. if (iscntrl(*(unsigned char *)buf)) {
  7618. return -1;
  7619. }
  7620. /* Find end of HTTP header */
  7621. response_length = get_http_header_len(buf, len);
  7622. if (response_length <= 0) {
  7623. return response_length;
  7624. }
  7625. buf[response_length - 1] = '\0';
  7626. /* TODO: Define mg_response_info and implement parsing */
  7627. (void)buf;
  7628. (void)len;
  7629. (void)ri;
  7630. /* RFC says that all initial whitespaces should be ingored */
  7631. while ((*buf != '\0') && isspace(*(unsigned char *)buf)) {
  7632. buf++;
  7633. }
  7634. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  7635. return -1;
  7636. }
  7637. /* The first word is the HTTP version */
  7638. /* Check for a valid HTTP version key */
  7639. if (strncmp(buf, "HTTP/", 5) != 0) {
  7640. /* Invalid request */
  7641. return -1;
  7642. }
  7643. buf += 5;
  7644. if (!isgraph(buf[0])) {
  7645. /* Invalid request */
  7646. return -1;
  7647. }
  7648. ri->http_version = buf;
  7649. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7650. return -1;
  7651. }
  7652. /* The second word is the status as a number */
  7653. tmp = buf;
  7654. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7655. return -1;
  7656. }
  7657. l = strtol(tmp, &tmp2, 10);
  7658. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  7659. /* Everything else but a 3 digit code is invalid */
  7660. return -1;
  7661. }
  7662. ri->status_code = (int)l;
  7663. /* The rest of the line is the status text */
  7664. ri->status_text = buf;
  7665. /* Find end of status text */
  7666. /* isgraph or isspace = isprint */
  7667. while (isprint(*buf)) {
  7668. buf++;
  7669. }
  7670. if ((*buf != '\r') && (*buf != '\n')) {
  7671. return -1;
  7672. }
  7673. /* Terminate string and forward buf to next line */
  7674. do {
  7675. *buf = 0;
  7676. buf++;
  7677. } while ((*buf) && isspace(*buf));
  7678. /* Parse all HTTP headers */
  7679. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  7680. if (ri->num_headers < 0) {
  7681. /* Error while parsing headers */
  7682. return -1;
  7683. }
  7684. return response_length + init_skip;
  7685. }
  7686. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7687. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7688. * buffer (which marks the end of HTTP request). Buffer buf may already
  7689. * have some data. The length of the data is stored in nread.
  7690. * Upon every read operation, increase nread by the number of bytes read. */
  7691. static int
  7692. read_message(FILE *fp,
  7693. struct mg_connection *conn,
  7694. char *buf,
  7695. int bufsiz,
  7696. int *nread)
  7697. {
  7698. int request_len, n = 0;
  7699. struct timespec last_action_time;
  7700. double request_timeout;
  7701. if (!conn) {
  7702. return 0;
  7703. }
  7704. memset(&last_action_time, 0, sizeof(last_action_time));
  7705. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7706. /* value of request_timeout is in seconds, config in milliseconds */
  7707. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7708. } else {
  7709. request_timeout = -1.0;
  7710. }
  7711. if (conn->handled_requests > 0) {
  7712. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7713. request_timeout =
  7714. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7715. }
  7716. }
  7717. request_len = get_http_header_len(buf, *nread);
  7718. /* first time reading from this connection */
  7719. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7720. while (request_len == 0) {
  7721. /* Full request not yet received */
  7722. if (conn->ctx->stop_flag != 0) {
  7723. /* Server is to be stopped. */
  7724. return -1;
  7725. }
  7726. if (*nread >= bufsiz) {
  7727. /* Request too long */
  7728. return -2;
  7729. }
  7730. n = pull_inner(
  7731. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7732. if (n == -2) {
  7733. /* Receive error */
  7734. return -1;
  7735. }
  7736. if (n > 0) {
  7737. *nread += n;
  7738. request_len = get_http_header_len(buf, *nread);
  7739. } else {
  7740. request_len = 0;
  7741. }
  7742. if ((request_len == 0) && (request_timeout >= 0)) {
  7743. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7744. > request_timeout) {
  7745. /* Timeout */
  7746. return -1;
  7747. }
  7748. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7749. }
  7750. }
  7751. return request_len;
  7752. }
  7753. #if !defined(NO_CACHING)
  7754. /* Return True if we should reply 304 Not Modified. */
  7755. static int
  7756. is_not_modified(const struct mg_connection *conn,
  7757. const struct mg_file_stat *filestat)
  7758. {
  7759. char etag[64];
  7760. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7761. const char *inm = mg_get_header(conn, "If-None-Match");
  7762. construct_etag(etag, sizeof(etag), filestat);
  7763. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  7764. || ((ims != NULL)
  7765. && (filestat->last_modified <= parse_date_string(ims)));
  7766. }
  7767. #endif /* !NO_CACHING */
  7768. #if !defined(NO_CGI) || !defined(NO_FILES)
  7769. static int
  7770. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7771. {
  7772. const char *expect, *body;
  7773. char buf[MG_BUF_LEN];
  7774. int to_read, nread, success = 0;
  7775. int64_t buffered_len;
  7776. double timeout = -1.0;
  7777. if (!conn) {
  7778. return 0;
  7779. }
  7780. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7781. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7782. }
  7783. expect = mg_get_header(conn, "Expect");
  7784. /* assert(fp != NULL); */
  7785. if (!fp) {
  7786. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  7787. return 0;
  7788. }
  7789. if ((conn->content_len == -1) && !conn->is_chunked) {
  7790. /* Content length is not specified by the client. */
  7791. mg_send_http_error(conn,
  7792. 411,
  7793. "%s",
  7794. "Error: Client did not specify content length");
  7795. } else if ((expect != NULL)
  7796. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7797. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7798. mg_send_http_error(conn,
  7799. 417,
  7800. "Error: Can not fulfill expectation %s",
  7801. expect);
  7802. } else {
  7803. if (expect != NULL) {
  7804. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7805. conn->status_code = 100;
  7806. } else {
  7807. conn->status_code = 200;
  7808. }
  7809. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7810. - conn->consumed_content;
  7811. /* assert(buffered_len >= 0); */
  7812. /* assert(conn->consumed_content == 0); */
  7813. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7814. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7815. return 0;
  7816. }
  7817. if (buffered_len > 0) {
  7818. if ((int64_t)buffered_len > conn->content_len) {
  7819. buffered_len = (int)conn->content_len;
  7820. }
  7821. body = conn->buf + conn->request_len + conn->consumed_content;
  7822. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7823. conn->consumed_content += buffered_len;
  7824. }
  7825. nread = 0;
  7826. while (conn->consumed_content < conn->content_len) {
  7827. to_read = sizeof(buf);
  7828. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7829. to_read = (int)(conn->content_len - conn->consumed_content);
  7830. }
  7831. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7832. if (nread == -2) {
  7833. /* error */
  7834. break;
  7835. }
  7836. if (nread > 0) {
  7837. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7838. break;
  7839. }
  7840. }
  7841. conn->consumed_content += nread;
  7842. }
  7843. if (conn->consumed_content == conn->content_len) {
  7844. success = (nread >= 0);
  7845. }
  7846. /* Each error code path in this function must send an error */
  7847. if (!success) {
  7848. /* NOTE: Maybe some data has already been sent. */
  7849. /* TODO (low): If some data has been sent, a correct error
  7850. * reply can no longer be sent, so just close the connection */
  7851. mg_send_http_error(conn, 500, "%s", "");
  7852. }
  7853. }
  7854. return success;
  7855. }
  7856. #endif
  7857. #if !defined(NO_CGI)
  7858. /* This structure helps to create an environment for the spawned CGI program.
  7859. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7860. * last element must be NULL.
  7861. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7862. * strings must reside in a contiguous buffer. The end of the buffer is
  7863. * marked by two '\0' characters.
  7864. * We satisfy both worlds: we create an envp array (which is vars), all
  7865. * entries are actually pointers inside buf. */
  7866. struct cgi_environment {
  7867. struct mg_connection *conn;
  7868. /* Data block */
  7869. char *buf; /* Environment buffer */
  7870. size_t buflen; /* Space available in buf */
  7871. size_t bufused; /* Space taken in buf */
  7872. /* Index block */
  7873. char **var; /* char **envp */
  7874. size_t varlen; /* Number of variables available in var */
  7875. size_t varused; /* Number of variables stored in var */
  7876. };
  7877. static void addenv(struct cgi_environment *env,
  7878. PRINTF_FORMAT_STRING(const char *fmt),
  7879. ...) PRINTF_ARGS(2, 3);
  7880. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7881. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7882. static void
  7883. addenv(struct cgi_environment *env, const char *fmt, ...)
  7884. {
  7885. size_t n, space;
  7886. int truncated = 0;
  7887. char *added;
  7888. va_list ap;
  7889. /* Calculate how much space is left in the buffer */
  7890. space = (env->buflen - env->bufused);
  7891. /* Calculate an estimate for the required space */
  7892. n = strlen(fmt) + 2 + 128;
  7893. do {
  7894. if (space <= n) {
  7895. /* Allocate new buffer */
  7896. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7897. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  7898. if (!added) {
  7899. /* Out of memory */
  7900. mg_cry(env->conn,
  7901. "%s: Cannot allocate memory for CGI variable [%s]",
  7902. __func__,
  7903. fmt);
  7904. return;
  7905. }
  7906. env->buf = added;
  7907. env->buflen = n;
  7908. space = (env->buflen - env->bufused);
  7909. }
  7910. /* Make a pointer to the free space int the buffer */
  7911. added = env->buf + env->bufused;
  7912. /* Copy VARIABLE=VALUE\0 string into the free space */
  7913. va_start(ap, fmt);
  7914. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7915. va_end(ap);
  7916. /* Do not add truncated strings to the environment */
  7917. if (truncated) {
  7918. /* Reallocate the buffer */
  7919. space = 0;
  7920. n = 1;
  7921. }
  7922. } while (truncated);
  7923. /* Calculate number of bytes added to the environment */
  7924. n = strlen(added) + 1;
  7925. env->bufused += n;
  7926. /* Now update the variable index */
  7927. space = (env->varlen - env->varused);
  7928. if (space < 2) {
  7929. mg_cry(env->conn,
  7930. "%s: Cannot register CGI variable [%s]",
  7931. __func__,
  7932. fmt);
  7933. return;
  7934. }
  7935. /* Append a pointer to the added string into the envp array */
  7936. env->var[env->varused] = added;
  7937. env->varused++;
  7938. }
  7939. /* Return 0 on success, non-zero if an error occurs. */
  7940. static int
  7941. prepare_cgi_environment(struct mg_connection *conn,
  7942. const char *prog,
  7943. struct cgi_environment *env)
  7944. {
  7945. const char *s;
  7946. struct vec var_vec;
  7947. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7948. int i, truncated, uri_len;
  7949. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  7950. return -1;
  7951. }
  7952. env->conn = conn;
  7953. env->buflen = CGI_ENVIRONMENT_SIZE;
  7954. env->bufused = 0;
  7955. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  7956. if (env->buf == NULL) {
  7957. mg_cry(conn,
  7958. "%s: Not enough memory for environmental buffer",
  7959. __func__);
  7960. return -1;
  7961. }
  7962. env->varlen = MAX_CGI_ENVIR_VARS;
  7963. env->varused = 0;
  7964. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  7965. if (env->var == NULL) {
  7966. mg_cry(conn,
  7967. "%s: Not enough memory for environmental variables",
  7968. __func__);
  7969. mg_free(env->buf);
  7970. return -1;
  7971. }
  7972. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7973. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7974. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7975. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7976. /* Prepare the environment block */
  7977. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7978. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7979. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7980. #if defined(USE_IPV6)
  7981. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7982. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7983. } else
  7984. #endif
  7985. {
  7986. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7987. }
  7988. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7989. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7990. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7991. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7992. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7993. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7994. /* SCRIPT_NAME */
  7995. uri_len = (int)strlen(conn->request_info.local_uri);
  7996. if (conn->path_info == NULL) {
  7997. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7998. /* URI: /path_to_script/script.cgi */
  7999. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8000. } else {
  8001. /* URI: /path_to_script/ ... using index.cgi */
  8002. const char *index_file = strrchr(prog, '/');
  8003. if (index_file) {
  8004. addenv(env,
  8005. "SCRIPT_NAME=%s%s",
  8006. conn->request_info.local_uri,
  8007. index_file + 1);
  8008. }
  8009. }
  8010. } else {
  8011. /* URI: /path_to_script/script.cgi/path_info */
  8012. addenv(env,
  8013. "SCRIPT_NAME=%.*s",
  8014. uri_len - (int)strlen(conn->path_info),
  8015. conn->request_info.local_uri);
  8016. }
  8017. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8018. if (conn->path_info == NULL) {
  8019. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8020. } else {
  8021. addenv(env,
  8022. "PATH_TRANSLATED=%s%s",
  8023. conn->ctx->config[DOCUMENT_ROOT],
  8024. conn->path_info);
  8025. }
  8026. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8027. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8028. addenv(env, "CONTENT_TYPE=%s", s);
  8029. }
  8030. if (conn->request_info.query_string != NULL) {
  8031. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8032. }
  8033. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8034. addenv(env, "CONTENT_LENGTH=%s", s);
  8035. }
  8036. if ((s = getenv("PATH")) != NULL) {
  8037. addenv(env, "PATH=%s", s);
  8038. }
  8039. if (conn->path_info != NULL) {
  8040. addenv(env, "PATH_INFO=%s", conn->path_info);
  8041. }
  8042. if (conn->status_code > 0) {
  8043. /* CGI error handler should show the status code */
  8044. addenv(env, "STATUS=%d", conn->status_code);
  8045. }
  8046. #if defined(_WIN32)
  8047. if ((s = getenv("COMSPEC")) != NULL) {
  8048. addenv(env, "COMSPEC=%s", s);
  8049. }
  8050. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8051. addenv(env, "SYSTEMROOT=%s", s);
  8052. }
  8053. if ((s = getenv("SystemDrive")) != NULL) {
  8054. addenv(env, "SystemDrive=%s", s);
  8055. }
  8056. if ((s = getenv("ProgramFiles")) != NULL) {
  8057. addenv(env, "ProgramFiles=%s", s);
  8058. }
  8059. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8060. addenv(env, "ProgramFiles(x86)=%s", s);
  8061. }
  8062. #else
  8063. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8064. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8065. }
  8066. #endif /* _WIN32 */
  8067. if ((s = getenv("PERLLIB")) != NULL) {
  8068. addenv(env, "PERLLIB=%s", s);
  8069. }
  8070. if (conn->request_info.remote_user != NULL) {
  8071. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8072. addenv(env, "%s", "AUTH_TYPE=Digest");
  8073. }
  8074. /* Add all headers as HTTP_* variables */
  8075. for (i = 0; i < conn->request_info.num_headers; i++) {
  8076. (void)mg_snprintf(conn,
  8077. &truncated,
  8078. http_var_name,
  8079. sizeof(http_var_name),
  8080. "HTTP_%s",
  8081. conn->request_info.http_headers[i].name);
  8082. if (truncated) {
  8083. mg_cry(conn,
  8084. "%s: HTTP header variable too long [%s]",
  8085. __func__,
  8086. conn->request_info.http_headers[i].name);
  8087. continue;
  8088. }
  8089. /* Convert variable name into uppercase, and change - to _ */
  8090. for (p = http_var_name; *p != '\0'; p++) {
  8091. if (*p == '-') {
  8092. *p = '_';
  8093. }
  8094. *p = (char)toupper(*(unsigned char *)p);
  8095. }
  8096. addenv(env,
  8097. "%s=%s",
  8098. http_var_name,
  8099. conn->request_info.http_headers[i].value);
  8100. }
  8101. /* Add user-specified variables */
  8102. s = conn->ctx->config[CGI_ENVIRONMENT];
  8103. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8104. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8105. }
  8106. env->var[env->varused] = NULL;
  8107. env->buf[env->bufused] = '\0';
  8108. return 0;
  8109. }
  8110. static void
  8111. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8112. {
  8113. char *buf;
  8114. size_t buflen;
  8115. int headers_len, data_len, i, truncated;
  8116. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8117. const char *status, *status_text, *connection_state;
  8118. char *pbuf, dir[PATH_MAX], *p;
  8119. struct mg_request_info ri;
  8120. struct cgi_environment blk;
  8121. FILE *in = NULL, *out = NULL, *err = NULL;
  8122. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8123. pid_t pid = (pid_t)-1;
  8124. if (conn == NULL) {
  8125. return;
  8126. }
  8127. buf = NULL;
  8128. buflen = 16384;
  8129. i = prepare_cgi_environment(conn, prog, &blk);
  8130. if (i != 0) {
  8131. blk.buf = NULL;
  8132. blk.var = NULL;
  8133. goto done;
  8134. }
  8135. /* CGI must be executed in its own directory. 'dir' must point to the
  8136. * directory containing executable program, 'p' must point to the
  8137. * executable program name relative to 'dir'. */
  8138. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8139. if (truncated) {
  8140. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  8141. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8142. goto done;
  8143. }
  8144. if ((p = strrchr(dir, '/')) != NULL) {
  8145. *p++ = '\0';
  8146. } else {
  8147. dir[0] = '.', dir[1] = '\0';
  8148. p = (char *)prog;
  8149. }
  8150. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8151. status = strerror(ERRNO);
  8152. mg_cry(conn,
  8153. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8154. prog,
  8155. status);
  8156. mg_send_http_error(conn,
  8157. 500,
  8158. "Error: Cannot create CGI pipe: %s",
  8159. status);
  8160. goto done;
  8161. }
  8162. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8163. if (pid == (pid_t)-1) {
  8164. status = strerror(ERRNO);
  8165. mg_cry(conn,
  8166. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8167. prog,
  8168. status);
  8169. mg_send_http_error(conn,
  8170. 500,
  8171. "Error: Cannot spawn CGI process [%s]: %s",
  8172. prog,
  8173. status);
  8174. goto done;
  8175. }
  8176. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  8177. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8178. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8179. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8180. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8181. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8182. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8183. /* Parent closes only one side of the pipes.
  8184. * If we don't mark them as closed, close() attempt before
  8185. * return from this function throws an exception on Windows.
  8186. * Windows does not like when closed descriptor is closed again. */
  8187. (void)close(fdin[0]);
  8188. (void)close(fdout[1]);
  8189. (void)close(fderr[1]);
  8190. fdin[0] = fdout[1] = fderr[1] = -1;
  8191. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8192. status = strerror(ERRNO);
  8193. mg_cry(conn,
  8194. "Error: CGI program \"%s\": Can not open stdin: %s",
  8195. prog,
  8196. status);
  8197. mg_send_http_error(conn,
  8198. 500,
  8199. "Error: CGI can not open fdin\nfopen: %s",
  8200. status);
  8201. goto done;
  8202. }
  8203. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8204. status = strerror(ERRNO);
  8205. mg_cry(conn,
  8206. "Error: CGI program \"%s\": Can not open stdout: %s",
  8207. prog,
  8208. status);
  8209. mg_send_http_error(conn,
  8210. 500,
  8211. "Error: CGI can not open fdout\nfopen: %s",
  8212. status);
  8213. goto done;
  8214. }
  8215. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8216. status = strerror(ERRNO);
  8217. mg_cry(conn,
  8218. "Error: CGI program \"%s\": Can not open stderr: %s",
  8219. prog,
  8220. status);
  8221. mg_send_http_error(conn,
  8222. 500,
  8223. "Error: CGI can not open fdout\nfopen: %s",
  8224. status);
  8225. goto done;
  8226. }
  8227. setbuf(in, NULL);
  8228. setbuf(out, NULL);
  8229. setbuf(err, NULL);
  8230. fout.access.fp = out;
  8231. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  8232. /* This is a POST/PUT request, or another request with body data. */
  8233. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8234. /* Error sending the body data */
  8235. mg_cry(conn,
  8236. "Error: CGI program \"%s\": Forward body data failed",
  8237. prog);
  8238. goto done;
  8239. }
  8240. }
  8241. /* Close so child gets an EOF. */
  8242. fclose(in);
  8243. in = NULL;
  8244. fdin[1] = -1;
  8245. /* Now read CGI reply into a buffer. We need to set correct
  8246. * status code, thus we need to see all HTTP headers first.
  8247. * Do not send anything back to client, until we buffer in all
  8248. * HTTP headers. */
  8249. data_len = 0;
  8250. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  8251. if (buf == NULL) {
  8252. mg_send_http_error(conn,
  8253. 500,
  8254. "Error: Not enough memory for CGI buffer (%u bytes)",
  8255. (unsigned int)buflen);
  8256. mg_cry(conn,
  8257. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  8258. "bytes)",
  8259. prog,
  8260. (unsigned int)buflen);
  8261. goto done;
  8262. }
  8263. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  8264. if (headers_len <= 0) {
  8265. /* Could not parse the CGI response. Check if some error message on
  8266. * stderr. */
  8267. i = pull_all(err, conn, buf, (int)buflen);
  8268. if (i > 0) {
  8269. mg_cry(conn,
  8270. "Error: CGI program \"%s\" sent error "
  8271. "message: [%.*s]",
  8272. prog,
  8273. i,
  8274. buf);
  8275. mg_send_http_error(conn,
  8276. 500,
  8277. "Error: CGI program \"%s\" sent error "
  8278. "message: [%.*s]",
  8279. prog,
  8280. i,
  8281. buf);
  8282. } else {
  8283. mg_cry(conn,
  8284. "Error: CGI program sent malformed or too big "
  8285. "(>%u bytes) HTTP headers: [%.*s]",
  8286. (unsigned)buflen,
  8287. data_len,
  8288. buf);
  8289. mg_send_http_error(conn,
  8290. 500,
  8291. "Error: CGI program sent malformed or too big "
  8292. "(>%u bytes) HTTP headers: [%.*s]",
  8293. (unsigned)buflen,
  8294. data_len,
  8295. buf);
  8296. }
  8297. goto done;
  8298. }
  8299. pbuf = buf;
  8300. buf[headers_len - 1] = '\0';
  8301. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  8302. /* Make up and send the status line */
  8303. status_text = "OK";
  8304. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  8305. != NULL) {
  8306. conn->status_code = atoi(status);
  8307. status_text = status;
  8308. while (isdigit(*(const unsigned char *)status_text)
  8309. || *status_text == ' ') {
  8310. status_text++;
  8311. }
  8312. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  8313. != NULL) {
  8314. conn->status_code = 302;
  8315. } else {
  8316. conn->status_code = 200;
  8317. }
  8318. connection_state =
  8319. get_header(ri.http_headers, ri.num_headers, "Connection");
  8320. if (!header_has_option(connection_state, "keep-alive")) {
  8321. conn->must_close = 1;
  8322. }
  8323. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  8324. /* Send headers */
  8325. for (i = 0; i < ri.num_headers; i++) {
  8326. mg_printf(conn,
  8327. "%s: %s\r\n",
  8328. ri.http_headers[i].name,
  8329. ri.http_headers[i].value);
  8330. }
  8331. mg_write(conn, "\r\n", 2);
  8332. /* Send chunk of data that may have been read after the headers */
  8333. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  8334. /* Read the rest of CGI output and send to the client */
  8335. send_file_data(conn, &fout, 0, INT64_MAX);
  8336. done:
  8337. mg_free(blk.var);
  8338. mg_free(blk.buf);
  8339. if (pid != (pid_t)-1) {
  8340. kill(pid, SIGKILL);
  8341. #if !defined(_WIN32)
  8342. {
  8343. int st;
  8344. while (waitpid(pid, &st, 0) != -1)
  8345. ; /* clean zombies */
  8346. }
  8347. #endif
  8348. }
  8349. if (fdin[0] != -1) {
  8350. close(fdin[0]);
  8351. }
  8352. if (fdout[1] != -1) {
  8353. close(fdout[1]);
  8354. }
  8355. if (in != NULL) {
  8356. fclose(in);
  8357. } else if (fdin[1] != -1) {
  8358. close(fdin[1]);
  8359. }
  8360. if (out != NULL) {
  8361. fclose(out);
  8362. } else if (fdout[0] != -1) {
  8363. close(fdout[0]);
  8364. }
  8365. if (err != NULL) {
  8366. fclose(err);
  8367. } else if (fderr[0] != -1) {
  8368. close(fderr[0]);
  8369. }
  8370. if (buf != NULL) {
  8371. mg_free(buf);
  8372. }
  8373. }
  8374. #endif /* !NO_CGI */
  8375. #if !defined(NO_FILES)
  8376. static void
  8377. mkcol(struct mg_connection *conn, const char *path)
  8378. {
  8379. int rc, body_len;
  8380. struct de de;
  8381. char date[64];
  8382. time_t curtime = time(NULL);
  8383. if (conn == NULL) {
  8384. return;
  8385. }
  8386. /* TODO (mid): Check the mg_send_http_error situations in this function */
  8387. memset(&de.file, 0, sizeof(de.file));
  8388. if (!mg_stat(conn, path, &de.file)) {
  8389. mg_cry(conn,
  8390. "%s: mg_stat(%s) failed: %s",
  8391. __func__,
  8392. path,
  8393. strerror(ERRNO));
  8394. }
  8395. if (de.file.last_modified) {
  8396. /* TODO (mid): This check does not seem to make any sense ! */
  8397. /* TODO (mid): Add a webdav unit test first, before changing
  8398. * anything here. */
  8399. mg_send_http_error(
  8400. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8401. return;
  8402. }
  8403. body_len = conn->data_len - conn->request_len;
  8404. if (body_len > 0) {
  8405. mg_send_http_error(
  8406. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8407. return;
  8408. }
  8409. rc = mg_mkdir(conn, path, 0755);
  8410. if (rc == 0) {
  8411. conn->status_code = 201;
  8412. gmt_time_string(date, sizeof(date), &curtime);
  8413. mg_printf(conn,
  8414. "HTTP/1.1 %d Created\r\n"
  8415. "Date: %s\r\n",
  8416. conn->status_code,
  8417. date);
  8418. send_static_cache_header(conn);
  8419. send_additional_header(conn);
  8420. mg_printf(conn,
  8421. "Content-Length: 0\r\n"
  8422. "Connection: %s\r\n\r\n",
  8423. suggest_connection_header(conn));
  8424. } else if (rc == -1) {
  8425. if (errno == EEXIST) {
  8426. mg_send_http_error(
  8427. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8428. } else if (errno == EACCES) {
  8429. mg_send_http_error(
  8430. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8431. } else if (errno == ENOENT) {
  8432. mg_send_http_error(
  8433. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8434. } else {
  8435. mg_send_http_error(
  8436. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8437. }
  8438. }
  8439. }
  8440. static void
  8441. put_file(struct mg_connection *conn, const char *path)
  8442. {
  8443. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8444. const char *range;
  8445. int64_t r1, r2;
  8446. int rc;
  8447. char date[64];
  8448. time_t curtime = time(NULL);
  8449. if (conn == NULL) {
  8450. return;
  8451. }
  8452. if (mg_stat(conn, path, &file.stat)) {
  8453. /* File already exists */
  8454. conn->status_code = 200;
  8455. if (file.stat.is_directory) {
  8456. /* This is an already existing directory,
  8457. * so there is nothing to do for the server. */
  8458. rc = 0;
  8459. } else {
  8460. /* File exists and is not a directory. */
  8461. /* Can it be replaced? */
  8462. if (file.access.membuf != NULL) {
  8463. /* This is an "in-memory" file, that can not be replaced */
  8464. mg_send_http_error(
  8465. conn,
  8466. 405,
  8467. "Error: Put not possible\nReplacing %s is not supported",
  8468. path);
  8469. return;
  8470. }
  8471. /* Check if the server may write this file */
  8472. if (access(path, W_OK) == 0) {
  8473. /* Access granted */
  8474. conn->status_code = 200;
  8475. rc = 1;
  8476. } else {
  8477. mg_send_http_error(
  8478. conn,
  8479. 403,
  8480. "Error: Put not possible\nReplacing %s is not allowed",
  8481. path);
  8482. return;
  8483. }
  8484. }
  8485. } else {
  8486. /* File should be created */
  8487. conn->status_code = 201;
  8488. rc = put_dir(conn, path);
  8489. }
  8490. if (rc == 0) {
  8491. /* put_dir returns 0 if path is a directory */
  8492. gmt_time_string(date, sizeof(date), &curtime);
  8493. mg_printf(conn,
  8494. "HTTP/1.1 %d %s\r\n",
  8495. conn->status_code,
  8496. mg_get_response_code_text(NULL, conn->status_code));
  8497. send_no_cache_header(conn);
  8498. send_additional_header(conn);
  8499. mg_printf(conn,
  8500. "Date: %s\r\n"
  8501. "Content-Length: 0\r\n"
  8502. "Connection: %s\r\n\r\n",
  8503. date,
  8504. suggest_connection_header(conn));
  8505. /* Request to create a directory has been fulfilled successfully.
  8506. * No need to put a file. */
  8507. return;
  8508. }
  8509. if (rc == -1) {
  8510. /* put_dir returns -1 if the path is too long */
  8511. mg_send_http_error(conn,
  8512. 414,
  8513. "Error: Path too long\nput_dir(%s): %s",
  8514. path,
  8515. strerror(ERRNO));
  8516. return;
  8517. }
  8518. if (rc == -2) {
  8519. /* put_dir returns -2 if the directory can not be created */
  8520. mg_send_http_error(conn,
  8521. 500,
  8522. "Error: Can not create directory\nput_dir(%s): %s",
  8523. path,
  8524. strerror(ERRNO));
  8525. return;
  8526. }
  8527. /* A file should be created or overwritten. */
  8528. /* Currently CivetWeb does not nead read+write access. */
  8529. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8530. || file.access.fp == NULL) {
  8531. (void)mg_fclose(&file.access);
  8532. mg_send_http_error(conn,
  8533. 500,
  8534. "Error: Can not create file\nfopen(%s): %s",
  8535. path,
  8536. strerror(ERRNO));
  8537. return;
  8538. }
  8539. fclose_on_exec(&file.access, conn);
  8540. range = mg_get_header(conn, "Content-Range");
  8541. r1 = r2 = 0;
  8542. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  8543. conn->status_code = 206; /* Partial content */
  8544. fseeko(file.access.fp, r1, SEEK_SET);
  8545. }
  8546. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8547. /* forward_body_data failed.
  8548. * The error code has already been sent to the client,
  8549. * and conn->status_code is already set. */
  8550. (void)mg_fclose(&file.access);
  8551. return;
  8552. }
  8553. if (mg_fclose(&file.access) != 0) {
  8554. /* fclose failed. This might have different reasons, but a likely
  8555. * one is "no space on disk", http 507. */
  8556. conn->status_code = 507;
  8557. }
  8558. gmt_time_string(date, sizeof(date), &curtime);
  8559. mg_printf(conn,
  8560. "HTTP/1.1 %d %s\r\n",
  8561. conn->status_code,
  8562. mg_get_response_code_text(NULL, conn->status_code));
  8563. send_no_cache_header(conn);
  8564. send_additional_header(conn);
  8565. mg_printf(conn,
  8566. "Date: %s\r\n"
  8567. "Content-Length: 0\r\n"
  8568. "Connection: %s\r\n\r\n",
  8569. date,
  8570. suggest_connection_header(conn));
  8571. }
  8572. static void
  8573. delete_file(struct mg_connection *conn, const char *path)
  8574. {
  8575. struct de de;
  8576. memset(&de.file, 0, sizeof(de.file));
  8577. if (!mg_stat(conn, path, &de.file)) {
  8578. /* mg_stat returns 0 if the file does not exist */
  8579. mg_send_http_error(conn,
  8580. 404,
  8581. "Error: Cannot delete file\nFile %s not found",
  8582. path);
  8583. return;
  8584. }
  8585. #if 0 /* Ignore if a file in memory is inside a folder */
  8586. if (de.access.membuf != NULL) {
  8587. /* the file is cached in memory */
  8588. mg_send_http_error(
  8589. conn,
  8590. 405,
  8591. "Error: Delete not possible\nDeleting %s is not supported",
  8592. path);
  8593. return;
  8594. }
  8595. #endif
  8596. if (de.file.is_directory) {
  8597. if (remove_directory(conn, path)) {
  8598. /* Delete is successful: Return 204 without content. */
  8599. mg_send_http_error(conn, 204, "%s", "");
  8600. } else {
  8601. /* Delete is not successful: Return 500 (Server error). */
  8602. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8603. }
  8604. return;
  8605. }
  8606. /* This is an existing file (not a directory).
  8607. * Check if write permission is granted. */
  8608. if (access(path, W_OK) != 0) {
  8609. /* File is read only */
  8610. mg_send_http_error(
  8611. conn,
  8612. 403,
  8613. "Error: Delete not possible\nDeleting %s is not allowed",
  8614. path);
  8615. return;
  8616. }
  8617. /* Try to delete it. */
  8618. if (mg_remove(conn, path) == 0) {
  8619. /* Delete was successful: Return 204 without content. */
  8620. mg_send_http_error(conn, 204, "%s", "");
  8621. } else {
  8622. /* Delete not successful (file locked). */
  8623. mg_send_http_error(conn,
  8624. 423,
  8625. "Error: Cannot delete file\nremove(%s): %s",
  8626. path,
  8627. strerror(ERRNO));
  8628. }
  8629. }
  8630. #endif /* !NO_FILES */
  8631. static void
  8632. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8633. static void
  8634. do_ssi_include(struct mg_connection *conn,
  8635. const char *ssi,
  8636. char *tag,
  8637. int include_level)
  8638. {
  8639. char file_name[MG_BUF_LEN], path[512], *p;
  8640. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8641. size_t len;
  8642. int truncated = 0;
  8643. if (conn == NULL) {
  8644. return;
  8645. }
  8646. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8647. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8648. * always < MG_BUF_LEN. */
  8649. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8650. /* File name is relative to the webserver root */
  8651. file_name[511] = 0;
  8652. (void)mg_snprintf(conn,
  8653. &truncated,
  8654. path,
  8655. sizeof(path),
  8656. "%s/%s",
  8657. conn->ctx->config[DOCUMENT_ROOT],
  8658. file_name);
  8659. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8660. /* File name is relative to the webserver working directory
  8661. * or it is absolute system path */
  8662. file_name[511] = 0;
  8663. (void)
  8664. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8665. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  8666. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  8667. /* File name is relative to the currect document */
  8668. file_name[511] = 0;
  8669. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8670. if (!truncated) {
  8671. if ((p = strrchr(path, '/')) != NULL) {
  8672. p[1] = '\0';
  8673. }
  8674. len = strlen(path);
  8675. (void)mg_snprintf(conn,
  8676. &truncated,
  8677. path + len,
  8678. sizeof(path) - len,
  8679. "%s",
  8680. file_name);
  8681. }
  8682. } else {
  8683. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8684. return;
  8685. }
  8686. if (truncated) {
  8687. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8688. return;
  8689. }
  8690. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8691. mg_cry(conn,
  8692. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8693. tag,
  8694. path,
  8695. strerror(ERRNO));
  8696. } else {
  8697. fclose_on_exec(&file.access, conn);
  8698. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8699. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8700. path) > 0) {
  8701. send_ssi_file(conn, path, &file, include_level + 1);
  8702. } else {
  8703. send_file_data(conn, &file, 0, INT64_MAX);
  8704. }
  8705. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8706. }
  8707. }
  8708. #if !defined(NO_POPEN)
  8709. static void
  8710. do_ssi_exec(struct mg_connection *conn, char *tag)
  8711. {
  8712. char cmd[1024] = "";
  8713. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8714. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8715. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8716. } else {
  8717. cmd[1023] = 0;
  8718. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8719. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8720. } else {
  8721. send_file_data(conn, &file, 0, INT64_MAX);
  8722. pclose(file.access.fp);
  8723. }
  8724. }
  8725. }
  8726. #endif /* !NO_POPEN */
  8727. static int
  8728. mg_fgetc(struct mg_file *filep, int offset)
  8729. {
  8730. if (filep == NULL) {
  8731. return EOF;
  8732. }
  8733. if ((filep->access.membuf != NULL) && (offset >= 0)
  8734. && (((unsigned int)(offset)) < filep->stat.size)) {
  8735. return ((const unsigned char *)filep->access.membuf)[offset];
  8736. } else if (filep->access.fp != NULL) {
  8737. return fgetc(filep->access.fp);
  8738. } else {
  8739. return EOF;
  8740. }
  8741. }
  8742. static void
  8743. send_ssi_file(struct mg_connection *conn,
  8744. const char *path,
  8745. struct mg_file *filep,
  8746. int include_level)
  8747. {
  8748. char buf[MG_BUF_LEN];
  8749. int ch, offset, len, in_tag, in_ssi_tag;
  8750. if (include_level > 10) {
  8751. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8752. return;
  8753. }
  8754. in_tag = in_ssi_tag = len = offset = 0;
  8755. /* Read file, byte by byte, and look for SSI include tags */
  8756. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  8757. if (in_tag) {
  8758. /* We are in a tag, either SSI tag or html tag */
  8759. if (ch == '>') {
  8760. /* Tag is closing */
  8761. buf[len++] = '>';
  8762. if (in_ssi_tag) {
  8763. /* Handle SSI tag */
  8764. buf[len] = 0;
  8765. if (!memcmp(buf + 5, "include", 7)) {
  8766. do_ssi_include(conn, path, buf + 12, include_level + 1);
  8767. #if !defined(NO_POPEN)
  8768. } else if (!memcmp(buf + 5, "exec", 4)) {
  8769. do_ssi_exec(conn, buf + 9);
  8770. #endif /* !NO_POPEN */
  8771. } else {
  8772. mg_cry(conn,
  8773. "%s: unknown SSI "
  8774. "command: \"%s\"",
  8775. path,
  8776. buf);
  8777. }
  8778. len = 0;
  8779. in_ssi_tag = in_tag = 0;
  8780. } else {
  8781. /* Not an SSI tag */
  8782. /* Flush buffer */
  8783. (void)mg_write(conn, buf, (size_t)len);
  8784. len = 0;
  8785. in_tag = 0;
  8786. }
  8787. } else {
  8788. /* Tag is still open */
  8789. buf[len++] = (char)(ch & 0xff);
  8790. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  8791. /* All SSI tags start with <!--# */
  8792. in_ssi_tag = 1;
  8793. }
  8794. if ((len + 2) > (int)sizeof(buf)) {
  8795. /* Tag to long for buffer */
  8796. mg_cry(conn, "%s: tag is too large", path);
  8797. len = 0;
  8798. return;
  8799. }
  8800. }
  8801. } else {
  8802. /* We are not in a tag yet. */
  8803. if (ch == '<') {
  8804. /* Tag is opening */
  8805. in_tag = 1;
  8806. /* Flush current buffer */
  8807. (void)mg_write(conn, buf, (size_t)len);
  8808. /* Store the < */
  8809. len = 1;
  8810. buf[0] = '<';
  8811. } else {
  8812. /* No Tag */
  8813. /* Add data to buffer */
  8814. buf[len++] = (char)(ch & 0xff);
  8815. /* Flush if buffer is full */
  8816. if (len == (int)sizeof(buf)) {
  8817. mg_write(conn, buf, (size_t)len);
  8818. len = 0;
  8819. }
  8820. }
  8821. }
  8822. }
  8823. /* Send the rest of buffered data */
  8824. if (len > 0) {
  8825. mg_write(conn, buf, (size_t)len);
  8826. }
  8827. }
  8828. static void
  8829. handle_ssi_file_request(struct mg_connection *conn,
  8830. const char *path,
  8831. struct mg_file *filep)
  8832. {
  8833. char date[64];
  8834. time_t curtime = time(NULL);
  8835. const char *cors1, *cors2, *cors3;
  8836. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  8837. return;
  8838. }
  8839. if (mg_get_header(conn, "Origin")) {
  8840. /* Cross-origin resource sharing (CORS). */
  8841. cors1 = "Access-Control-Allow-Origin: ";
  8842. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8843. cors3 = "\r\n";
  8844. } else {
  8845. cors1 = cors2 = cors3 = "";
  8846. }
  8847. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8848. /* File exists (precondition for calling this function),
  8849. * but can not be opened by the server. */
  8850. mg_send_http_error(conn,
  8851. 500,
  8852. "Error: Cannot read file\nfopen(%s): %s",
  8853. path,
  8854. strerror(ERRNO));
  8855. } else {
  8856. conn->must_close = 1;
  8857. gmt_time_string(date, sizeof(date), &curtime);
  8858. fclose_on_exec(&filep->access, conn);
  8859. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8860. send_no_cache_header(conn);
  8861. send_additional_header(conn);
  8862. mg_printf(conn,
  8863. "%s%s%s"
  8864. "Date: %s\r\n"
  8865. "Content-Type: text/html\r\n"
  8866. "Connection: %s\r\n\r\n",
  8867. cors1,
  8868. cors2,
  8869. cors3,
  8870. date,
  8871. suggest_connection_header(conn));
  8872. send_ssi_file(conn, path, filep, 0);
  8873. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8874. }
  8875. }
  8876. #if !defined(NO_FILES)
  8877. static void
  8878. send_options(struct mg_connection *conn)
  8879. {
  8880. char date[64];
  8881. time_t curtime = time(NULL);
  8882. if (!conn) {
  8883. return;
  8884. }
  8885. conn->status_code = 200;
  8886. conn->must_close = 1;
  8887. gmt_time_string(date, sizeof(date), &curtime);
  8888. /* We do not set a "Cache-Control" header here, but leave the default.
  8889. * Since browsers do not send an OPTIONS request, we can not test the
  8890. * effect anyway. */
  8891. mg_printf(conn,
  8892. "HTTP/1.1 200 OK\r\n"
  8893. "Date: %s\r\n"
  8894. "Connection: %s\r\n"
  8895. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8896. "PROPFIND, MKCOL\r\n"
  8897. "DAV: 1\r\n",
  8898. date,
  8899. suggest_connection_header(conn));
  8900. send_additional_header(conn);
  8901. mg_printf(conn, "\r\n");
  8902. }
  8903. /* Writes PROPFIND properties for a collection element */
  8904. static void
  8905. print_props(struct mg_connection *conn,
  8906. const char *uri,
  8907. struct mg_file_stat *filep)
  8908. {
  8909. char mtime[64];
  8910. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  8911. return;
  8912. }
  8913. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8914. mg_printf(conn,
  8915. "<d:response>"
  8916. "<d:href>%s</d:href>"
  8917. "<d:propstat>"
  8918. "<d:prop>"
  8919. "<d:resourcetype>%s</d:resourcetype>"
  8920. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8921. "<d:getlastmodified>%s</d:getlastmodified>"
  8922. "</d:prop>"
  8923. "<d:status>HTTP/1.1 200 OK</d:status>"
  8924. "</d:propstat>"
  8925. "</d:response>\n",
  8926. uri,
  8927. filep->is_directory ? "<d:collection/>" : "",
  8928. filep->size,
  8929. mtime);
  8930. }
  8931. static int
  8932. print_dav_dir_entry(struct de *de, void *data)
  8933. {
  8934. char href[PATH_MAX];
  8935. int truncated;
  8936. struct mg_connection *conn = (struct mg_connection *)data;
  8937. if (!de || !conn) {
  8938. return -1;
  8939. }
  8940. mg_snprintf(conn,
  8941. &truncated,
  8942. href,
  8943. sizeof(href),
  8944. "%s%s",
  8945. conn->request_info.local_uri,
  8946. de->file_name);
  8947. if (!truncated) {
  8948. size_t href_encoded_size;
  8949. char *href_encoded;
  8950. href_encoded_size = PATH_MAX * 3; /* worst case */
  8951. href_encoded = mg_malloc(href_encoded_size);
  8952. if (href_encoded == NULL) {
  8953. return -1;
  8954. }
  8955. mg_url_encode(href, href_encoded, href_encoded_size);
  8956. print_props(conn, href_encoded, &de->file);
  8957. mg_free(href_encoded);
  8958. }
  8959. return 0;
  8960. }
  8961. static void
  8962. handle_propfind(struct mg_connection *conn,
  8963. const char *path,
  8964. struct mg_file_stat *filep)
  8965. {
  8966. const char *depth = mg_get_header(conn, "Depth");
  8967. char date[64];
  8968. time_t curtime = time(NULL);
  8969. gmt_time_string(date, sizeof(date), &curtime);
  8970. if (!conn || !path || !filep || !conn->ctx) {
  8971. return;
  8972. }
  8973. conn->must_close = 1;
  8974. conn->status_code = 207;
  8975. mg_printf(conn,
  8976. "HTTP/1.1 207 Multi-Status\r\n"
  8977. "Date: %s\r\n",
  8978. date);
  8979. send_static_cache_header(conn);
  8980. send_additional_header(conn);
  8981. mg_printf(conn,
  8982. "Connection: %s\r\n"
  8983. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8984. suggest_connection_header(conn));
  8985. mg_printf(conn,
  8986. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8987. "<d:multistatus xmlns:d='DAV:'>\n");
  8988. /* Print properties for the requested resource itself */
  8989. print_props(conn, conn->request_info.local_uri, filep);
  8990. /* If it is a directory, print directory entries too if Depth is not 0 */
  8991. if (filep && filep->is_directory
  8992. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8993. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  8994. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8995. }
  8996. mg_printf(conn, "%s\n", "</d:multistatus>");
  8997. }
  8998. #endif
  8999. void
  9000. mg_lock_connection(struct mg_connection *conn)
  9001. {
  9002. if (conn) {
  9003. (void)pthread_mutex_lock(&conn->mutex);
  9004. }
  9005. }
  9006. void
  9007. mg_unlock_connection(struct mg_connection *conn)
  9008. {
  9009. if (conn) {
  9010. (void)pthread_mutex_unlock(&conn->mutex);
  9011. }
  9012. }
  9013. void
  9014. mg_lock_context(struct mg_context *ctx)
  9015. {
  9016. if (ctx) {
  9017. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9018. }
  9019. }
  9020. void
  9021. mg_unlock_context(struct mg_context *ctx)
  9022. {
  9023. if (ctx) {
  9024. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9025. }
  9026. }
  9027. #if defined(USE_TIMERS)
  9028. #define TIMER_API static
  9029. #include "timer.inl"
  9030. #endif /* USE_TIMERS */
  9031. #ifdef USE_LUA
  9032. #include "mod_lua.inl"
  9033. #endif /* USE_LUA */
  9034. #ifdef USE_DUKTAPE
  9035. #include "mod_duktape.inl"
  9036. #endif /* USE_DUKTAPE */
  9037. #if defined(USE_WEBSOCKET)
  9038. #if !defined(NO_SSL_DL)
  9039. #define SHA_API static
  9040. #include "sha1.inl"
  9041. #endif
  9042. static int
  9043. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9044. {
  9045. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9046. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9047. SHA_CTX sha_ctx;
  9048. int truncated;
  9049. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9050. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9051. if (truncated) {
  9052. conn->must_close = 1;
  9053. return 0;
  9054. }
  9055. SHA1_Init(&sha_ctx);
  9056. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9057. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9058. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9059. mg_printf(conn,
  9060. "HTTP/1.1 101 Switching Protocols\r\n"
  9061. "Upgrade: websocket\r\n"
  9062. "Connection: Upgrade\r\n"
  9063. "Sec-WebSocket-Accept: %s\r\n",
  9064. b64_sha);
  9065. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9066. mg_printf(conn,
  9067. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9068. conn->request_info.acceptedWebSocketSubprotocol);
  9069. } else {
  9070. mg_printf(conn, "%s", "\r\n");
  9071. }
  9072. return 1;
  9073. }
  9074. static void
  9075. read_websocket(struct mg_connection *conn,
  9076. mg_websocket_data_handler ws_data_handler,
  9077. void *callback_data)
  9078. {
  9079. /* Pointer to the beginning of the portion of the incoming websocket
  9080. * message queue.
  9081. * The original websocket upgrade request is never removed, so the queue
  9082. * begins after it. */
  9083. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9084. int n, error, exit_by_callback;
  9085. /* body_len is the length of the entire queue in bytes
  9086. * len is the length of the current message
  9087. * data_len is the length of the current message's data payload
  9088. * header_len is the length of the current message's header */
  9089. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  9090. /* "The masking key is a 32-bit value chosen at random by the client."
  9091. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9092. */
  9093. unsigned char mask[4];
  9094. /* data points to the place where the message is stored when passed to
  9095. * the
  9096. * websocket_data callback. This is either mem on the stack, or a
  9097. * dynamically allocated buffer if it is too large. */
  9098. unsigned char mem[4096];
  9099. unsigned char *data = mem;
  9100. unsigned char mop; /* mask flag and opcode */
  9101. double timeout = -1.0;
  9102. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  9103. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9104. }
  9105. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  9106. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9107. }
  9108. mg_set_thread_name("wsock");
  9109. /* Loop continuously, reading messages from the socket, invoking the
  9110. * callback, and waiting repeatedly until an error occurs. */
  9111. while (!conn->ctx->stop_flag) {
  9112. header_len = 0;
  9113. assert(conn->data_len >= conn->request_len);
  9114. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9115. len = buf[1] & 127;
  9116. mask_len = (buf[1] & 128) ? 4 : 0;
  9117. if ((len < 126) && (body_len >= mask_len)) {
  9118. /* inline 7-bit length field */
  9119. data_len = len;
  9120. header_len = 2 + mask_len;
  9121. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9122. /* 16-bit length field */
  9123. header_len = 4 + mask_len;
  9124. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9125. } else if (body_len >= (10 + mask_len)) {
  9126. /* 64-bit length field */
  9127. uint32_t l1, l2;
  9128. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9129. memcpy(&l2, &buf[6], 4);
  9130. header_len = 10 + mask_len;
  9131. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9132. }
  9133. }
  9134. if ((header_len > 0) && (body_len >= header_len)) {
  9135. /* Allocate space to hold websocket payload */
  9136. data = mem;
  9137. if (data_len > sizeof(mem)) {
  9138. data = (unsigned char *)mg_malloc_ctx(data_len, conn->ctx);
  9139. if (data == NULL) {
  9140. /* Allocation failed, exit the loop and then close the
  9141. * connection */
  9142. mg_cry(conn, "websocket out of memory; closing connection");
  9143. break;
  9144. }
  9145. }
  9146. /* Copy the mask before we shift the queue and destroy it */
  9147. if (mask_len > 0) {
  9148. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9149. } else {
  9150. memset(mask, 0, sizeof(mask));
  9151. }
  9152. /* Read frame payload from the first message in the queue into
  9153. * data and advance the queue by moving the memory in place. */
  9154. assert(body_len >= header_len);
  9155. if (data_len + header_len > body_len) {
  9156. mop = buf[0]; /* current mask and opcode */
  9157. /* Overflow case */
  9158. len = body_len - header_len;
  9159. memcpy(data, buf + header_len, len);
  9160. error = 0;
  9161. while (len < data_len) {
  9162. n = pull_inner(NULL,
  9163. conn,
  9164. (char *)(data + len),
  9165. (int)(data_len - len),
  9166. timeout);
  9167. if (n <= -2) {
  9168. error = 1;
  9169. break;
  9170. } else if (n > 0) {
  9171. len += (size_t)n;
  9172. } else {
  9173. /* Timeout: should retry */
  9174. /* TODO: retry condition */
  9175. }
  9176. }
  9177. if (error) {
  9178. mg_cry(conn, "Websocket pull failed; closing connection");
  9179. break;
  9180. }
  9181. conn->data_len = conn->request_len;
  9182. } else {
  9183. mop = buf[0]; /* current mask and opcode, overwritten by
  9184. * memmove() */
  9185. /* Length of the message being read at the front of the
  9186. * queue */
  9187. len = data_len + header_len;
  9188. /* Copy the data payload into the data pointer for the
  9189. * callback */
  9190. memcpy(data, buf + header_len, data_len);
  9191. /* Move the queue forward len bytes */
  9192. memmove(buf, buf + len, body_len - len);
  9193. /* Mark the queue as advanced */
  9194. conn->data_len -= (int)len;
  9195. }
  9196. /* Apply mask if necessary */
  9197. if (mask_len > 0) {
  9198. for (i = 0; i < data_len; ++i) {
  9199. data[i] ^= mask[i & 3];
  9200. }
  9201. }
  9202. /* Exit the loop if callback signals to exit (server side),
  9203. * or "connection close" opcode received (client side). */
  9204. exit_by_callback = 0;
  9205. if ((ws_data_handler != NULL)
  9206. && !ws_data_handler(
  9207. conn, mop, (char *)data, data_len, callback_data)) {
  9208. exit_by_callback = 1;
  9209. }
  9210. if (data != mem) {
  9211. mg_free(data);
  9212. }
  9213. if (exit_by_callback
  9214. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9215. /* Opcode == 8, connection close */
  9216. break;
  9217. }
  9218. /* Not breaking the loop, process next websocket frame. */
  9219. } else {
  9220. /* Read from the socket into the next available location in the
  9221. * message queue. */
  9222. n = pull_inner(NULL,
  9223. conn,
  9224. conn->buf + conn->data_len,
  9225. conn->buf_size - conn->data_len,
  9226. timeout);
  9227. if (n <= -2) {
  9228. /* Error, no bytes read */
  9229. break;
  9230. }
  9231. if (n > 0) {
  9232. conn->data_len += n;
  9233. } else {
  9234. /* Timeout: should retry */
  9235. /* TODO: get timeout def */
  9236. }
  9237. }
  9238. }
  9239. mg_set_thread_name("worker");
  9240. }
  9241. static int
  9242. mg_websocket_write_exec(struct mg_connection *conn,
  9243. int opcode,
  9244. const char *data,
  9245. size_t dataLen,
  9246. uint32_t masking_key)
  9247. {
  9248. unsigned char header[14];
  9249. size_t headerLen = 1;
  9250. int retval = -1;
  9251. #if defined(__GNUC__) || defined(__MINGW32__)
  9252. /* Disable spurious conversion warning for GCC */
  9253. #pragma GCC diagnostic push
  9254. #pragma GCC diagnostic ignored "-Wconversion"
  9255. #endif
  9256. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  9257. #if defined(__GNUC__) || defined(__MINGW32__)
  9258. #pragma GCC diagnostic pop
  9259. #endif
  9260. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  9261. if (dataLen < 126) {
  9262. /* inline 7-bit length field */
  9263. header[1] = (unsigned char)dataLen;
  9264. headerLen = 2;
  9265. } else if (dataLen <= 0xFFFF) {
  9266. /* 16-bit length field */
  9267. uint16_t len = htons((uint16_t)dataLen);
  9268. header[1] = 126;
  9269. memcpy(header + 2, &len, 2);
  9270. headerLen = 4;
  9271. } else {
  9272. /* 64-bit length field */
  9273. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  9274. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  9275. header[1] = 127;
  9276. memcpy(header + 2, &len1, 4);
  9277. memcpy(header + 6, &len2, 4);
  9278. headerLen = 10;
  9279. }
  9280. if (masking_key) {
  9281. /* add mask */
  9282. header[1] |= 0x80;
  9283. memcpy(header + headerLen, &masking_key, 4);
  9284. headerLen += 4;
  9285. }
  9286. /* Note that POSIX/Winsock's send() is threadsafe
  9287. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  9288. * but mongoose's mg_printf/mg_write is not (because of the loop in
  9289. * push(), although that is only a problem if the packet is large or
  9290. * outgoing buffer is full). */
  9291. /* TODO: Check if this lock should be moved to user land.
  9292. * Currently the server sets this lock for websockets, but
  9293. * not for any other connection. It must be set for every
  9294. * conn read/written by more than one thread, no matter if
  9295. * it is a websocket or regular connection. */
  9296. (void)mg_lock_connection(conn);
  9297. retval = mg_write(conn, header, headerLen);
  9298. if (dataLen > 0) {
  9299. retval = mg_write(conn, data, dataLen);
  9300. }
  9301. /* TODO: Remove this unlock as well, when lock is moved. */
  9302. mg_unlock_connection(conn);
  9303. return retval;
  9304. }
  9305. int
  9306. mg_websocket_write(struct mg_connection *conn,
  9307. int opcode,
  9308. const char *data,
  9309. size_t dataLen)
  9310. {
  9311. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  9312. }
  9313. static void
  9314. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  9315. {
  9316. size_t i = 0;
  9317. i = 0;
  9318. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  9319. /* Convert in 32 bit words, if data is 4 byte aligned */
  9320. while (i < (in_len - 3)) {
  9321. *(uint32_t *)(void *)(out + i) =
  9322. *(uint32_t *)(void *)(in + i) ^ masking_key;
  9323. i += 4;
  9324. }
  9325. }
  9326. if (i != in_len) {
  9327. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  9328. while (i < in_len) {
  9329. *(uint8_t *)(void *)(out + i) =
  9330. *(uint8_t *)(void *)(in + i)
  9331. ^ *(((uint8_t *)&masking_key) + (i % 4));
  9332. i++;
  9333. }
  9334. }
  9335. }
  9336. int
  9337. mg_websocket_client_write(struct mg_connection *conn,
  9338. int opcode,
  9339. const char *data,
  9340. size_t dataLen)
  9341. {
  9342. int retval = -1;
  9343. char *masked_data =
  9344. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  9345. uint32_t masking_key = (uint32_t)get_random();
  9346. if (masked_data == NULL) {
  9347. /* Return -1 in an error case */
  9348. mg_cry(conn,
  9349. "Cannot allocate buffer for masked websocket response: "
  9350. "Out of memory");
  9351. return -1;
  9352. }
  9353. mask_data(data, dataLen, masking_key, masked_data);
  9354. retval = mg_websocket_write_exec(
  9355. conn, opcode, masked_data, dataLen, masking_key);
  9356. mg_free(masked_data);
  9357. return retval;
  9358. }
  9359. static void
  9360. handle_websocket_request(struct mg_connection *conn,
  9361. const char *path,
  9362. int is_callback_resource,
  9363. struct mg_websocket_subprotocols *subprotocols,
  9364. mg_websocket_connect_handler ws_connect_handler,
  9365. mg_websocket_ready_handler ws_ready_handler,
  9366. mg_websocket_data_handler ws_data_handler,
  9367. mg_websocket_close_handler ws_close_handler,
  9368. void *cbData)
  9369. {
  9370. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  9371. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  9372. int lua_websock = 0;
  9373. #if !defined(USE_LUA)
  9374. (void)path;
  9375. #endif
  9376. /* Step 1: Check websocket protocol version. */
  9377. /* Step 1.1: Check Sec-WebSocket-Key. */
  9378. if (!websock_key) {
  9379. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  9380. * requires a Sec-WebSocket-Key header.
  9381. */
  9382. /* It could be the hixie draft version
  9383. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  9384. */
  9385. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  9386. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  9387. char key3[8];
  9388. if ((key1 != NULL) && (key2 != NULL)) {
  9389. /* This version uses 8 byte body data in a GET request */
  9390. conn->content_len = 8;
  9391. if (8 == mg_read(conn, key3, 8)) {
  9392. /* This is the hixie version */
  9393. mg_send_http_error(conn,
  9394. 426,
  9395. "%s",
  9396. "Protocol upgrade to RFC 6455 required");
  9397. return;
  9398. }
  9399. }
  9400. /* This is an unknown version */
  9401. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  9402. return;
  9403. }
  9404. /* Step 1.2: Check websocket protocol version. */
  9405. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  9406. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  9407. /* Reject wrong versions */
  9408. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  9409. return;
  9410. }
  9411. /* Step 1.3: Could check for "Host", but we do not really nead this
  9412. * value for anything, so just ignore it. */
  9413. /* Step 2: If a callback is responsible, call it. */
  9414. if (is_callback_resource) {
  9415. /* Step 2.1 check and select subprotocol */
  9416. const char *protocols[64]; // max 64 headers
  9417. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  9418. "Sec-WebSocket-Protocol",
  9419. protocols,
  9420. 64);
  9421. if ((nbSubprotocolHeader > 0) && subprotocols) {
  9422. int cnt = 0;
  9423. int idx;
  9424. unsigned long len;
  9425. const char *sep, *curSubProtocol,
  9426. *acceptedWebSocketSubprotocol = NULL;
  9427. /* look for matching subprotocol */
  9428. do {
  9429. const char *protocol = protocols[cnt];
  9430. do {
  9431. sep = strchr(protocol, ',');
  9432. curSubProtocol = protocol;
  9433. len = sep ? (unsigned long)(sep - protocol)
  9434. : (unsigned long)strlen(protocol);
  9435. while (sep && isspace(*++sep))
  9436. ; // ignore leading whitespaces
  9437. protocol = sep;
  9438. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  9439. if ((strlen(subprotocols->subprotocols[idx]) == len)
  9440. && (strncmp(curSubProtocol,
  9441. subprotocols->subprotocols[idx],
  9442. len) == 0)) {
  9443. acceptedWebSocketSubprotocol =
  9444. subprotocols->subprotocols[idx];
  9445. break;
  9446. }
  9447. }
  9448. } while (sep && !acceptedWebSocketSubprotocol);
  9449. } while (++cnt < nbSubprotocolHeader
  9450. && !acceptedWebSocketSubprotocol);
  9451. conn->request_info.acceptedWebSocketSubprotocol =
  9452. acceptedWebSocketSubprotocol;
  9453. } else if (nbSubprotocolHeader > 0) {
  9454. /* keep legacy behavior */
  9455. const char *protocol = protocols[0];
  9456. /* The protocol is a comma separated list of names. */
  9457. /* The server must only return one value from this list. */
  9458. /* First check if it is a list or just a single value. */
  9459. const char *sep = strrchr(protocol, ',');
  9460. if (sep == NULL) {
  9461. /* Just a single protocol -> accept it. */
  9462. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  9463. } else {
  9464. /* Multiple protocols -> accept the last one. */
  9465. /* This is just a quick fix if the client offers multiple
  9466. * protocols. The handler should have a list of accepted
  9467. * protocols on his own
  9468. * and use it to select one protocol among those the client has
  9469. * offered.
  9470. */
  9471. while (isspace(*++sep)) {
  9472. ; /* ignore leading whitespaces */
  9473. }
  9474. conn->request_info.acceptedWebSocketSubprotocol = sep;
  9475. }
  9476. }
  9477. if ((ws_connect_handler != NULL)
  9478. && (ws_connect_handler(conn, cbData) != 0)) {
  9479. /* C callback has returned non-zero, do not proceed with
  9480. * handshake.
  9481. */
  9482. /* Note that C callbacks are no longer called when Lua is
  9483. * responsible, so C can no longer filter callbacks for Lua. */
  9484. return;
  9485. }
  9486. }
  9487. #if defined(USE_LUA)
  9488. /* Step 3: No callback. Check if Lua is responsible. */
  9489. else {
  9490. /* Step 3.1: Check if Lua is responsible. */
  9491. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  9492. lua_websock =
  9493. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  9494. strlen(
  9495. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  9496. path);
  9497. }
  9498. if (lua_websock) {
  9499. /* Step 3.2: Lua is responsible: call it. */
  9500. conn->lua_websocket_state = lua_websocket_new(path, conn);
  9501. if (!conn->lua_websocket_state) {
  9502. /* Lua rejected the new client */
  9503. return;
  9504. }
  9505. }
  9506. }
  9507. #endif
  9508. /* Step 4: Check if there is a responsible websocket handler. */
  9509. if (!is_callback_resource && !lua_websock) {
  9510. /* There is no callback, and Lua is not responsible either. */
  9511. /* Reply with a 404 Not Found. We are still at a standard
  9512. * HTTP request here, before the websocket handshake, so
  9513. * we can still send standard HTTP error replies. */
  9514. mg_send_http_error(conn, 404, "%s", "Not found");
  9515. return;
  9516. }
  9517. /* Step 5: The websocket connection has been accepted */
  9518. if (!send_websocket_handshake(conn, websock_key)) {
  9519. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  9520. return;
  9521. }
  9522. /* Step 6: Call the ready handler */
  9523. if (is_callback_resource) {
  9524. if (ws_ready_handler != NULL) {
  9525. ws_ready_handler(conn, cbData);
  9526. }
  9527. #if defined(USE_LUA)
  9528. } else if (lua_websock) {
  9529. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9530. /* the ready handler returned false */
  9531. return;
  9532. }
  9533. #endif
  9534. }
  9535. /* Step 7: Enter the read loop */
  9536. if (is_callback_resource) {
  9537. read_websocket(conn, ws_data_handler, cbData);
  9538. #if defined(USE_LUA)
  9539. } else if (lua_websock) {
  9540. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9541. #endif
  9542. }
  9543. /* Step 8: Call the close handler */
  9544. if (ws_close_handler) {
  9545. ws_close_handler(conn, cbData);
  9546. }
  9547. }
  9548. static int
  9549. is_websocket_protocol(const struct mg_connection *conn)
  9550. {
  9551. const char *upgrade, *connection;
  9552. /* A websocket protocoll has the following HTTP headers:
  9553. *
  9554. * Connection: Upgrade
  9555. * Upgrade: Websocket
  9556. */
  9557. upgrade = mg_get_header(conn, "Upgrade");
  9558. if (upgrade == NULL) {
  9559. return 0; /* fail early, don't waste time checking other header
  9560. * fields
  9561. */
  9562. }
  9563. if (!mg_strcasestr(upgrade, "websocket")) {
  9564. return 0;
  9565. }
  9566. connection = mg_get_header(conn, "Connection");
  9567. if (connection == NULL) {
  9568. return 0;
  9569. }
  9570. if (!mg_strcasestr(connection, "upgrade")) {
  9571. return 0;
  9572. }
  9573. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9574. * "Sec-WebSocket-Version" are also required.
  9575. * Don't check them here, since even an unsupported websocket protocol
  9576. * request still IS a websocket request (in contrast to a standard HTTP
  9577. * request). It will fail later in handle_websocket_request.
  9578. */
  9579. return 1;
  9580. }
  9581. #endif /* !USE_WEBSOCKET */
  9582. static int
  9583. isbyte(int n)
  9584. {
  9585. return (n >= 0) && (n <= 255);
  9586. }
  9587. static int
  9588. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9589. {
  9590. int n, a, b, c, d, slash = 32, len = 0;
  9591. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  9592. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  9593. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  9594. && (slash < 33)) {
  9595. len = n;
  9596. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9597. | (uint32_t)d;
  9598. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9599. }
  9600. return len;
  9601. }
  9602. static int
  9603. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9604. {
  9605. int throttle = 0;
  9606. struct vec vec, val;
  9607. uint32_t net, mask;
  9608. char mult;
  9609. double v;
  9610. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9611. mult = ',';
  9612. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9613. || (v < 0) || ((lowercase(&mult) != 'k')
  9614. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9615. continue;
  9616. }
  9617. v *= (lowercase(&mult) == 'k')
  9618. ? 1024
  9619. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9620. if (vec.len == 1 && vec.ptr[0] == '*') {
  9621. throttle = (int)v;
  9622. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9623. if ((remote_ip & mask) == net) {
  9624. throttle = (int)v;
  9625. }
  9626. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9627. throttle = (int)v;
  9628. }
  9629. }
  9630. return throttle;
  9631. }
  9632. static uint32_t
  9633. get_remote_ip(const struct mg_connection *conn)
  9634. {
  9635. if (!conn) {
  9636. return 0;
  9637. }
  9638. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9639. }
  9640. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9641. #include "handle_form.inl"
  9642. #if defined(MG_LEGACY_INTERFACE)
  9643. /* Implement the deprecated mg_upload function by calling the new
  9644. * mg_handle_form_request function. While mg_upload could only handle
  9645. * HTML forms sent as POST request in multipart/form-data format
  9646. * containing only file input elements, mg_handle_form_request can
  9647. * handle all form input elements and all standard request methods. */
  9648. struct mg_upload_user_data {
  9649. struct mg_connection *conn;
  9650. const char *destination_dir;
  9651. int num_uploaded_files;
  9652. };
  9653. /* Helper function for deprecated mg_upload. */
  9654. static int
  9655. mg_upload_field_found(const char *key,
  9656. const char *filename,
  9657. char *path,
  9658. size_t pathlen,
  9659. void *user_data)
  9660. {
  9661. int truncated = 0;
  9662. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9663. (void)key;
  9664. if (!filename) {
  9665. mg_cry(fud->conn, "%s: No filename set", __func__);
  9666. return FORM_FIELD_STORAGE_ABORT;
  9667. }
  9668. mg_snprintf(fud->conn,
  9669. &truncated,
  9670. path,
  9671. pathlen - 1,
  9672. "%s/%s",
  9673. fud->destination_dir,
  9674. filename);
  9675. if (!truncated) {
  9676. mg_cry(fud->conn, "%s: File path too long", __func__);
  9677. return FORM_FIELD_STORAGE_ABORT;
  9678. }
  9679. return FORM_FIELD_STORAGE_STORE;
  9680. }
  9681. /* Helper function for deprecated mg_upload. */
  9682. static int
  9683. mg_upload_field_get(const char *key,
  9684. const char *value,
  9685. size_t value_size,
  9686. void *user_data)
  9687. {
  9688. /* Function should never be called */
  9689. (void)key;
  9690. (void)value;
  9691. (void)value_size;
  9692. (void)user_data;
  9693. return 0;
  9694. }
  9695. /* Helper function for deprecated mg_upload. */
  9696. static int
  9697. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9698. {
  9699. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9700. (void)file_size;
  9701. fud->num_uploaded_files++;
  9702. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9703. return 0;
  9704. }
  9705. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9706. int
  9707. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9708. {
  9709. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9710. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9711. mg_upload_field_get,
  9712. mg_upload_field_stored,
  9713. 0};
  9714. int ret;
  9715. fdh.user_data = (void *)&fud;
  9716. ret = mg_handle_form_request(conn, &fdh);
  9717. if (ret < 0) {
  9718. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9719. }
  9720. return fud.num_uploaded_files;
  9721. }
  9722. #endif
  9723. static int
  9724. get_first_ssl_listener_index(const struct mg_context *ctx)
  9725. {
  9726. unsigned int i;
  9727. int idx = -1;
  9728. if (ctx) {
  9729. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  9730. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9731. }
  9732. }
  9733. return idx;
  9734. }
  9735. static void
  9736. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9737. {
  9738. char host[1025];
  9739. const char *host_header;
  9740. size_t hostlen;
  9741. host_header = mg_get_header(conn, "Host");
  9742. hostlen = sizeof(host);
  9743. if (host_header != NULL) {
  9744. char *pos;
  9745. mg_strlcpy(host, host_header, hostlen);
  9746. host[hostlen - 1] = '\0';
  9747. pos = strchr(host, ':');
  9748. if (pos != NULL) {
  9749. *pos = '\0';
  9750. }
  9751. } else {
  9752. /* Cannot get host from the Host: header.
  9753. * Fallback to our IP address. */
  9754. if (conn) {
  9755. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9756. }
  9757. }
  9758. /* Send host, port, uri and (if it exists) ?query_string */
  9759. if (conn) {
  9760. mg_printf(conn,
  9761. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9762. host,
  9763. #if defined(USE_IPV6)
  9764. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9765. == AF_INET6)
  9766. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9767. .lsa.sin6.sin6_port)
  9768. :
  9769. #endif
  9770. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9771. .lsa.sin.sin_port),
  9772. conn->request_info.local_uri,
  9773. (conn->request_info.query_string == NULL) ? "" : "?",
  9774. (conn->request_info.query_string == NULL)
  9775. ? ""
  9776. : conn->request_info.query_string);
  9777. }
  9778. }
  9779. static void
  9780. mg_set_handler_type(struct mg_context *ctx,
  9781. const char *uri,
  9782. int handler_type,
  9783. int is_delete_request,
  9784. mg_request_handler handler,
  9785. struct mg_websocket_subprotocols *subprotocols,
  9786. mg_websocket_connect_handler connect_handler,
  9787. mg_websocket_ready_handler ready_handler,
  9788. mg_websocket_data_handler data_handler,
  9789. mg_websocket_close_handler close_handler,
  9790. mg_authorization_handler auth_handler,
  9791. void *cbdata)
  9792. {
  9793. struct mg_handler_info *tmp_rh, **lastref;
  9794. size_t urilen = strlen(uri);
  9795. if (handler_type == WEBSOCKET_HANDLER) {
  9796. /* assert(handler == NULL); */
  9797. /* assert(is_delete_request || connect_handler!=NULL ||
  9798. * ready_handler!=NULL || data_handler!=NULL ||
  9799. * close_handler!=NULL);
  9800. */
  9801. /* assert(auth_handler == NULL); */
  9802. if (handler != NULL) {
  9803. return;
  9804. }
  9805. if (!is_delete_request && (connect_handler == NULL)
  9806. && (ready_handler == NULL) && (data_handler == NULL)
  9807. && (close_handler == NULL)) {
  9808. return;
  9809. }
  9810. if (auth_handler != NULL) {
  9811. return;
  9812. }
  9813. } else if (handler_type == REQUEST_HANDLER) {
  9814. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9815. * data_handler==NULL && close_handler==NULL); */
  9816. /* assert(is_delete_request || (handler!=NULL));
  9817. */
  9818. /* assert(auth_handler == NULL); */
  9819. if ((connect_handler != NULL) || (ready_handler != NULL)
  9820. || (data_handler != NULL) || (close_handler != NULL)) {
  9821. return;
  9822. }
  9823. if (!is_delete_request && (handler == NULL)) {
  9824. return;
  9825. }
  9826. if (auth_handler != NULL) {
  9827. return;
  9828. }
  9829. } else { /* AUTH_HANDLER */
  9830. /* assert(handler == NULL); */
  9831. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9832. * data_handler==NULL && close_handler==NULL); */
  9833. /* assert(auth_handler != NULL); */
  9834. if (handler != NULL) {
  9835. return;
  9836. }
  9837. if ((connect_handler != NULL) || (ready_handler != NULL)
  9838. || (data_handler != NULL) || (close_handler != NULL)) {
  9839. return;
  9840. }
  9841. if (!is_delete_request && (auth_handler == NULL)) {
  9842. return;
  9843. }
  9844. }
  9845. if (!ctx) {
  9846. return;
  9847. }
  9848. mg_lock_context(ctx);
  9849. /* first try to find an existing handler */
  9850. lastref = &(ctx->handlers);
  9851. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9852. if (tmp_rh->handler_type == handler_type) {
  9853. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  9854. if (!is_delete_request) {
  9855. /* update existing handler */
  9856. if (handler_type == REQUEST_HANDLER) {
  9857. tmp_rh->handler = handler;
  9858. } else if (handler_type == WEBSOCKET_HANDLER) {
  9859. tmp_rh->subprotocols = subprotocols;
  9860. tmp_rh->connect_handler = connect_handler;
  9861. tmp_rh->ready_handler = ready_handler;
  9862. tmp_rh->data_handler = data_handler;
  9863. tmp_rh->close_handler = close_handler;
  9864. } else { /* AUTH_HANDLER */
  9865. tmp_rh->auth_handler = auth_handler;
  9866. }
  9867. tmp_rh->cbdata = cbdata;
  9868. } else {
  9869. /* remove existing handler */
  9870. *lastref = tmp_rh->next;
  9871. mg_free(tmp_rh->uri);
  9872. mg_free(tmp_rh);
  9873. }
  9874. mg_unlock_context(ctx);
  9875. return;
  9876. }
  9877. }
  9878. lastref = &(tmp_rh->next);
  9879. }
  9880. if (is_delete_request) {
  9881. /* no handler to set, this was a remove request to a non-existing
  9882. * handler */
  9883. mg_unlock_context(ctx);
  9884. return;
  9885. }
  9886. tmp_rh =
  9887. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  9888. 1,
  9889. ctx);
  9890. if (tmp_rh == NULL) {
  9891. mg_unlock_context(ctx);
  9892. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9893. return;
  9894. }
  9895. tmp_rh->uri = mg_strdup(uri);
  9896. if (!tmp_rh->uri) {
  9897. mg_unlock_context(ctx);
  9898. mg_free(tmp_rh);
  9899. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9900. return;
  9901. }
  9902. tmp_rh->uri_len = urilen;
  9903. if (handler_type == REQUEST_HANDLER) {
  9904. tmp_rh->handler = handler;
  9905. } else if (handler_type == WEBSOCKET_HANDLER) {
  9906. tmp_rh->subprotocols = subprotocols;
  9907. tmp_rh->connect_handler = connect_handler;
  9908. tmp_rh->ready_handler = ready_handler;
  9909. tmp_rh->data_handler = data_handler;
  9910. tmp_rh->close_handler = close_handler;
  9911. } else { /* AUTH_HANDLER */
  9912. tmp_rh->auth_handler = auth_handler;
  9913. }
  9914. tmp_rh->cbdata = cbdata;
  9915. tmp_rh->handler_type = handler_type;
  9916. tmp_rh->next = NULL;
  9917. *lastref = tmp_rh;
  9918. mg_unlock_context(ctx);
  9919. }
  9920. void
  9921. mg_set_request_handler(struct mg_context *ctx,
  9922. const char *uri,
  9923. mg_request_handler handler,
  9924. void *cbdata)
  9925. {
  9926. mg_set_handler_type(ctx,
  9927. uri,
  9928. REQUEST_HANDLER,
  9929. handler == NULL,
  9930. handler,
  9931. NULL,
  9932. NULL,
  9933. NULL,
  9934. NULL,
  9935. NULL,
  9936. NULL,
  9937. cbdata);
  9938. }
  9939. void
  9940. mg_set_websocket_handler(struct mg_context *ctx,
  9941. const char *uri,
  9942. mg_websocket_connect_handler connect_handler,
  9943. mg_websocket_ready_handler ready_handler,
  9944. mg_websocket_data_handler data_handler,
  9945. mg_websocket_close_handler close_handler,
  9946. void *cbdata)
  9947. {
  9948. mg_set_websocket_handler_with_subprotocols(ctx,
  9949. uri,
  9950. NULL,
  9951. connect_handler,
  9952. ready_handler,
  9953. data_handler,
  9954. close_handler,
  9955. cbdata);
  9956. }
  9957. void
  9958. mg_set_websocket_handler_with_subprotocols(
  9959. struct mg_context *ctx,
  9960. const char *uri,
  9961. struct mg_websocket_subprotocols *subprotocols,
  9962. mg_websocket_connect_handler connect_handler,
  9963. mg_websocket_ready_handler ready_handler,
  9964. mg_websocket_data_handler data_handler,
  9965. mg_websocket_close_handler close_handler,
  9966. void *cbdata)
  9967. {
  9968. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9969. && (data_handler == NULL)
  9970. && (close_handler == NULL);
  9971. mg_set_handler_type(ctx,
  9972. uri,
  9973. WEBSOCKET_HANDLER,
  9974. is_delete_request,
  9975. NULL,
  9976. subprotocols,
  9977. connect_handler,
  9978. ready_handler,
  9979. data_handler,
  9980. close_handler,
  9981. NULL,
  9982. cbdata);
  9983. }
  9984. void
  9985. mg_set_auth_handler(struct mg_context *ctx,
  9986. const char *uri,
  9987. mg_request_handler handler,
  9988. void *cbdata)
  9989. {
  9990. mg_set_handler_type(ctx,
  9991. uri,
  9992. AUTH_HANDLER,
  9993. handler == NULL,
  9994. NULL,
  9995. NULL,
  9996. NULL,
  9997. NULL,
  9998. NULL,
  9999. NULL,
  10000. handler,
  10001. cbdata);
  10002. }
  10003. static int
  10004. get_request_handler(struct mg_connection *conn,
  10005. int handler_type,
  10006. mg_request_handler *handler,
  10007. struct mg_websocket_subprotocols **subprotocols,
  10008. mg_websocket_connect_handler *connect_handler,
  10009. mg_websocket_ready_handler *ready_handler,
  10010. mg_websocket_data_handler *data_handler,
  10011. mg_websocket_close_handler *close_handler,
  10012. mg_authorization_handler *auth_handler,
  10013. void **cbdata)
  10014. {
  10015. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10016. if (request_info) {
  10017. const char *uri = request_info->local_uri;
  10018. size_t urilen = strlen(uri);
  10019. struct mg_handler_info *tmp_rh;
  10020. if (!conn || !conn->ctx) {
  10021. return 0;
  10022. }
  10023. mg_lock_context(conn->ctx);
  10024. /* first try for an exact match */
  10025. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10026. tmp_rh = tmp_rh->next) {
  10027. if (tmp_rh->handler_type == handler_type) {
  10028. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10029. if (handler_type == WEBSOCKET_HANDLER) {
  10030. *subprotocols = tmp_rh->subprotocols;
  10031. *connect_handler = tmp_rh->connect_handler;
  10032. *ready_handler = tmp_rh->ready_handler;
  10033. *data_handler = tmp_rh->data_handler;
  10034. *close_handler = tmp_rh->close_handler;
  10035. } else if (handler_type == REQUEST_HANDLER) {
  10036. *handler = tmp_rh->handler;
  10037. } else { /* AUTH_HANDLER */
  10038. *auth_handler = tmp_rh->auth_handler;
  10039. }
  10040. *cbdata = tmp_rh->cbdata;
  10041. mg_unlock_context(conn->ctx);
  10042. return 1;
  10043. }
  10044. }
  10045. }
  10046. /* next try for a partial match, we will accept uri/something */
  10047. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10048. tmp_rh = tmp_rh->next) {
  10049. if (tmp_rh->handler_type == handler_type) {
  10050. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10051. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  10052. if (handler_type == WEBSOCKET_HANDLER) {
  10053. *subprotocols = tmp_rh->subprotocols;
  10054. *connect_handler = tmp_rh->connect_handler;
  10055. *ready_handler = tmp_rh->ready_handler;
  10056. *data_handler = tmp_rh->data_handler;
  10057. *close_handler = tmp_rh->close_handler;
  10058. } else if (handler_type == REQUEST_HANDLER) {
  10059. *handler = tmp_rh->handler;
  10060. } else { /* AUTH_HANDLER */
  10061. *auth_handler = tmp_rh->auth_handler;
  10062. }
  10063. *cbdata = tmp_rh->cbdata;
  10064. mg_unlock_context(conn->ctx);
  10065. return 1;
  10066. }
  10067. }
  10068. }
  10069. /* finally try for pattern match */
  10070. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10071. tmp_rh = tmp_rh->next) {
  10072. if (tmp_rh->handler_type == handler_type) {
  10073. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10074. if (handler_type == WEBSOCKET_HANDLER) {
  10075. *subprotocols = tmp_rh->subprotocols;
  10076. *connect_handler = tmp_rh->connect_handler;
  10077. *ready_handler = tmp_rh->ready_handler;
  10078. *data_handler = tmp_rh->data_handler;
  10079. *close_handler = tmp_rh->close_handler;
  10080. } else if (handler_type == REQUEST_HANDLER) {
  10081. *handler = tmp_rh->handler;
  10082. } else { /* AUTH_HANDLER */
  10083. *auth_handler = tmp_rh->auth_handler;
  10084. }
  10085. *cbdata = tmp_rh->cbdata;
  10086. mg_unlock_context(conn->ctx);
  10087. return 1;
  10088. }
  10089. }
  10090. }
  10091. mg_unlock_context(conn->ctx);
  10092. }
  10093. return 0; /* none found */
  10094. }
  10095. /* Check if the script file is in a path, allowed for script files.
  10096. * This can be used if uploading files is possible not only for the server
  10097. * admin, and the upload mechanism does not check the file extension.
  10098. */
  10099. static int
  10100. is_in_script_path(const struct mg_connection *conn, const char *path)
  10101. {
  10102. /* TODO (Feature): Add config value for allowed script path.
  10103. * Default: All allowed. */
  10104. (void)conn;
  10105. (void)path;
  10106. return 1;
  10107. }
  10108. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10109. static int
  10110. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10111. void *cbdata)
  10112. {
  10113. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10114. if (pcallbacks->websocket_connect) {
  10115. return pcallbacks->websocket_connect(conn);
  10116. }
  10117. /* No handler set - assume "OK" */
  10118. return 0;
  10119. }
  10120. static void
  10121. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10122. {
  10123. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10124. if (pcallbacks->websocket_ready) {
  10125. pcallbacks->websocket_ready(conn);
  10126. }
  10127. }
  10128. static int
  10129. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10130. int bits,
  10131. char *data,
  10132. size_t len,
  10133. void *cbdata)
  10134. {
  10135. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10136. if (pcallbacks->websocket_data) {
  10137. return pcallbacks->websocket_data(conn, bits, data, len);
  10138. }
  10139. /* No handler set - assume "OK" */
  10140. return 1;
  10141. }
  10142. #endif
  10143. /* This is the heart of the Civetweb's logic.
  10144. * This function is called when the request is read, parsed and validated,
  10145. * and Civetweb must decide what action to take: serve a file, or
  10146. * a directory, or call embedded function, etcetera. */
  10147. static void
  10148. handle_request(struct mg_connection *conn)
  10149. {
  10150. struct mg_request_info *ri = &conn->request_info;
  10151. char path[PATH_MAX];
  10152. int uri_len, ssl_index;
  10153. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  10154. is_put_or_delete_request = 0, is_callback_resource = 0;
  10155. int i;
  10156. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10157. mg_request_handler callback_handler = NULL;
  10158. struct mg_websocket_subprotocols *subprotocols;
  10159. mg_websocket_connect_handler ws_connect_handler = NULL;
  10160. mg_websocket_ready_handler ws_ready_handler = NULL;
  10161. mg_websocket_data_handler ws_data_handler = NULL;
  10162. mg_websocket_close_handler ws_close_handler = NULL;
  10163. void *callback_data = NULL;
  10164. mg_authorization_handler auth_handler = NULL;
  10165. void *auth_callback_data = NULL;
  10166. int handler_type;
  10167. time_t curtime = time(NULL);
  10168. char date[64];
  10169. path[0] = 0;
  10170. /* 1. get the request url */
  10171. /* 1.1. split into url and query string */
  10172. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  10173. != NULL) {
  10174. *((char *)conn->request_info.query_string++) = '\0';
  10175. }
  10176. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  10177. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  10178. ssl_index = get_first_ssl_listener_index(conn->ctx);
  10179. if (ssl_index >= 0) {
  10180. redirect_to_https_port(conn, ssl_index);
  10181. } else {
  10182. /* A http to https forward port has been specified,
  10183. * but no https port to forward to. */
  10184. mg_send_http_error(conn,
  10185. 503,
  10186. "%s",
  10187. "Error: SSL forward not configured properly");
  10188. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  10189. }
  10190. return;
  10191. }
  10192. uri_len = (int)strlen(ri->local_uri);
  10193. /* 1.3. decode url (if config says so) */
  10194. if (should_decode_url(conn)) {
  10195. mg_url_decode(
  10196. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  10197. }
  10198. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  10199. * not possible */
  10200. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  10201. /* step 1. completed, the url is known now */
  10202. uri_len = (int)strlen(ri->local_uri);
  10203. DEBUG_TRACE("URL: %s", ri->local_uri);
  10204. /* 2. if this ip has limited speed, set it for this connection */
  10205. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  10206. get_remote_ip(conn),
  10207. ri->local_uri);
  10208. /* 3. call a "handle everything" callback, if registered */
  10209. if (conn->ctx->callbacks.begin_request != NULL) {
  10210. /* Note that since V1.7 the "begin_request" function is called
  10211. * before an authorization check. If an authorization check is
  10212. * required, use a request_handler instead. */
  10213. i = conn->ctx->callbacks.begin_request(conn);
  10214. if (i > 0) {
  10215. /* callback already processed the request. Store the
  10216. return value as a status code for the access log. */
  10217. conn->status_code = i;
  10218. discard_unread_request_data(conn);
  10219. return;
  10220. } else if (i == 0) {
  10221. /* civetweb should process the request */
  10222. } else {
  10223. /* unspecified - may change with the next version */
  10224. return;
  10225. }
  10226. }
  10227. /* request not yet handled by a handler or redirect, so the request
  10228. * is processed here */
  10229. /* 4. Check for CORS preflight requests and handle them (if configured).
  10230. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  10231. */
  10232. if (!strcmp(ri->request_method, "OPTIONS")) {
  10233. /* Send a response to CORS preflights only if
  10234. * access_control_allow_methods is not NULL and not an empty string.
  10235. * In this case, scripts can still handle CORS. */
  10236. const char *cors_meth_cfg =
  10237. conn->ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  10238. const char *cors_orig_cfg =
  10239. conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10240. const char *cors_origin =
  10241. get_header(ri->http_headers, ri->num_headers, "Origin");
  10242. const char *cors_acrm = get_header(ri->http_headers,
  10243. ri->num_headers,
  10244. "Access-Control-Request-Method");
  10245. /* Todo: check if cors_origin is in cors_orig_cfg.
  10246. * Or, let the client check this. */
  10247. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  10248. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  10249. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  10250. /* This is a valid CORS preflight, and the server is configured to
  10251. * handle it automatically. */
  10252. const char *cors_acrh =
  10253. get_header(ri->http_headers,
  10254. ri->num_headers,
  10255. "Access-Control-Request-Headers");
  10256. gmt_time_string(date, sizeof(date), &curtime);
  10257. mg_printf(conn,
  10258. "HTTP/1.1 200 OK\r\n"
  10259. "Date: %s\r\n"
  10260. "Access-Control-Allow-Origin: %s\r\n"
  10261. "Access-Control-Allow-Methods: %s\r\n"
  10262. "Content-Length: 0\r\n"
  10263. "Connection: %s\r\n",
  10264. date,
  10265. cors_orig_cfg,
  10266. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  10267. suggest_connection_header(conn));
  10268. if (cors_acrh != NULL) {
  10269. /* CORS request is asking for additional headers */
  10270. const char *cors_hdr_cfg =
  10271. conn->ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  10272. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  10273. /* Allow only if access_control_allow_headers is
  10274. * not NULL and not an empty string. If this
  10275. * configuration is set to *, allow everything.
  10276. * Otherwise this configuration must be a list
  10277. * of allowed HTTP header names. */
  10278. mg_printf(conn,
  10279. "Access-Control-Allow-Headers: %s\r\n",
  10280. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  10281. : cors_hdr_cfg));
  10282. }
  10283. }
  10284. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  10285. mg_printf(conn, "\r\n");
  10286. return;
  10287. }
  10288. }
  10289. /* 5. interpret the url to find out how the request must be handled
  10290. */
  10291. /* 5.1. first test, if the request targets the regular http(s)://
  10292. * protocol namespace or the websocket ws(s):// protocol namespace.
  10293. */
  10294. is_websocket_request = is_websocket_protocol(conn);
  10295. #if defined(USE_WEBSOCKET)
  10296. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  10297. #else
  10298. handler_type = REQUEST_HANDLER;
  10299. #endif /* defined(USE_WEBSOCKET) */
  10300. /* 5.2. check if the request will be handled by a callback */
  10301. if (get_request_handler(conn,
  10302. handler_type,
  10303. &callback_handler,
  10304. &subprotocols,
  10305. &ws_connect_handler,
  10306. &ws_ready_handler,
  10307. &ws_data_handler,
  10308. &ws_close_handler,
  10309. NULL,
  10310. &callback_data)) {
  10311. /* 5.2.1. A callback will handle this request. All requests
  10312. * handled
  10313. * by a callback have to be considered as requests to a script
  10314. * resource. */
  10315. is_callback_resource = 1;
  10316. is_script_resource = 1;
  10317. is_put_or_delete_request = is_put_or_delete_method(conn);
  10318. } else {
  10319. no_callback_resource:
  10320. /* 5.2.2. No callback is responsible for this request. The URI
  10321. * addresses a file based resource (static content or Lua/cgi
  10322. * scripts in the file system). */
  10323. is_callback_resource = 0;
  10324. interpret_uri(conn,
  10325. path,
  10326. sizeof(path),
  10327. &file.stat,
  10328. &is_found,
  10329. &is_script_resource,
  10330. &is_websocket_request,
  10331. &is_put_or_delete_request);
  10332. }
  10333. /* 6. authorization check */
  10334. /* 6.1. a custom authorization handler is installed */
  10335. if (get_request_handler(conn,
  10336. AUTH_HANDLER,
  10337. NULL,
  10338. NULL,
  10339. NULL,
  10340. NULL,
  10341. NULL,
  10342. NULL,
  10343. &auth_handler,
  10344. &auth_callback_data)) {
  10345. if (!auth_handler(conn, auth_callback_data)) {
  10346. return;
  10347. }
  10348. } else if (is_put_or_delete_request && !is_script_resource
  10349. && !is_callback_resource) {
  10350. /* 6.2. this request is a PUT/DELETE to a real file */
  10351. /* 6.2.1. thus, the server must have real files */
  10352. #if defined(NO_FILES)
  10353. if (1) {
  10354. #else
  10355. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10356. #endif
  10357. /* This server does not have any real files, thus the
  10358. * PUT/DELETE methods are not valid. */
  10359. mg_send_http_error(conn,
  10360. 405,
  10361. "%s method not allowed",
  10362. conn->request_info.request_method);
  10363. return;
  10364. }
  10365. #if !defined(NO_FILES)
  10366. /* 6.2.2. Check if put authorization for static files is
  10367. * available.
  10368. */
  10369. if (!is_authorized_for_put(conn)) {
  10370. send_authorization_request(conn);
  10371. return;
  10372. }
  10373. #endif
  10374. } else {
  10375. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  10376. * or it is a PUT or DELETE request to a resource that does not
  10377. * correspond to a file. Check authorization. */
  10378. if (!check_authorization(conn, path)) {
  10379. send_authorization_request(conn);
  10380. return;
  10381. }
  10382. }
  10383. /* request is authorized or does not need authorization */
  10384. /* 7. check if there are request handlers for this uri */
  10385. if (is_callback_resource) {
  10386. if (!is_websocket_request) {
  10387. i = callback_handler(conn, callback_data);
  10388. if (i > 0) {
  10389. /* Do nothing, callback has served the request. Store
  10390. * then return value as status code for the log and discard
  10391. * all data from the client not used by the callback. */
  10392. conn->status_code = i;
  10393. discard_unread_request_data(conn);
  10394. } else {
  10395. /* The handler did NOT handle the request. */
  10396. /* Some proper reactions would be:
  10397. * a) close the connections without sending anything
  10398. * b) send a 404 not found
  10399. * c) try if there is a file matching the URI
  10400. * It would be possible to do a, b or c in the callback
  10401. * implementation, and return 1 - we cannot do anything
  10402. * here, that is not possible in the callback.
  10403. *
  10404. * TODO: What would be the best reaction here?
  10405. * (Note: The reaction may change, if there is a better idea.)
  10406. */
  10407. /* For the moment, use option c: We look for a proper file,
  10408. * but since a file request is not always a script resource,
  10409. * the authorization check might be different. */
  10410. interpret_uri(conn,
  10411. path,
  10412. sizeof(path),
  10413. &file.stat,
  10414. &is_found,
  10415. &is_script_resource,
  10416. &is_websocket_request,
  10417. &is_put_or_delete_request);
  10418. callback_handler = NULL;
  10419. /* Here we are at a dead end:
  10420. * According to URI matching, a callback should be
  10421. * responsible for handling the request,
  10422. * we called it, but the callback declared itself
  10423. * not responsible.
  10424. * We use a goto here, to get out of this dead end,
  10425. * and continue with the default handling.
  10426. * A goto here is simpler and better to understand
  10427. * than some curious loop. */
  10428. goto no_callback_resource;
  10429. }
  10430. } else {
  10431. #if defined(USE_WEBSOCKET)
  10432. handle_websocket_request(conn,
  10433. path,
  10434. is_callback_resource,
  10435. subprotocols,
  10436. ws_connect_handler,
  10437. ws_ready_handler,
  10438. ws_data_handler,
  10439. ws_close_handler,
  10440. callback_data);
  10441. #endif
  10442. }
  10443. return;
  10444. }
  10445. /* 8. handle websocket requests */
  10446. #if defined(USE_WEBSOCKET)
  10447. if (is_websocket_request) {
  10448. if (is_script_resource) {
  10449. if (is_in_script_path(conn, path)) {
  10450. /* Websocket Lua script */
  10451. handle_websocket_request(conn,
  10452. path,
  10453. 0 /* Lua Script */,
  10454. NULL,
  10455. NULL,
  10456. NULL,
  10457. NULL,
  10458. NULL,
  10459. &conn->ctx->callbacks);
  10460. } else {
  10461. /* Script was in an illegal path */
  10462. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10463. }
  10464. } else {
  10465. #if defined(MG_LEGACY_INTERFACE)
  10466. handle_websocket_request(
  10467. conn,
  10468. path,
  10469. !is_script_resource /* could be deprecated global callback */,
  10470. NULL,
  10471. deprecated_websocket_connect_wrapper,
  10472. deprecated_websocket_ready_wrapper,
  10473. deprecated_websocket_data_wrapper,
  10474. NULL,
  10475. &conn->ctx->callbacks);
  10476. #else
  10477. mg_send_http_error(conn, 404, "%s", "Not found");
  10478. #endif
  10479. }
  10480. return;
  10481. } else
  10482. #endif
  10483. #if defined(NO_FILES)
  10484. /* 9a. In case the server uses only callbacks, this uri is
  10485. * unknown.
  10486. * Then, all request handling ends here. */
  10487. mg_send_http_error(conn, 404, "%s", "Not Found");
  10488. #else
  10489. /* 9b. This request is either for a static file or resource handled
  10490. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  10491. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10492. mg_send_http_error(conn, 404, "%s", "Not Found");
  10493. return;
  10494. }
  10495. /* 10. Request is handled by a script */
  10496. if (is_script_resource) {
  10497. handle_file_based_request(conn, path, &file);
  10498. return;
  10499. }
  10500. /* 11. Handle put/delete/mkcol requests */
  10501. if (is_put_or_delete_request) {
  10502. /* 11.1. PUT method */
  10503. if (!strcmp(ri->request_method, "PUT")) {
  10504. put_file(conn, path);
  10505. return;
  10506. }
  10507. /* 11.2. DELETE method */
  10508. if (!strcmp(ri->request_method, "DELETE")) {
  10509. delete_file(conn, path);
  10510. return;
  10511. }
  10512. /* 11.3. MKCOL method */
  10513. if (!strcmp(ri->request_method, "MKCOL")) {
  10514. mkcol(conn, path);
  10515. return;
  10516. }
  10517. /* 11.4. PATCH method
  10518. * This method is not supported for static resources,
  10519. * only for scripts (Lua, CGI) and callbacks. */
  10520. mg_send_http_error(conn,
  10521. 405,
  10522. "%s method not allowed",
  10523. conn->request_info.request_method);
  10524. return;
  10525. }
  10526. /* 11. File does not exist, or it was configured that it should be
  10527. * hidden */
  10528. if (!is_found || (must_hide_file(conn, path))) {
  10529. mg_send_http_error(conn, 404, "%s", "Not found");
  10530. return;
  10531. }
  10532. /* 12. Directory uris should end with a slash */
  10533. if (file.stat.is_directory && (uri_len > 0)
  10534. && (ri->local_uri[uri_len - 1] != '/')) {
  10535. gmt_time_string(date, sizeof(date), &curtime);
  10536. mg_printf(conn,
  10537. "HTTP/1.1 301 Moved Permanently\r\n"
  10538. "Location: %s/\r\n"
  10539. "Date: %s\r\n"
  10540. /* "Cache-Control: private\r\n" (= default) */
  10541. "Content-Length: 0\r\n"
  10542. "Connection: %s\r\n",
  10543. ri->request_uri,
  10544. date,
  10545. suggest_connection_header(conn));
  10546. send_additional_header(conn);
  10547. mg_printf(conn, "\r\n");
  10548. return;
  10549. }
  10550. /* 13. Handle other methods than GET/HEAD */
  10551. /* 13.1. Handle PROPFIND */
  10552. if (!strcmp(ri->request_method, "PROPFIND")) {
  10553. handle_propfind(conn, path, &file.stat);
  10554. return;
  10555. }
  10556. /* 13.2. Handle OPTIONS for files */
  10557. if (!strcmp(ri->request_method, "OPTIONS")) {
  10558. /* This standard handler is only used for real files.
  10559. * Scripts should support the OPTIONS method themselves, to allow a
  10560. * maximum flexibility.
  10561. * Lua and CGI scripts may fully support CORS this way (including
  10562. * preflights). */
  10563. send_options(conn);
  10564. return;
  10565. }
  10566. /* 13.3. everything but GET and HEAD (e.g. POST) */
  10567. if ((0 != strcmp(ri->request_method, "GET"))
  10568. && (0 != strcmp(ri->request_method, "HEAD"))) {
  10569. mg_send_http_error(conn,
  10570. 405,
  10571. "%s method not allowed",
  10572. conn->request_info.request_method);
  10573. return;
  10574. }
  10575. /* 14. directories */
  10576. if (file.stat.is_directory) {
  10577. /* Substitute files have already been handled above. */
  10578. /* Here we can either generate and send a directory listing,
  10579. * or send an "access denied" error. */
  10580. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  10581. "yes")) {
  10582. handle_directory_request(conn, path);
  10583. } else {
  10584. mg_send_http_error(conn,
  10585. 403,
  10586. "%s",
  10587. "Error: Directory listing denied");
  10588. }
  10589. return;
  10590. }
  10591. handle_file_based_request(conn, path, &file);
  10592. #endif /* !defined(NO_FILES) */
  10593. #if 0
  10594. /* Perform redirect and auth checks before calling begin_request()
  10595. * handler.
  10596. * Otherwise, begin_request() would need to perform auth checks and
  10597. * redirects. */
  10598. #endif
  10599. }
  10600. static void
  10601. handle_file_based_request(struct mg_connection *conn,
  10602. const char *path,
  10603. struct mg_file *file)
  10604. {
  10605. if (!conn || !conn->ctx) {
  10606. return;
  10607. }
  10608. if (0) {
  10609. #ifdef USE_LUA
  10610. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10611. strlen(
  10612. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10613. path) > 0) {
  10614. if (is_in_script_path(conn, path)) {
  10615. /* Lua server page: an SSI like page containing mostly plain html
  10616. * code
  10617. * plus some tags with server generated contents. */
  10618. handle_lsp_request(conn, path, file, NULL);
  10619. } else {
  10620. /* Script was in an illegal path */
  10621. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10622. }
  10623. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10624. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10625. path) > 0) {
  10626. if (is_in_script_path(conn, path)) {
  10627. /* Lua in-server module script: a CGI like script used to generate
  10628. * the
  10629. * entire reply. */
  10630. mg_exec_lua_script(conn, path, NULL);
  10631. } else {
  10632. /* Script was in an illegal path */
  10633. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10634. }
  10635. #endif
  10636. #if defined(USE_DUKTAPE)
  10637. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10638. strlen(
  10639. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10640. path) > 0) {
  10641. if (is_in_script_path(conn, path)) {
  10642. /* Call duktape to generate the page */
  10643. mg_exec_duktape_script(conn, path);
  10644. } else {
  10645. /* Script was in an illegal path */
  10646. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10647. }
  10648. #endif
  10649. #if !defined(NO_CGI)
  10650. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10651. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10652. path) > 0) {
  10653. if (is_in_script_path(conn, path)) {
  10654. /* CGI scripts may support all HTTP methods */
  10655. handle_cgi_request(conn, path);
  10656. } else {
  10657. /* Script was in an illegal path */
  10658. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10659. }
  10660. #endif /* !NO_CGI */
  10661. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10662. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10663. path) > 0) {
  10664. if (is_in_script_path(conn, path)) {
  10665. handle_ssi_file_request(conn, path, file);
  10666. } else {
  10667. /* Script was in an illegal path */
  10668. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10669. }
  10670. #if !defined(NO_CACHING)
  10671. } else if ((!conn->in_error_handler)
  10672. && is_not_modified(conn, &file->stat)) {
  10673. /* Send 304 "Not Modified" - this must not send any body data */
  10674. handle_not_modified_static_file_request(conn, file);
  10675. #endif /* !NO_CACHING */
  10676. } else {
  10677. handle_static_file_request(conn, path, file, NULL, NULL);
  10678. }
  10679. }
  10680. static void
  10681. close_all_listening_sockets(struct mg_context *ctx)
  10682. {
  10683. unsigned int i;
  10684. if (!ctx) {
  10685. return;
  10686. }
  10687. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10688. closesocket(ctx->listening_sockets[i].sock);
  10689. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10690. }
  10691. mg_free(ctx->listening_sockets);
  10692. ctx->listening_sockets = NULL;
  10693. mg_free(ctx->listening_socket_fds);
  10694. ctx->listening_socket_fds = NULL;
  10695. }
  10696. /* Valid listening port specification is: [ip_address:]port[s]
  10697. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10698. * Examples for IPv6: [::]:80, [::1]:80,
  10699. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10700. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10701. * In order to bind to both, IPv4 and IPv6, you can either add
  10702. * both ports using 8080,[::]:8080, or the short form +8080.
  10703. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10704. * one only accepting IPv4 the other only IPv6. +8080 creates
  10705. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10706. * environment, they might work differently, or might not work
  10707. * at all - it must be tested what options work best in the
  10708. * relevant network environment.
  10709. */
  10710. static int
  10711. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10712. {
  10713. unsigned int a, b, c, d, port;
  10714. int ch, len;
  10715. char *cb;
  10716. #if defined(USE_IPV6)
  10717. char buf[100] = {0};
  10718. #endif
  10719. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10720. * Also, all-zeroes in the socket address means binding to all addresses
  10721. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10722. memset(so, 0, sizeof(*so));
  10723. so->lsa.sin.sin_family = AF_INET;
  10724. *ip_version = 0;
  10725. /* Initialize port and len as invalid. */
  10726. port = 0;
  10727. len = 0;
  10728. /* Test for different ways to format this string */
  10729. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10730. == 5) {
  10731. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10732. so->lsa.sin.sin_addr.s_addr =
  10733. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10734. so->lsa.sin.sin_port = htons((uint16_t)port);
  10735. *ip_version = 4;
  10736. #if defined(USE_IPV6)
  10737. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10738. && mg_inet_pton(
  10739. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10740. /* IPv6 address, examples: see above */
  10741. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10742. */
  10743. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10744. *ip_version = 6;
  10745. #endif
  10746. } else if ((vec->ptr[0] == '+')
  10747. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10748. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10749. /* Add 1 to len for the + character we skipped before */
  10750. len++;
  10751. #if defined(USE_IPV6)
  10752. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10753. so->lsa.sin6.sin6_family = AF_INET6;
  10754. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10755. *ip_version = 4 + 6;
  10756. #else
  10757. /* Bind to IPv4 only, since IPv6 is not built in. */
  10758. so->lsa.sin.sin_port = htons((uint16_t)port);
  10759. *ip_version = 4;
  10760. #endif
  10761. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10762. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10763. so->lsa.sin.sin_port = htons((uint16_t)port);
  10764. *ip_version = 4;
  10765. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  10766. /* Could be a hostname */
  10767. /* Will only work for RFC 952 compliant hostnames,
  10768. * starting with a letter, containing only letters,
  10769. * digits and hyphen ('-'). Newer specs may allow
  10770. * more, but this is not guaranteed here, since it
  10771. * may interfere with rules for port option lists. */
  10772. *cb = 0;
  10773. if (mg_inet_pton(
  10774. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  10775. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  10776. *ip_version = 4;
  10777. so->lsa.sin.sin_family = AF_INET;
  10778. so->lsa.sin.sin_port = htons((uint16_t)port);
  10779. len += (int)(cb - vec->ptr) + 1;
  10780. } else {
  10781. port = 0;
  10782. len = 0;
  10783. }
  10784. #if defined(USE_IPV6)
  10785. } else if (mg_inet_pton(AF_INET6,
  10786. vec->ptr,
  10787. &so->lsa.sin6,
  10788. sizeof(so->lsa.sin6))) {
  10789. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  10790. *ip_version = 6;
  10791. so->lsa.sin6.sin6_family = AF_INET6;
  10792. so->lsa.sin.sin_port = htons((uint16_t)port);
  10793. len += (int)(cb - vec->ptr) + 1;
  10794. } else {
  10795. port = 0;
  10796. len = 0;
  10797. }
  10798. #endif
  10799. }
  10800. *cb = ':';
  10801. } else {
  10802. /* Parsing failure. */
  10803. }
  10804. /* sscanf and the option splitting code ensure the following condition
  10805. */
  10806. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  10807. *ip_version = 0;
  10808. return 0;
  10809. }
  10810. ch = vec->ptr[len]; /* Next character after the port number */
  10811. so->is_ssl = (ch == 's');
  10812. so->ssl_redir = (ch == 'r');
  10813. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  10814. if (is_valid_port(port)
  10815. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  10816. return 1;
  10817. }
  10818. /* Reset ip_version to 0 of there is an error */
  10819. *ip_version = 0;
  10820. return 0;
  10821. }
  10822. static int
  10823. set_ports_option(struct mg_context *ctx)
  10824. {
  10825. const char *list;
  10826. int on = 1;
  10827. #if defined(USE_IPV6)
  10828. int off = 0;
  10829. #endif
  10830. struct vec vec;
  10831. struct socket so, *ptr;
  10832. struct pollfd *pfd;
  10833. union usa usa;
  10834. socklen_t len;
  10835. int ip_version;
  10836. int portsTotal = 0;
  10837. int portsOk = 0;
  10838. if (!ctx) {
  10839. return 0;
  10840. }
  10841. memset(&so, 0, sizeof(so));
  10842. memset(&usa, 0, sizeof(usa));
  10843. len = sizeof(usa);
  10844. list = ctx->config[LISTENING_PORTS];
  10845. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10846. portsTotal++;
  10847. if (!parse_port_string(&vec, &so, &ip_version)) {
  10848. mg_cry(fc(ctx),
  10849. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  10850. (int)vec.len,
  10851. vec.ptr,
  10852. portsTotal,
  10853. "[IP_ADDRESS:]PORT[s|r]");
  10854. continue;
  10855. }
  10856. #if !defined(NO_SSL)
  10857. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10858. mg_cry(fc(ctx),
  10859. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10860. "option set?",
  10861. portsTotal);
  10862. continue;
  10863. }
  10864. #endif
  10865. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10866. == INVALID_SOCKET) {
  10867. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10868. continue;
  10869. }
  10870. #ifdef _WIN32
  10871. /* Windows SO_REUSEADDR lets many procs binds to a
  10872. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10873. * if someone already has the socket -- DTL */
  10874. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10875. * Windows might need a few seconds before
  10876. * the same port can be used again in the
  10877. * same process, so a short Sleep may be
  10878. * required between mg_stop and mg_start.
  10879. */
  10880. if (setsockopt(so.sock,
  10881. SOL_SOCKET,
  10882. SO_EXCLUSIVEADDRUSE,
  10883. (SOCK_OPT_TYPE)&on,
  10884. sizeof(on)) != 0) {
  10885. /* Set reuse option, but don't abort on errors. */
  10886. mg_cry(fc(ctx),
  10887. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10888. portsTotal);
  10889. }
  10890. #else
  10891. if (setsockopt(so.sock,
  10892. SOL_SOCKET,
  10893. SO_REUSEADDR,
  10894. (SOCK_OPT_TYPE)&on,
  10895. sizeof(on)) != 0) {
  10896. /* Set reuse option, but don't abort on errors. */
  10897. mg_cry(fc(ctx),
  10898. "cannot set socket option SO_REUSEADDR (entry %i)",
  10899. portsTotal);
  10900. }
  10901. #endif
  10902. if (ip_version > 4) {
  10903. #if defined(USE_IPV6)
  10904. if (ip_version == 6) {
  10905. if (so.lsa.sa.sa_family == AF_INET6
  10906. && setsockopt(so.sock,
  10907. IPPROTO_IPV6,
  10908. IPV6_V6ONLY,
  10909. (void *)&off,
  10910. sizeof(off)) != 0) {
  10911. /* Set IPv6 only option, but don't abort on errors. */
  10912. mg_cry(fc(ctx),
  10913. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10914. portsTotal);
  10915. }
  10916. }
  10917. #else
  10918. mg_cry(fc(ctx), "IPv6 not available");
  10919. closesocket(so.sock);
  10920. so.sock = INVALID_SOCKET;
  10921. continue;
  10922. #endif
  10923. }
  10924. if (so.lsa.sa.sa_family == AF_INET) {
  10925. len = sizeof(so.lsa.sin);
  10926. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10927. mg_cry(fc(ctx),
  10928. "cannot bind to %.*s: %d (%s)",
  10929. (int)vec.len,
  10930. vec.ptr,
  10931. (int)ERRNO,
  10932. strerror(errno));
  10933. closesocket(so.sock);
  10934. so.sock = INVALID_SOCKET;
  10935. continue;
  10936. }
  10937. }
  10938. #if defined(USE_IPV6)
  10939. else if (so.lsa.sa.sa_family == AF_INET6) {
  10940. len = sizeof(so.lsa.sin6);
  10941. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10942. mg_cry(fc(ctx),
  10943. "cannot bind to IPv6 %.*s: %d (%s)",
  10944. (int)vec.len,
  10945. vec.ptr,
  10946. (int)ERRNO,
  10947. strerror(errno));
  10948. closesocket(so.sock);
  10949. so.sock = INVALID_SOCKET;
  10950. continue;
  10951. }
  10952. }
  10953. #endif
  10954. else {
  10955. mg_cry(fc(ctx),
  10956. "cannot bind: address family not supported (entry %i)",
  10957. portsTotal);
  10958. closesocket(so.sock);
  10959. so.sock = INVALID_SOCKET;
  10960. continue;
  10961. }
  10962. if (listen(so.sock, SOMAXCONN) != 0) {
  10963. mg_cry(fc(ctx),
  10964. "cannot listen to %.*s: %d (%s)",
  10965. (int)vec.len,
  10966. vec.ptr,
  10967. (int)ERRNO,
  10968. strerror(errno));
  10969. closesocket(so.sock);
  10970. so.sock = INVALID_SOCKET;
  10971. continue;
  10972. }
  10973. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  10974. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  10975. int err = (int)ERRNO;
  10976. mg_cry(fc(ctx),
  10977. "call to getsockname failed %.*s: %d (%s)",
  10978. (int)vec.len,
  10979. vec.ptr,
  10980. err,
  10981. strerror(errno));
  10982. closesocket(so.sock);
  10983. so.sock = INVALID_SOCKET;
  10984. continue;
  10985. }
  10986. /* Update lsa port in case of random free ports */
  10987. #if defined(USE_IPV6)
  10988. if (so.lsa.sa.sa_family == AF_INET6) {
  10989. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10990. } else
  10991. #endif
  10992. {
  10993. so.lsa.sin.sin_port = usa.sin.sin_port;
  10994. }
  10995. if ((ptr = (struct socket *)
  10996. mg_realloc_ctx(ctx->listening_sockets,
  10997. (ctx->num_listening_sockets + 1)
  10998. * sizeof(ctx->listening_sockets[0]),
  10999. ctx)) == NULL) {
  11000. mg_cry(fc(ctx), "%s", "Out of memory");
  11001. closesocket(so.sock);
  11002. so.sock = INVALID_SOCKET;
  11003. continue;
  11004. }
  11005. if ((pfd = (struct pollfd *)
  11006. mg_realloc_ctx(ctx->listening_socket_fds,
  11007. (ctx->num_listening_sockets + 1)
  11008. * sizeof(ctx->listening_socket_fds[0]),
  11009. ctx)) == NULL) {
  11010. mg_cry(fc(ctx), "%s", "Out of memory");
  11011. closesocket(so.sock);
  11012. so.sock = INVALID_SOCKET;
  11013. mg_free(ptr);
  11014. continue;
  11015. }
  11016. set_close_on_exec(so.sock, fc(ctx));
  11017. ctx->listening_sockets = ptr;
  11018. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  11019. ctx->listening_socket_fds = pfd;
  11020. ctx->num_listening_sockets++;
  11021. portsOk++;
  11022. }
  11023. if (portsOk != portsTotal) {
  11024. close_all_listening_sockets(ctx);
  11025. portsOk = 0;
  11026. }
  11027. return portsOk;
  11028. }
  11029. static const char *
  11030. header_val(const struct mg_connection *conn, const char *header)
  11031. {
  11032. const char *header_value;
  11033. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11034. return "-";
  11035. } else {
  11036. return header_value;
  11037. }
  11038. }
  11039. static void
  11040. log_access(const struct mg_connection *conn)
  11041. {
  11042. const struct mg_request_info *ri;
  11043. struct mg_file fi;
  11044. char date[64], src_addr[IP_ADDR_STR_LEN];
  11045. struct tm *tm;
  11046. const char *referer;
  11047. const char *user_agent;
  11048. char buf[4096];
  11049. if (!conn || !conn->ctx) {
  11050. return;
  11051. }
  11052. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  11053. if (mg_fopen(conn,
  11054. conn->ctx->config[ACCESS_LOG_FILE],
  11055. MG_FOPEN_MODE_APPEND,
  11056. &fi) == 0) {
  11057. fi.access.fp = NULL;
  11058. }
  11059. } else {
  11060. fi.access.fp = NULL;
  11061. }
  11062. /* Log is written to a file and/or a callback. If both are not set,
  11063. * executing the rest of the function is pointless. */
  11064. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  11065. return;
  11066. }
  11067. tm = localtime(&conn->conn_birth_time);
  11068. if (tm != NULL) {
  11069. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11070. } else {
  11071. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11072. date[sizeof(date) - 1] = '\0';
  11073. }
  11074. ri = &conn->request_info;
  11075. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11076. referer = header_val(conn, "Referer");
  11077. user_agent = header_val(conn, "User-Agent");
  11078. mg_snprintf(conn,
  11079. NULL, /* Ignore truncation in access log */
  11080. buf,
  11081. sizeof(buf),
  11082. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11083. src_addr,
  11084. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11085. date,
  11086. ri->request_method ? ri->request_method : "-",
  11087. ri->request_uri ? ri->request_uri : "-",
  11088. ri->query_string ? "?" : "",
  11089. ri->query_string ? ri->query_string : "",
  11090. ri->http_version,
  11091. conn->status_code,
  11092. conn->num_bytes_sent,
  11093. referer,
  11094. user_agent);
  11095. if (conn->ctx->callbacks.log_access) {
  11096. conn->ctx->callbacks.log_access(conn, buf);
  11097. }
  11098. if (fi.access.fp) {
  11099. int ok = 1;
  11100. flockfile(fi.access.fp);
  11101. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11102. ok = 0;
  11103. }
  11104. if (fflush(fi.access.fp) != 0) {
  11105. ok = 0;
  11106. }
  11107. funlockfile(fi.access.fp);
  11108. if (mg_fclose(&fi.access) != 0) {
  11109. ok = 0;
  11110. }
  11111. if (!ok) {
  11112. mg_cry(conn,
  11113. "Error writing log file %s",
  11114. conn->ctx->config[ACCESS_LOG_FILE]);
  11115. }
  11116. }
  11117. }
  11118. /* Verify given socket address against the ACL.
  11119. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  11120. */
  11121. static int
  11122. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  11123. {
  11124. int allowed, flag;
  11125. uint32_t net, mask;
  11126. struct vec vec;
  11127. if (ctx) {
  11128. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  11129. /* If any ACL is set, deny by default */
  11130. allowed = (list == NULL) ? '+' : '-';
  11131. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11132. flag = vec.ptr[0];
  11133. if ((flag != '+' && flag != '-')
  11134. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  11135. mg_cry(fc(ctx),
  11136. "%s: subnet must be [+|-]x.x.x.x[/x]",
  11137. __func__);
  11138. return -1;
  11139. }
  11140. if (net == (remote_ip & mask)) {
  11141. allowed = flag;
  11142. }
  11143. }
  11144. return allowed == '+';
  11145. }
  11146. return -1;
  11147. }
  11148. #if !defined(_WIN32)
  11149. static int
  11150. set_uid_option(struct mg_context *ctx)
  11151. {
  11152. struct passwd *pw;
  11153. if (ctx) {
  11154. const char *uid = ctx->config[RUN_AS_USER];
  11155. int success = 0;
  11156. if (uid == NULL) {
  11157. success = 1;
  11158. } else {
  11159. if ((pw = getpwnam(uid)) == NULL) {
  11160. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  11161. } else if (setgid(pw->pw_gid) == -1) {
  11162. mg_cry(fc(ctx),
  11163. "%s: setgid(%s): %s",
  11164. __func__,
  11165. uid,
  11166. strerror(errno));
  11167. } else if (setgroups(0, NULL)) {
  11168. mg_cry(fc(ctx),
  11169. "%s: setgroups(): %s",
  11170. __func__,
  11171. strerror(errno));
  11172. } else if (setuid(pw->pw_uid) == -1) {
  11173. mg_cry(fc(ctx),
  11174. "%s: setuid(%s): %s",
  11175. __func__,
  11176. uid,
  11177. strerror(errno));
  11178. } else {
  11179. success = 1;
  11180. }
  11181. }
  11182. return success;
  11183. }
  11184. return 0;
  11185. }
  11186. #endif /* !_WIN32 */
  11187. static void
  11188. tls_dtor(void *key)
  11189. {
  11190. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  11191. /* key == pthread_getspecific(sTlsKey); */
  11192. if (tls) {
  11193. if (tls->is_master == 2) {
  11194. tls->is_master = -3; /* Mark memory as dead */
  11195. mg_free(tls);
  11196. }
  11197. }
  11198. pthread_setspecific(sTlsKey, NULL);
  11199. }
  11200. #if !defined(NO_SSL)
  11201. static int
  11202. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  11203. static const char *ssl_error(void);
  11204. static int
  11205. refresh_trust(struct mg_connection *conn)
  11206. {
  11207. static int reload_lock = 0;
  11208. static long int data_check = 0;
  11209. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  11210. struct stat cert_buf;
  11211. long int t;
  11212. const char *pem;
  11213. const char *chain;
  11214. int should_verify_peer;
  11215. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  11216. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  11217. * refresh_trust still can not work. */
  11218. return 0;
  11219. }
  11220. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  11221. if (chain == NULL) {
  11222. /* pem is not NULL here */
  11223. chain = pem;
  11224. }
  11225. if (*chain == 0) {
  11226. chain = NULL;
  11227. }
  11228. t = data_check;
  11229. if (stat(pem, &cert_buf) != -1) {
  11230. t = (long int)cert_buf.st_mtime;
  11231. }
  11232. if (data_check != t) {
  11233. data_check = t;
  11234. should_verify_peer = 0;
  11235. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11236. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  11237. == 0) {
  11238. should_verify_peer = 1;
  11239. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  11240. "optional") == 0) {
  11241. should_verify_peer = 1;
  11242. }
  11243. }
  11244. if (should_verify_peer) {
  11245. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  11246. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  11247. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  11248. ca_file,
  11249. ca_path) != 1) {
  11250. mg_cry(fc(conn->ctx),
  11251. "SSL_CTX_load_verify_locations error: %s "
  11252. "ssl_verify_peer requires setting "
  11253. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11254. "present in "
  11255. "the .conf file?",
  11256. ssl_error());
  11257. return 0;
  11258. }
  11259. }
  11260. if (1 == mg_atomic_inc(p_reload_lock)) {
  11261. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  11262. return 0;
  11263. }
  11264. *p_reload_lock = 0;
  11265. }
  11266. }
  11267. /* lock while cert is reloading */
  11268. while (*p_reload_lock) {
  11269. sleep(1);
  11270. }
  11271. return 1;
  11272. }
  11273. #ifdef OPENSSL_API_1_1
  11274. #else
  11275. static pthread_mutex_t *ssl_mutexes;
  11276. #endif /* OPENSSL_API_1_1 */
  11277. static int
  11278. sslize(struct mg_connection *conn,
  11279. SSL_CTX *s,
  11280. int (*func)(SSL *),
  11281. volatile int *stop_server)
  11282. {
  11283. int ret, err;
  11284. int short_trust;
  11285. unsigned i;
  11286. if (!conn) {
  11287. return 0;
  11288. }
  11289. short_trust =
  11290. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  11291. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  11292. if (short_trust) {
  11293. int trust_ret = refresh_trust(conn);
  11294. if (!trust_ret) {
  11295. return trust_ret;
  11296. }
  11297. }
  11298. conn->ssl = SSL_new(s);
  11299. if (conn->ssl == NULL) {
  11300. return 0;
  11301. }
  11302. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  11303. if (ret != 1) {
  11304. err = SSL_get_error(conn->ssl, ret);
  11305. (void)err; /* TODO: set some error message */
  11306. SSL_free(conn->ssl);
  11307. conn->ssl = NULL;
  11308. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11309. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11310. #ifndef OPENSSL_API_1_1
  11311. ERR_remove_state(0);
  11312. #endif
  11313. return 0;
  11314. }
  11315. /* SSL functions may fail and require to be called again:
  11316. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  11317. * Here "func" could be SSL_connect or SSL_accept. */
  11318. for (i = 16; i <= 1024; i *= 2) {
  11319. ret = func(conn->ssl);
  11320. if (ret != 1) {
  11321. err = SSL_get_error(conn->ssl, ret);
  11322. if ((err == SSL_ERROR_WANT_CONNECT)
  11323. || (err == SSL_ERROR_WANT_ACCEPT)
  11324. || (err == SSL_ERROR_WANT_READ)
  11325. || (err == SSL_ERROR_WANT_WRITE)) {
  11326. /* Need to retry the function call "later".
  11327. * See https://linux.die.net/man/3/ssl_get_error
  11328. * This is typical for non-blocking sockets. */
  11329. if (*stop_server) {
  11330. /* Don't wait if the server is going to be stopped. */
  11331. break;
  11332. }
  11333. mg_sleep(i);
  11334. } else if (err == SSL_ERROR_SYSCALL) {
  11335. /* This is an IO error. Look at errno. */
  11336. err = errno;
  11337. /* TODO: set some error message */
  11338. (void)err;
  11339. break;
  11340. } else {
  11341. /* This is an SSL specific error */
  11342. /* TODO: set some error message */
  11343. break;
  11344. }
  11345. } else {
  11346. /* success */
  11347. break;
  11348. }
  11349. }
  11350. if (ret != 1) {
  11351. SSL_free(conn->ssl);
  11352. conn->ssl = NULL;
  11353. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11354. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11355. #ifndef OPENSSL_API_1_1
  11356. ERR_remove_state(0);
  11357. #endif
  11358. return 0;
  11359. }
  11360. return 1;
  11361. }
  11362. /* Return OpenSSL error message (from CRYPTO lib) */
  11363. static const char *
  11364. ssl_error(void)
  11365. {
  11366. unsigned long err;
  11367. err = ERR_get_error();
  11368. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  11369. }
  11370. static int
  11371. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  11372. {
  11373. int i;
  11374. const char hexdigit[] = "0123456789abcdef";
  11375. if ((memlen <= 0) || (buflen <= 0)) {
  11376. return 0;
  11377. }
  11378. if (buflen < (3 * memlen)) {
  11379. return 0;
  11380. }
  11381. for (i = 0; i < memlen; i++) {
  11382. if (i > 0) {
  11383. buf[3 * i - 1] = ' ';
  11384. }
  11385. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  11386. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  11387. }
  11388. buf[3 * memlen - 1] = 0;
  11389. return 1;
  11390. }
  11391. static void
  11392. ssl_get_client_cert_info(struct mg_connection *conn)
  11393. {
  11394. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  11395. if (cert) {
  11396. char str_subject[1024];
  11397. char str_issuer[1024];
  11398. char str_finger[1024];
  11399. unsigned char buf[256];
  11400. char *str_serial = NULL;
  11401. unsigned int ulen;
  11402. int ilen;
  11403. unsigned char *tmp_buf;
  11404. unsigned char *tmp_p;
  11405. /* Handle to algorithm used for fingerprint */
  11406. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  11407. /* Get Subject and issuer */
  11408. X509_NAME *subj = X509_get_subject_name(cert);
  11409. X509_NAME *iss = X509_get_issuer_name(cert);
  11410. /* Get serial number */
  11411. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  11412. /* Translate serial number to a hex string */
  11413. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  11414. str_serial = BN_bn2hex(serial_bn);
  11415. BN_free(serial_bn);
  11416. /* Translate subject and issuer to a string */
  11417. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  11418. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  11419. /* Calculate SHA1 fingerprint and store as a hex string */
  11420. ulen = 0;
  11421. /* ASN1_digest is deprecated. Do the calculation manually,
  11422. * using EVP_Digest. */
  11423. ilen = i2d_X509((void *)cert, NULL);
  11424. tmp_buf =
  11425. (ilen > 0)
  11426. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  11427. : NULL;
  11428. if (tmp_buf) {
  11429. tmp_p = tmp_buf;
  11430. (void)i2d_X509((void *)cert, &tmp_p);
  11431. if (!EVP_Digest(
  11432. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  11433. ulen = 0;
  11434. }
  11435. mg_free(tmp_buf);
  11436. }
  11437. if (!hexdump2string(
  11438. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  11439. *str_finger = 0;
  11440. }
  11441. conn->request_info.client_cert =
  11442. (struct client_cert *)mg_malloc_ctx(sizeof(struct client_cert),
  11443. conn->ctx);
  11444. if (conn->request_info.client_cert) {
  11445. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  11446. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  11447. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  11448. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  11449. } else {
  11450. mg_cry(
  11451. conn,
  11452. "Out of memory: Cannot allocate memory for client certificate");
  11453. }
  11454. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  11455. * see https://linux.die.net/man/3/bn_bn2hex */
  11456. OPENSSL_free(str_serial);
  11457. /* Free certificate memory */
  11458. X509_free(cert);
  11459. }
  11460. }
  11461. #ifdef OPENSSL_API_1_1
  11462. #else
  11463. static void
  11464. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  11465. {
  11466. (void)line;
  11467. (void)file;
  11468. if (mode & 1) {
  11469. /* 1 is CRYPTO_LOCK */
  11470. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  11471. } else {
  11472. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  11473. }
  11474. }
  11475. #endif /* OPENSSL_API_1_1 */
  11476. #if !defined(NO_SSL_DL)
  11477. static void *
  11478. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  11479. {
  11480. union {
  11481. void *p;
  11482. void (*fp)(void);
  11483. } u;
  11484. void *dll_handle;
  11485. struct ssl_func *fp;
  11486. int ok;
  11487. int truncated = 0;
  11488. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  11489. mg_snprintf(NULL,
  11490. NULL, /* No truncation check for ebuf */
  11491. ebuf,
  11492. ebuf_len,
  11493. "%s: cannot load %s",
  11494. __func__,
  11495. dll_name);
  11496. return NULL;
  11497. }
  11498. ok = 1;
  11499. for (fp = sw; fp->name != NULL; fp++) {
  11500. #ifdef _WIN32
  11501. /* GetProcAddress() returns pointer to function */
  11502. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  11503. #else
  11504. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  11505. * pointers to function pointers. We need to use a union to make a
  11506. * cast. */
  11507. u.p = dlsym(dll_handle, fp->name);
  11508. #endif /* _WIN32 */
  11509. if (u.fp == NULL) {
  11510. if (ok) {
  11511. mg_snprintf(NULL,
  11512. &truncated,
  11513. ebuf,
  11514. ebuf_len,
  11515. "%s: %s: cannot find %s",
  11516. __func__,
  11517. dll_name,
  11518. fp->name);
  11519. ok = 0;
  11520. } else {
  11521. size_t cur_len = strlen(ebuf);
  11522. if (!truncated) {
  11523. mg_snprintf(NULL,
  11524. &truncated,
  11525. ebuf + cur_len,
  11526. ebuf_len - cur_len - 3,
  11527. ", %s",
  11528. fp->name);
  11529. if (truncated) {
  11530. /* If truncated, add "..." */
  11531. strcat(ebuf, "...");
  11532. }
  11533. }
  11534. }
  11535. /* Debug:
  11536. * printf("Missing function: %s\n", fp->name); */
  11537. } else {
  11538. fp->ptr = u.fp;
  11539. }
  11540. }
  11541. if (!ok) {
  11542. (void)dlclose(dll_handle);
  11543. return NULL;
  11544. }
  11545. return dll_handle;
  11546. }
  11547. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  11548. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  11549. #endif /* NO_SSL_DL */
  11550. #if defined(SSL_ALREADY_INITIALIZED)
  11551. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  11552. #else
  11553. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  11554. #endif
  11555. static int
  11556. initialize_ssl(char *ebuf, size_t ebuf_len)
  11557. {
  11558. #ifdef OPENSSL_API_1_1
  11559. if (ebuf_len > 0) {
  11560. ebuf[0] = 0;
  11561. }
  11562. #if !defined(NO_SSL_DL)
  11563. if (!cryptolib_dll_handle) {
  11564. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11565. if (!cryptolib_dll_handle) {
  11566. return 0;
  11567. }
  11568. }
  11569. #endif /* NO_SSL_DL */
  11570. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11571. return 1;
  11572. }
  11573. #else /* not OPENSSL_API_1_1 */
  11574. int i;
  11575. size_t size;
  11576. if (ebuf_len > 0) {
  11577. ebuf[0] = 0;
  11578. }
  11579. #if !defined(NO_SSL_DL)
  11580. if (!cryptolib_dll_handle) {
  11581. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11582. if (!cryptolib_dll_handle) {
  11583. return 0;
  11584. }
  11585. }
  11586. #endif /* NO_SSL_DL */
  11587. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11588. return 1;
  11589. }
  11590. /* Initialize locking callbacks, needed for thread safety.
  11591. * http://www.openssl.org/support/faq.html#PROG1
  11592. */
  11593. i = CRYPTO_num_locks();
  11594. if (i < 0) {
  11595. i = 0;
  11596. }
  11597. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  11598. if (size == 0) {
  11599. ssl_mutexes = NULL;
  11600. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  11601. mg_snprintf(NULL,
  11602. NULL, /* No truncation check for ebuf */
  11603. ebuf,
  11604. ebuf_len,
  11605. "%s: cannot allocate mutexes: %s",
  11606. __func__,
  11607. ssl_error());
  11608. return 0;
  11609. }
  11610. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11611. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  11612. }
  11613. CRYPTO_set_locking_callback(&ssl_locking_callback);
  11614. CRYPTO_set_id_callback(&mg_current_thread_id);
  11615. #endif /* OPENSSL_API_1_1 */
  11616. return 1;
  11617. }
  11618. static int
  11619. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  11620. {
  11621. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  11622. mg_cry(fc(ctx),
  11623. "%s: cannot open certificate file %s: %s",
  11624. __func__,
  11625. pem,
  11626. ssl_error());
  11627. return 0;
  11628. }
  11629. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  11630. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  11631. mg_cry(fc(ctx),
  11632. "%s: cannot open private key file %s: %s",
  11633. __func__,
  11634. pem,
  11635. ssl_error());
  11636. return 0;
  11637. }
  11638. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  11639. mg_cry(fc(ctx),
  11640. "%s: certificate and private key do not match: %s",
  11641. __func__,
  11642. pem);
  11643. return 0;
  11644. }
  11645. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11646. * chain files that contain private keys and certificates in
  11647. * SSL_CTX_use_certificate_chain_file.
  11648. * The CivetWeb-Server used pem-Files that contained both information.
  11649. * In order to make wolfSSL work, it is split in two files.
  11650. * One file that contains key and certificate used by the server and
  11651. * an optional chain file for the ssl stack.
  11652. */
  11653. if (chain) {
  11654. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11655. mg_cry(fc(ctx),
  11656. "%s: cannot use certificate chain file %s: %s",
  11657. __func__,
  11658. pem,
  11659. ssl_error());
  11660. return 0;
  11661. }
  11662. }
  11663. return 1;
  11664. }
  11665. #ifdef OPENSSL_API_1_1
  11666. static unsigned long
  11667. ssl_get_protocol(int version_id)
  11668. {
  11669. long unsigned ret = SSL_OP_ALL;
  11670. if (version_id > 0)
  11671. ret |= SSL_OP_NO_SSLv2;
  11672. if (version_id > 1)
  11673. ret |= SSL_OP_NO_SSLv3;
  11674. if (version_id > 2)
  11675. ret |= SSL_OP_NO_TLSv1;
  11676. if (version_id > 3)
  11677. ret |= SSL_OP_NO_TLSv1_1;
  11678. return ret;
  11679. }
  11680. #else
  11681. static long
  11682. ssl_get_protocol(int version_id)
  11683. {
  11684. long ret = SSL_OP_ALL;
  11685. if (version_id > 0)
  11686. ret |= SSL_OP_NO_SSLv2;
  11687. if (version_id > 1)
  11688. ret |= SSL_OP_NO_SSLv3;
  11689. if (version_id > 2)
  11690. ret |= SSL_OP_NO_TLSv1;
  11691. if (version_id > 3)
  11692. ret |= SSL_OP_NO_TLSv1_1;
  11693. return ret;
  11694. }
  11695. #endif /* OPENSSL_API_1_1 */
  11696. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11697. static int
  11698. set_ssl_option(struct mg_context *ctx)
  11699. {
  11700. const char *pem;
  11701. const char *chain;
  11702. int callback_ret;
  11703. int should_verify_peer;
  11704. int peer_certificate_optional;
  11705. const char *ca_path;
  11706. const char *ca_file;
  11707. int use_default_verify_paths;
  11708. int verify_depth;
  11709. time_t now_rt = time(NULL);
  11710. struct timespec now_mt;
  11711. md5_byte_t ssl_context_id[16];
  11712. md5_state_t md5state;
  11713. int protocol_ver;
  11714. char ebuf[128];
  11715. /* If PEM file is not specified and the init_ssl callback
  11716. * is not specified, skip SSL initialization. */
  11717. if (!ctx) {
  11718. return 0;
  11719. }
  11720. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11721. && ctx->callbacks.init_ssl == NULL) {
  11722. return 1;
  11723. }
  11724. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11725. if (chain == NULL) {
  11726. chain = pem;
  11727. }
  11728. if ((chain != NULL) && (*chain == 0)) {
  11729. chain = NULL;
  11730. }
  11731. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11732. mg_cry(fc(ctx), "%s", ebuf);
  11733. return 0;
  11734. }
  11735. #if !defined(NO_SSL_DL)
  11736. if (!ssllib_dll_handle) {
  11737. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11738. if (!ssllib_dll_handle) {
  11739. mg_cry(fc(ctx), "%s", ebuf);
  11740. return 0;
  11741. }
  11742. }
  11743. #endif /* NO_SSL_DL */
  11744. #ifdef OPENSSL_API_1_1
  11745. /* Initialize SSL library */
  11746. OPENSSL_init_ssl(0, NULL);
  11747. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11748. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11749. NULL);
  11750. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11751. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11752. return 0;
  11753. }
  11754. #else
  11755. /* Initialize SSL library */
  11756. SSL_library_init();
  11757. SSL_load_error_strings();
  11758. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11759. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11760. return 0;
  11761. }
  11762. #endif /* OPENSSL_API_1_1 */
  11763. SSL_CTX_clear_options(ctx->ssl_ctx,
  11764. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11765. | SSL_OP_NO_TLSv1_1);
  11766. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11767. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11768. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11769. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11770. #if !defined(NO_SSL_DL)
  11771. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11772. #endif /* NO_SSL_DL */
  11773. /* If a callback has been specified, call it. */
  11774. callback_ret =
  11775. (ctx->callbacks.init_ssl == NULL)
  11776. ? 0
  11777. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11778. /* If callback returns 0, civetweb sets up the SSL certificate.
  11779. * If it returns 1, civetweb assumes the calback already did this.
  11780. * If it returns -1, initializing ssl fails. */
  11781. if (callback_ret < 0) {
  11782. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11783. return 0;
  11784. }
  11785. if (callback_ret > 0) {
  11786. if (pem != NULL) {
  11787. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11788. }
  11789. return 1;
  11790. }
  11791. /* Use some UID as session context ID. */
  11792. md5_init(&md5state);
  11793. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  11794. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  11795. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  11796. md5_append(&md5state,
  11797. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  11798. strlen(ctx->config[LISTENING_PORTS]));
  11799. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  11800. md5_finish(&md5state, ssl_context_id);
  11801. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  11802. (const unsigned char *)&ssl_context_id,
  11803. sizeof(ssl_context_id));
  11804. if (pem != NULL) {
  11805. if (!ssl_use_pem_file(ctx, pem, chain)) {
  11806. return 0;
  11807. }
  11808. }
  11809. /* Should we support client certificates? */
  11810. /* Default is "no". */
  11811. should_verify_peer = 0;
  11812. peer_certificate_optional = 0;
  11813. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11814. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  11815. /* Yes, they are mandatory */
  11816. should_verify_peer = 1;
  11817. peer_certificate_optional = 0;
  11818. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  11819. == 0) {
  11820. /* Yes, they are optional */
  11821. should_verify_peer = 1;
  11822. peer_certificate_optional = 1;
  11823. }
  11824. }
  11825. use_default_verify_paths =
  11826. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  11827. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  11828. if (should_verify_peer) {
  11829. ca_path = ctx->config[SSL_CA_PATH];
  11830. ca_file = ctx->config[SSL_CA_FILE];
  11831. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  11832. != 1) {
  11833. mg_cry(fc(ctx),
  11834. "SSL_CTX_load_verify_locations error: %s "
  11835. "ssl_verify_peer requires setting "
  11836. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11837. "present in "
  11838. "the .conf file?",
  11839. ssl_error());
  11840. return 0;
  11841. }
  11842. if (peer_certificate_optional) {
  11843. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  11844. } else {
  11845. SSL_CTX_set_verify(ctx->ssl_ctx,
  11846. SSL_VERIFY_PEER
  11847. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11848. NULL);
  11849. }
  11850. if (use_default_verify_paths
  11851. && (SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1)) {
  11852. mg_cry(fc(ctx),
  11853. "SSL_CTX_set_default_verify_paths error: %s",
  11854. ssl_error());
  11855. return 0;
  11856. }
  11857. if (ctx->config[SSL_VERIFY_DEPTH]) {
  11858. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  11859. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  11860. }
  11861. }
  11862. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  11863. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  11864. != 1) {
  11865. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  11866. }
  11867. }
  11868. return 1;
  11869. }
  11870. static void
  11871. uninitialize_ssl(void)
  11872. {
  11873. #ifdef OPENSSL_API_1_1
  11874. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11875. /* Shutdown according to
  11876. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11877. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11878. */
  11879. CONF_modules_unload(1);
  11880. #else
  11881. int i;
  11882. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11883. /* Shutdown according to
  11884. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11885. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11886. */
  11887. CRYPTO_set_locking_callback(NULL);
  11888. CRYPTO_set_id_callback(NULL);
  11889. ENGINE_cleanup();
  11890. CONF_modules_unload(1);
  11891. ERR_free_strings();
  11892. EVP_cleanup();
  11893. CRYPTO_cleanup_all_ex_data();
  11894. ERR_remove_state(0);
  11895. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11896. pthread_mutex_destroy(&ssl_mutexes[i]);
  11897. }
  11898. mg_free(ssl_mutexes);
  11899. ssl_mutexes = NULL;
  11900. #endif /* OPENSSL_API_1_1 */
  11901. }
  11902. }
  11903. #endif /* !NO_SSL */
  11904. static int
  11905. set_gpass_option(struct mg_context *ctx)
  11906. {
  11907. if (ctx) {
  11908. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11909. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  11910. if ((path != NULL) && !mg_stat(fc(ctx), path, &file.stat)) {
  11911. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  11912. return 0;
  11913. }
  11914. return 1;
  11915. }
  11916. return 0;
  11917. }
  11918. static int
  11919. set_acl_option(struct mg_context *ctx)
  11920. {
  11921. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  11922. }
  11923. static void
  11924. reset_per_request_attributes(struct mg_connection *conn)
  11925. {
  11926. if (!conn) {
  11927. return;
  11928. }
  11929. conn->connection_type = 0; /* Not yet a valid request/response */
  11930. conn->path_info = NULL;
  11931. conn->num_bytes_sent = conn->consumed_content = 0;
  11932. conn->status_code = -1;
  11933. conn->is_chunked = 0;
  11934. conn->must_close = 0;
  11935. conn->request_len = 0;
  11936. conn->throttle = 0;
  11937. conn->data_len = 0;
  11938. conn->chunk_remainder = 0;
  11939. conn->response_info.content_length = conn->request_info.content_length = -1;
  11940. conn->response_info.http_version = conn->request_info.http_version = NULL;
  11941. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  11942. conn->response_info.status_text = NULL;
  11943. conn->response_info.status_code = 0;
  11944. conn->request_info.remote_user = NULL;
  11945. conn->request_info.request_method = NULL;
  11946. conn->request_info.request_uri = NULL;
  11947. conn->request_info.local_uri = NULL;
  11948. #if defined(MG_LEGACY_INTERFACE)
  11949. /* Legacy before split into local_uri and request_uri */
  11950. conn->request_info.uri = NULL;
  11951. #endif
  11952. }
  11953. #if 0
  11954. /* Note: set_sock_timeout is not required for non-blocking sockets.
  11955. * Leave this function here (commented out) for reference until
  11956. * CivetWeb 1.9 is tested, and the tests confirme this function is
  11957. * no longer required.
  11958. */
  11959. static int
  11960. set_sock_timeout(SOCKET sock, int milliseconds)
  11961. {
  11962. int r0 = 0, r1, r2;
  11963. #ifdef _WIN32
  11964. /* Windows specific */
  11965. DWORD tv = (DWORD)milliseconds;
  11966. #else
  11967. /* Linux, ... (not Windows) */
  11968. struct timeval tv;
  11969. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  11970. * max. time waiting for the acknowledged of TCP data before the connection
  11971. * will be forcefully closed and ETIMEDOUT is returned to the application.
  11972. * If this option is not set, the default timeout of 20-30 minutes is used.
  11973. */
  11974. /* #define TCP_USER_TIMEOUT (18) */
  11975. #if defined(TCP_USER_TIMEOUT)
  11976. unsigned int uto = (unsigned int)milliseconds;
  11977. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  11978. #endif
  11979. memset(&tv, 0, sizeof(tv));
  11980. tv.tv_sec = milliseconds / 1000;
  11981. tv.tv_usec = (milliseconds * 1000) % 1000000;
  11982. #endif /* _WIN32 */
  11983. r1 = setsockopt(
  11984. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11985. r2 = setsockopt(
  11986. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11987. return r0 || r1 || r2;
  11988. }
  11989. #endif
  11990. static int
  11991. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11992. {
  11993. if (setsockopt(sock,
  11994. IPPROTO_TCP,
  11995. TCP_NODELAY,
  11996. (SOCK_OPT_TYPE)&nodelay_on,
  11997. sizeof(nodelay_on)) != 0) {
  11998. /* Error */
  11999. return 1;
  12000. }
  12001. /* OK */
  12002. return 0;
  12003. }
  12004. static void
  12005. close_socket_gracefully(struct mg_connection *conn)
  12006. {
  12007. #if defined(_WIN32)
  12008. char buf[MG_BUF_LEN];
  12009. int n;
  12010. #endif
  12011. struct linger linger;
  12012. int error_code = 0;
  12013. int linger_timeout = -2;
  12014. socklen_t opt_len = sizeof(error_code);
  12015. if (!conn) {
  12016. return;
  12017. }
  12018. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  12019. * "Note that enabling a nonzero timeout on a nonblocking socket
  12020. * is not recommended.", so set it to blocking now */
  12021. set_blocking_mode(conn->client.sock, 1);
  12022. /* Send FIN to the client */
  12023. shutdown(conn->client.sock, SHUTDOWN_WR);
  12024. #if defined(_WIN32)
  12025. /* Read and discard pending incoming data. If we do not do that and
  12026. * close
  12027. * the socket, the data in the send buffer may be discarded. This
  12028. * behaviour is seen on Windows, when client keeps sending data
  12029. * when server decides to close the connection; then when client
  12030. * does recv() it gets no data back. */
  12031. do {
  12032. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  12033. } while (n > 0);
  12034. #endif
  12035. if (conn->ctx->config[LINGER_TIMEOUT]) {
  12036. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  12037. }
  12038. /* Set linger option according to configuration */
  12039. if (linger_timeout >= 0) {
  12040. /* Set linger option to avoid socket hanging out after close. This
  12041. * prevent ephemeral port exhaust problem under high QPS. */
  12042. linger.l_onoff = 1;
  12043. #if defined(_MSC_VER)
  12044. #pragma warning(push)
  12045. #pragma warning(disable : 4244)
  12046. #endif
  12047. linger.l_linger = (linger_timeout + 999) / 1000;
  12048. #if defined(_MSC_VER)
  12049. #pragma warning(pop)
  12050. #endif
  12051. } else {
  12052. linger.l_onoff = 0;
  12053. linger.l_linger = 0;
  12054. }
  12055. if (linger_timeout < -1) {
  12056. /* Default: don't configure any linger */
  12057. } else if (getsockopt(conn->client.sock,
  12058. SOL_SOCKET,
  12059. SO_ERROR,
  12060. (char *)&error_code,
  12061. &opt_len) != 0) {
  12062. /* Cannot determine if socket is already closed. This should
  12063. * not occur and never did in a test. Log an error message
  12064. * and continue. */
  12065. mg_cry(conn,
  12066. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  12067. __func__,
  12068. strerror(ERRNO));
  12069. } else if (error_code == ECONNRESET) {
  12070. /* Socket already closed by client/peer, close socket without linger */
  12071. } else {
  12072. /* Set linger timeout */
  12073. if (setsockopt(conn->client.sock,
  12074. SOL_SOCKET,
  12075. SO_LINGER,
  12076. (char *)&linger,
  12077. sizeof(linger)) != 0) {
  12078. mg_cry(conn,
  12079. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  12080. __func__,
  12081. linger.l_onoff,
  12082. linger.l_linger,
  12083. strerror(ERRNO));
  12084. }
  12085. }
  12086. /* Now we know that our FIN is ACK-ed, safe to close */
  12087. closesocket(conn->client.sock);
  12088. conn->client.sock = INVALID_SOCKET;
  12089. }
  12090. static void
  12091. close_connection(struct mg_connection *conn)
  12092. {
  12093. if (!conn || !conn->ctx) {
  12094. return;
  12095. }
  12096. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12097. if (conn->lua_websocket_state) {
  12098. lua_websocket_close(conn, conn->lua_websocket_state);
  12099. conn->lua_websocket_state = NULL;
  12100. }
  12101. #endif
  12102. /* call the connection_close callback if assigned */
  12103. if ((conn->ctx->callbacks.connection_close != NULL)
  12104. && (conn->ctx->context_type == 1)) {
  12105. conn->ctx->callbacks.connection_close(conn);
  12106. }
  12107. mg_lock_connection(conn);
  12108. conn->must_close = 1;
  12109. #ifndef NO_SSL
  12110. if (conn->ssl != NULL) {
  12111. /* Run SSL_shutdown twice to ensure completly close SSL connection
  12112. */
  12113. SSL_shutdown(conn->ssl);
  12114. SSL_free(conn->ssl);
  12115. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12116. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12117. #ifndef OPENSSL_API_1_1
  12118. ERR_remove_state(0);
  12119. #endif
  12120. conn->ssl = NULL;
  12121. }
  12122. #endif
  12123. if (conn->client.sock != INVALID_SOCKET) {
  12124. close_socket_gracefully(conn);
  12125. conn->client.sock = INVALID_SOCKET;
  12126. }
  12127. mg_unlock_connection(conn);
  12128. }
  12129. void
  12130. mg_close_connection(struct mg_connection *conn)
  12131. {
  12132. #if defined(USE_WEBSOCKET)
  12133. struct mg_context *client_ctx = NULL;
  12134. #endif /* defined(USE_WEBSOCKET) */
  12135. if (conn == NULL) {
  12136. return;
  12137. }
  12138. #if defined(USE_WEBSOCKET)
  12139. if (conn->ctx->context_type == 2) {
  12140. unsigned int i;
  12141. /* ws/wss client */
  12142. client_ctx = conn->ctx;
  12143. /* client context: loops must end */
  12144. conn->ctx->stop_flag = 1;
  12145. /* We need to get the client thread out of the select/recv call here. */
  12146. /* Since we use a sleep quantum of some seconds to check for recv
  12147. * timeouts, we will just wait a few seconds in mg_join_thread. */
  12148. /* join worker thread */
  12149. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  12150. if (client_ctx->worker_threadids[i] != 0) {
  12151. mg_join_thread(client_ctx->worker_threadids[i]);
  12152. }
  12153. }
  12154. }
  12155. #endif /* defined(USE_WEBSOCKET) */
  12156. close_connection(conn);
  12157. #ifndef NO_SSL
  12158. if (conn->client_ssl_ctx != NULL) {
  12159. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  12160. }
  12161. #endif
  12162. #if defined(USE_WEBSOCKET)
  12163. if (client_ctx != NULL) {
  12164. /* free context */
  12165. mg_free(client_ctx->worker_threadids);
  12166. mg_free(client_ctx);
  12167. (void)pthread_mutex_destroy(&conn->mutex);
  12168. mg_free(conn);
  12169. } else if (conn->ctx->context_type == 0) { /* Client */
  12170. mg_free(conn);
  12171. }
  12172. #else
  12173. if (conn->ctx->context_type == 0) { /* Client */
  12174. mg_free(conn);
  12175. }
  12176. #endif /* defined(USE_WEBSOCKET) */
  12177. }
  12178. static struct mg_context common_client_context;
  12179. static struct mg_connection *
  12180. mg_connect_client_impl(const struct mg_client_options *client_options,
  12181. int use_ssl,
  12182. char *ebuf,
  12183. size_t ebuf_len)
  12184. {
  12185. struct mg_connection *conn = NULL;
  12186. SOCKET sock;
  12187. union usa sa;
  12188. unsigned max_req_size =
  12189. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  12190. if (!connect_socket(&common_client_context,
  12191. client_options->host,
  12192. client_options->port,
  12193. use_ssl,
  12194. ebuf,
  12195. ebuf_len,
  12196. &sock,
  12197. &sa)) {
  12198. return NULL;
  12199. }
  12200. if ((conn = (struct mg_connection *)mg_calloc_ctx(
  12201. 1, sizeof(*conn) + max_req_size, &common_client_context))
  12202. == NULL) {
  12203. mg_snprintf(NULL,
  12204. NULL, /* No truncation check for ebuf */
  12205. ebuf,
  12206. ebuf_len,
  12207. "calloc(): %s",
  12208. strerror(ERRNO));
  12209. closesocket(sock);
  12210. return NULL;
  12211. }
  12212. #ifndef NO_SSL
  12213. #ifdef OPENSSL_API_1_1
  12214. if (use_ssl
  12215. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  12216. mg_snprintf(NULL,
  12217. NULL, /* No truncation check for ebuf */
  12218. ebuf,
  12219. ebuf_len,
  12220. "SSL_CTX_new error");
  12221. closesocket(sock);
  12222. mg_free(conn);
  12223. return NULL;
  12224. }
  12225. #else
  12226. if (use_ssl
  12227. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  12228. == NULL) {
  12229. mg_snprintf(NULL,
  12230. NULL, /* No truncation check for ebuf */
  12231. ebuf,
  12232. ebuf_len,
  12233. "SSL_CTX_new error");
  12234. closesocket(sock);
  12235. mg_free(conn);
  12236. return NULL;
  12237. }
  12238. #endif /* OPENSSL_API_1_1 */
  12239. #endif /* NO_SSL */
  12240. #ifdef USE_IPV6
  12241. socklen_t len = (sa.sa.sa_family == AF_INET)
  12242. ? sizeof(conn->client.rsa.sin)
  12243. : sizeof(conn->client.rsa.sin6);
  12244. struct sockaddr *psa = (sa.sa.sa_family == AF_INET)
  12245. ? (struct sockaddr *)&(conn->client.rsa.sin)
  12246. : (struct sockaddr *)&(conn->client.rsa.sin6);
  12247. #else
  12248. socklen_t len = sizeof(conn->client.rsa.sin);
  12249. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  12250. #endif
  12251. conn->buf_size = (int)max_req_size;
  12252. conn->buf = (char *)(conn + 1);
  12253. conn->ctx = &common_client_context;
  12254. conn->client.sock = sock;
  12255. conn->client.lsa = sa;
  12256. if (getsockname(sock, psa, &len) != 0) {
  12257. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  12258. }
  12259. conn->client.is_ssl = use_ssl ? 1 : 0;
  12260. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12261. #ifndef NO_SSL
  12262. if (use_ssl) {
  12263. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  12264. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  12265. * SSL_CTX_set_verify call is needed to switch off server
  12266. * certificate checking, which is off by default in OpenSSL and
  12267. * on in yaSSL. */
  12268. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  12269. * SSL_VERIFY_PEER, verify_ssl_server); */
  12270. if (client_options->client_cert) {
  12271. if (!ssl_use_pem_file(&common_client_context,
  12272. client_options->client_cert,
  12273. NULL)) {
  12274. mg_snprintf(NULL,
  12275. NULL, /* No truncation check for ebuf */
  12276. ebuf,
  12277. ebuf_len,
  12278. "Can not use SSL client certificate");
  12279. SSL_CTX_free(conn->client_ssl_ctx);
  12280. closesocket(sock);
  12281. mg_free(conn);
  12282. return NULL;
  12283. }
  12284. }
  12285. if (client_options->server_cert) {
  12286. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  12287. client_options->server_cert,
  12288. NULL);
  12289. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  12290. } else {
  12291. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  12292. }
  12293. if (!sslize(conn,
  12294. conn->client_ssl_ctx,
  12295. SSL_connect,
  12296. &(conn->ctx->stop_flag))) {
  12297. mg_snprintf(NULL,
  12298. NULL, /* No truncation check for ebuf */
  12299. ebuf,
  12300. ebuf_len,
  12301. "SSL connection error");
  12302. SSL_CTX_free(conn->client_ssl_ctx);
  12303. closesocket(sock);
  12304. mg_free(conn);
  12305. return NULL;
  12306. }
  12307. }
  12308. #endif
  12309. set_blocking_mode(sock, 0);
  12310. return conn;
  12311. }
  12312. CIVETWEB_API struct mg_connection *
  12313. mg_connect_client_secure(const struct mg_client_options *client_options,
  12314. char *error_buffer,
  12315. size_t error_buffer_size)
  12316. {
  12317. return mg_connect_client_impl(client_options,
  12318. 1,
  12319. error_buffer,
  12320. error_buffer_size);
  12321. }
  12322. struct mg_connection *
  12323. mg_connect_client(const char *host,
  12324. int port,
  12325. int use_ssl,
  12326. char *error_buffer,
  12327. size_t error_buffer_size)
  12328. {
  12329. struct mg_client_options opts;
  12330. memset(&opts, 0, sizeof(opts));
  12331. opts.host = host;
  12332. opts.port = port;
  12333. return mg_connect_client_impl(&opts,
  12334. use_ssl,
  12335. error_buffer,
  12336. error_buffer_size);
  12337. }
  12338. static const struct {
  12339. const char *proto;
  12340. size_t proto_len;
  12341. unsigned default_port;
  12342. } abs_uri_protocols[] = {{"http://", 7, 80},
  12343. {"https://", 8, 443},
  12344. {"ws://", 5, 80},
  12345. {"wss://", 6, 443},
  12346. {NULL, 0, 0}};
  12347. /* Check if the uri is valid.
  12348. * return 0 for invalid uri,
  12349. * return 1 for *,
  12350. * return 2 for relative uri,
  12351. * return 3 for absolute uri without port,
  12352. * return 4 for absolute uri with port */
  12353. static int
  12354. get_uri_type(const char *uri)
  12355. {
  12356. int i;
  12357. const char *hostend, *portbegin;
  12358. char *portend;
  12359. unsigned long port;
  12360. /* According to the HTTP standard
  12361. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  12362. * URI can be an asterisk (*) or should start with slash (relative uri),
  12363. * or it should start with the protocol (absolute uri). */
  12364. if ((uri[0] == '*') && (uri[1] == '\0')) {
  12365. /* asterisk */
  12366. return 1;
  12367. }
  12368. /* Valid URIs according to RFC 3986
  12369. * (https://www.ietf.org/rfc/rfc3986.txt)
  12370. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  12371. * and unreserved characters A-Z a-z 0-9 and -._~
  12372. * and % encoded symbols.
  12373. */
  12374. for (i = 0; uri[i] != 0; i++) {
  12375. if (uri[i] < 33) {
  12376. /* control characters and spaces are invalid */
  12377. return 0;
  12378. }
  12379. if (uri[i] > 126) {
  12380. /* non-ascii characters must be % encoded */
  12381. return 0;
  12382. } else {
  12383. switch (uri[i]) {
  12384. case '"': /* 34 */
  12385. case '<': /* 60 */
  12386. case '>': /* 62 */
  12387. case '\\': /* 92 */
  12388. case '^': /* 94 */
  12389. case '`': /* 96 */
  12390. case '{': /* 123 */
  12391. case '|': /* 124 */
  12392. case '}': /* 125 */
  12393. return 0;
  12394. default:
  12395. /* character is ok */
  12396. break;
  12397. }
  12398. }
  12399. }
  12400. /* A relative uri starts with a / character */
  12401. if (uri[0] == '/') {
  12402. /* relative uri */
  12403. return 2;
  12404. }
  12405. /* It could be an absolute uri: */
  12406. /* This function only checks if the uri is valid, not if it is
  12407. * addressing the current server. So civetweb can also be used
  12408. * as a proxy server. */
  12409. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  12410. if (mg_strncasecmp(uri,
  12411. abs_uri_protocols[i].proto,
  12412. abs_uri_protocols[i].proto_len) == 0) {
  12413. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  12414. if (!hostend) {
  12415. return 0;
  12416. }
  12417. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  12418. if (!portbegin) {
  12419. return 3;
  12420. }
  12421. port = strtoul(portbegin + 1, &portend, 10);
  12422. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  12423. return 0;
  12424. }
  12425. return 4;
  12426. }
  12427. }
  12428. return 0;
  12429. }
  12430. /* Return NULL or the relative uri at the current server */
  12431. static const char *
  12432. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  12433. {
  12434. const char *server_domain;
  12435. size_t server_domain_len;
  12436. size_t request_domain_len = 0;
  12437. unsigned long port = 0;
  12438. int i, auth_domain_check_enabled;
  12439. const char *hostbegin = NULL;
  12440. const char *hostend = NULL;
  12441. const char *portbegin;
  12442. char *portend;
  12443. auth_domain_check_enabled =
  12444. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  12445. if (!auth_domain_check_enabled) {
  12446. return 0;
  12447. }
  12448. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  12449. if (!server_domain) {
  12450. return 0;
  12451. }
  12452. server_domain_len = strlen(server_domain);
  12453. if (!server_domain_len) {
  12454. return 0;
  12455. }
  12456. /* DNS is case insensitive, so use case insensitive string compare here
  12457. */
  12458. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  12459. if (mg_strncasecmp(uri,
  12460. abs_uri_protocols[i].proto,
  12461. abs_uri_protocols[i].proto_len) == 0) {
  12462. hostbegin = uri + abs_uri_protocols[i].proto_len;
  12463. hostend = strchr(hostbegin, '/');
  12464. if (!hostend) {
  12465. return 0;
  12466. }
  12467. portbegin = strchr(hostbegin, ':');
  12468. if ((!portbegin) || (portbegin > hostend)) {
  12469. port = abs_uri_protocols[i].default_port;
  12470. request_domain_len = (size_t)(hostend - hostbegin);
  12471. } else {
  12472. port = strtoul(portbegin + 1, &portend, 10);
  12473. if ((portend != hostend) || (port <= 0)
  12474. || !is_valid_port(port)) {
  12475. return 0;
  12476. }
  12477. request_domain_len = (size_t)(portbegin - hostbegin);
  12478. }
  12479. /* protocol found, port set */
  12480. break;
  12481. }
  12482. }
  12483. if (!port) {
  12484. /* port remains 0 if the protocol is not found */
  12485. return 0;
  12486. }
  12487. /* Check if the request is directed to a different server. */
  12488. /* First check if the port is the same (IPv4 and IPv6). */
  12489. #if defined(USE_IPV6)
  12490. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  12491. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  12492. /* Request is directed to a different port */
  12493. return 0;
  12494. }
  12495. } else
  12496. #endif
  12497. {
  12498. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  12499. /* Request is directed to a different port */
  12500. return 0;
  12501. }
  12502. }
  12503. /* Finally check if the server corresponds to the authentication
  12504. * domain of the server (the server domain).
  12505. * Allow full matches (like http://mydomain.com/path/file.ext), and
  12506. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  12507. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  12508. * or http://mydomain.com.fake/path/file.ext).
  12509. */
  12510. if (auth_domain_check_enabled) {
  12511. if ((request_domain_len == server_domain_len)
  12512. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  12513. /* Request is directed to this server - full name match. */
  12514. } else {
  12515. if (request_domain_len < (server_domain_len + 2)) {
  12516. /* Request is directed to another server: The server name is
  12517. * longer
  12518. * than
  12519. * the request name. Drop this case here to avoid overflows in
  12520. * the
  12521. * following checks. */
  12522. return 0;
  12523. }
  12524. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  12525. /* Request is directed to another server: It could be a
  12526. * substring
  12527. * like notmyserver.com */
  12528. return 0;
  12529. }
  12530. if (0 != memcmp(server_domain,
  12531. hostbegin + request_domain_len - server_domain_len,
  12532. server_domain_len)) {
  12533. /* Request is directed to another server:
  12534. * The server name is different. */
  12535. return 0;
  12536. }
  12537. }
  12538. }
  12539. return hostend;
  12540. }
  12541. static int
  12542. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12543. {
  12544. if (ebuf_len > 0) {
  12545. ebuf[0] = '\0';
  12546. }
  12547. *err = 0;
  12548. reset_per_request_attributes(conn);
  12549. if (!conn) {
  12550. mg_snprintf(conn,
  12551. NULL, /* No truncation check for ebuf */
  12552. ebuf,
  12553. ebuf_len,
  12554. "%s",
  12555. "Internal error");
  12556. *err = 500;
  12557. return 0;
  12558. }
  12559. /* Set the time the request was received. This value should be used for
  12560. * timeouts. */
  12561. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  12562. conn->request_len =
  12563. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  12564. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  12565. */
  12566. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  12567. mg_snprintf(conn,
  12568. NULL, /* No truncation check for ebuf */
  12569. ebuf,
  12570. ebuf_len,
  12571. "%s",
  12572. "Invalid message size");
  12573. *err = 500;
  12574. return 0;
  12575. }
  12576. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  12577. mg_snprintf(conn,
  12578. NULL, /* No truncation check for ebuf */
  12579. ebuf,
  12580. ebuf_len,
  12581. "%s",
  12582. "Message too large");
  12583. *err = 413;
  12584. return 0;
  12585. }
  12586. if (conn->request_len <= 0) {
  12587. if (conn->data_len > 0) {
  12588. mg_snprintf(conn,
  12589. NULL, /* No truncation check for ebuf */
  12590. ebuf,
  12591. ebuf_len,
  12592. "%s",
  12593. "Malformed message");
  12594. *err = 400;
  12595. } else {
  12596. /* Server did not recv anything -> just close the connection */
  12597. conn->must_close = 1;
  12598. mg_snprintf(conn,
  12599. NULL, /* No truncation check for ebuf */
  12600. ebuf,
  12601. ebuf_len,
  12602. "%s",
  12603. "No data received");
  12604. *err = 0;
  12605. }
  12606. return 0;
  12607. }
  12608. return 1;
  12609. }
  12610. static int
  12611. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12612. {
  12613. const char *cl;
  12614. if (!get_message(conn, ebuf, ebuf_len, err)) {
  12615. return 0;
  12616. }
  12617. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  12618. <= 0) {
  12619. mg_snprintf(conn,
  12620. NULL, /* No truncation check for ebuf */
  12621. ebuf,
  12622. ebuf_len,
  12623. "%s",
  12624. "Bad request");
  12625. *err = 400;
  12626. return 0;
  12627. }
  12628. /* Message is a valid request */
  12629. if ((cl = get_header(conn->request_info.http_headers,
  12630. conn->request_info.num_headers,
  12631. "Content-Length")) != NULL) {
  12632. /* Request/response has content length set */
  12633. char *endptr = NULL;
  12634. conn->content_len = strtoll(cl, &endptr, 10);
  12635. if (endptr == cl) {
  12636. mg_snprintf(conn,
  12637. NULL, /* No truncation check for ebuf */
  12638. ebuf,
  12639. ebuf_len,
  12640. "%s",
  12641. "Bad request");
  12642. *err = 411;
  12643. return 0;
  12644. }
  12645. /* Publish the content length back to the request info. */
  12646. conn->request_info.content_length = conn->content_len;
  12647. } else if ((cl = get_header(conn->request_info.http_headers,
  12648. conn->request_info.num_headers,
  12649. "Transfer-Encoding")) != NULL
  12650. && !mg_strcasecmp(cl, "chunked")) {
  12651. conn->is_chunked = 1;
  12652. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  12653. || !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  12654. /* POST or PUT request without content length set */
  12655. conn->content_len = -1;
  12656. } else if (!mg_strncasecmp(conn->request_info.request_method, "HTTP/", 5)) {
  12657. /* Response without content length set */
  12658. conn->content_len = -1;
  12659. } else {
  12660. /* Other request */
  12661. conn->content_len = 0;
  12662. }
  12663. conn->connection_type = 1; /* Valid request */
  12664. return 1;
  12665. }
  12666. /* conn is assumed to be valid in this internal function */
  12667. static int
  12668. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12669. {
  12670. const char *cl;
  12671. if (!get_message(conn, ebuf, ebuf_len, err)) {
  12672. return 0;
  12673. }
  12674. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  12675. <= 0) {
  12676. mg_snprintf(conn,
  12677. NULL, /* No truncation check for ebuf */
  12678. ebuf,
  12679. ebuf_len,
  12680. "%s",
  12681. "Bad response");
  12682. *err = 400;
  12683. return 0;
  12684. }
  12685. /* Message is a valid response */
  12686. if ((cl = get_header(conn->response_info.http_headers,
  12687. conn->response_info.num_headers,
  12688. "Content-Length")) != NULL) {
  12689. /* Request/response has content length set */
  12690. char *endptr = NULL;
  12691. conn->content_len = strtoll(cl, &endptr, 10);
  12692. if (endptr == cl) {
  12693. mg_snprintf(conn,
  12694. NULL, /* No truncation check for ebuf */
  12695. ebuf,
  12696. ebuf_len,
  12697. "%s",
  12698. "Bad request");
  12699. *err = 411;
  12700. return 0;
  12701. }
  12702. /* Publish the content length back to the response info. */
  12703. conn->response_info.content_length = conn->content_len;
  12704. /* TODO: check if it is still used in response_info */
  12705. conn->request_info.content_length = conn->content_len;
  12706. } else if ((cl = get_header(conn->response_info.http_headers,
  12707. conn->response_info.num_headers,
  12708. "Transfer-Encoding")) != NULL
  12709. && !mg_strcasecmp(cl, "chunked")) {
  12710. conn->is_chunked = 1;
  12711. } else {
  12712. conn->content_len = -1;
  12713. }
  12714. conn->connection_type = 2; /* Valid response */
  12715. return 1;
  12716. }
  12717. int
  12718. mg_get_response(struct mg_connection *conn,
  12719. char *ebuf,
  12720. size_t ebuf_len,
  12721. int timeout)
  12722. {
  12723. if (ebuf_len > 0) {
  12724. ebuf[0] = '\0';
  12725. }
  12726. if (!conn) {
  12727. mg_snprintf(conn,
  12728. NULL, /* No truncation check for ebuf */
  12729. ebuf,
  12730. ebuf_len,
  12731. "%s",
  12732. "Parameter error");
  12733. return -1;
  12734. }
  12735. /* Implementation of API function for HTTP clients */
  12736. int err, ret;
  12737. struct mg_context *octx = conn->ctx;
  12738. struct mg_context rctx = *(conn->ctx);
  12739. char txt[32]; /* will not overflow */
  12740. if (timeout >= 0) {
  12741. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  12742. rctx.config[REQUEST_TIMEOUT] = txt;
  12743. /* Not required for non-blocking sockets.
  12744. set_sock_timeout(conn->client.sock, timeout);
  12745. */
  12746. } else {
  12747. rctx.config[REQUEST_TIMEOUT] = NULL;
  12748. }
  12749. conn->ctx = &rctx;
  12750. ret = get_response(conn, ebuf, ebuf_len, &err);
  12751. conn->ctx = octx;
  12752. #if defined(MG_LEGACY_INTERFACE)
  12753. /* TODO: 1) uri is deprecated;
  12754. * 2) here, ri.uri is the http response code */
  12755. conn->request_info.uri = conn->request_info.request_uri;
  12756. #endif
  12757. conn->request_info.local_uri = conn->request_info.request_uri;
  12758. /* TODO (mid): Define proper return values - maybe return length?
  12759. * For the first test use <0 for error and >0 for OK */
  12760. return (ret == 0) ? -1 : +1;
  12761. }
  12762. struct mg_connection *
  12763. mg_download(const char *host,
  12764. int port,
  12765. int use_ssl,
  12766. char *ebuf,
  12767. size_t ebuf_len,
  12768. const char *fmt,
  12769. ...)
  12770. {
  12771. struct mg_connection *conn;
  12772. va_list ap;
  12773. int i;
  12774. int reqerr;
  12775. if (ebuf_len > 0) {
  12776. ebuf[0] = '\0';
  12777. }
  12778. va_start(ap, fmt);
  12779. /* open a connection */
  12780. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  12781. if (conn != NULL) {
  12782. i = mg_vprintf(conn, fmt, ap);
  12783. if (i <= 0) {
  12784. mg_snprintf(conn,
  12785. NULL, /* No truncation check for ebuf */
  12786. ebuf,
  12787. ebuf_len,
  12788. "%s",
  12789. "Error sending request");
  12790. } else {
  12791. get_response(conn, ebuf, ebuf_len, &reqerr);
  12792. #if defined(MG_LEGACY_INTERFACE)
  12793. /* TODO: 1) uri is deprecated;
  12794. * 2) here, ri.uri is the http response code */
  12795. conn->request_info.uri = conn->request_info.request_uri;
  12796. #endif
  12797. conn->request_info.local_uri = conn->request_info.request_uri;
  12798. }
  12799. }
  12800. /* if an error occured, close the connection */
  12801. if ((ebuf[0] != '\0') && (conn != NULL)) {
  12802. mg_close_connection(conn);
  12803. conn = NULL;
  12804. }
  12805. va_end(ap);
  12806. return conn;
  12807. }
  12808. struct websocket_client_thread_data {
  12809. struct mg_connection *conn;
  12810. mg_websocket_data_handler data_handler;
  12811. mg_websocket_close_handler close_handler;
  12812. void *callback_data;
  12813. };
  12814. #if defined(USE_WEBSOCKET)
  12815. #ifdef _WIN32
  12816. static unsigned __stdcall websocket_client_thread(void *data)
  12817. #else
  12818. static void *
  12819. websocket_client_thread(void *data)
  12820. #endif
  12821. {
  12822. struct websocket_client_thread_data *cdata =
  12823. (struct websocket_client_thread_data *)data;
  12824. mg_set_thread_name("ws-clnt");
  12825. if (cdata->conn->ctx) {
  12826. if (cdata->conn->ctx->callbacks.init_thread) {
  12827. /* 3 indicates a websocket client thread */
  12828. /* TODO: check if conn->ctx can be set */
  12829. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  12830. }
  12831. }
  12832. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  12833. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  12834. if (cdata->close_handler != NULL) {
  12835. cdata->close_handler(cdata->conn, cdata->callback_data);
  12836. }
  12837. /* The websocket_client context has only this thread. If it runs out,
  12838. set the stop_flag to 2 (= "stopped"). */
  12839. cdata->conn->ctx->stop_flag = 2;
  12840. mg_free((void *)cdata);
  12841. #ifdef _WIN32
  12842. return 0;
  12843. #else
  12844. return NULL;
  12845. #endif
  12846. }
  12847. #endif
  12848. struct mg_connection *
  12849. mg_connect_websocket_client(const char *host,
  12850. int port,
  12851. int use_ssl,
  12852. char *error_buffer,
  12853. size_t error_buffer_size,
  12854. const char *path,
  12855. const char *origin,
  12856. mg_websocket_data_handler data_func,
  12857. mg_websocket_close_handler close_func,
  12858. void *user_data)
  12859. {
  12860. struct mg_connection *conn = NULL;
  12861. #if defined(USE_WEBSOCKET)
  12862. struct mg_context *newctx = NULL;
  12863. struct websocket_client_thread_data *thread_data;
  12864. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  12865. static const char *handshake_req;
  12866. if (origin != NULL) {
  12867. handshake_req = "GET %s HTTP/1.1\r\n"
  12868. "Host: %s\r\n"
  12869. "Upgrade: websocket\r\n"
  12870. "Connection: Upgrade\r\n"
  12871. "Sec-WebSocket-Key: %s\r\n"
  12872. "Sec-WebSocket-Version: 13\r\n"
  12873. "Origin: %s\r\n"
  12874. "\r\n";
  12875. } else {
  12876. handshake_req = "GET %s HTTP/1.1\r\n"
  12877. "Host: %s\r\n"
  12878. "Upgrade: websocket\r\n"
  12879. "Connection: Upgrade\r\n"
  12880. "Sec-WebSocket-Key: %s\r\n"
  12881. "Sec-WebSocket-Version: 13\r\n"
  12882. "\r\n";
  12883. }
  12884. /* Establish the client connection and request upgrade */
  12885. conn = mg_download(host,
  12886. port,
  12887. use_ssl,
  12888. error_buffer,
  12889. error_buffer_size,
  12890. handshake_req,
  12891. path,
  12892. host,
  12893. magic,
  12894. origin);
  12895. /* Connection object will be null if something goes wrong */
  12896. if (conn == NULL) {
  12897. if (!*error_buffer) {
  12898. /* There should be already an error message */
  12899. mg_snprintf(conn,
  12900. NULL, /* No truncation check for ebuf */
  12901. error_buffer,
  12902. error_buffer_size,
  12903. "Unexpected error");
  12904. }
  12905. return NULL;
  12906. }
  12907. if (conn->response_info.status_code != 101) {
  12908. /* We sent an "upgrade" request. For a correct websocket
  12909. * protocol handshake, we expect a "101 Continue" response.
  12910. * Otherwise it is a protocol violation. Maybe the HTTP
  12911. * Server does not know websockets. */
  12912. if (!*error_buffer) {
  12913. /* set an error, if not yet set */
  12914. mg_snprintf(conn,
  12915. NULL, /* No truncation check for ebuf */
  12916. error_buffer,
  12917. error_buffer_size,
  12918. "Unexpected server reply");
  12919. }
  12920. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  12921. mg_free(conn);
  12922. return conn;
  12923. }
  12924. /* For client connections, mg_context is fake. Since we need to set a
  12925. * callback function, we need to create a copy and modify it. */
  12926. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  12927. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  12928. newctx->user_data = user_data;
  12929. newctx->context_type = 2; /* ws/wss client context type */
  12930. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  12931. newctx->worker_threadids =
  12932. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  12933. sizeof(pthread_t),
  12934. newctx);
  12935. conn->ctx = newctx;
  12936. thread_data = (struct websocket_client_thread_data *)
  12937. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  12938. thread_data->conn = conn;
  12939. thread_data->data_handler = data_func;
  12940. thread_data->close_handler = close_func;
  12941. thread_data->callback_data = user_data;
  12942. /* Start a thread to read the websocket client connection
  12943. * This thread will automatically stop when mg_disconnect is
  12944. * called on the client connection */
  12945. if (mg_start_thread_with_id(websocket_client_thread,
  12946. (void *)thread_data,
  12947. newctx->worker_threadids) != 0) {
  12948. mg_free((void *)thread_data);
  12949. mg_free((void *)newctx->worker_threadids);
  12950. mg_free((void *)newctx);
  12951. mg_free((void *)conn);
  12952. conn = NULL;
  12953. DEBUG_TRACE("%s",
  12954. "Websocket client connect thread could not be started\r\n");
  12955. }
  12956. #else
  12957. /* Appease "unused parameter" warnings */
  12958. (void)host;
  12959. (void)port;
  12960. (void)use_ssl;
  12961. (void)error_buffer;
  12962. (void)error_buffer_size;
  12963. (void)path;
  12964. (void)origin;
  12965. (void)user_data;
  12966. (void)data_func;
  12967. (void)close_func;
  12968. #endif
  12969. return conn;
  12970. }
  12971. static void
  12972. process_new_connection(struct mg_connection *conn)
  12973. {
  12974. if (conn && conn->ctx) {
  12975. struct mg_request_info *ri = &conn->request_info;
  12976. int keep_alive_enabled, keep_alive, discard_len;
  12977. char ebuf[100];
  12978. const char *hostend;
  12979. int reqerr, uri_type;
  12980. #if defined(USE_SERVER_STATS)
  12981. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  12982. mg_atomic_add(&(conn->ctx->total_connections), 1);
  12983. if (mcon > (conn->ctx->max_connections)) {
  12984. /* could use atomic compare exchange, but this
  12985. * seems overkill for statistics data */
  12986. conn->ctx->max_connections = mcon;
  12987. }
  12988. #endif
  12989. keep_alive_enabled =
  12990. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  12991. /* Important: on new connection, reset the receiving buffer. Credit
  12992. * goes to crule42. */
  12993. conn->data_len = 0;
  12994. conn->handled_requests = 0;
  12995. do {
  12996. DEBUG_TRACE("calling get_request (%i times for this connection)",
  12997. conn->handled_requests + 1);
  12998. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  12999. /* The request sent by the client could not be understood by
  13000. * the server, or it was incomplete or a timeout. Send an
  13001. * error message and close the connection. */
  13002. if (reqerr > 0) {
  13003. /*assert(ebuf[0] != '\0');*/
  13004. mg_send_http_error(conn, reqerr, "%s", ebuf);
  13005. }
  13006. } else if (strcmp(ri->http_version, "1.0")
  13007. && strcmp(ri->http_version, "1.1")) {
  13008. mg_snprintf(conn,
  13009. NULL, /* No truncation check for ebuf */
  13010. ebuf,
  13011. sizeof(ebuf),
  13012. "Bad HTTP version: [%s]",
  13013. ri->http_version);
  13014. mg_send_http_error(conn, 505, "%s", ebuf);
  13015. }
  13016. if (ebuf[0] == '\0') {
  13017. uri_type = get_uri_type(conn->request_info.request_uri);
  13018. switch (uri_type) {
  13019. case 1:
  13020. /* Asterisk */
  13021. conn->request_info.local_uri = NULL;
  13022. break;
  13023. case 2:
  13024. /* relative uri */
  13025. conn->request_info.local_uri =
  13026. conn->request_info.request_uri;
  13027. break;
  13028. case 3:
  13029. case 4:
  13030. /* absolute uri (with/without port) */
  13031. hostend = get_rel_url_at_current_server(
  13032. conn->request_info.request_uri, conn);
  13033. if (hostend) {
  13034. conn->request_info.local_uri = hostend;
  13035. } else {
  13036. conn->request_info.local_uri = NULL;
  13037. }
  13038. break;
  13039. default:
  13040. mg_snprintf(conn,
  13041. NULL, /* No truncation check for ebuf */
  13042. ebuf,
  13043. sizeof(ebuf),
  13044. "Invalid URI");
  13045. mg_send_http_error(conn, 400, "%s", ebuf);
  13046. conn->request_info.local_uri = NULL;
  13047. break;
  13048. }
  13049. #if defined(MG_LEGACY_INTERFACE)
  13050. /* Legacy before split into local_uri and request_uri */
  13051. conn->request_info.uri = conn->request_info.local_uri;
  13052. #endif
  13053. }
  13054. DEBUG_TRACE("http: %s, error: %s",
  13055. (ri->http_version ? ri->http_version : "none"),
  13056. (ebuf[0] ? ebuf : "none"));
  13057. if (ebuf[0] == '\0') {
  13058. if (conn->request_info.local_uri) {
  13059. /* handle request to local server */
  13060. handle_request(conn);
  13061. DEBUG_TRACE("%s", "handle_request done");
  13062. if (conn->ctx->callbacks.end_request != NULL) {
  13063. conn->ctx->callbacks.end_request(conn,
  13064. conn->status_code);
  13065. DEBUG_TRACE("%s", "end_request callback done");
  13066. }
  13067. log_access(conn);
  13068. } else {
  13069. /* TODO: handle non-local request (PROXY) */
  13070. conn->must_close = 1;
  13071. }
  13072. } else {
  13073. conn->must_close = 1;
  13074. }
  13075. if (ri->remote_user != NULL) {
  13076. mg_free((void *)ri->remote_user);
  13077. /* Important! When having connections with and without auth
  13078. * would cause double free and then crash */
  13079. ri->remote_user = NULL;
  13080. }
  13081. /* NOTE(lsm): order is important here. should_keep_alive() call
  13082. * is
  13083. * using parsed request, which will be invalid after memmove's
  13084. * below.
  13085. * Therefore, memorize should_keep_alive() result now for later
  13086. * use
  13087. * in loop exit condition. */
  13088. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  13089. && (conn->content_len >= 0) && should_keep_alive(conn);
  13090. /* Discard all buffered data for this request */
  13091. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  13092. && ((conn->request_len + conn->content_len)
  13093. < (int64_t)conn->data_len))
  13094. ? (int)(conn->request_len + conn->content_len)
  13095. : conn->data_len;
  13096. /*assert(discard_len >= 0);*/
  13097. if (discard_len < 0) {
  13098. DEBUG_TRACE("internal error: discard_len = %li",
  13099. (long int)discard_len);
  13100. break;
  13101. }
  13102. conn->data_len -= discard_len;
  13103. if (conn->data_len > 0) {
  13104. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  13105. memmove(conn->buf,
  13106. conn->buf + discard_len,
  13107. (size_t)conn->data_len);
  13108. }
  13109. /* assert(conn->data_len >= 0); */
  13110. /* assert(conn->data_len <= conn->buf_size); */
  13111. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  13112. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  13113. (long int)conn->data_len,
  13114. (long int)conn->buf_size);
  13115. break;
  13116. }
  13117. conn->handled_requests++;
  13118. } while (keep_alive);
  13119. #if defined(USE_SERVER_STATS)
  13120. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  13121. mg_atomic_dec(&(conn->ctx->active_connections));
  13122. #endif
  13123. }
  13124. }
  13125. #if defined(ALTERNATIVE_QUEUE)
  13126. static void
  13127. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13128. {
  13129. unsigned int i;
  13130. for (;;) {
  13131. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13132. /* find a free worker slot and signal it */
  13133. if (ctx->client_socks[i].in_use == 0) {
  13134. ctx->client_socks[i] = *sp;
  13135. ctx->client_socks[i].in_use = 1;
  13136. event_signal(ctx->client_wait_events[i]);
  13137. return;
  13138. }
  13139. }
  13140. /* queue is full */
  13141. mg_sleep(1);
  13142. }
  13143. }
  13144. static int
  13145. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13146. {
  13147. DEBUG_TRACE("%s", "going idle");
  13148. ctx->client_socks[thread_index].in_use = 0;
  13149. event_wait(ctx->client_wait_events[thread_index]);
  13150. *sp = ctx->client_socks[thread_index];
  13151. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13152. return !ctx->stop_flag;
  13153. }
  13154. #else /* ALTERNATIVE_QUEUE */
  13155. /* Worker threads take accepted socket from the queue */
  13156. static int
  13157. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13158. {
  13159. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13160. (void)thread_index;
  13161. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13162. DEBUG_TRACE("%s", "going idle");
  13163. /* If the queue is empty, wait. We're idle at this point. */
  13164. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  13165. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  13166. }
  13167. /* If we're stopping, sq_head may be equal to sq_tail. */
  13168. if (ctx->sq_head > ctx->sq_tail) {
  13169. /* Copy socket from the queue and increment tail */
  13170. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  13171. ctx->sq_tail++;
  13172. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13173. /* Wrap pointers if needed */
  13174. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  13175. ctx->sq_tail -= QUEUE_SIZE(ctx);
  13176. ctx->sq_head -= QUEUE_SIZE(ctx);
  13177. }
  13178. }
  13179. (void)pthread_cond_signal(&ctx->sq_empty);
  13180. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13181. return !ctx->stop_flag;
  13182. #undef QUEUE_SIZE
  13183. }
  13184. /* Master thread adds accepted socket to a queue */
  13185. static void
  13186. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13187. {
  13188. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13189. if (!ctx) {
  13190. return;
  13191. }
  13192. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13193. /* If the queue is full, wait */
  13194. while ((ctx->stop_flag == 0)
  13195. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  13196. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  13197. }
  13198. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  13199. /* Copy socket to the queue and increment head */
  13200. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  13201. ctx->sq_head++;
  13202. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  13203. }
  13204. (void)pthread_cond_signal(&ctx->sq_full);
  13205. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13206. #undef QUEUE_SIZE
  13207. }
  13208. #endif /* ALTERNATIVE_QUEUE */
  13209. struct worker_thread_args {
  13210. struct mg_context *ctx;
  13211. int index;
  13212. };
  13213. static void *
  13214. worker_thread_run(struct worker_thread_args *thread_args)
  13215. {
  13216. struct mg_context *ctx = thread_args->ctx;
  13217. struct mg_connection *conn;
  13218. struct mg_workerTLS tls;
  13219. #if defined(MG_LEGACY_INTERFACE)
  13220. uint32_t addr;
  13221. #endif
  13222. mg_set_thread_name("worker");
  13223. tls.is_master = 0;
  13224. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13225. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13226. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13227. #endif
  13228. /* Initialize thread local storage before calling any callback */
  13229. pthread_setspecific(sTlsKey, &tls);
  13230. if (ctx->callbacks.init_thread) {
  13231. /* call init_thread for a worker thread (type 1) */
  13232. ctx->callbacks.init_thread(ctx, 1);
  13233. }
  13234. /* Connection structure has been pre-allocated */
  13235. if (((int)thread_args->index < 0)
  13236. || ((unsigned)thread_args->index
  13237. >= (unsigned)ctx->cfg_worker_threads)) {
  13238. mg_cry(fc(ctx),
  13239. "Internal error: Invalid worker index %i",
  13240. (int)thread_args->index);
  13241. return NULL;
  13242. }
  13243. conn = ctx->worker_connections + thread_args->index;
  13244. /* Request buffers are not pre-allocated. They are private to the
  13245. * request and do not contain any state information that might be
  13246. * of interest to anyone observing a server status. */
  13247. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->ctx);
  13248. if (conn->buf == NULL) {
  13249. mg_cry(fc(ctx),
  13250. "Out of memory: Cannot allocate buffer for worker %i",
  13251. (int)thread_args->index);
  13252. return NULL;
  13253. }
  13254. conn->buf_size = (int)ctx->max_request_size;
  13255. conn->ctx = ctx;
  13256. conn->thread_index = thread_args->index;
  13257. conn->request_info.user_data = ctx->user_data;
  13258. /* Allocate a mutex for this connection to allow communication both
  13259. * within the request handler and from elsewhere in the application
  13260. */
  13261. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13262. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  13263. * signal sq_empty condvar to wake up the master waiting in
  13264. * produce_socket() */
  13265. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  13266. conn->conn_birth_time = time(NULL);
  13267. /* Fill in IP, port info early so even if SSL setup below fails,
  13268. * error handler would have the corresponding info.
  13269. * Thanks to Johannes Winkelmann for the patch.
  13270. */
  13271. #if defined(USE_IPV6)
  13272. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  13273. conn->request_info.remote_port =
  13274. ntohs(conn->client.rsa.sin6.sin6_port);
  13275. } else
  13276. #endif
  13277. {
  13278. conn->request_info.remote_port =
  13279. ntohs(conn->client.rsa.sin.sin_port);
  13280. }
  13281. sockaddr_to_string(conn->request_info.remote_addr,
  13282. sizeof(conn->request_info.remote_addr),
  13283. &conn->client.rsa);
  13284. DEBUG_TRACE("Start processing connection from %s",
  13285. conn->request_info.remote_addr);
  13286. #if defined(MG_LEGACY_INTERFACE)
  13287. /* This legacy interface only works for the IPv4 case */
  13288. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  13289. memcpy(&conn->request_info.remote_ip, &addr, 4);
  13290. #endif
  13291. conn->request_info.is_ssl = conn->client.is_ssl;
  13292. if (conn->client.is_ssl) {
  13293. #ifndef NO_SSL
  13294. /* HTTPS connection */
  13295. if (sslize(conn,
  13296. conn->ctx->ssl_ctx,
  13297. SSL_accept,
  13298. &(conn->ctx->stop_flag))) {
  13299. /* Get SSL client certificate information (if set) */
  13300. ssl_get_client_cert_info(conn);
  13301. /* process HTTPS connection */
  13302. process_new_connection(conn);
  13303. /* Free client certificate info */
  13304. if (conn->request_info.client_cert) {
  13305. mg_free((void *)(conn->request_info.client_cert->subject));
  13306. mg_free((void *)(conn->request_info.client_cert->issuer));
  13307. mg_free((void *)(conn->request_info.client_cert->serial));
  13308. mg_free((void *)(conn->request_info.client_cert->finger));
  13309. conn->request_info.client_cert->subject = 0;
  13310. conn->request_info.client_cert->issuer = 0;
  13311. conn->request_info.client_cert->serial = 0;
  13312. conn->request_info.client_cert->finger = 0;
  13313. mg_free(conn->request_info.client_cert);
  13314. conn->request_info.client_cert = 0;
  13315. }
  13316. }
  13317. #endif
  13318. } else {
  13319. /* process HTTP connection */
  13320. process_new_connection(conn);
  13321. }
  13322. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  13323. conn->request_info.remote_addr,
  13324. difftime(time(NULL), conn->conn_birth_time));
  13325. close_connection(conn);
  13326. DEBUG_TRACE("%s", "Connection closed");
  13327. }
  13328. pthread_setspecific(sTlsKey, NULL);
  13329. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13330. CloseHandle(tls.pthread_cond_helper_mutex);
  13331. #endif
  13332. pthread_mutex_destroy(&conn->mutex);
  13333. /* Free the request buffer. */
  13334. conn->buf_size = 0;
  13335. mg_free(conn->buf);
  13336. conn->buf = NULL;
  13337. DEBUG_TRACE("%s", "exiting");
  13338. return NULL;
  13339. }
  13340. /* Threads have different return types on Windows and Unix. */
  13341. #ifdef _WIN32
  13342. static unsigned __stdcall worker_thread(void *thread_func_param)
  13343. {
  13344. struct worker_thread_args *pwta =
  13345. (struct worker_thread_args *)thread_func_param;
  13346. worker_thread_run(pwta);
  13347. mg_free(thread_func_param);
  13348. return 0;
  13349. }
  13350. #else
  13351. static void *
  13352. worker_thread(void *thread_func_param)
  13353. {
  13354. struct worker_thread_args *pwta =
  13355. (struct worker_thread_args *)thread_func_param;
  13356. worker_thread_run(pwta);
  13357. mg_free(thread_func_param);
  13358. return NULL;
  13359. }
  13360. #endif /* _WIN32 */
  13361. static void
  13362. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  13363. {
  13364. struct socket so;
  13365. char src_addr[IP_ADDR_STR_LEN];
  13366. socklen_t len = sizeof(so.rsa);
  13367. int on = 1;
  13368. if (!listener) {
  13369. return;
  13370. }
  13371. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  13372. == INVALID_SOCKET) {
  13373. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  13374. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  13375. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  13376. closesocket(so.sock);
  13377. } else {
  13378. /* Put so socket structure into the queue */
  13379. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  13380. set_close_on_exec(so.sock, fc(ctx));
  13381. so.is_ssl = listener->is_ssl;
  13382. so.ssl_redir = listener->ssl_redir;
  13383. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  13384. mg_cry(fc(ctx),
  13385. "%s: getsockname() failed: %s",
  13386. __func__,
  13387. strerror(ERRNO));
  13388. }
  13389. /* Set TCP keep-alive. This is needed because if HTTP-level
  13390. * keep-alive
  13391. * is enabled, and client resets the connection, server won't get
  13392. * TCP FIN or RST and will keep the connection open forever. With
  13393. * TCP keep-alive, next keep-alive handshake will figure out that
  13394. * the client is down and will close the server end.
  13395. * Thanks to Igor Klopov who suggested the patch. */
  13396. if (setsockopt(so.sock,
  13397. SOL_SOCKET,
  13398. SO_KEEPALIVE,
  13399. (SOCK_OPT_TYPE)&on,
  13400. sizeof(on)) != 0) {
  13401. mg_cry(fc(ctx),
  13402. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  13403. __func__,
  13404. strerror(ERRNO));
  13405. }
  13406. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  13407. * to effectively fill up the underlying IP packet payload and
  13408. * reduce the overhead of sending lots of small buffers. However
  13409. * this hurts the server's throughput (ie. operations per second)
  13410. * when HTTP 1.1 persistent connections are used and the responses
  13411. * are relatively small (eg. less than 1400 bytes).
  13412. */
  13413. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  13414. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  13415. if (set_tcp_nodelay(so.sock, 1) != 0) {
  13416. mg_cry(fc(ctx),
  13417. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  13418. __func__,
  13419. strerror(ERRNO));
  13420. }
  13421. }
  13422. /* We are using non-blocking sockets. Thus, the
  13423. * set_sock_timeout(so.sock, timeout);
  13424. * call is no longer required. */
  13425. set_blocking_mode(so.sock, 0);
  13426. so.in_use = 0;
  13427. produce_socket(ctx, &so);
  13428. }
  13429. }
  13430. static void
  13431. master_thread_run(void *thread_func_param)
  13432. {
  13433. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  13434. struct mg_workerTLS tls;
  13435. struct pollfd *pfd;
  13436. unsigned int i;
  13437. unsigned int workerthreadcount;
  13438. if (!ctx) {
  13439. return;
  13440. }
  13441. mg_set_thread_name("master");
  13442. /* Increase priority of the master thread */
  13443. #if defined(_WIN32)
  13444. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  13445. #elif defined(USE_MASTER_THREAD_PRIORITY)
  13446. int min_prio = sched_get_priority_min(SCHED_RR);
  13447. int max_prio = sched_get_priority_max(SCHED_RR);
  13448. if ((min_prio >= 0) && (max_prio >= 0)
  13449. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  13450. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  13451. struct sched_param sched_param = {0};
  13452. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  13453. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  13454. }
  13455. #endif
  13456. /* Initialize thread local storage */
  13457. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13458. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13459. #endif
  13460. tls.is_master = 1;
  13461. pthread_setspecific(sTlsKey, &tls);
  13462. if (ctx->callbacks.init_thread) {
  13463. /* Callback for the master thread (type 0) */
  13464. ctx->callbacks.init_thread(ctx, 0);
  13465. }
  13466. /* Server starts *now* */
  13467. ctx->start_time = time(NULL);
  13468. /* Start the server */
  13469. pfd = ctx->listening_socket_fds;
  13470. while (ctx->stop_flag == 0) {
  13471. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13472. pfd[i].fd = ctx->listening_sockets[i].sock;
  13473. pfd[i].events = POLLIN;
  13474. }
  13475. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  13476. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13477. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  13478. * successful poll, and POLLIN is defined as
  13479. * (POLLRDNORM | POLLRDBAND)
  13480. * Therefore, we're checking pfd[i].revents & POLLIN, not
  13481. * pfd[i].revents == POLLIN. */
  13482. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  13483. accept_new_connection(&ctx->listening_sockets[i], ctx);
  13484. }
  13485. }
  13486. }
  13487. }
  13488. /* Here stop_flag is 1 - Initiate shutdown. */
  13489. DEBUG_TRACE("%s", "stopping workers");
  13490. /* Stop signal received: somebody called mg_stop. Quit. */
  13491. close_all_listening_sockets(ctx);
  13492. /* Wakeup workers that are waiting for connections to handle. */
  13493. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13494. #if defined(ALTERNATIVE_QUEUE)
  13495. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13496. event_signal(ctx->client_wait_events[i]);
  13497. /* Since we know all sockets, we can shutdown the connections. */
  13498. if (ctx->client_socks[i].in_use) {
  13499. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  13500. }
  13501. }
  13502. #else
  13503. pthread_cond_broadcast(&ctx->sq_full);
  13504. #endif
  13505. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13506. /* Join all worker threads to avoid leaking threads. */
  13507. workerthreadcount = ctx->cfg_worker_threads;
  13508. for (i = 0; i < workerthreadcount; i++) {
  13509. if (ctx->worker_threadids[i] != 0) {
  13510. mg_join_thread(ctx->worker_threadids[i]);
  13511. }
  13512. }
  13513. #if defined(USE_LUA)
  13514. /* Free Lua state of lua background task */
  13515. if (ctx->lua_background_state) {
  13516. lua_close((lua_State *)ctx->lua_background_state);
  13517. ctx->lua_background_state = 0;
  13518. }
  13519. #endif
  13520. #if !defined(NO_SSL)
  13521. if (ctx->ssl_ctx != NULL) {
  13522. uninitialize_ssl();
  13523. }
  13524. #endif
  13525. DEBUG_TRACE("%s", "exiting");
  13526. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13527. CloseHandle(tls.pthread_cond_helper_mutex);
  13528. #endif
  13529. pthread_setspecific(sTlsKey, NULL);
  13530. /* Signal mg_stop() that we're done.
  13531. * WARNING: This must be the very last thing this
  13532. * thread does, as ctx becomes invalid after this line. */
  13533. ctx->stop_flag = 2;
  13534. }
  13535. /* Threads have different return types on Windows and Unix. */
  13536. #ifdef _WIN32
  13537. static unsigned __stdcall master_thread(void *thread_func_param)
  13538. {
  13539. master_thread_run(thread_func_param);
  13540. return 0;
  13541. }
  13542. #else
  13543. static void *
  13544. master_thread(void *thread_func_param)
  13545. {
  13546. master_thread_run(thread_func_param);
  13547. return NULL;
  13548. }
  13549. #endif /* _WIN32 */
  13550. static void
  13551. free_context(struct mg_context *ctx)
  13552. {
  13553. int i;
  13554. struct mg_handler_info *tmp_rh;
  13555. if (ctx == NULL) {
  13556. return;
  13557. }
  13558. if (ctx->callbacks.exit_context) {
  13559. ctx->callbacks.exit_context(ctx);
  13560. }
  13561. /* All threads exited, no sync is needed. Destroy thread mutex and
  13562. * condvars
  13563. */
  13564. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  13565. #if defined(ALTERNATIVE_QUEUE)
  13566. mg_free(ctx->client_socks);
  13567. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13568. event_destroy(ctx->client_wait_events[i]);
  13569. }
  13570. mg_free(ctx->client_wait_events);
  13571. #else
  13572. (void)pthread_cond_destroy(&ctx->sq_empty);
  13573. (void)pthread_cond_destroy(&ctx->sq_full);
  13574. #endif
  13575. /* Destroy other context global data structures mutex */
  13576. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  13577. #if defined(USE_TIMERS)
  13578. timers_exit(ctx);
  13579. #endif
  13580. /* Deallocate config parameters */
  13581. for (i = 0; i < NUM_OPTIONS; i++) {
  13582. if (ctx->config[i] != NULL) {
  13583. #if defined(_MSC_VER)
  13584. #pragma warning(suppress : 6001)
  13585. #endif
  13586. mg_free(ctx->config[i]);
  13587. }
  13588. }
  13589. /* Deallocate request handlers */
  13590. while (ctx->handlers) {
  13591. tmp_rh = ctx->handlers;
  13592. ctx->handlers = tmp_rh->next;
  13593. mg_free(tmp_rh->uri);
  13594. mg_free(tmp_rh);
  13595. }
  13596. #ifndef NO_SSL
  13597. /* Deallocate SSL context */
  13598. if (ctx->ssl_ctx != NULL) {
  13599. SSL_CTX_free(ctx->ssl_ctx);
  13600. }
  13601. #endif /* !NO_SSL */
  13602. /* Deallocate worker thread ID array */
  13603. if (ctx->worker_threadids != NULL) {
  13604. mg_free(ctx->worker_threadids);
  13605. }
  13606. /* Deallocate worker thread ID array */
  13607. if (ctx->worker_connections != NULL) {
  13608. mg_free(ctx->worker_connections);
  13609. }
  13610. /* Deallocate the tls variable */
  13611. if (mg_atomic_dec(&sTlsInit) == 0) {
  13612. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13613. DeleteCriticalSection(&global_log_file_lock);
  13614. #endif /* _WIN32 && !__SYMBIAN32__ */
  13615. #if !defined(_WIN32)
  13616. pthread_mutexattr_destroy(&pthread_mutex_attr);
  13617. #endif
  13618. pthread_key_delete(sTlsKey);
  13619. #if defined(USE_LUA)
  13620. lua_exit_optional_libraries();
  13621. #endif
  13622. }
  13623. /* deallocate system name string */
  13624. mg_free(ctx->systemName);
  13625. /* Deallocate context itself */
  13626. mg_free(ctx);
  13627. }
  13628. void
  13629. mg_stop(struct mg_context *ctx)
  13630. {
  13631. pthread_t mt;
  13632. if (!ctx) {
  13633. return;
  13634. }
  13635. /* We don't use a lock here. Calling mg_stop with the same ctx from
  13636. * two threads is not allowed. */
  13637. mt = ctx->masterthreadid;
  13638. if (mt == 0) {
  13639. return;
  13640. }
  13641. ctx->masterthreadid = 0;
  13642. /* Set stop flag, so all threads know they have to exit. */
  13643. ctx->stop_flag = 1;
  13644. /* Wait until everything has stopped. */
  13645. while (ctx->stop_flag != 2) {
  13646. (void)mg_sleep(10);
  13647. }
  13648. mg_join_thread(mt);
  13649. free_context(ctx);
  13650. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13651. (void)WSACleanup();
  13652. #endif /* _WIN32 && !__SYMBIAN32__ */
  13653. }
  13654. static void
  13655. get_system_name(char **sysName)
  13656. {
  13657. #if defined(_WIN32)
  13658. #if !defined(__SYMBIAN32__)
  13659. #if defined(_WIN32_WCE)
  13660. *sysName = mg_strdup("WinCE");
  13661. #else
  13662. char name[128];
  13663. DWORD dwVersion = 0;
  13664. DWORD dwMajorVersion = 0;
  13665. DWORD dwMinorVersion = 0;
  13666. DWORD dwBuild = 0;
  13667. BOOL wowRet, isWoW = FALSE;
  13668. #ifdef _MSC_VER
  13669. #pragma warning(push)
  13670. /* GetVersion was declared deprecated */
  13671. #pragma warning(disable : 4996)
  13672. #endif
  13673. dwVersion = GetVersion();
  13674. #ifdef _MSC_VER
  13675. #pragma warning(pop)
  13676. #endif
  13677. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13678. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13679. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  13680. (void)dwBuild;
  13681. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  13682. sprintf(name,
  13683. "Windows %u.%u%s",
  13684. (unsigned)dwMajorVersion,
  13685. (unsigned)dwMinorVersion,
  13686. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  13687. *sysName = mg_strdup(name);
  13688. #endif
  13689. #else
  13690. *sysName = mg_strdup("Symbian");
  13691. #endif
  13692. #else
  13693. struct utsname name;
  13694. memset(&name, 0, sizeof(name));
  13695. uname(&name);
  13696. *sysName = mg_strdup(name.sysname);
  13697. #endif
  13698. }
  13699. struct mg_context *
  13700. mg_start(const struct mg_callbacks *callbacks,
  13701. void *user_data,
  13702. const char **options)
  13703. {
  13704. struct mg_context *ctx;
  13705. const char *name, *value, *default_value;
  13706. int idx, ok, workerthreadcount;
  13707. unsigned int i;
  13708. int itmp;
  13709. void (*exit_callback)(const struct mg_context *ctx) = 0;
  13710. struct mg_workerTLS tls;
  13711. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13712. WSADATA data;
  13713. WSAStartup(MAKEWORD(2, 2), &data);
  13714. #endif /* _WIN32 && !__SYMBIAN32__ */
  13715. /* Allocate context and initialize reasonable general case defaults. */
  13716. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  13717. return NULL;
  13718. }
  13719. /* Random number generator will initialize at the first call */
  13720. ctx->auth_nonce_mask =
  13721. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  13722. if (mg_atomic_inc(&sTlsInit) == 1) {
  13723. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13724. InitializeCriticalSection(&global_log_file_lock);
  13725. #endif /* _WIN32 && !__SYMBIAN32__ */
  13726. #if !defined(_WIN32)
  13727. pthread_mutexattr_init(&pthread_mutex_attr);
  13728. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  13729. #endif
  13730. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  13731. /* Fatal error - abort start. However, this situation should
  13732. * never occur in practice. */
  13733. mg_atomic_dec(&sTlsInit);
  13734. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  13735. mg_free(ctx);
  13736. return NULL;
  13737. }
  13738. #if defined(USE_LUA)
  13739. lua_init_optional_libraries();
  13740. #endif
  13741. } else {
  13742. /* TODO (low): instead of sleeping, check if sTlsKey is already
  13743. * initialized. */
  13744. mg_sleep(1);
  13745. }
  13746. tls.is_master = -1;
  13747. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13748. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13749. tls.pthread_cond_helper_mutex = NULL;
  13750. #endif
  13751. pthread_setspecific(sTlsKey, &tls);
  13752. /* Dummy use this function - in some #ifdef combinations it's used,
  13753. * while it's not used in others, but GCC seems to stupid to understand
  13754. * #pragma GCC diagnostic ignored "-Wunused-function"
  13755. * in cases the function is unused, and it also complains on
  13756. * __attribute((unused))__ in cases it is used.
  13757. * So dummy use it, to have our peace. */
  13758. (void)mg_current_thread_id();
  13759. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  13760. #if !defined(ALTERNATIVE_QUEUE)
  13761. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  13762. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  13763. #endif
  13764. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  13765. if (!ok) {
  13766. /* Fatal error - abort start. However, this situation should never
  13767. * occur in practice. */
  13768. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  13769. mg_free(ctx);
  13770. pthread_setspecific(sTlsKey, NULL);
  13771. return NULL;
  13772. }
  13773. if (callbacks) {
  13774. ctx->callbacks = *callbacks;
  13775. exit_callback = callbacks->exit_context;
  13776. ctx->callbacks.exit_context = 0;
  13777. }
  13778. ctx->user_data = user_data;
  13779. ctx->handlers = NULL;
  13780. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13781. ctx->shared_lua_websockets = 0;
  13782. #endif
  13783. while (options && (name = *options++) != NULL) {
  13784. if ((idx = get_option_index(name)) == -1) {
  13785. mg_cry(fc(ctx), "Invalid option: %s", name);
  13786. free_context(ctx);
  13787. pthread_setspecific(sTlsKey, NULL);
  13788. return NULL;
  13789. } else if ((value = *options++) == NULL) {
  13790. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  13791. free_context(ctx);
  13792. pthread_setspecific(sTlsKey, NULL);
  13793. return NULL;
  13794. }
  13795. if (ctx->config[idx] != NULL) {
  13796. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  13797. mg_free(ctx->config[idx]);
  13798. }
  13799. ctx->config[idx] = mg_strdup(value);
  13800. DEBUG_TRACE("[%s] -> [%s]", name, value);
  13801. }
  13802. /* Set default value if needed */
  13803. for (i = 0; config_options[i].name != NULL; i++) {
  13804. default_value = config_options[i].default_value;
  13805. if ((ctx->config[i] == NULL) && (default_value != NULL)) {
  13806. ctx->config[i] = mg_strdup(default_value);
  13807. }
  13808. }
  13809. itmp = atoi(ctx->config[MAX_REQUEST_SIZE]);
  13810. if (itmp < 1024) {
  13811. mg_cry(fc(ctx), "max_request_size too small");
  13812. free_context(ctx);
  13813. pthread_setspecific(sTlsKey, NULL);
  13814. return NULL;
  13815. }
  13816. ctx->max_request_size = (unsigned)itmp;
  13817. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  13818. if (workerthreadcount > MAX_WORKER_THREADS) {
  13819. mg_cry(fc(ctx), "Too many worker threads");
  13820. free_context(ctx);
  13821. pthread_setspecific(sTlsKey, NULL);
  13822. return NULL;
  13823. }
  13824. if (workerthreadcount <= 0) {
  13825. mg_cry(fc(ctx), "Invalid number of worker threads");
  13826. free_context(ctx);
  13827. pthread_setspecific(sTlsKey, NULL);
  13828. return NULL;
  13829. }
  13830. #if defined(NO_FILES)
  13831. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  13832. mg_cry(fc(ctx), "%s", "Document root must not be set");
  13833. free_context(ctx);
  13834. pthread_setspecific(sTlsKey, NULL);
  13835. return NULL;
  13836. }
  13837. #endif
  13838. get_system_name(&ctx->systemName);
  13839. #if defined(USE_LUA)
  13840. /* If a Lua background script has been configured, start it. */
  13841. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  13842. char ebuf[256];
  13843. void *state = (void *)mg_prepare_lua_context_script(
  13844. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  13845. if (!state) {
  13846. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  13847. free_context(ctx);
  13848. pthread_setspecific(sTlsKey, NULL);
  13849. return NULL;
  13850. }
  13851. ctx->lua_background_state = state;
  13852. } else {
  13853. ctx->lua_background_state = 0;
  13854. }
  13855. #endif
  13856. /* NOTE(lsm): order is important here. SSL certificates must
  13857. * be initialized before listening ports. UID must be set last. */
  13858. if (!set_gpass_option(ctx) ||
  13859. #if !defined(NO_SSL)
  13860. !set_ssl_option(ctx) ||
  13861. #endif
  13862. !set_ports_option(ctx) ||
  13863. #if !defined(_WIN32)
  13864. !set_uid_option(ctx) ||
  13865. #endif
  13866. !set_acl_option(ctx)) {
  13867. free_context(ctx);
  13868. pthread_setspecific(sTlsKey, NULL);
  13869. return NULL;
  13870. }
  13871. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  13872. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  13873. * won't kill the whole process. */
  13874. (void)signal(SIGPIPE, SIG_IGN);
  13875. #endif /* !_WIN32 && !__SYMBIAN32__ */
  13876. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  13877. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13878. sizeof(pthread_t),
  13879. ctx);
  13880. if (ctx->worker_threadids == NULL) {
  13881. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  13882. free_context(ctx);
  13883. pthread_setspecific(sTlsKey, NULL);
  13884. return NULL;
  13885. }
  13886. ctx->worker_connections =
  13887. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13888. sizeof(struct mg_connection),
  13889. ctx);
  13890. if (ctx->worker_connections == NULL) {
  13891. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  13892. free_context(ctx);
  13893. pthread_setspecific(sTlsKey, NULL);
  13894. return NULL;
  13895. }
  13896. #if defined(ALTERNATIVE_QUEUE)
  13897. ctx->client_wait_events = mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  13898. ctx->cfg_worker_threads,
  13899. ctx);
  13900. if (ctx->client_wait_events == NULL) {
  13901. mg_cry(fc(ctx), "Not enough memory for worker event array");
  13902. mg_free(ctx->worker_threadids);
  13903. free_context(ctx);
  13904. pthread_setspecific(sTlsKey, NULL);
  13905. return NULL;
  13906. }
  13907. ctx->client_socks = mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  13908. ctx->cfg_worker_threads,
  13909. ctx);
  13910. if (ctx->client_wait_events == NULL) {
  13911. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  13912. mg_free(ctx->client_socks);
  13913. mg_free(ctx->worker_threadids);
  13914. free_context(ctx);
  13915. pthread_setspecific(sTlsKey, NULL);
  13916. return NULL;
  13917. }
  13918. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13919. ctx->client_wait_events[i] = event_create();
  13920. if (ctx->client_wait_events[i] == 0) {
  13921. mg_cry(fc(ctx), "Error creating worker event %i", i);
  13922. while (i > 0) {
  13923. i--;
  13924. event_destroy(ctx->client_wait_events[i]);
  13925. }
  13926. mg_free(ctx->client_socks);
  13927. mg_free(ctx->worker_threadids);
  13928. free_context(ctx);
  13929. pthread_setspecific(sTlsKey, NULL);
  13930. return NULL;
  13931. }
  13932. }
  13933. #endif
  13934. #if defined(USE_TIMERS)
  13935. if (timers_init(ctx) != 0) {
  13936. mg_cry(fc(ctx), "Error creating timers");
  13937. free_context(ctx);
  13938. pthread_setspecific(sTlsKey, NULL);
  13939. return NULL;
  13940. }
  13941. #endif
  13942. /* Context has been created - init user libraries */
  13943. if (ctx->callbacks.init_context) {
  13944. ctx->callbacks.init_context(ctx);
  13945. }
  13946. ctx->callbacks.exit_context = exit_callback;
  13947. ctx->context_type = 1; /* server context */
  13948. /* Start master (listening) thread */
  13949. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  13950. /* Start worker threads */
  13951. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13952. struct worker_thread_args *wta = (struct worker_thread_args *)
  13953. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  13954. if (wta) {
  13955. wta->ctx = ctx;
  13956. wta->index = (int)i;
  13957. }
  13958. if ((wta == NULL)
  13959. || (mg_start_thread_with_id(worker_thread,
  13960. wta,
  13961. &ctx->worker_threadids[i]) != 0)) {
  13962. /* thread was not created */
  13963. if (wta != NULL) {
  13964. mg_free(wta);
  13965. }
  13966. if (i > 0) {
  13967. mg_cry(fc(ctx),
  13968. "Cannot start worker thread %i: error %ld",
  13969. i + 1,
  13970. (long)ERRNO);
  13971. } else {
  13972. mg_cry(fc(ctx),
  13973. "Cannot create threads: error %ld",
  13974. (long)ERRNO);
  13975. free_context(ctx);
  13976. pthread_setspecific(sTlsKey, NULL);
  13977. return NULL;
  13978. }
  13979. break;
  13980. }
  13981. }
  13982. pthread_setspecific(sTlsKey, NULL);
  13983. return ctx;
  13984. }
  13985. /* Feature check API function */
  13986. unsigned
  13987. mg_check_feature(unsigned feature)
  13988. {
  13989. static const unsigned feature_set = 0
  13990. /* Set bits for available features according to API documentation.
  13991. * This bit mask is created at compile time, according to the active
  13992. * preprocessor defines. It is a single const value at runtime. */
  13993. #if !defined(NO_FILES)
  13994. | 0x0001u
  13995. #endif
  13996. #if !defined(NO_SSL)
  13997. | 0x0002u
  13998. #endif
  13999. #if !defined(NO_CGI)
  14000. | 0x0004u
  14001. #endif
  14002. #if defined(USE_IPV6)
  14003. | 0x0008u
  14004. #endif
  14005. #if defined(USE_WEBSOCKET)
  14006. | 0x0010u
  14007. #endif
  14008. #if defined(USE_LUA)
  14009. | 0x0020u
  14010. #endif
  14011. #if defined(USE_DUKTAPE)
  14012. | 0x0040u
  14013. #endif
  14014. #if !defined(NO_CACHING)
  14015. | 0x0080u
  14016. #endif
  14017. #if defined(USE_SERVER_STATS)
  14018. | 0x0100u
  14019. #endif
  14020. /* Set some extra bits not defined in the API documentation.
  14021. * These bits may change without further notice. */
  14022. #if defined(MG_LEGACY_INTERFACE)
  14023. | 0x8000u
  14024. #endif
  14025. #if defined(MEMORY_DEBUGGING)
  14026. | 0x0100u
  14027. #endif
  14028. #if defined(USE_TIMERS)
  14029. | 0x0200u
  14030. #endif
  14031. #if !defined(NO_NONCE_CHECK)
  14032. | 0x0400u
  14033. #endif
  14034. #if !defined(NO_POPEN)
  14035. | 0x0800u
  14036. #endif
  14037. ;
  14038. return (feature & feature_set);
  14039. }
  14040. /* Get system information. It can be printed or stored by the caller.
  14041. * Return the size of available information. */
  14042. static int
  14043. mg_get_system_info_impl(char *buffer, int buflen)
  14044. {
  14045. char block[256];
  14046. int system_info_length = 0;
  14047. #if defined(_WIN32)
  14048. const char *eol = "\r\n";
  14049. #else
  14050. const char *eol = "\n";
  14051. #endif
  14052. if (buffer == NULL) {
  14053. /* Avoid some warning (although, if some dillweed supplies
  14054. * buffer==NULL combined with buflen>0, he deserves a crash).
  14055. */
  14056. buflen = 0;
  14057. }
  14058. /* Server version */
  14059. {
  14060. const char *version = mg_version();
  14061. mg_snprintf(NULL,
  14062. NULL,
  14063. block,
  14064. sizeof(block),
  14065. "Server Version: %s%s",
  14066. version,
  14067. eol);
  14068. system_info_length += (int)strlen(block);
  14069. if (system_info_length < buflen) {
  14070. strcat(buffer, block);
  14071. }
  14072. }
  14073. /* System info */
  14074. {
  14075. #if defined(_WIN32)
  14076. #if !defined(__SYMBIAN32__)
  14077. DWORD dwVersion = 0;
  14078. DWORD dwMajorVersion = 0;
  14079. DWORD dwMinorVersion = 0;
  14080. SYSTEM_INFO si;
  14081. GetSystemInfo(&si);
  14082. #ifdef _MSC_VER
  14083. #pragma warning(push)
  14084. /* GetVersion was declared deprecated */
  14085. #pragma warning(disable : 4996)
  14086. #endif
  14087. dwVersion = GetVersion();
  14088. #ifdef _MSC_VER
  14089. #pragma warning(pop)
  14090. #endif
  14091. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14092. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14093. mg_snprintf(NULL,
  14094. NULL,
  14095. block,
  14096. sizeof(block),
  14097. "Windows %u.%u%s",
  14098. (unsigned)dwMajorVersion,
  14099. (unsigned)dwMinorVersion,
  14100. eol);
  14101. system_info_length += (int)strlen(block);
  14102. if (system_info_length < buflen) {
  14103. strcat(buffer, block);
  14104. }
  14105. mg_snprintf(NULL,
  14106. NULL,
  14107. block,
  14108. sizeof(block),
  14109. "CPU: type %u, cores %u, mask %x%s",
  14110. (unsigned)si.wProcessorArchitecture,
  14111. (unsigned)si.dwNumberOfProcessors,
  14112. (unsigned)si.dwActiveProcessorMask,
  14113. eol);
  14114. system_info_length += (int)strlen(block);
  14115. if (system_info_length < buflen) {
  14116. strcat(buffer, block);
  14117. }
  14118. #else
  14119. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  14120. system_info_length += (int)strlen(block);
  14121. if (system_info_length < buflen) {
  14122. strcat(buffer, block);
  14123. }
  14124. #endif
  14125. #else
  14126. struct utsname name;
  14127. memset(&name, 0, sizeof(name));
  14128. uname(&name);
  14129. mg_snprintf(NULL,
  14130. NULL,
  14131. block,
  14132. sizeof(block),
  14133. "%s %s (%s) - %s%s",
  14134. name.sysname,
  14135. name.version,
  14136. name.release,
  14137. name.machine,
  14138. eol);
  14139. system_info_length += (int)strlen(block);
  14140. if (system_info_length < buflen) {
  14141. strcat(buffer, block);
  14142. }
  14143. #endif
  14144. }
  14145. /* Features */
  14146. {
  14147. mg_snprintf(NULL,
  14148. NULL,
  14149. block,
  14150. sizeof(block),
  14151. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  14152. mg_check_feature(0xFFFFFFFFu),
  14153. eol,
  14154. mg_check_feature(1) ? " Files" : "",
  14155. mg_check_feature(2) ? " HTTPS" : "",
  14156. mg_check_feature(4) ? " CGI" : "",
  14157. mg_check_feature(8) ? " IPv6" : "",
  14158. mg_check_feature(16) ? " WebSockets" : "",
  14159. mg_check_feature(32) ? " Lua" : "",
  14160. mg_check_feature(64) ? " JavaScript" : "",
  14161. mg_check_feature(128) ? " Cache" : "",
  14162. eol);
  14163. system_info_length += (int)strlen(block);
  14164. if (system_info_length < buflen) {
  14165. strcat(buffer, block);
  14166. }
  14167. #ifdef USE_LUA
  14168. mg_snprintf(NULL,
  14169. NULL,
  14170. block,
  14171. sizeof(block),
  14172. "Lua Version: %u (%s)%s",
  14173. (unsigned)LUA_VERSION_NUM,
  14174. LUA_RELEASE,
  14175. eol);
  14176. system_info_length += (int)strlen(block);
  14177. if (system_info_length < buflen) {
  14178. strcat(buffer, block);
  14179. }
  14180. #endif
  14181. #if defined(USE_DUKTAPE)
  14182. mg_snprintf(NULL,
  14183. NULL,
  14184. block,
  14185. sizeof(block),
  14186. "JavaScript: Duktape %u.%u.%u%s",
  14187. (unsigned)DUK_VERSION / 10000,
  14188. ((unsigned)DUK_VERSION / 100) % 100,
  14189. (unsigned)DUK_VERSION % 100,
  14190. eol);
  14191. system_info_length += (int)strlen(block);
  14192. if (system_info_length < buflen) {
  14193. strcat(buffer, block);
  14194. }
  14195. #endif
  14196. }
  14197. /* Build date */
  14198. {
  14199. mg_snprintf(
  14200. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  14201. system_info_length += (int)strlen(block);
  14202. if (system_info_length < buflen) {
  14203. strcat(buffer, block);
  14204. }
  14205. }
  14206. /* Compiler information */
  14207. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  14208. {
  14209. #if defined(_MSC_VER)
  14210. mg_snprintf(NULL,
  14211. NULL,
  14212. block,
  14213. sizeof(block),
  14214. "MSC: %u (%u)%s",
  14215. (unsigned)_MSC_VER,
  14216. (unsigned)_MSC_FULL_VER,
  14217. eol);
  14218. system_info_length += (int)strlen(block);
  14219. if (system_info_length < buflen) {
  14220. strcat(buffer, block);
  14221. }
  14222. #elif defined(__MINGW64__)
  14223. mg_snprintf(NULL,
  14224. NULL,
  14225. block,
  14226. sizeof(block),
  14227. "MinGW64: %u.%u%s",
  14228. (unsigned)__MINGW64_VERSION_MAJOR,
  14229. (unsigned)__MINGW64_VERSION_MINOR,
  14230. eol);
  14231. system_info_length += (int)strlen(block);
  14232. if (system_info_length < buflen) {
  14233. strcat(buffer, block);
  14234. }
  14235. mg_snprintf(NULL,
  14236. NULL,
  14237. block,
  14238. sizeof(block),
  14239. "MinGW32: %u.%u%s",
  14240. (unsigned)__MINGW32_MAJOR_VERSION,
  14241. (unsigned)__MINGW32_MINOR_VERSION,
  14242. eol);
  14243. system_info_length += (int)strlen(block);
  14244. if (system_info_length < buflen) {
  14245. strcat(buffer, block);
  14246. }
  14247. #elif defined(__MINGW32__)
  14248. mg_snprintf(NULL,
  14249. NULL,
  14250. block,
  14251. sizeof(block),
  14252. "MinGW32: %u.%u%s",
  14253. (unsigned)__MINGW32_MAJOR_VERSION,
  14254. (unsigned)__MINGW32_MINOR_VERSION,
  14255. eol);
  14256. system_info_length += (int)strlen(block);
  14257. if (system_info_length < buflen) {
  14258. strcat(buffer, block);
  14259. }
  14260. #elif defined(__clang__)
  14261. mg_snprintf(NULL,
  14262. NULL,
  14263. block,
  14264. sizeof(block),
  14265. "clang: %u.%u.%u (%s)%s",
  14266. __clang_major__,
  14267. __clang_minor__,
  14268. __clang_patchlevel__,
  14269. __clang_version__,
  14270. eol);
  14271. system_info_length += (int)strlen(block);
  14272. if (system_info_length < buflen) {
  14273. strcat(buffer, block);
  14274. }
  14275. #elif defined(__GNUC__)
  14276. mg_snprintf(NULL,
  14277. NULL,
  14278. block,
  14279. sizeof(block),
  14280. "gcc: %u.%u.%u%s",
  14281. (unsigned)__GNUC__,
  14282. (unsigned)__GNUC_MINOR__,
  14283. (unsigned)__GNUC_PATCHLEVEL__,
  14284. eol);
  14285. system_info_length += (int)strlen(block);
  14286. if (system_info_length < buflen) {
  14287. strcat(buffer, block);
  14288. }
  14289. #elif defined(__INTEL_COMPILER)
  14290. mg_snprintf(NULL,
  14291. NULL,
  14292. block,
  14293. sizeof(block),
  14294. "Intel C/C++: %u%s",
  14295. (unsigned)__INTEL_COMPILER,
  14296. eol);
  14297. system_info_length += (int)strlen(block);
  14298. if (system_info_length < buflen) {
  14299. strcat(buffer, block);
  14300. }
  14301. #elif defined(__BORLANDC__)
  14302. mg_snprintf(NULL,
  14303. NULL,
  14304. block,
  14305. sizeof(block),
  14306. "Borland C: 0x%x%s",
  14307. (unsigned)__BORLANDC__,
  14308. eol);
  14309. system_info_length += (int)strlen(block);
  14310. if (system_info_length < buflen) {
  14311. strcat(buffer, block);
  14312. }
  14313. #elif defined(__SUNPRO_C)
  14314. mg_snprintf(NULL,
  14315. NULL,
  14316. block,
  14317. sizeof(block),
  14318. "Solaris: 0x%x%s",
  14319. (unsigned)__SUNPRO_C,
  14320. eol);
  14321. system_info_length += (int)strlen(block);
  14322. if (system_info_length < buflen) {
  14323. strcat(buffer, block);
  14324. }
  14325. #else
  14326. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  14327. system_info_length += (int)strlen(block);
  14328. if (system_info_length < buflen) {
  14329. strcat(buffer, block);
  14330. }
  14331. #endif
  14332. }
  14333. /* Determine 32/64 bit data mode.
  14334. * see https://en.wikipedia.org/wiki/64-bit_computing */
  14335. {
  14336. mg_snprintf(NULL,
  14337. NULL,
  14338. block,
  14339. sizeof(block),
  14340. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  14341. "ptr:%u, size:%u, time:%u%s",
  14342. (unsigned)sizeof(short),
  14343. (unsigned)sizeof(int),
  14344. (unsigned)sizeof(long),
  14345. (unsigned)sizeof(long long),
  14346. (unsigned)sizeof(float),
  14347. (unsigned)sizeof(double),
  14348. (unsigned)sizeof(long double),
  14349. (unsigned)sizeof(char),
  14350. (unsigned)sizeof(wchar_t),
  14351. (unsigned)sizeof(void *),
  14352. (unsigned)sizeof(size_t),
  14353. (unsigned)sizeof(time_t),
  14354. eol);
  14355. system_info_length += (int)strlen(block);
  14356. if (system_info_length < buflen) {
  14357. strcat(buffer, block);
  14358. }
  14359. }
  14360. return system_info_length;
  14361. }
  14362. #if defined(USE_SERVER_STATS)
  14363. /* Get context information. It can be printed or stored by the caller.
  14364. * Return the size of available information. */
  14365. static int
  14366. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  14367. {
  14368. char block[256];
  14369. int context_info_length = 0;
  14370. #if defined(_WIN32)
  14371. const char *eol = "\r\n";
  14372. #else
  14373. const char *eol = "\n";
  14374. #endif
  14375. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  14376. const char *eoobj = "}";
  14377. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  14378. if ((buffer == NULL) || (buflen < 10)) {
  14379. buflen = 0;
  14380. }
  14381. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  14382. context_info_length += (int)strlen(block);
  14383. if (context_info_length < buflen) {
  14384. strcat(buffer, block);
  14385. }
  14386. /* Memory information */
  14387. if (ms) {
  14388. mg_snprintf(NULL,
  14389. NULL,
  14390. block,
  14391. sizeof(block),
  14392. "\"memory\" : {%s"
  14393. "\"blocks\" : %i,%s"
  14394. "\"used\" : %" INT64_FMT ",%s"
  14395. "\"maxUsed\" : %" INT64_FMT "%s"
  14396. "}%s%s",
  14397. eol,
  14398. ms->blockCount,
  14399. eol,
  14400. ms->totalMemUsed,
  14401. eol,
  14402. ms->maxMemUsed,
  14403. eol,
  14404. (ctx ? "," : ""),
  14405. eol);
  14406. context_info_length += (int)strlen(block);
  14407. if (context_info_length + reserved_len < buflen) {
  14408. strcat(buffer, block);
  14409. }
  14410. }
  14411. /* Connections information */
  14412. if (ctx) {
  14413. mg_snprintf(NULL,
  14414. NULL,
  14415. block,
  14416. sizeof(block),
  14417. "\"connections\" : {%s"
  14418. "\"active\" : %i,%s"
  14419. "\"maxActive\" : %i,%s"
  14420. "\"total\" : %" INT64_FMT "%s"
  14421. "},%s",
  14422. eol,
  14423. ctx->active_connections,
  14424. eol,
  14425. ctx->max_connections,
  14426. eol,
  14427. ctx->total_connections,
  14428. eol,
  14429. eol);
  14430. context_info_length += (int)strlen(block);
  14431. if (context_info_length + reserved_len < buflen) {
  14432. strcat(buffer, block);
  14433. }
  14434. }
  14435. /* Requests information */
  14436. if (ctx) {
  14437. mg_snprintf(NULL,
  14438. NULL,
  14439. block,
  14440. sizeof(block),
  14441. "\"requests\" : {%s"
  14442. "\"total\" : %" INT64_FMT "%s"
  14443. "}%s",
  14444. eol,
  14445. ctx->total_requests,
  14446. eol,
  14447. eol);
  14448. context_info_length += (int)strlen(block);
  14449. if (context_info_length + reserved_len < buflen) {
  14450. strcat(buffer, block);
  14451. }
  14452. }
  14453. if ((buflen > 0) && buffer && buffer[0]) {
  14454. if (context_info_length < buflen) {
  14455. strcat(buffer, eoobj);
  14456. strcat(buffer, eol);
  14457. context_info_length += reserved_len;
  14458. }
  14459. }
  14460. return context_info_length;
  14461. }
  14462. #endif
  14463. /* Get system information. It can be printed or stored by the caller.
  14464. * Return the size of available information. */
  14465. int
  14466. mg_get_system_info(char *buffer, int buflen)
  14467. {
  14468. if ((buffer == NULL) || (buflen < 1)) {
  14469. return mg_get_system_info_impl(NULL, 0);
  14470. } else {
  14471. /* Reset buffer, so we can always use strcat. */
  14472. buffer[0] = 0;
  14473. return mg_get_system_info_impl(buffer, buflen);
  14474. }
  14475. }
  14476. /* Get context information. It can be printed or stored by the caller.
  14477. * Return the size of available information. */
  14478. int
  14479. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  14480. {
  14481. #if defined(USE_SERVER_STATS)
  14482. if ((buffer == NULL) || (buflen < 1)) {
  14483. return mg_get_context_info_impl(ctx, NULL, 0);
  14484. } else {
  14485. /* Reset buffer, so we can always use strcat. */
  14486. buffer[0] = 0;
  14487. return mg_get_context_info_impl(ctx, buffer, buflen);
  14488. }
  14489. #else
  14490. (void)ctx;
  14491. if ((buffer != NULL) && (buflen > 0)) {
  14492. buffer[0] = 0;
  14493. }
  14494. return 0;
  14495. #endif
  14496. }
  14497. /* mg_init_library counter */
  14498. static int mg_init_library_called = 0;
  14499. #if !defined(NO_SSL)
  14500. static int mg_ssl_initialized = 0;
  14501. #endif
  14502. /* Initialize this library. This function does not need to be thread safe. */
  14503. unsigned
  14504. mg_init_library(unsigned features)
  14505. {
  14506. #if !defined(NO_SSL)
  14507. char ebuf[128];
  14508. #endif
  14509. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  14510. unsigned features_inited = features_to_init;
  14511. #if !defined(NO_SSL)
  14512. if (features_to_init & 2) {
  14513. if (!mg_ssl_initialized) {
  14514. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  14515. mg_ssl_initialized = 1;
  14516. } else {
  14517. (void)ebuf;
  14518. /* TODO: print error */
  14519. features_inited &= ~(2u);
  14520. }
  14521. } else {
  14522. /* ssl already initialized */
  14523. }
  14524. }
  14525. #endif
  14526. /* Start Windows. */
  14527. if (mg_init_library_called <= 0) {
  14528. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14529. WSADATA data;
  14530. WSAStartup(MAKEWORD(2, 2), &data);
  14531. #endif /* _WIN32 && !__SYMBIAN32__ */
  14532. mg_init_library_called = 1;
  14533. } else {
  14534. mg_init_library_called++;
  14535. }
  14536. return features_inited;
  14537. }
  14538. /* Un-initialize this library. */
  14539. unsigned
  14540. mg_exit_library(void)
  14541. {
  14542. if (mg_init_library_called <= 0) {
  14543. return 0;
  14544. }
  14545. mg_init_library_called--;
  14546. if (mg_init_library_called == 0) {
  14547. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14548. (void)WSACleanup();
  14549. #endif /* _WIN32 && !__SYMBIAN32__ */
  14550. #if !defined(NO_SSL)
  14551. if (mg_ssl_initialized) {
  14552. uninitialize_ssl();
  14553. mg_ssl_initialized = 0;
  14554. }
  14555. #endif
  14556. }
  14557. return 1;
  14558. }
  14559. /* End of civetweb.c */