civetweb.c 425 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117
  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. #ifndef MAX_REQUEST_SIZE
  541. #define MAX_REQUEST_SIZE (16384)
  542. #endif
  543. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  544. "request size length must be a positive number");
  545. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  546. #if defined(_WIN32_WCE)
  547. /* Create substitutes for POSIX functions in Win32. */
  548. #if defined(__MINGW32__)
  549. /* Show no warning in case system functions are not used. */
  550. #pragma GCC diagnostic push
  551. #pragma GCC diagnostic ignored "-Wunused-function"
  552. #endif
  553. static time_t
  554. time(time_t *ptime)
  555. {
  556. time_t t;
  557. SYSTEMTIME st;
  558. FILETIME ft;
  559. GetSystemTime(&st);
  560. SystemTimeToFileTime(&st, &ft);
  561. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  562. if (ptime != NULL) {
  563. *ptime = t;
  564. }
  565. return t;
  566. }
  567. static struct tm *
  568. localtime_s(const time_t *ptime, struct tm *ptm)
  569. {
  570. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  571. FILETIME ft, lft;
  572. SYSTEMTIME st;
  573. TIME_ZONE_INFORMATION tzinfo;
  574. if (ptm == NULL) {
  575. return NULL;
  576. }
  577. *(int64_t *)&ft = t;
  578. FileTimeToLocalFileTime(&ft, &lft);
  579. FileTimeToSystemTime(&lft, &st);
  580. ptm->tm_year = st.wYear - 1900;
  581. ptm->tm_mon = st.wMonth - 1;
  582. ptm->tm_wday = st.wDayOfWeek;
  583. ptm->tm_mday = st.wDay;
  584. ptm->tm_hour = st.wHour;
  585. ptm->tm_min = st.wMinute;
  586. ptm->tm_sec = st.wSecond;
  587. ptm->tm_yday = 0; /* hope nobody uses this */
  588. ptm->tm_isdst =
  589. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  590. return ptm;
  591. }
  592. static struct tm *
  593. gmtime_s(const time_t *ptime, struct tm *ptm)
  594. {
  595. /* FIXME(lsm): fix this. */
  596. return localtime_s(ptime, ptm);
  597. }
  598. static int mg_atomic_inc(volatile int *addr);
  599. static struct tm tm_array[MAX_WORKER_THREADS];
  600. static int tm_index = 0;
  601. static struct tm *
  602. localtime(const time_t *ptime)
  603. {
  604. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  605. return localtime_s(ptime, tm_array + i);
  606. }
  607. static struct tm *
  608. gmtime(const time_t *ptime)
  609. {
  610. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  611. return gmtime_s(ptime, tm_array + i);
  612. }
  613. static size_t
  614. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  615. {
  616. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  617. * for WinCE"); */
  618. return 0;
  619. }
  620. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  621. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  622. #define remove(f) mg_remove(NULL, f)
  623. static int
  624. rename(const char *a, const char *b)
  625. {
  626. wchar_t wa[PATH_MAX];
  627. wchar_t wb[PATH_MAX];
  628. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  629. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  630. return MoveFileW(wa, wb) ? 0 : -1;
  631. }
  632. struct stat {
  633. int64_t st_size;
  634. time_t st_mtime;
  635. };
  636. static int
  637. stat(const char *name, struct stat *st)
  638. {
  639. wchar_t wbuf[PATH_MAX];
  640. WIN32_FILE_ATTRIBUTE_DATA attr;
  641. time_t creation_time, write_time;
  642. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  643. memset(&attr, 0, sizeof(attr));
  644. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  645. st->st_size =
  646. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  647. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  648. attr.ftLastWriteTime.dwHighDateTime);
  649. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  650. attr.ftCreationTime.dwHighDateTime);
  651. if (creation_time > write_time) {
  652. st->st_mtime = creation_time;
  653. } else {
  654. st->st_mtime = write_time;
  655. }
  656. return 0;
  657. }
  658. #define access(x, a) 1 /* not required anyway */
  659. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  660. /* Values from errno.h in Windows SDK (Visual Studio). */
  661. #define EEXIST 17
  662. #define EACCES 13
  663. #define ENOENT 2
  664. #if defined(__MINGW32__)
  665. /* Enable unused function warning again */
  666. #pragma GCC diagnostic pop
  667. #endif
  668. #endif /* defined(_WIN32_WCE) */
  669. static int
  670. mg_atomic_inc(volatile int *addr)
  671. {
  672. int ret;
  673. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  674. /* Depending on the SDK, this function uses either
  675. * (volatile unsigned int *) or (volatile LONG *),
  676. * so whatever you use, the other SDK is likely to raise a warning. */
  677. ret = InterlockedIncrement((volatile long *)addr);
  678. #elif defined(__GNUC__) \
  679. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  680. ret = __sync_add_and_fetch(addr, 1);
  681. #else
  682. ret = (++(*addr));
  683. #endif
  684. return ret;
  685. }
  686. static int
  687. mg_atomic_dec(volatile int *addr)
  688. {
  689. int ret;
  690. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  691. /* Depending on the SDK, this function uses either
  692. * (volatile unsigned int *) or (volatile LONG *),
  693. * so whatever you use, the other SDK is likely to raise a warning. */
  694. ret = InterlockedDecrement((volatile long *)addr);
  695. #elif defined(__GNUC__) \
  696. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  697. ret = __sync_sub_and_fetch(addr, 1);
  698. #else
  699. ret = (--(*addr));
  700. #endif
  701. return ret;
  702. }
  703. #if defined(__GNUC__) || defined(__MINGW32__)
  704. /* Show no warning in case system functions are not used. */
  705. #pragma GCC diagnostic push
  706. #pragma GCC diagnostic ignored "-Wunused-function"
  707. #endif
  708. #if defined(__clang__)
  709. /* Show no warning in case system functions are not used. */
  710. #pragma clang diagnostic push
  711. #pragma clang diagnostic ignored "-Wunused-function"
  712. #endif
  713. #if defined(USE_SERVER_STATS)
  714. static int64_t
  715. mg_atomic_add(volatile int64_t *addr, int64_t value)
  716. {
  717. int64_t ret;
  718. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  719. ret = InterlockedAdd64(addr, value);
  720. #elif defined(__GNUC__) \
  721. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  722. ret = __sync_add_and_fetch(addr, value);
  723. #else
  724. ret = (++(*addr));
  725. #endif
  726. return ret;
  727. }
  728. #endif
  729. #if defined(__GNUC__)
  730. /* Show no warning in case system functions are not used. */
  731. #pragma GCC diagnostic pop
  732. #endif
  733. #if defined(__clang__)
  734. /* Show no warning in case system functions are not used. */
  735. #pragma clang diagnostic pop
  736. #endif
  737. #if defined(USE_SERVER_STATS)
  738. struct mg_memory_stat {
  739. volatile int64_t totalMemUsed;
  740. volatile int64_t maxMemUsed;
  741. volatile int blockCount;
  742. };
  743. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  744. static void *
  745. mg_malloc_ex(size_t size,
  746. struct mg_context *ctx,
  747. const char *file,
  748. unsigned line)
  749. {
  750. void *data = malloc(size + 2 * sizeof(uintptr_t));
  751. void *memory = 0;
  752. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  753. #if defined(MEMORY_DEBUGGING)
  754. char mallocStr[256];
  755. #else
  756. (void)file;
  757. (void)line;
  758. #endif
  759. if (data) {
  760. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  761. if (mmem > mstat->maxMemUsed) {
  762. /* could use atomic compare exchange, but this
  763. * seems overkill for statistics data */
  764. mstat->maxMemUsed = mmem;
  765. }
  766. mg_atomic_inc(&mstat->blockCount);
  767. ((uintptr_t *)data)[0] = size;
  768. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  769. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  770. }
  771. #if defined(MEMORY_DEBUGGING)
  772. sprintf(mallocStr,
  773. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  774. memory,
  775. (unsigned long)size,
  776. (unsigned long)mstat->totalMemUsed,
  777. (unsigned long)mstat->blockCount,
  778. file,
  779. line);
  780. #if defined(_WIN32)
  781. OutputDebugStringA(mallocStr);
  782. #else
  783. DEBUG_TRACE("%s", mallocStr);
  784. #endif
  785. #endif
  786. return memory;
  787. }
  788. static void *
  789. mg_calloc_ex(size_t count,
  790. size_t size,
  791. struct mg_context *ctx,
  792. const char *file,
  793. unsigned line)
  794. {
  795. void *data = mg_malloc_ex(size * count, ctx, file, line);
  796. if (data) {
  797. memset(data, 0, size * count);
  798. }
  799. return data;
  800. }
  801. static void
  802. mg_free_ex(void *memory, const char *file, unsigned line)
  803. {
  804. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  805. #if defined(MEMORY_DEBUGGING)
  806. char mallocStr[256];
  807. #else
  808. (void)file;
  809. (void)line;
  810. #endif
  811. if (memory) {
  812. uintptr_t size = ((uintptr_t *)data)[0];
  813. struct mg_memory_stat *mstat =
  814. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  815. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  816. mg_atomic_dec(&mstat->blockCount);
  817. #if defined(MEMORY_DEBUGGING)
  818. sprintf(mallocStr,
  819. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  820. memory,
  821. (unsigned long)size,
  822. (unsigned long)mstat->totalMemUsed,
  823. (unsigned long)mstat->blockCount,
  824. file,
  825. line);
  826. #if defined(_WIN32)
  827. OutputDebugStringA(mallocStr);
  828. #else
  829. DEBUG_TRACE("%s", mallocStr);
  830. #endif
  831. #endif
  832. free(data);
  833. }
  834. }
  835. static void *
  836. mg_realloc_ex(void *memory,
  837. size_t newsize,
  838. struct mg_context *ctx,
  839. const char *file,
  840. unsigned line)
  841. {
  842. void *data;
  843. void *_realloc;
  844. uintptr_t oldsize;
  845. #if defined(MEMORY_DEBUGGING)
  846. char mallocStr[256];
  847. #else
  848. (void)file;
  849. (void)line;
  850. #endif
  851. if (newsize) {
  852. if (memory) {
  853. /* Reallocate existing block */
  854. struct mg_memory_stat *mstat;
  855. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  856. oldsize = ((uintptr_t *)data)[0];
  857. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  858. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  859. if (_realloc) {
  860. data = _realloc;
  861. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  862. #if defined(MEMORY_DEBUGGING)
  863. sprintf(mallocStr,
  864. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  865. memory,
  866. (unsigned long)oldsize,
  867. (unsigned long)mstat->totalMemUsed,
  868. (unsigned long)mstat->blockCount,
  869. file,
  870. line);
  871. #if defined(_WIN32)
  872. OutputDebugStringA(mallocStr);
  873. #else
  874. DEBUG_TRACE("%s", mallocStr);
  875. #endif
  876. #endif
  877. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  878. #if defined(MEMORY_DEBUGGING)
  879. sprintf(mallocStr,
  880. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  881. memory,
  882. (unsigned long)newsize,
  883. (unsigned long)mstat->totalMemUsed,
  884. (unsigned long)mstat->blockCount,
  885. file,
  886. line);
  887. #if defined(_WIN32)
  888. OutputDebugStringA(mallocStr);
  889. #else
  890. DEBUG_TRACE("%s", mallocStr);
  891. #endif
  892. #endif
  893. *(uintptr_t *)data = newsize;
  894. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  895. } else {
  896. #if defined(MEMORY_DEBUGGING)
  897. #if defined(_WIN32)
  898. OutputDebugStringA("MEM: realloc failed\n");
  899. #else
  900. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  901. #endif
  902. #endif
  903. return _realloc;
  904. }
  905. } else {
  906. /* Allocate new block */
  907. data = mg_malloc_ex(newsize, ctx, file, line);
  908. }
  909. } else {
  910. /* Free existing block */
  911. data = 0;
  912. mg_free_ex(memory, file, line);
  913. }
  914. return data;
  915. }
  916. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  917. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  918. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  919. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  920. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  921. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  922. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  923. #else /* USE_SERVER_STATS */
  924. static __inline void *
  925. mg_malloc(size_t a)
  926. {
  927. return malloc(a);
  928. }
  929. static __inline void *
  930. mg_calloc(size_t a, size_t b)
  931. {
  932. return calloc(a, b);
  933. }
  934. static __inline void *
  935. mg_realloc(void *a, size_t b)
  936. {
  937. return realloc(a, b);
  938. }
  939. static __inline void
  940. mg_free(void *a)
  941. {
  942. free(a);
  943. }
  944. #define mg_malloc_ctx(a, c) mg_malloc(a)
  945. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  946. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  947. #define mg_free_ctx(a, c) mg_free(a)
  948. #endif /* USE_SERVER_STATS */
  949. static void mg_vsnprintf(const struct mg_connection *conn,
  950. int *truncated,
  951. char *buf,
  952. size_t buflen,
  953. const char *fmt,
  954. va_list ap);
  955. static void mg_snprintf(const struct mg_connection *conn,
  956. int *truncated,
  957. char *buf,
  958. size_t buflen,
  959. PRINTF_FORMAT_STRING(const char *fmt),
  960. ...) PRINTF_ARGS(5, 6);
  961. /* This following lines are just meant as a reminder to use the mg-functions
  962. * for memory management */
  963. #ifdef malloc
  964. #undef malloc
  965. #endif
  966. #ifdef calloc
  967. #undef calloc
  968. #endif
  969. #ifdef realloc
  970. #undef realloc
  971. #endif
  972. #ifdef free
  973. #undef free
  974. #endif
  975. #ifdef snprintf
  976. #undef snprintf
  977. #endif
  978. #ifdef vsnprintf
  979. #undef vsnprintf
  980. #endif
  981. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  982. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  983. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  984. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  985. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  986. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  987. * but this define only works well for Windows. */
  988. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  989. #endif
  990. static pthread_key_t sTlsKey; /* Thread local storage index */
  991. static int sTlsInit = 0;
  992. static int thread_idx_max = 0;
  993. struct mg_workerTLS {
  994. int is_master;
  995. unsigned long thread_idx;
  996. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  997. HANDLE pthread_cond_helper_mutex;
  998. struct mg_workerTLS *next_waiting_thread;
  999. #endif
  1000. };
  1001. #if defined(__GNUC__) || defined(__MINGW32__)
  1002. /* Show no warning in case system functions are not used. */
  1003. #pragma GCC diagnostic push
  1004. #pragma GCC diagnostic ignored "-Wunused-function"
  1005. #endif
  1006. #if defined(__clang__)
  1007. /* Show no warning in case system functions are not used. */
  1008. #pragma clang diagnostic push
  1009. #pragma clang diagnostic ignored "-Wunused-function"
  1010. #endif
  1011. /* Get a unique thread ID as unsigned long, independent from the data type
  1012. * of thread IDs defined by the operating system API.
  1013. * If two calls to mg_current_thread_id return the same value, they calls
  1014. * are done from the same thread. If they return different values, they are
  1015. * done from different threads. (Provided this function is used in the same
  1016. * process context and threads are not repeatedly created and deleted, but
  1017. * CivetWeb does not do that).
  1018. * This function must match the signature required for SSL id callbacks:
  1019. * CRYPTO_set_id_callback
  1020. */
  1021. static unsigned long
  1022. mg_current_thread_id(void)
  1023. {
  1024. #ifdef _WIN32
  1025. return GetCurrentThreadId();
  1026. #else
  1027. #ifdef __clang__
  1028. #pragma clang diagnostic push
  1029. #pragma clang diagnostic ignored "-Wunreachable-code"
  1030. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1031. * or not, so one of the two conditions will be unreachable by construction.
  1032. * Unfortunately the C standard does not define a way to check this at
  1033. * compile time, since the #if preprocessor conditions can not use the sizeof
  1034. * operator as an argument. */
  1035. #endif
  1036. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1037. /* This is the problematic case for CRYPTO_set_id_callback:
  1038. * The OS pthread_t can not be cast to unsigned long. */
  1039. struct mg_workerTLS *tls =
  1040. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1041. if (tls == NULL) {
  1042. /* SSL called from an unknown thread: Create some thread index.
  1043. */
  1044. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1045. tls->is_master = -2; /* -2 means "3rd party thread" */
  1046. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1047. pthread_setspecific(sTlsKey, tls);
  1048. }
  1049. return tls->thread_idx;
  1050. } else {
  1051. /* pthread_t may be any data type, so a simple cast to unsigned long
  1052. * can rise a warning/error, depending on the platform.
  1053. * Here memcpy is used as an anything-to-anything cast. */
  1054. unsigned long ret = 0;
  1055. pthread_t t = pthread_self();
  1056. memcpy(&ret, &t, sizeof(pthread_t));
  1057. return ret;
  1058. }
  1059. #ifdef __clang__
  1060. #pragma clang diagnostic pop
  1061. #endif
  1062. #endif
  1063. }
  1064. static uint64_t
  1065. mg_get_current_time_ns()
  1066. {
  1067. struct timespec tsnow;
  1068. clock_gettime(CLOCK_REALTIME, &tsnow);
  1069. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1070. }
  1071. #if defined(__GNUC__)
  1072. /* Show no warning in case system functions are not used. */
  1073. #pragma GCC diagnostic pop
  1074. #endif
  1075. #if defined(__clang__)
  1076. /* Show no warning in case system functions are not used. */
  1077. #pragma clang diagnostic pop
  1078. #endif
  1079. #if !defined(DEBUG_TRACE)
  1080. #if defined(DEBUG)
  1081. static void DEBUG_TRACE_FUNC(const char *func,
  1082. unsigned line,
  1083. PRINTF_FORMAT_STRING(const char *fmt),
  1084. ...) PRINTF_ARGS(3, 4);
  1085. static void
  1086. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1087. {
  1088. va_list args;
  1089. uint64_t nsnow;
  1090. static uint64_t nslast;
  1091. struct timespec tsnow;
  1092. /* Get some operating system independent thread id */
  1093. unsigned long thread_id = mg_current_thread_id();
  1094. clock_gettime(CLOCK_REALTIME, &tsnow);
  1095. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1096. + ((uint64_t)tsnow.tv_nsec);
  1097. if (!nslast) {
  1098. nslast = nsnow;
  1099. }
  1100. flockfile(stdout);
  1101. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1102. (unsigned long)tsnow.tv_sec,
  1103. (unsigned long)tsnow.tv_nsec,
  1104. nsnow - nslast,
  1105. thread_id,
  1106. func,
  1107. line);
  1108. va_start(args, fmt);
  1109. vprintf(fmt, args);
  1110. va_end(args);
  1111. putchar('\n');
  1112. fflush(stdout);
  1113. funlockfile(stdout);
  1114. nslast = nsnow;
  1115. }
  1116. #define DEBUG_TRACE(fmt, ...) \
  1117. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1118. #else
  1119. #define DEBUG_TRACE(fmt, ...) \
  1120. do { \
  1121. } while (0)
  1122. #endif /* DEBUG */
  1123. #endif /* DEBUG_TRACE */
  1124. #define MD5_STATIC static
  1125. #include "md5.inl"
  1126. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1127. #ifdef NO_SOCKLEN_T
  1128. typedef int socklen_t;
  1129. #endif /* NO_SOCKLEN_T */
  1130. #define _DARWIN_UNLIMITED_SELECT
  1131. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1132. #if !defined(MSG_NOSIGNAL)
  1133. #define MSG_NOSIGNAL (0)
  1134. #endif
  1135. #if !defined(SOMAXCONN)
  1136. #define SOMAXCONN (100)
  1137. #endif
  1138. /* Size of the accepted socket queue */
  1139. #if !defined(MGSQLEN)
  1140. #define MGSQLEN (20)
  1141. #endif
  1142. #if defined(NO_SSL)
  1143. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1144. typedef struct SSL_CTX SSL_CTX;
  1145. #else
  1146. #if defined(NO_SSL_DL)
  1147. #include <openssl/ssl.h>
  1148. #include <openssl/err.h>
  1149. #include <openssl/crypto.h>
  1150. #include <openssl/x509.h>
  1151. #include <openssl/pem.h>
  1152. #include <openssl/engine.h>
  1153. #include <openssl/conf.h>
  1154. #include <openssl/dh.h>
  1155. #include <openssl/bn.h>
  1156. #include <openssl/opensslv.h>
  1157. #else
  1158. /* SSL loaded dynamically from DLL.
  1159. * I put the prototypes here to be independent from OpenSSL source
  1160. * installation. */
  1161. typedef struct ssl_st SSL;
  1162. typedef struct ssl_method_st SSL_METHOD;
  1163. typedef struct ssl_ctx_st SSL_CTX;
  1164. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1165. typedef struct x509_name X509_NAME;
  1166. typedef struct asn1_integer ASN1_INTEGER;
  1167. typedef struct bignum BIGNUM;
  1168. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1169. typedef struct evp_md EVP_MD;
  1170. typedef struct x509 X509;
  1171. #define SSL_CTRL_OPTIONS (32)
  1172. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1173. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1174. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1175. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1176. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1177. #define SSL_VERIFY_NONE (0)
  1178. #define SSL_VERIFY_PEER (1)
  1179. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1180. #define SSL_VERIFY_CLIENT_ONCE (4)
  1181. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1182. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1183. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1184. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1185. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1186. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1187. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1188. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1189. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1190. #define SSL_ERROR_NONE (0)
  1191. #define SSL_ERROR_SSL (1)
  1192. #define SSL_ERROR_WANT_READ (2)
  1193. #define SSL_ERROR_WANT_WRITE (3)
  1194. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1195. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1196. #define SSL_ERROR_ZERO_RETURN (6)
  1197. #define SSL_ERROR_WANT_CONNECT (7)
  1198. #define SSL_ERROR_WANT_ACCEPT (8)
  1199. struct ssl_func {
  1200. const char *name; /* SSL function name */
  1201. void (*ptr)(void); /* Function pointer */
  1202. };
  1203. #ifdef OPENSSL_API_1_1
  1204. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1205. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1206. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1207. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1208. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1209. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1210. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1211. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1212. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1213. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1214. #define OPENSSL_init_ssl \
  1215. (*(int (*)(uint64_t opts, \
  1216. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1217. #define SSL_CTX_use_PrivateKey_file \
  1218. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1219. #define SSL_CTX_use_certificate_file \
  1220. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1221. #define SSL_CTX_set_default_passwd_cb \
  1222. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1223. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1224. #define SSL_CTX_use_certificate_chain_file \
  1225. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1226. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1227. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1228. #define SSL_CTX_set_verify \
  1229. (*(void (*)(SSL_CTX *, \
  1230. int, \
  1231. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1232. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1233. #define SSL_CTX_load_verify_locations \
  1234. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1235. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1236. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1237. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1238. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1239. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1240. #define SSL_CIPHER_get_name \
  1241. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1242. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1243. #define SSL_CTX_set_session_id_context \
  1244. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1245. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1246. #define SSL_CTX_set_cipher_list \
  1247. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1248. #define SSL_CTX_set_options \
  1249. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1250. #define SSL_CTX_clear_options(ctx, op) \
  1251. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1252. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1253. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1254. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1255. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1256. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1257. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1258. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1259. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1260. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1261. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1262. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1263. #define X509_NAME_oneline \
  1264. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1265. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1266. #define EVP_get_digestbyname \
  1267. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1268. #define EVP_Digest \
  1269. (*(int (*)( \
  1270. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1271. crypto_sw[10].ptr)
  1272. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1273. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1274. #define ASN1_INTEGER_to_BN \
  1275. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1276. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1277. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1278. #define OPENSSL_free(a) CRYPTO_free(a)
  1279. /* set_ssl_option() function updates this array.
  1280. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1281. * of respective functions. The macros above (like SSL_connect()) are really
  1282. * just calling these functions indirectly via the pointer. */
  1283. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1284. {"SSL_accept", NULL},
  1285. {"SSL_connect", NULL},
  1286. {"SSL_read", NULL},
  1287. {"SSL_write", NULL},
  1288. {"SSL_get_error", NULL},
  1289. {"SSL_set_fd", NULL},
  1290. {"SSL_new", NULL},
  1291. {"SSL_CTX_new", NULL},
  1292. {"TLS_server_method", NULL},
  1293. {"OPENSSL_init_ssl", NULL},
  1294. {"SSL_CTX_use_PrivateKey_file", NULL},
  1295. {"SSL_CTX_use_certificate_file", NULL},
  1296. {"SSL_CTX_set_default_passwd_cb", NULL},
  1297. {"SSL_CTX_free", NULL},
  1298. {"SSL_CTX_use_certificate_chain_file", NULL},
  1299. {"TLS_client_method", NULL},
  1300. {"SSL_pending", NULL},
  1301. {"SSL_CTX_set_verify", NULL},
  1302. {"SSL_shutdown", NULL},
  1303. {"SSL_CTX_load_verify_locations", NULL},
  1304. {"SSL_CTX_set_default_verify_paths", NULL},
  1305. {"SSL_CTX_set_verify_depth", NULL},
  1306. {"SSL_get_peer_certificate", NULL},
  1307. {"SSL_get_version", NULL},
  1308. {"SSL_get_current_cipher", NULL},
  1309. {"SSL_CIPHER_get_name", NULL},
  1310. {"SSL_CTX_check_private_key", NULL},
  1311. {"SSL_CTX_set_session_id_context", NULL},
  1312. {"SSL_CTX_ctrl", NULL},
  1313. {"SSL_CTX_set_cipher_list", NULL},
  1314. {"SSL_CTX_set_options", NULL},
  1315. {NULL, NULL}};
  1316. /* Similar array as ssl_sw. These functions could be located in different
  1317. * lib. */
  1318. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1319. {"ERR_error_string", NULL},
  1320. {"ERR_remove_state", NULL},
  1321. {"CONF_modules_unload", NULL},
  1322. {"X509_free", NULL},
  1323. {"X509_get_subject_name", NULL},
  1324. {"X509_get_issuer_name", NULL},
  1325. {"X509_NAME_oneline", NULL},
  1326. {"X509_get_serialNumber", NULL},
  1327. {"EVP_get_digestbyname", NULL},
  1328. {"EVP_Digest", NULL},
  1329. {"i2d_X509", NULL},
  1330. {"BN_bn2hex", NULL},
  1331. {"ASN1_INTEGER_to_BN", NULL},
  1332. {"BN_free", NULL},
  1333. {"CRYPTO_free", NULL},
  1334. {NULL, NULL}};
  1335. #else
  1336. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1337. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1338. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1339. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1340. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1341. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1342. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1343. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1344. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1345. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1346. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1347. #define SSL_CTX_use_PrivateKey_file \
  1348. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1349. #define SSL_CTX_use_certificate_file \
  1350. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1351. #define SSL_CTX_set_default_passwd_cb \
  1352. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1353. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1354. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1355. #define SSL_CTX_use_certificate_chain_file \
  1356. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1357. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1358. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1359. #define SSL_CTX_set_verify \
  1360. (*(void (*)(SSL_CTX *, \
  1361. int, \
  1362. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1363. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1364. #define SSL_CTX_load_verify_locations \
  1365. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1366. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1367. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1368. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1369. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1370. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1371. #define SSL_CIPHER_get_name \
  1372. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1373. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1374. #define SSL_CTX_set_session_id_context \
  1375. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1376. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1377. #define SSL_CTX_set_cipher_list \
  1378. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1379. #define SSL_CTX_set_options(ctx, op) \
  1380. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1381. #define SSL_CTX_clear_options(ctx, op) \
  1382. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1383. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1384. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1385. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1386. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1387. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1388. #define CRYPTO_set_locking_callback \
  1389. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1390. #define CRYPTO_set_id_callback \
  1391. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1392. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1393. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1394. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1395. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1396. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1397. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1398. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1399. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1400. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1401. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1402. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1403. #define X509_NAME_oneline \
  1404. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1405. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1406. #define i2c_ASN1_INTEGER \
  1407. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1408. #define EVP_get_digestbyname \
  1409. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1410. #define EVP_Digest \
  1411. (*(int (*)( \
  1412. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1413. crypto_sw[18].ptr)
  1414. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1415. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1416. #define ASN1_INTEGER_to_BN \
  1417. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1418. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1419. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1420. #define OPENSSL_free(a) CRYPTO_free(a)
  1421. /* set_ssl_option() function updates this array.
  1422. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1423. * of respective functions. The macros above (like SSL_connect()) are really
  1424. * just calling these functions indirectly via the pointer. */
  1425. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1426. {"SSL_accept", NULL},
  1427. {"SSL_connect", NULL},
  1428. {"SSL_read", NULL},
  1429. {"SSL_write", NULL},
  1430. {"SSL_get_error", NULL},
  1431. {"SSL_set_fd", NULL},
  1432. {"SSL_new", NULL},
  1433. {"SSL_CTX_new", NULL},
  1434. {"SSLv23_server_method", NULL},
  1435. {"SSL_library_init", NULL},
  1436. {"SSL_CTX_use_PrivateKey_file", NULL},
  1437. {"SSL_CTX_use_certificate_file", NULL},
  1438. {"SSL_CTX_set_default_passwd_cb", NULL},
  1439. {"SSL_CTX_free", NULL},
  1440. {"SSL_load_error_strings", NULL},
  1441. {"SSL_CTX_use_certificate_chain_file", NULL},
  1442. {"SSLv23_client_method", NULL},
  1443. {"SSL_pending", NULL},
  1444. {"SSL_CTX_set_verify", NULL},
  1445. {"SSL_shutdown", NULL},
  1446. {"SSL_CTX_load_verify_locations", NULL},
  1447. {"SSL_CTX_set_default_verify_paths", NULL},
  1448. {"SSL_CTX_set_verify_depth", NULL},
  1449. {"SSL_get_peer_certificate", NULL},
  1450. {"SSL_get_version", NULL},
  1451. {"SSL_get_current_cipher", NULL},
  1452. {"SSL_CIPHER_get_name", NULL},
  1453. {"SSL_CTX_check_private_key", NULL},
  1454. {"SSL_CTX_set_session_id_context", NULL},
  1455. {"SSL_CTX_ctrl", NULL},
  1456. {"SSL_CTX_set_cipher_list", NULL},
  1457. {NULL, NULL}};
  1458. /* Similar array as ssl_sw. These functions could be located in different
  1459. * lib. */
  1460. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1461. {"CRYPTO_set_locking_callback", NULL},
  1462. {"CRYPTO_set_id_callback", NULL},
  1463. {"ERR_get_error", NULL},
  1464. {"ERR_error_string", NULL},
  1465. {"ERR_remove_state", NULL},
  1466. {"ERR_free_strings", NULL},
  1467. {"ENGINE_cleanup", NULL},
  1468. {"CONF_modules_unload", NULL},
  1469. {"CRYPTO_cleanup_all_ex_data", NULL},
  1470. {"EVP_cleanup", NULL},
  1471. {"X509_free", NULL},
  1472. {"X509_get_subject_name", NULL},
  1473. {"X509_get_issuer_name", NULL},
  1474. {"X509_NAME_oneline", NULL},
  1475. {"X509_get_serialNumber", NULL},
  1476. {"i2c_ASN1_INTEGER", NULL},
  1477. {"EVP_get_digestbyname", NULL},
  1478. {"EVP_Digest", NULL},
  1479. {"i2d_X509", NULL},
  1480. {"BN_bn2hex", NULL},
  1481. {"ASN1_INTEGER_to_BN", NULL},
  1482. {"BN_free", NULL},
  1483. {"CRYPTO_free", NULL},
  1484. {NULL, NULL}};
  1485. #endif /* OPENSSL_API_1_1 */
  1486. #endif /* NO_SSL_DL */
  1487. #endif /* NO_SSL */
  1488. #if !defined(NO_CACHING)
  1489. static const char *month_names[] = {"Jan",
  1490. "Feb",
  1491. "Mar",
  1492. "Apr",
  1493. "May",
  1494. "Jun",
  1495. "Jul",
  1496. "Aug",
  1497. "Sep",
  1498. "Oct",
  1499. "Nov",
  1500. "Dec"};
  1501. #endif /* !NO_CACHING */
  1502. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1503. * union u. */
  1504. union usa {
  1505. struct sockaddr sa;
  1506. struct sockaddr_in sin;
  1507. #if defined(USE_IPV6)
  1508. struct sockaddr_in6 sin6;
  1509. #endif
  1510. };
  1511. /* Describes a string (chunk of memory). */
  1512. struct vec {
  1513. const char *ptr;
  1514. size_t len;
  1515. };
  1516. struct mg_file_stat {
  1517. /* File properties filled by mg_stat: */
  1518. uint64_t size;
  1519. time_t last_modified;
  1520. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1521. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1522. * case we need a "Content-Eencoding: gzip" header */
  1523. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1524. };
  1525. struct mg_file_in_memory {
  1526. char *p;
  1527. uint32_t pos;
  1528. char mode;
  1529. };
  1530. struct mg_file_access {
  1531. /* File properties filled by mg_fopen: */
  1532. FILE *fp;
  1533. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1534. * support library. Use some struct mg_file_in_memory *mf; instead of
  1535. * membuf char pointer. */
  1536. const char *membuf;
  1537. };
  1538. struct mg_file {
  1539. struct mg_file_stat stat;
  1540. struct mg_file_access access;
  1541. };
  1542. #define STRUCT_FILE_INITIALIZER \
  1543. { \
  1544. { \
  1545. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1546. } \
  1547. , \
  1548. { \
  1549. (FILE *) NULL, (const char *)NULL \
  1550. } \
  1551. }
  1552. /* Describes listening socket, or socket which was accept()-ed by the master
  1553. * thread and queued for future handling by the worker thread. */
  1554. struct socket {
  1555. SOCKET sock; /* Listening socket */
  1556. union usa lsa; /* Local socket address */
  1557. union usa rsa; /* Remote socket address */
  1558. unsigned char is_ssl; /* Is port SSL-ed */
  1559. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1560. * port */
  1561. unsigned char in_use; /* Is valid */
  1562. };
  1563. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1564. enum {
  1565. CGI_EXTENSIONS,
  1566. CGI_ENVIRONMENT,
  1567. PUT_DELETE_PASSWORDS_FILE,
  1568. CGI_INTERPRETER,
  1569. PROTECT_URI,
  1570. AUTHENTICATION_DOMAIN,
  1571. ENABLE_AUTH_DOMAIN_CHECK,
  1572. SSI_EXTENSIONS,
  1573. THROTTLE,
  1574. ACCESS_LOG_FILE,
  1575. ENABLE_DIRECTORY_LISTING,
  1576. ERROR_LOG_FILE,
  1577. GLOBAL_PASSWORDS_FILE,
  1578. INDEX_FILES,
  1579. ENABLE_KEEP_ALIVE,
  1580. ACCESS_CONTROL_LIST,
  1581. EXTRA_MIME_TYPES,
  1582. LISTENING_PORTS,
  1583. DOCUMENT_ROOT,
  1584. SSL_CERTIFICATE,
  1585. SSL_CERTIFICATE_CHAIN,
  1586. NUM_THREADS,
  1587. RUN_AS_USER,
  1588. REWRITE,
  1589. HIDE_FILES,
  1590. REQUEST_TIMEOUT,
  1591. KEEP_ALIVE_TIMEOUT,
  1592. LINGER_TIMEOUT,
  1593. SSL_DO_VERIFY_PEER,
  1594. SSL_CA_PATH,
  1595. SSL_CA_FILE,
  1596. SSL_VERIFY_DEPTH,
  1597. SSL_DEFAULT_VERIFY_PATHS,
  1598. SSL_CIPHER_LIST,
  1599. SSL_PROTOCOL_VERSION,
  1600. SSL_SHORT_TRUST,
  1601. #if defined(USE_WEBSOCKET)
  1602. WEBSOCKET_TIMEOUT,
  1603. #endif
  1604. DECODE_URL,
  1605. #if defined(USE_LUA)
  1606. LUA_PRELOAD_FILE,
  1607. LUA_SCRIPT_EXTENSIONS,
  1608. LUA_SERVER_PAGE_EXTENSIONS,
  1609. #endif
  1610. #if defined(USE_DUKTAPE)
  1611. DUKTAPE_SCRIPT_EXTENSIONS,
  1612. #endif
  1613. #if defined(USE_WEBSOCKET)
  1614. WEBSOCKET_ROOT,
  1615. #endif
  1616. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1617. LUA_WEBSOCKET_EXTENSIONS,
  1618. #endif
  1619. ACCESS_CONTROL_ALLOW_ORIGIN,
  1620. ERROR_PAGES,
  1621. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1622. * socket option typedef TCP_NODELAY. */
  1623. #if !defined(NO_CACHING)
  1624. STATIC_FILE_MAX_AGE,
  1625. #endif
  1626. #if defined(__linux__)
  1627. ALLOW_SENDFILE_CALL,
  1628. #endif
  1629. #if defined(_WIN32)
  1630. CASE_SENSITIVE_FILES,
  1631. #endif
  1632. #if defined(USE_LUA)
  1633. LUA_BACKGROUND_SCRIPT,
  1634. #endif
  1635. NUM_OPTIONS
  1636. };
  1637. /* Config option name, config types, default value */
  1638. static struct mg_option config_options[] = {
  1639. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1640. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1641. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1642. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1643. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1644. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1645. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1646. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1647. {"throttle", CONFIG_TYPE_STRING, NULL},
  1648. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1649. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1650. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1651. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1652. {"index_files",
  1653. CONFIG_TYPE_STRING,
  1654. #ifdef USE_LUA
  1655. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1656. "index.shtml,index.php"},
  1657. #else
  1658. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1659. #endif
  1660. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1661. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1662. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1663. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1664. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1665. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1666. {"ssl_certificate_chain", CONFIG_TYPE_FILE, NULL},
  1667. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1668. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1669. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1670. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1671. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1672. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1673. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1674. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1675. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1676. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1677. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1678. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1679. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1680. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1681. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1682. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1683. #if defined(USE_WEBSOCKET)
  1684. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1685. #endif
  1686. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1687. #if defined(USE_LUA)
  1688. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1689. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1690. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1691. #endif
  1692. #if defined(USE_DUKTAPE)
  1693. /* The support for duktape is still in alpha version state.
  1694. * The name of this config option might change. */
  1695. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1696. #endif
  1697. #if defined(USE_WEBSOCKET)
  1698. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1699. #endif
  1700. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1701. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1702. #endif
  1703. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1704. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1705. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1706. #if !defined(NO_CACHING)
  1707. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1708. #endif
  1709. #if defined(__linux__)
  1710. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1711. #endif
  1712. #if defined(_WIN32)
  1713. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1714. #endif
  1715. #if defined(USE_LUA)
  1716. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1717. #endif
  1718. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1719. /* Check if the config_options and the corresponding enum have compatible
  1720. * sizes. */
  1721. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1722. == (NUM_OPTIONS + 1),
  1723. "config_options and enum not sync");
  1724. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1725. struct mg_handler_info {
  1726. /* Name/Pattern of the URI. */
  1727. char *uri;
  1728. size_t uri_len;
  1729. /* handler type */
  1730. int handler_type;
  1731. /* Handler for http/https or authorization requests. */
  1732. mg_request_handler handler;
  1733. /* Handler for ws/wss (websocket) requests. */
  1734. mg_websocket_connect_handler connect_handler;
  1735. mg_websocket_ready_handler ready_handler;
  1736. mg_websocket_data_handler data_handler;
  1737. mg_websocket_close_handler close_handler;
  1738. /* accepted subprotocols for ws/wss requests. */
  1739. struct mg_websocket_subprotocols *subprotocols;
  1740. /* Handler for authorization requests */
  1741. mg_authorization_handler auth_handler;
  1742. /* User supplied argument for the handler function. */
  1743. void *cbdata;
  1744. /* next handler in a linked list */
  1745. struct mg_handler_info *next;
  1746. };
  1747. struct mg_context {
  1748. volatile int stop_flag; /* Should we stop event loop */
  1749. SSL_CTX *ssl_ctx; /* SSL context */
  1750. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1751. struct mg_callbacks callbacks; /* User-defined callback function */
  1752. void *user_data; /* User-defined data */
  1753. int context_type; /* 1 = server context,
  1754. * 2 = ws/wss client context,
  1755. */
  1756. struct socket *listening_sockets;
  1757. struct pollfd *listening_socket_fds;
  1758. unsigned int num_listening_sockets;
  1759. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1760. #ifdef ALTERNATIVE_QUEUE
  1761. struct socket *client_socks;
  1762. void **client_wait_events;
  1763. #else
  1764. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1765. volatile int sq_head; /* Head of the socket queue */
  1766. volatile int sq_tail; /* Tail of the socket queue */
  1767. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1768. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1769. #endif
  1770. pthread_t masterthreadid; /* The master thread ID */
  1771. unsigned int
  1772. cfg_worker_threads; /* The number of configured worker threads. */
  1773. pthread_t *worker_threadids; /* The worker thread IDs */
  1774. struct mg_connection *worker_connections; /* The connection struct, pre-
  1775. * allocated for each worker */
  1776. time_t start_time; /* Server start time, used for authentication */
  1777. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1778. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1779. unsigned long nonce_count; /* Used nonces, used for authentication */
  1780. char *systemName; /* What operating system is running */
  1781. /* linked list of uri handlers */
  1782. struct mg_handler_info *handlers;
  1783. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1784. /* linked list of shared lua websockets */
  1785. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1786. #endif
  1787. #if defined(USE_TIMERS)
  1788. struct ttimers *timers;
  1789. #endif
  1790. #if defined(USE_LUA)
  1791. void *lua_background_state;
  1792. #endif
  1793. #if defined(USE_SERVER_STATS)
  1794. int active_connections;
  1795. int max_connections;
  1796. int64_t total_connections;
  1797. int64_t total_requests;
  1798. struct mg_memory_stat ctx_memory;
  1799. #endif
  1800. };
  1801. #if defined(USE_SERVER_STATS)
  1802. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  1803. static struct mg_memory_stat *
  1804. get_memory_stat(struct mg_context *ctx)
  1805. {
  1806. if (ctx) {
  1807. return &(ctx->ctx_memory);
  1808. }
  1809. return &mg_common_memory;
  1810. }
  1811. #endif
  1812. struct mg_connection {
  1813. struct mg_request_info request_info;
  1814. struct mg_context *ctx;
  1815. SSL *ssl; /* SSL descriptor */
  1816. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1817. struct socket client; /* Connected client */
  1818. time_t conn_birth_time; /* Time (wall clock) when connection was
  1819. * established */
  1820. struct timespec req_time; /* Time (since system start) when the request
  1821. * was received */
  1822. int64_t num_bytes_sent; /* Total bytes sent to client */
  1823. int64_t content_len; /* Content-Length header value */
  1824. int64_t consumed_content; /* How many bytes of content have been read */
  1825. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1826. * data available, 2: all data read */
  1827. size_t chunk_remainder; /* Unread data from the last chunk */
  1828. char *buf; /* Buffer for received data */
  1829. char *path_info; /* PATH_INFO part of the URL */
  1830. int must_close; /* 1 if connection must be closed */
  1831. int in_error_handler; /* 1 if in handler for user defined error
  1832. * pages */
  1833. int handled_requests; /* Number of requests handled by this connection */
  1834. int buf_size; /* Buffer size */
  1835. int request_len; /* Size of the request + headers in a buffer */
  1836. int data_len; /* Total size of data in a buffer */
  1837. int status_code; /* HTTP reply status code, e.g. 200 */
  1838. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1839. * throttle */
  1840. time_t last_throttle_time; /* Last time throttled data was sent */
  1841. int64_t last_throttle_bytes; /* Bytes sent this second */
  1842. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1843. * atomic transmissions for websockets */
  1844. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1845. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1846. #endif
  1847. int thread_index; /* Thread index within ctx */
  1848. };
  1849. /* Directory entry */
  1850. struct de {
  1851. struct mg_connection *conn;
  1852. char *file_name;
  1853. struct mg_file_stat file;
  1854. };
  1855. #if defined(USE_WEBSOCKET)
  1856. static int is_websocket_protocol(const struct mg_connection *conn);
  1857. #else
  1858. #define is_websocket_protocol(conn) (0)
  1859. #endif
  1860. #if !defined(NO_THREAD_NAME)
  1861. #if defined(_WIN32) && defined(_MSC_VER)
  1862. /* Set the thread name for debugging purposes in Visual Studio
  1863. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1864. */
  1865. #pragma pack(push, 8)
  1866. typedef struct tagTHREADNAME_INFO {
  1867. DWORD dwType; /* Must be 0x1000. */
  1868. LPCSTR szName; /* Pointer to name (in user addr space). */
  1869. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1870. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1871. } THREADNAME_INFO;
  1872. #pragma pack(pop)
  1873. #elif defined(__linux__)
  1874. #include <sys/prctl.h>
  1875. #include <sys/sendfile.h>
  1876. #include <sys/eventfd.h>
  1877. #if defined(ALTERNATIVE_QUEUE)
  1878. static void *
  1879. event_create(void)
  1880. {
  1881. int ret = eventfd(0, EFD_CLOEXEC);
  1882. if (ret == -1) {
  1883. /* Linux uses -1 on error, Windows NULL. */
  1884. /* However, Linux does not return 0 on success either. */
  1885. return 0;
  1886. }
  1887. return (void *)ret;
  1888. }
  1889. static int
  1890. event_wait(void *eventhdl)
  1891. {
  1892. uint64_t u;
  1893. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1894. if (s != sizeof(uint64_t)) {
  1895. /* error */
  1896. return 0;
  1897. }
  1898. (void)u; /* the value is not required */
  1899. return 1;
  1900. }
  1901. static int
  1902. event_signal(void *eventhdl)
  1903. {
  1904. uint64_t u = 1;
  1905. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1906. if (s != sizeof(uint64_t)) {
  1907. /* error */
  1908. return 0;
  1909. }
  1910. return 1;
  1911. }
  1912. static void
  1913. event_destroy(void *eventhdl)
  1914. {
  1915. close((int)eventhdl);
  1916. }
  1917. #endif
  1918. #endif
  1919. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1920. struct posix_event {
  1921. pthread_mutex_t mutex;
  1922. pthread_cond_t cond;
  1923. };
  1924. static void *
  1925. event_create(void)
  1926. {
  1927. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1928. if (ret == 0) {
  1929. /* out of memory */
  1930. return 0;
  1931. }
  1932. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1933. /* pthread mutex not available */
  1934. mg_free(ret);
  1935. return 0;
  1936. }
  1937. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1938. /* pthread cond not available */
  1939. pthread_mutex_destroy(&(ret->mutex));
  1940. mg_free(ret);
  1941. return 0;
  1942. }
  1943. return (void *)ret;
  1944. }
  1945. static int
  1946. event_wait(void *eventhdl)
  1947. {
  1948. struct posix_event *ev = (struct posix_event *)eventhdl;
  1949. pthread_mutex_lock(&(ev->mutex));
  1950. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1951. pthread_mutex_unlock(&(ev->mutex));
  1952. return 1;
  1953. }
  1954. static int
  1955. event_signal(void *eventhdl)
  1956. {
  1957. struct posix_event *ev = (struct posix_event *)eventhdl;
  1958. pthread_mutex_lock(&(ev->mutex));
  1959. pthread_cond_signal(&(ev->cond));
  1960. pthread_mutex_unlock(&(ev->mutex));
  1961. return 1;
  1962. }
  1963. static void
  1964. event_destroy(void *eventhdl)
  1965. {
  1966. struct posix_event *ev = (struct posix_event *)eventhdl;
  1967. pthread_cond_destroy(&(ev->cond));
  1968. pthread_mutex_destroy(&(ev->mutex));
  1969. mg_free(ev);
  1970. }
  1971. #endif
  1972. static void
  1973. mg_set_thread_name(const char *name)
  1974. {
  1975. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1976. mg_snprintf(
  1977. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1978. #if defined(_WIN32)
  1979. #if defined(_MSC_VER)
  1980. /* Windows and Visual Studio Compiler */
  1981. __try
  1982. {
  1983. THREADNAME_INFO info;
  1984. info.dwType = 0x1000;
  1985. info.szName = threadName;
  1986. info.dwThreadID = ~0U;
  1987. info.dwFlags = 0;
  1988. RaiseException(0x406D1388,
  1989. 0,
  1990. sizeof(info) / sizeof(ULONG_PTR),
  1991. (ULONG_PTR *)&info);
  1992. }
  1993. __except(EXCEPTION_EXECUTE_HANDLER)
  1994. {
  1995. }
  1996. #elif defined(__MINGW32__)
  1997. /* No option known to set thread name for MinGW */
  1998. #endif
  1999. #elif defined(__GLIBC__) \
  2000. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2001. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2002. (void)pthread_setname_np(pthread_self(), threadName);
  2003. #elif defined(__linux__)
  2004. /* on linux we can use the old prctl function */
  2005. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2006. #endif
  2007. }
  2008. #else /* !defined(NO_THREAD_NAME) */
  2009. void
  2010. mg_set_thread_name(const char *threadName)
  2011. {
  2012. }
  2013. #endif
  2014. #if defined(MG_LEGACY_INTERFACE)
  2015. const char **
  2016. mg_get_valid_option_names(void)
  2017. {
  2018. /* This function is deprecated. Use mg_get_valid_options instead. */
  2019. static const char *
  2020. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2021. int i;
  2022. for (i = 0; config_options[i].name != NULL; i++) {
  2023. data[i * 2] = config_options[i].name;
  2024. data[i * 2 + 1] = config_options[i].default_value;
  2025. }
  2026. return data;
  2027. }
  2028. #endif
  2029. const struct mg_option *
  2030. mg_get_valid_options(void)
  2031. {
  2032. return config_options;
  2033. }
  2034. /* Do not open file (used in is_file_in_memory) */
  2035. #define MG_FOPEN_MODE_NONE (0)
  2036. /* Open file for read only access */
  2037. #define MG_FOPEN_MODE_READ (1)
  2038. /* Open file for writing, create and overwrite */
  2039. #define MG_FOPEN_MODE_WRITE (2)
  2040. /* Open file for writing, create and append */
  2041. #define MG_FOPEN_MODE_APPEND (4)
  2042. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2043. * output filep and return 1, otherwise return 0 and don't modify anything. */
  2044. static int
  2045. open_file_in_memory(const struct mg_connection *conn,
  2046. const char *path,
  2047. struct mg_file *filep,
  2048. int mode)
  2049. {
  2050. #if defined(MG_USE_OPEN_FILE)
  2051. size_t size = 0;
  2052. const char *buf = NULL;
  2053. if (!conn) {
  2054. return 0;
  2055. }
  2056. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2057. return 0;
  2058. }
  2059. if (conn->ctx->callbacks.open_file) {
  2060. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2061. if (buf != NULL) {
  2062. if (filep == NULL) {
  2063. /* This is a file in memory, but we cannot store the properties
  2064. * now.
  2065. * Called from "is_file_in_memory" function. */
  2066. return 1;
  2067. }
  2068. /* NOTE: override filep->size only on success. Otherwise, it might
  2069. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2070. filep->access.membuf = buf;
  2071. filep->access.fp = NULL;
  2072. /* Size was set by the callback */
  2073. filep->stat.size = size;
  2074. /* Assume the data may change during runtime by setting
  2075. * last_modified = now */
  2076. filep->stat.last_modified = time(NULL);
  2077. filep->stat.is_directory = 0;
  2078. filep->stat.is_gzipped = 0;
  2079. }
  2080. }
  2081. return (buf != NULL);
  2082. #else
  2083. (void)conn;
  2084. (void)path;
  2085. (void)filep;
  2086. (void)mode;
  2087. return 0;
  2088. #endif
  2089. }
  2090. static int
  2091. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2092. {
  2093. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2094. }
  2095. static int
  2096. is_file_opened(const struct mg_file_access *fileacc)
  2097. {
  2098. if (!fileacc) {
  2099. return 0;
  2100. }
  2101. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2102. }
  2103. static int mg_stat(const struct mg_connection *conn,
  2104. const char *path,
  2105. struct mg_file_stat *filep);
  2106. /* mg_fopen will open a file either in memory or on the disk.
  2107. * The input parameter path is a string in UTF-8 encoding.
  2108. * The input parameter mode is MG_FOPEN_MODE_*
  2109. * On success, either fp or membuf will be set in the output
  2110. * struct file. All status members will also be set.
  2111. * The function returns 1 on success, 0 on error. */
  2112. static int
  2113. mg_fopen(const struct mg_connection *conn,
  2114. const char *path,
  2115. int mode,
  2116. struct mg_file *filep)
  2117. {
  2118. int found;
  2119. if (!filep) {
  2120. return 0;
  2121. }
  2122. filep->access.fp = NULL;
  2123. filep->access.membuf = NULL;
  2124. if (!is_file_in_memory(conn, path)) {
  2125. /* filep is initialized in mg_stat: all fields with memset to,
  2126. * some fields like size and modification date with values */
  2127. found = mg_stat(conn, path, &(filep->stat));
  2128. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2129. /* file does not exist and will not be created */
  2130. return 0;
  2131. }
  2132. #ifdef _WIN32
  2133. {
  2134. wchar_t wbuf[PATH_MAX];
  2135. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2136. switch (mode) {
  2137. case MG_FOPEN_MODE_READ:
  2138. filep->access.fp = _wfopen(wbuf, L"rb");
  2139. break;
  2140. case MG_FOPEN_MODE_WRITE:
  2141. filep->access.fp = _wfopen(wbuf, L"wb");
  2142. break;
  2143. case MG_FOPEN_MODE_APPEND:
  2144. filep->access.fp = _wfopen(wbuf, L"ab");
  2145. break;
  2146. }
  2147. }
  2148. #else
  2149. /* Linux et al already use unicode. No need to convert. */
  2150. switch (mode) {
  2151. case MG_FOPEN_MODE_READ:
  2152. filep->access.fp = fopen(path, "r");
  2153. break;
  2154. case MG_FOPEN_MODE_WRITE:
  2155. filep->access.fp = fopen(path, "w");
  2156. break;
  2157. case MG_FOPEN_MODE_APPEND:
  2158. filep->access.fp = fopen(path, "a");
  2159. break;
  2160. }
  2161. #endif
  2162. if (!found) {
  2163. /* File did not exist before fopen was called.
  2164. * Maybe it has been created now. Get stat info
  2165. * like creation time now. */
  2166. found = mg_stat(conn, path, &(filep->stat));
  2167. (void)found;
  2168. }
  2169. /* file is on disk */
  2170. return (filep->access.fp != NULL);
  2171. } else {
  2172. /* is_file_in_memory returned true */
  2173. if (open_file_in_memory(conn, path, filep, mode)) {
  2174. /* file is in memory */
  2175. return (filep->access.membuf != NULL);
  2176. }
  2177. }
  2178. /* Open failed */
  2179. return 0;
  2180. }
  2181. /* return 0 on success, just like fclose */
  2182. static int
  2183. mg_fclose(struct mg_file_access *fileacc)
  2184. {
  2185. int ret = -1;
  2186. if (fileacc != NULL) {
  2187. if (fileacc->fp != NULL) {
  2188. ret = fclose(fileacc->fp);
  2189. } else if (fileacc->membuf != NULL) {
  2190. ret = 0;
  2191. }
  2192. /* reset all members of fileacc */
  2193. memset(fileacc, 0, sizeof(*fileacc));
  2194. }
  2195. return ret;
  2196. }
  2197. static void
  2198. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2199. {
  2200. for (; *src != '\0' && n > 1; n--) {
  2201. *dst++ = *src++;
  2202. }
  2203. *dst = '\0';
  2204. }
  2205. static int
  2206. lowercase(const char *s)
  2207. {
  2208. return tolower(*(const unsigned char *)s);
  2209. }
  2210. int
  2211. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2212. {
  2213. int diff = 0;
  2214. if (len > 0) {
  2215. do {
  2216. diff = lowercase(s1++) - lowercase(s2++);
  2217. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2218. }
  2219. return diff;
  2220. }
  2221. int
  2222. mg_strcasecmp(const char *s1, const char *s2)
  2223. {
  2224. int diff;
  2225. do {
  2226. diff = lowercase(s1++) - lowercase(s2++);
  2227. } while (diff == 0 && s1[-1] != '\0');
  2228. return diff;
  2229. }
  2230. static char *
  2231. mg_strndup(const char *ptr, size_t len)
  2232. {
  2233. char *p;
  2234. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2235. mg_strlcpy(p, ptr, len + 1);
  2236. }
  2237. return p;
  2238. }
  2239. static char *
  2240. mg_strdup(const char *str)
  2241. {
  2242. return mg_strndup(str, strlen(str));
  2243. }
  2244. static const char *
  2245. mg_strcasestr(const char *big_str, const char *small_str)
  2246. {
  2247. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2248. if (big_len >= small_len) {
  2249. for (i = 0; i <= (big_len - small_len); i++) {
  2250. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2251. return big_str + i;
  2252. }
  2253. }
  2254. }
  2255. return NULL;
  2256. }
  2257. /* Return null terminated string of given maximum length.
  2258. * Report errors if length is exceeded. */
  2259. static void
  2260. mg_vsnprintf(const struct mg_connection *conn,
  2261. int *truncated,
  2262. char *buf,
  2263. size_t buflen,
  2264. const char *fmt,
  2265. va_list ap)
  2266. {
  2267. int n, ok;
  2268. if (buflen == 0) {
  2269. return;
  2270. }
  2271. #ifdef __clang__
  2272. #pragma clang diagnostic push
  2273. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2274. /* Using fmt as a non-literal is intended here, since it is mostly called
  2275. * indirectly by mg_snprintf */
  2276. #endif
  2277. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2278. ok = (n >= 0) && ((size_t)n < buflen);
  2279. #ifdef __clang__
  2280. #pragma clang diagnostic pop
  2281. #endif
  2282. if (ok) {
  2283. if (truncated) {
  2284. *truncated = 0;
  2285. }
  2286. } else {
  2287. if (truncated) {
  2288. *truncated = 1;
  2289. }
  2290. mg_cry(conn,
  2291. "truncating vsnprintf buffer: [%.*s]",
  2292. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2293. buf);
  2294. n = (int)buflen - 1;
  2295. }
  2296. buf[n] = '\0';
  2297. }
  2298. static void
  2299. mg_snprintf(const struct mg_connection *conn,
  2300. int *truncated,
  2301. char *buf,
  2302. size_t buflen,
  2303. const char *fmt,
  2304. ...)
  2305. {
  2306. va_list ap;
  2307. va_start(ap, fmt);
  2308. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2309. va_end(ap);
  2310. }
  2311. static int
  2312. get_option_index(const char *name)
  2313. {
  2314. int i;
  2315. for (i = 0; config_options[i].name != NULL; i++) {
  2316. if (strcmp(config_options[i].name, name) == 0) {
  2317. return i;
  2318. }
  2319. }
  2320. return -1;
  2321. }
  2322. const char *
  2323. mg_get_option(const struct mg_context *ctx, const char *name)
  2324. {
  2325. int i;
  2326. if ((i = get_option_index(name)) == -1) {
  2327. return NULL;
  2328. } else if (!ctx || ctx->config[i] == NULL) {
  2329. return "";
  2330. } else {
  2331. return ctx->config[i];
  2332. }
  2333. }
  2334. struct mg_context *
  2335. mg_get_context(const struct mg_connection *conn)
  2336. {
  2337. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2338. }
  2339. void *
  2340. mg_get_user_data(const struct mg_context *ctx)
  2341. {
  2342. return (ctx == NULL) ? NULL : ctx->user_data;
  2343. }
  2344. void
  2345. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2346. {
  2347. if (conn != NULL) {
  2348. conn->request_info.conn_data = data;
  2349. }
  2350. }
  2351. void *
  2352. mg_get_user_connection_data(const struct mg_connection *conn)
  2353. {
  2354. if (conn != NULL) {
  2355. return conn->request_info.conn_data;
  2356. }
  2357. return NULL;
  2358. }
  2359. #if defined(MG_LEGACY_INTERFACE)
  2360. /* Deprecated: Use mg_get_server_ports instead. */
  2361. size_t
  2362. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2363. {
  2364. size_t i;
  2365. if (!ctx) {
  2366. return 0;
  2367. }
  2368. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2369. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2370. ports[i] =
  2371. #if defined(USE_IPV6)
  2372. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2373. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2374. :
  2375. #endif
  2376. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2377. }
  2378. return i;
  2379. }
  2380. #endif
  2381. int
  2382. mg_get_server_ports(const struct mg_context *ctx,
  2383. int size,
  2384. struct mg_server_ports *ports)
  2385. {
  2386. int i, cnt = 0;
  2387. if (size <= 0) {
  2388. return -1;
  2389. }
  2390. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2391. if (!ctx) {
  2392. return -1;
  2393. }
  2394. if (!ctx->listening_sockets) {
  2395. return -1;
  2396. }
  2397. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2398. ports[cnt].port =
  2399. #if defined(USE_IPV6)
  2400. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2401. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2402. :
  2403. #endif
  2404. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2405. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2406. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2407. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2408. /* IPv4 */
  2409. ports[cnt].protocol = 1;
  2410. cnt++;
  2411. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2412. /* IPv6 */
  2413. ports[cnt].protocol = 3;
  2414. cnt++;
  2415. }
  2416. }
  2417. return cnt;
  2418. }
  2419. static void
  2420. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2421. {
  2422. buf[0] = '\0';
  2423. if (!usa) {
  2424. return;
  2425. }
  2426. if (usa->sa.sa_family == AF_INET) {
  2427. getnameinfo(&usa->sa,
  2428. sizeof(usa->sin),
  2429. buf,
  2430. (unsigned)len,
  2431. NULL,
  2432. 0,
  2433. NI_NUMERICHOST);
  2434. }
  2435. #if defined(USE_IPV6)
  2436. else if (usa->sa.sa_family == AF_INET6) {
  2437. getnameinfo(&usa->sa,
  2438. sizeof(usa->sin6),
  2439. buf,
  2440. (unsigned)len,
  2441. NULL,
  2442. 0,
  2443. NI_NUMERICHOST);
  2444. }
  2445. #endif
  2446. }
  2447. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2448. * included in all responses other than 100, 101, 5xx. */
  2449. static void
  2450. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2451. {
  2452. struct tm *tm;
  2453. tm = ((t != NULL) ? gmtime(t) : NULL);
  2454. if (tm != NULL) {
  2455. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2456. } else {
  2457. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2458. buf[buf_len - 1] = '\0';
  2459. }
  2460. }
  2461. /* difftime for struct timespec. Return value is in seconds. */
  2462. static double
  2463. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2464. {
  2465. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2466. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2467. }
  2468. /* Print error message to the opened error log stream. */
  2469. void
  2470. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2471. {
  2472. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2473. va_list ap;
  2474. struct mg_file fi;
  2475. time_t timestamp;
  2476. va_start(ap, fmt);
  2477. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2478. va_end(ap);
  2479. buf[sizeof(buf) - 1] = 0;
  2480. if (!conn) {
  2481. puts(buf);
  2482. return;
  2483. }
  2484. /* Do not lock when getting the callback value, here and below.
  2485. * I suppose this is fine, since function cannot disappear in the
  2486. * same way string option can. */
  2487. if ((conn->ctx->callbacks.log_message == NULL)
  2488. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2489. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2490. if (mg_fopen(conn,
  2491. conn->ctx->config[ERROR_LOG_FILE],
  2492. MG_FOPEN_MODE_APPEND,
  2493. &fi) == 0) {
  2494. fi.access.fp = NULL;
  2495. }
  2496. } else {
  2497. fi.access.fp = NULL;
  2498. }
  2499. if (fi.access.fp != NULL) {
  2500. flockfile(fi.access.fp);
  2501. timestamp = time(NULL);
  2502. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2503. fprintf(fi.access.fp,
  2504. "[%010lu] [error] [client %s] ",
  2505. (unsigned long)timestamp,
  2506. src_addr);
  2507. if (conn->request_info.request_method != NULL) {
  2508. fprintf(fi.access.fp,
  2509. "%s %s: ",
  2510. conn->request_info.request_method,
  2511. conn->request_info.request_uri);
  2512. }
  2513. fprintf(fi.access.fp, "%s", buf);
  2514. fputc('\n', fi.access.fp);
  2515. fflush(fi.access.fp);
  2516. funlockfile(fi.access.fp);
  2517. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2518. * mg_cry here anyway ;-) */
  2519. }
  2520. }
  2521. }
  2522. /* Return fake connection structure. Used for logging, if connection
  2523. * is not applicable at the moment of logging. */
  2524. static struct mg_connection *
  2525. fc(struct mg_context *ctx)
  2526. {
  2527. static struct mg_connection fake_connection;
  2528. fake_connection.ctx = ctx;
  2529. return &fake_connection;
  2530. }
  2531. const char *
  2532. mg_version(void)
  2533. {
  2534. return CIVETWEB_VERSION;
  2535. }
  2536. const struct mg_request_info *
  2537. mg_get_request_info(const struct mg_connection *conn)
  2538. {
  2539. if (!conn) {
  2540. return NULL;
  2541. }
  2542. return &conn->request_info;
  2543. }
  2544. int
  2545. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2546. {
  2547. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2548. return -1;
  2549. } else {
  2550. int truncated = 0;
  2551. const struct mg_request_info *ri = &conn->request_info;
  2552. #ifdef __clang__
  2553. #pragma clang diagnostic push
  2554. #pragma clang diagnostic ignored "-Wunreachable-code"
  2555. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2556. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2557. * unreachable, but splitting into four different #ifdef clauses here is more
  2558. * complicated.
  2559. */
  2560. #endif
  2561. const char *proto =
  2562. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2563. : (ri->is_ssl ? "https" : "http"));
  2564. #ifdef __clang__
  2565. #pragma clang diagnostic pop
  2566. #endif
  2567. if (ri->local_uri == NULL) {
  2568. return -1;
  2569. }
  2570. if ((ri->request_uri != NULL)
  2571. && strcmp(ri->local_uri, ri->request_uri)) {
  2572. mg_snprintf(conn,
  2573. &truncated,
  2574. buf,
  2575. buflen,
  2576. "%s://%s",
  2577. proto,
  2578. ri->request_uri);
  2579. if (truncated) {
  2580. return -1;
  2581. }
  2582. return 0;
  2583. } else {
  2584. #if defined(USE_IPV6)
  2585. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2586. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2587. : htons(conn->client.lsa.sin.sin_port);
  2588. #else
  2589. int port = htons(conn->client.lsa.sin.sin_port);
  2590. #endif
  2591. int def_port = ri->is_ssl ? 443 : 80;
  2592. int auth_domain_check_enabled =
  2593. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2594. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2595. "yes"));
  2596. const char *server_domain =
  2597. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2598. char portstr[16];
  2599. char server_ip[48];
  2600. if (port != def_port) {
  2601. sprintf(portstr, ":%u", (unsigned)port);
  2602. } else {
  2603. portstr[0] = 0;
  2604. }
  2605. if (!auth_domain_check_enabled || !server_domain) {
  2606. sockaddr_to_string(server_ip,
  2607. sizeof(server_ip),
  2608. &conn->client.lsa);
  2609. server_domain = server_ip;
  2610. }
  2611. mg_snprintf(conn,
  2612. &truncated,
  2613. buf,
  2614. buflen,
  2615. "%s://%s%s%s",
  2616. proto,
  2617. server_domain,
  2618. portstr,
  2619. ri->local_uri);
  2620. if (truncated) {
  2621. return -1;
  2622. }
  2623. return 0;
  2624. }
  2625. }
  2626. }
  2627. /* Skip the characters until one of the delimiters characters found.
  2628. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2629. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2630. * Delimiters can be quoted with quotechar. */
  2631. static char *
  2632. skip_quoted(char **buf,
  2633. const char *delimiters,
  2634. const char *whitespace,
  2635. char quotechar)
  2636. {
  2637. char *p, *begin_word, *end_word, *end_whitespace;
  2638. begin_word = *buf;
  2639. end_word = begin_word + strcspn(begin_word, delimiters);
  2640. /* Check for quotechar */
  2641. if (end_word > begin_word) {
  2642. p = end_word - 1;
  2643. while (*p == quotechar) {
  2644. /* While the delimiter is quoted, look for the next delimiter. */
  2645. /* This happens, e.g., in calls from parse_auth_header,
  2646. * if the user name contains a " character. */
  2647. /* If there is anything beyond end_word, copy it. */
  2648. if (*end_word != '\0') {
  2649. size_t end_off = strcspn(end_word + 1, delimiters);
  2650. memmove(p, end_word, end_off + 1);
  2651. p += end_off; /* p must correspond to end_word - 1 */
  2652. end_word += end_off + 1;
  2653. } else {
  2654. *p = '\0';
  2655. break;
  2656. }
  2657. }
  2658. for (p++; p < end_word; p++) {
  2659. *p = '\0';
  2660. }
  2661. }
  2662. if (*end_word == '\0') {
  2663. *buf = end_word;
  2664. } else {
  2665. #if defined(__GNUC__) || defined(__MINGW32__)
  2666. /* Disable spurious conversion warning for GCC */
  2667. #pragma GCC diagnostic push
  2668. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2669. #endif
  2670. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2671. #if defined(__GNUC__) || defined(__MINGW32__)
  2672. #pragma GCC diagnostic pop
  2673. #endif
  2674. for (p = end_word; p < end_whitespace; p++) {
  2675. *p = '\0';
  2676. }
  2677. *buf = end_whitespace;
  2678. }
  2679. return begin_word;
  2680. }
  2681. /* Simplified version of skip_quoted without quote char
  2682. * and whitespace == delimiters */
  2683. static char *
  2684. skip(char **buf, const char *delimiters)
  2685. {
  2686. return skip_quoted(buf, delimiters, delimiters, 0);
  2687. }
  2688. /* Return HTTP header value, or NULL if not found. */
  2689. static const char *
  2690. get_header(const struct mg_request_info *ri, const char *name)
  2691. {
  2692. int i;
  2693. if (ri) {
  2694. for (i = 0; i < ri->num_headers; i++) {
  2695. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2696. return ri->http_headers[i].value;
  2697. }
  2698. }
  2699. }
  2700. return NULL;
  2701. }
  2702. const char *
  2703. mg_get_header(const struct mg_connection *conn, const char *name)
  2704. {
  2705. if (!conn) {
  2706. return NULL;
  2707. }
  2708. return get_header(&conn->request_info, name);
  2709. }
  2710. /* A helper function for traversing a comma separated list of values.
  2711. * It returns a list pointer shifted to the next value, or NULL if the end
  2712. * of the list found.
  2713. * Value is stored in val vector. If value has form "x=y", then eq_val
  2714. * vector is initialized to point to the "y" part, and val vector length
  2715. * is adjusted to point only to "x". */
  2716. static const char *
  2717. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2718. {
  2719. int end;
  2720. reparse:
  2721. if (val == NULL || list == NULL || *list == '\0') {
  2722. /* End of the list */
  2723. list = NULL;
  2724. } else {
  2725. /* Skip over leading LWS */
  2726. while (*list == ' ' || *list == '\t')
  2727. list++;
  2728. val->ptr = list;
  2729. if ((list = strchr(val->ptr, ',')) != NULL) {
  2730. /* Comma found. Store length and shift the list ptr */
  2731. val->len = ((size_t)(list - val->ptr));
  2732. list++;
  2733. } else {
  2734. /* This value is the last one */
  2735. list = val->ptr + strlen(val->ptr);
  2736. val->len = ((size_t)(list - val->ptr));
  2737. }
  2738. /* Adjust length for trailing LWS */
  2739. end = (int)val->len - 1;
  2740. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2741. end--;
  2742. val->len = (size_t)(end + 1);
  2743. if (val->len == 0) {
  2744. /* Ignore any empty entries. */
  2745. goto reparse;
  2746. }
  2747. if (eq_val != NULL) {
  2748. /* Value has form "x=y", adjust pointers and lengths
  2749. * so that val points to "x", and eq_val points to "y". */
  2750. eq_val->len = 0;
  2751. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2752. if (eq_val->ptr != NULL) {
  2753. eq_val->ptr++; /* Skip over '=' character */
  2754. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2755. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2756. }
  2757. }
  2758. }
  2759. return list;
  2760. }
  2761. /* A helper function for checking if a comma separated list of values contains
  2762. * the given option (case insensitvely).
  2763. * 'header' can be NULL, in which case false is returned. */
  2764. static int
  2765. header_has_option(const char *header, const char *option)
  2766. {
  2767. struct vec opt_vec;
  2768. struct vec eq_vec;
  2769. assert(option != NULL);
  2770. assert(option[0] != '\0');
  2771. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2772. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2773. return 1;
  2774. }
  2775. return 0;
  2776. }
  2777. /* Perform case-insensitive match of string against pattern */
  2778. static int
  2779. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2780. {
  2781. const char *or_str;
  2782. size_t i;
  2783. int j, len, res;
  2784. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2785. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2786. return (res > 0) ? res : match_prefix(or_str + 1,
  2787. (size_t)((pattern + pattern_len)
  2788. - (or_str + 1)),
  2789. str);
  2790. }
  2791. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2792. if (pattern[i] == '?' && str[j] != '\0') {
  2793. continue;
  2794. } else if (pattern[i] == '$') {
  2795. return (str[j] == '\0') ? j : -1;
  2796. } else if (pattern[i] == '*') {
  2797. i++;
  2798. if (pattern[i] == '*') {
  2799. i++;
  2800. len = (int)strlen(str + j);
  2801. } else {
  2802. len = (int)strcspn(str + j, "/");
  2803. }
  2804. if (i == pattern_len) {
  2805. return j + len;
  2806. }
  2807. do {
  2808. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2809. } while (res == -1 && len-- > 0);
  2810. return (res == -1) ? -1 : j + res + len;
  2811. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2812. return -1;
  2813. }
  2814. }
  2815. return j;
  2816. }
  2817. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2818. * This function must tolerate situations when connection info is not
  2819. * set up, for example if request parsing failed. */
  2820. static int
  2821. should_keep_alive(const struct mg_connection *conn)
  2822. {
  2823. if (conn != NULL) {
  2824. const char *http_version = conn->request_info.http_version;
  2825. const char *header = mg_get_header(conn, "Connection");
  2826. if (conn->must_close || conn->status_code == 401
  2827. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2828. || (header != NULL && !header_has_option(header, "keep-alive"))
  2829. || (header == NULL && http_version
  2830. && 0 != strcmp(http_version, "1.1"))) {
  2831. return 0;
  2832. }
  2833. return 1;
  2834. }
  2835. return 0;
  2836. }
  2837. static int
  2838. should_decode_url(const struct mg_connection *conn)
  2839. {
  2840. if (!conn || !conn->ctx) {
  2841. return 0;
  2842. }
  2843. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2844. }
  2845. static const char *
  2846. suggest_connection_header(const struct mg_connection *conn)
  2847. {
  2848. return should_keep_alive(conn) ? "keep-alive" : "close";
  2849. }
  2850. static int
  2851. send_no_cache_header(struct mg_connection *conn)
  2852. {
  2853. /* Send all current and obsolete cache opt-out directives. */
  2854. return mg_printf(conn,
  2855. "Cache-Control: no-cache, no-store, "
  2856. "must-revalidate, private, max-age=0\r\n"
  2857. "Pragma: no-cache\r\n"
  2858. "Expires: 0\r\n");
  2859. }
  2860. static int
  2861. send_static_cache_header(struct mg_connection *conn)
  2862. {
  2863. #if !defined(NO_CACHING)
  2864. /* Read the server config to check how long a file may be cached.
  2865. * The configuration is in seconds. */
  2866. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2867. if (max_age <= 0) {
  2868. /* 0 means "do not cache". All values <0 are reserved
  2869. * and may be used differently in the future. */
  2870. /* If a file should not be cached, do not only send
  2871. * max-age=0, but also pragmas and Expires headers. */
  2872. return send_no_cache_header(conn);
  2873. }
  2874. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2875. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2876. /* See also https://www.mnot.net/cache_docs/ */
  2877. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2878. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2879. * year to 31622400 seconds. For the moment, we just send whatever has
  2880. * been configured, still the behavior for >1 year should be considered
  2881. * as undefined. */
  2882. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2883. #else /* NO_CACHING */
  2884. return send_no_cache_header(conn);
  2885. #endif /* !NO_CACHING */
  2886. }
  2887. static int
  2888. send_additional_header(struct mg_connection *conn)
  2889. {
  2890. int i = 0;
  2891. (void)conn;
  2892. #if 0
  2893. /* TODO (Feature): Configure additional response header */
  2894. i += mg_printf(conn, "Strict-Transport-Security: max-age=%u\r\n", 3600);
  2895. i += mg_printf(conn, "X-Some-Test-Header: %u\r\n", 42);
  2896. #endif
  2897. return i;
  2898. }
  2899. static void handle_file_based_request(struct mg_connection *conn,
  2900. const char *path,
  2901. struct mg_file *filep);
  2902. const char *
  2903. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  2904. {
  2905. /* See IANA HTTP status code assignment:
  2906. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2907. */
  2908. switch (response_code) {
  2909. /* RFC2616 Section 10.1 - Informational 1xx */
  2910. case 100:
  2911. return "Continue"; /* RFC2616 Section 10.1.1 */
  2912. case 101:
  2913. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2914. case 102:
  2915. return "Processing"; /* RFC2518 Section 10.1 */
  2916. /* RFC2616 Section 10.2 - Successful 2xx */
  2917. case 200:
  2918. return "OK"; /* RFC2616 Section 10.2.1 */
  2919. case 201:
  2920. return "Created"; /* RFC2616 Section 10.2.2 */
  2921. case 202:
  2922. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2923. case 203:
  2924. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2925. case 204:
  2926. return "No Content"; /* RFC2616 Section 10.2.5 */
  2927. case 205:
  2928. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2929. case 206:
  2930. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2931. case 207:
  2932. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2933. case 208:
  2934. return "Already Reported"; /* RFC5842 Section 7.1 */
  2935. case 226:
  2936. return "IM used"; /* RFC3229 Section 10.4.1 */
  2937. /* RFC2616 Section 10.3 - Redirection 3xx */
  2938. case 300:
  2939. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2940. case 301:
  2941. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2942. case 302:
  2943. return "Found"; /* RFC2616 Section 10.3.3 */
  2944. case 303:
  2945. return "See Other"; /* RFC2616 Section 10.3.4 */
  2946. case 304:
  2947. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2948. case 305:
  2949. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2950. case 307:
  2951. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2952. case 308:
  2953. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2954. /* RFC2616 Section 10.4 - Client Error 4xx */
  2955. case 400:
  2956. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2957. case 401:
  2958. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2959. case 402:
  2960. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2961. case 403:
  2962. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2963. case 404:
  2964. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2965. case 405:
  2966. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2967. case 406:
  2968. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2969. case 407:
  2970. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2971. case 408:
  2972. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2973. case 409:
  2974. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2975. case 410:
  2976. return "Gone"; /* RFC2616 Section 10.4.11 */
  2977. case 411:
  2978. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2979. case 412:
  2980. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2981. case 413:
  2982. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2983. case 414:
  2984. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2985. case 415:
  2986. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2987. case 416:
  2988. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2989. case 417:
  2990. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2991. case 421:
  2992. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2993. case 422:
  2994. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2995. * Section 11.2 */
  2996. case 423:
  2997. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2998. case 424:
  2999. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3000. * Section 11.4 */
  3001. case 426:
  3002. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3003. case 428:
  3004. return "Precondition Required"; /* RFC 6585, Section 3 */
  3005. case 429:
  3006. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3007. case 431:
  3008. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3009. case 451:
  3010. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3011. * Section 3 */
  3012. /* RFC2616 Section 10.5 - Server Error 5xx */
  3013. case 500:
  3014. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3015. case 501:
  3016. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3017. case 502:
  3018. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3019. case 503:
  3020. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3021. case 504:
  3022. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3023. case 505:
  3024. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3025. case 506:
  3026. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3027. case 507:
  3028. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3029. * Section 11.5 */
  3030. case 508:
  3031. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3032. case 510:
  3033. return "Not Extended"; /* RFC 2774, Section 7 */
  3034. case 511:
  3035. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3036. /* Other status codes, not shown in the IANA HTTP status code assignment.
  3037. * E.g., "de facto" standards due to common use, ... */
  3038. case 418:
  3039. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3040. case 419:
  3041. return "Authentication Timeout"; /* common use */
  3042. case 420:
  3043. return "Enhance Your Calm"; /* common use */
  3044. case 440:
  3045. return "Login Timeout"; /* common use */
  3046. case 509:
  3047. return "Bandwidth Limit Exceeded"; /* common use */
  3048. default:
  3049. /* This error code is unknown. This should not happen. */
  3050. if (conn) {
  3051. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3052. }
  3053. /* Return at least a category according to RFC 2616 Section 10. */
  3054. if (response_code >= 100 && response_code < 200) {
  3055. /* Unknown informational status code */
  3056. return "Information";
  3057. }
  3058. if (response_code >= 200 && response_code < 300) {
  3059. /* Unknown success code */
  3060. return "Success";
  3061. }
  3062. if (response_code >= 300 && response_code < 400) {
  3063. /* Unknown redirection code */
  3064. return "Redirection";
  3065. }
  3066. if (response_code >= 400 && response_code < 500) {
  3067. /* Unknown request error code */
  3068. return "Client Error";
  3069. }
  3070. if (response_code >= 500 && response_code < 600) {
  3071. /* Unknown server error code */
  3072. return "Server Error";
  3073. }
  3074. /* Response code not even within reasonable range */
  3075. return "";
  3076. }
  3077. }
  3078. void
  3079. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3080. {
  3081. char buf[MG_BUF_LEN];
  3082. va_list ap;
  3083. int len, i, page_handler_found, scope, truncated, has_body;
  3084. char date[64];
  3085. time_t curtime = time(NULL);
  3086. const char *error_handler = NULL;
  3087. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3088. const char *error_page_file_ext, *tstr;
  3089. const char *status_text = mg_get_response_code_text(conn, status);
  3090. if (conn == NULL) {
  3091. return;
  3092. }
  3093. conn->status_code = status;
  3094. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  3095. || conn->ctx->callbacks.http_error(conn, status)) {
  3096. if (!conn->in_error_handler) {
  3097. /* Send user defined error pages, if defined */
  3098. error_handler = conn->ctx->config[ERROR_PAGES];
  3099. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3100. page_handler_found = 0;
  3101. if (error_handler != NULL) {
  3102. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3103. switch (scope) {
  3104. case 1: /* Handler for specific error, e.g. 404 error */
  3105. mg_snprintf(conn,
  3106. &truncated,
  3107. buf,
  3108. sizeof(buf) - 32,
  3109. "%serror%03u.",
  3110. error_handler,
  3111. status);
  3112. break;
  3113. case 2: /* Handler for error group, e.g., 5xx error handler
  3114. * for all server errors (500-599) */
  3115. mg_snprintf(conn,
  3116. &truncated,
  3117. buf,
  3118. sizeof(buf) - 32,
  3119. "%serror%01uxx.",
  3120. error_handler,
  3121. status / 100);
  3122. break;
  3123. default: /* Handler for all errors */
  3124. mg_snprintf(conn,
  3125. &truncated,
  3126. buf,
  3127. sizeof(buf) - 32,
  3128. "%serror.",
  3129. error_handler);
  3130. break;
  3131. }
  3132. /* String truncation in buf may only occur if error_handler
  3133. * is too long. This string is from the config, not from a
  3134. * client. */
  3135. (void)truncated;
  3136. len = (int)strlen(buf);
  3137. tstr = strchr(error_page_file_ext, '.');
  3138. while (tstr) {
  3139. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  3140. i++)
  3141. buf[len + i - 1] = tstr[i];
  3142. buf[len + i - 1] = 0;
  3143. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3144. page_handler_found = 1;
  3145. break;
  3146. }
  3147. tstr = strchr(tstr + i, '.');
  3148. }
  3149. }
  3150. }
  3151. if (page_handler_found) {
  3152. conn->in_error_handler = 1;
  3153. handle_file_based_request(conn, buf, &error_page_file);
  3154. conn->in_error_handler = 0;
  3155. return;
  3156. }
  3157. }
  3158. /* No custom error page. Send default error page. */
  3159. gmt_time_string(date, sizeof(date), &curtime);
  3160. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3161. has_body = (status > 199 && status != 204 && status != 304);
  3162. conn->must_close = 1;
  3163. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3164. send_no_cache_header(conn);
  3165. send_additional_header(conn);
  3166. if (has_body) {
  3167. mg_printf(conn,
  3168. "%s",
  3169. "Content-Type: text/plain; charset=utf-8\r\n");
  3170. }
  3171. mg_printf(conn,
  3172. "Date: %s\r\n"
  3173. "Connection: close\r\n\r\n",
  3174. date);
  3175. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3176. if (has_body) {
  3177. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3178. if (fmt != NULL) {
  3179. va_start(ap, fmt);
  3180. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3181. va_end(ap);
  3182. mg_write(conn, buf, strlen(buf));
  3183. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3184. }
  3185. } else {
  3186. /* No body allowed. Close the connection. */
  3187. DEBUG_TRACE("Error %i", status);
  3188. }
  3189. }
  3190. }
  3191. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3192. /* Create substitutes for POSIX functions in Win32. */
  3193. #if defined(__MINGW32__)
  3194. /* Show no warning in case system functions are not used. */
  3195. #pragma GCC diagnostic push
  3196. #pragma GCC diagnostic ignored "-Wunused-function"
  3197. #endif
  3198. static int
  3199. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3200. {
  3201. (void)unused;
  3202. *mutex = CreateMutex(NULL, FALSE, NULL);
  3203. return (*mutex == NULL) ? -1 : 0;
  3204. }
  3205. static int
  3206. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3207. {
  3208. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3209. }
  3210. static int
  3211. pthread_mutex_lock(pthread_mutex_t *mutex)
  3212. {
  3213. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3214. }
  3215. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3216. static int
  3217. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3218. {
  3219. switch (WaitForSingleObject(*mutex, 0)) {
  3220. case WAIT_OBJECT_0:
  3221. return 0;
  3222. case WAIT_TIMEOUT:
  3223. return -2; /* EBUSY */
  3224. }
  3225. return -1;
  3226. }
  3227. #endif
  3228. static int
  3229. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3230. {
  3231. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3232. }
  3233. static int
  3234. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3235. {
  3236. (void)unused;
  3237. InitializeCriticalSection(&cv->threadIdSec);
  3238. cv->waiting_thread = NULL;
  3239. return 0;
  3240. }
  3241. static int
  3242. pthread_cond_timedwait(pthread_cond_t *cv,
  3243. pthread_mutex_t *mutex,
  3244. const struct timespec *abstime)
  3245. {
  3246. struct mg_workerTLS **ptls,
  3247. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3248. int ok;
  3249. int64_t nsnow, nswaitabs, nswaitrel;
  3250. DWORD mswaitrel;
  3251. EnterCriticalSection(&cv->threadIdSec);
  3252. /* Add this thread to cv's waiting list */
  3253. ptls = &cv->waiting_thread;
  3254. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3255. ;
  3256. tls->next_waiting_thread = NULL;
  3257. *ptls = tls;
  3258. LeaveCriticalSection(&cv->threadIdSec);
  3259. if (abstime) {
  3260. nsnow = mg_get_current_time_ns();
  3261. nswaitabs =
  3262. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3263. nswaitrel = nswaitabs - nsnow;
  3264. if (nswaitrel < 0) {
  3265. nswaitrel = 0;
  3266. }
  3267. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3268. } else {
  3269. mswaitrel = INFINITE;
  3270. }
  3271. pthread_mutex_unlock(mutex);
  3272. ok = (WAIT_OBJECT_0
  3273. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3274. if (!ok) {
  3275. ok = 1;
  3276. EnterCriticalSection(&cv->threadIdSec);
  3277. ptls = &cv->waiting_thread;
  3278. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3279. if (*ptls == tls) {
  3280. *ptls = tls->next_waiting_thread;
  3281. ok = 0;
  3282. break;
  3283. }
  3284. }
  3285. LeaveCriticalSection(&cv->threadIdSec);
  3286. if (ok) {
  3287. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3288. }
  3289. }
  3290. /* This thread has been removed from cv's waiting list */
  3291. pthread_mutex_lock(mutex);
  3292. return ok ? 0 : -1;
  3293. }
  3294. static int
  3295. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3296. {
  3297. return pthread_cond_timedwait(cv, mutex, NULL);
  3298. }
  3299. static int
  3300. pthread_cond_signal(pthread_cond_t *cv)
  3301. {
  3302. HANDLE wkup = NULL;
  3303. BOOL ok = FALSE;
  3304. EnterCriticalSection(&cv->threadIdSec);
  3305. if (cv->waiting_thread) {
  3306. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3307. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3308. ok = SetEvent(wkup);
  3309. assert(ok);
  3310. }
  3311. LeaveCriticalSection(&cv->threadIdSec);
  3312. return ok ? 0 : 1;
  3313. }
  3314. static int
  3315. pthread_cond_broadcast(pthread_cond_t *cv)
  3316. {
  3317. EnterCriticalSection(&cv->threadIdSec);
  3318. while (cv->waiting_thread) {
  3319. pthread_cond_signal(cv);
  3320. }
  3321. LeaveCriticalSection(&cv->threadIdSec);
  3322. return 0;
  3323. }
  3324. static int
  3325. pthread_cond_destroy(pthread_cond_t *cv)
  3326. {
  3327. EnterCriticalSection(&cv->threadIdSec);
  3328. assert(cv->waiting_thread == NULL);
  3329. LeaveCriticalSection(&cv->threadIdSec);
  3330. DeleteCriticalSection(&cv->threadIdSec);
  3331. return 0;
  3332. }
  3333. #ifdef ALTERNATIVE_QUEUE
  3334. static void *
  3335. event_create(void)
  3336. {
  3337. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3338. }
  3339. static int
  3340. event_wait(void *eventhdl)
  3341. {
  3342. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3343. return (res == WAIT_OBJECT_0);
  3344. }
  3345. static int
  3346. event_signal(void *eventhdl)
  3347. {
  3348. return (int)SetEvent((HANDLE)eventhdl);
  3349. }
  3350. static void
  3351. event_destroy(void *eventhdl)
  3352. {
  3353. CloseHandle((HANDLE)eventhdl);
  3354. }
  3355. #endif
  3356. #if defined(__MINGW32__)
  3357. /* Enable unused function warning again */
  3358. #pragma GCC diagnostic pop
  3359. #endif
  3360. /* For Windows, change all slashes to backslashes in path names. */
  3361. static void
  3362. change_slashes_to_backslashes(char *path)
  3363. {
  3364. int i;
  3365. for (i = 0; path[i] != '\0'; i++) {
  3366. if (path[i] == '/') {
  3367. path[i] = '\\';
  3368. }
  3369. /* remove double backslash (check i > 0 to preserve UNC paths,
  3370. * like \\server\file.txt) */
  3371. if ((path[i] == '\\') && (i > 0)) {
  3372. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3373. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3374. }
  3375. }
  3376. }
  3377. }
  3378. static int
  3379. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3380. {
  3381. int diff;
  3382. do {
  3383. diff = tolower(*s1) - tolower(*s2);
  3384. s1++;
  3385. s2++;
  3386. } while (diff == 0 && s1[-1] != '\0');
  3387. return diff;
  3388. }
  3389. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3390. * wbuf and wbuf_len is a target buffer and its length. */
  3391. static void
  3392. path_to_unicode(const struct mg_connection *conn,
  3393. const char *path,
  3394. wchar_t *wbuf,
  3395. size_t wbuf_len)
  3396. {
  3397. char buf[PATH_MAX], buf2[PATH_MAX];
  3398. wchar_t wbuf2[MAX_PATH + 1];
  3399. DWORD long_len, err;
  3400. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3401. mg_strlcpy(buf, path, sizeof(buf));
  3402. change_slashes_to_backslashes(buf);
  3403. /* Convert to Unicode and back. If doubly-converted string does not
  3404. * match the original, something is fishy, reject. */
  3405. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3406. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3407. WideCharToMultiByte(
  3408. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3409. if (strcmp(buf, buf2) != 0) {
  3410. wbuf[0] = L'\0';
  3411. }
  3412. /* Windows file systems are not case sensitive, but you can still use
  3413. * uppercase and lowercase letters (on all modern file systems).
  3414. * The server can check if the URI uses the same upper/lowercase
  3415. * letters an the file system, effectively making Windows servers
  3416. * case sensitive (like Linux servers are). It is still not possible
  3417. * to use two files with the same name in different cases on Windows
  3418. * (like /a and /A) - this would be possible in Linux.
  3419. * As a default, Windows is not case sensitive, but the case sensitive
  3420. * file name check can be activated by an additional configuration. */
  3421. if (conn) {
  3422. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3423. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3424. /* Use case sensitive compare function */
  3425. fcompare = wcscmp;
  3426. }
  3427. }
  3428. (void)conn; /* conn is currently unused */
  3429. #if !defined(_WIN32_WCE)
  3430. /* Only accept a full file path, not a Windows short (8.3) path. */
  3431. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3432. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3433. if (long_len == 0) {
  3434. err = GetLastError();
  3435. if (err == ERROR_FILE_NOT_FOUND) {
  3436. /* File does not exist. This is not always a problem here. */
  3437. return;
  3438. }
  3439. }
  3440. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3441. /* Short name is used. */
  3442. wbuf[0] = L'\0';
  3443. }
  3444. #else
  3445. (void)long_len;
  3446. (void)wbuf2;
  3447. (void)err;
  3448. if (strchr(path, '~')) {
  3449. wbuf[0] = L'\0';
  3450. }
  3451. #endif
  3452. }
  3453. /* Windows happily opens files with some garbage at the end of file name.
  3454. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3455. * "a.cgi", despite one would expect an error back.
  3456. * This function returns non-0 if path ends with some garbage. */
  3457. static int
  3458. path_cannot_disclose_cgi(const char *path)
  3459. {
  3460. static const char *allowed_last_characters = "_-";
  3461. int last = path[strlen(path) - 1];
  3462. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3463. }
  3464. static int
  3465. mg_stat(const struct mg_connection *conn,
  3466. const char *path,
  3467. struct mg_file_stat *filep)
  3468. {
  3469. wchar_t wbuf[PATH_MAX];
  3470. WIN32_FILE_ATTRIBUTE_DATA info;
  3471. time_t creation_time;
  3472. if (!filep) {
  3473. return 0;
  3474. }
  3475. memset(filep, 0, sizeof(*filep));
  3476. if (conn && is_file_in_memory(conn, path)) {
  3477. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3478. * memset */
  3479. /* Quick fix (for 1.9.x): */
  3480. /* mg_stat must fill all fields, also for files in memory */
  3481. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3482. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3483. filep->size = tmp_file.stat.size;
  3484. filep->location = 2;
  3485. /* TODO: for 1.10: restructure how files in memory are handled */
  3486. /* The "file in memory" feature is a candidate for deletion.
  3487. * Please join the discussion at
  3488. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3489. */
  3490. filep->last_modified = time(NULL); /* TODO */
  3491. /* last_modified = now ... assumes the file may change during runtime,
  3492. * so every mg_fopen call may return different data */
  3493. /* last_modified = conn->ctx.start_time;
  3494. * May be used it the data does not change during runtime. This allows
  3495. * browser caching. Since we do not know, we have to assume the file
  3496. * in memory may change. */
  3497. return 1;
  3498. }
  3499. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3500. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3501. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3502. filep->last_modified =
  3503. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3504. info.ftLastWriteTime.dwHighDateTime);
  3505. /* On Windows, the file creation time can be higher than the
  3506. * modification time, e.g. when a file is copied.
  3507. * Since the Last-Modified timestamp is used for caching
  3508. * it should be based on the most recent timestamp. */
  3509. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3510. info.ftCreationTime.dwHighDateTime);
  3511. if (creation_time > filep->last_modified) {
  3512. filep->last_modified = creation_time;
  3513. }
  3514. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3515. /* If file name is fishy, reset the file structure and return
  3516. * error.
  3517. * Note it is important to reset, not just return the error, cause
  3518. * functions like is_file_opened() check the struct. */
  3519. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3520. memset(filep, 0, sizeof(*filep));
  3521. return 0;
  3522. }
  3523. return 1;
  3524. }
  3525. return 0;
  3526. }
  3527. static int
  3528. mg_remove(const struct mg_connection *conn, const char *path)
  3529. {
  3530. wchar_t wbuf[PATH_MAX];
  3531. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3532. return DeleteFileW(wbuf) ? 0 : -1;
  3533. }
  3534. static int
  3535. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3536. {
  3537. wchar_t wbuf[PATH_MAX];
  3538. (void)mode;
  3539. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3540. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3541. }
  3542. /* Create substitutes for POSIX functions in Win32. */
  3543. #if defined(__MINGW32__)
  3544. /* Show no warning in case system functions are not used. */
  3545. #pragma GCC diagnostic push
  3546. #pragma GCC diagnostic ignored "-Wunused-function"
  3547. #endif
  3548. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3549. static DIR *
  3550. mg_opendir(const struct mg_connection *conn, const char *name)
  3551. {
  3552. DIR *dir = NULL;
  3553. wchar_t wpath[PATH_MAX];
  3554. DWORD attrs;
  3555. if (name == NULL) {
  3556. SetLastError(ERROR_BAD_ARGUMENTS);
  3557. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3558. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3559. } else {
  3560. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3561. attrs = GetFileAttributesW(wpath);
  3562. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3563. == FILE_ATTRIBUTE_DIRECTORY)) {
  3564. (void)wcscat(wpath, L"\\*");
  3565. dir->handle = FindFirstFileW(wpath, &dir->info);
  3566. dir->result.d_name[0] = '\0';
  3567. } else {
  3568. mg_free(dir);
  3569. dir = NULL;
  3570. }
  3571. }
  3572. return dir;
  3573. }
  3574. static int
  3575. mg_closedir(DIR *dir)
  3576. {
  3577. int result = 0;
  3578. if (dir != NULL) {
  3579. if (dir->handle != INVALID_HANDLE_VALUE)
  3580. result = FindClose(dir->handle) ? 0 : -1;
  3581. mg_free(dir);
  3582. } else {
  3583. result = -1;
  3584. SetLastError(ERROR_BAD_ARGUMENTS);
  3585. }
  3586. return result;
  3587. }
  3588. static struct dirent *
  3589. mg_readdir(DIR *dir)
  3590. {
  3591. struct dirent *result = 0;
  3592. if (dir) {
  3593. if (dir->handle != INVALID_HANDLE_VALUE) {
  3594. result = &dir->result;
  3595. (void)WideCharToMultiByte(CP_UTF8,
  3596. 0,
  3597. dir->info.cFileName,
  3598. -1,
  3599. result->d_name,
  3600. sizeof(result->d_name),
  3601. NULL,
  3602. NULL);
  3603. if (!FindNextFileW(dir->handle, &dir->info)) {
  3604. (void)FindClose(dir->handle);
  3605. dir->handle = INVALID_HANDLE_VALUE;
  3606. }
  3607. } else {
  3608. SetLastError(ERROR_FILE_NOT_FOUND);
  3609. }
  3610. } else {
  3611. SetLastError(ERROR_BAD_ARGUMENTS);
  3612. }
  3613. return result;
  3614. }
  3615. #ifndef HAVE_POLL
  3616. static int
  3617. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3618. {
  3619. struct timeval tv;
  3620. fd_set set;
  3621. unsigned int i;
  3622. int result;
  3623. SOCKET maxfd = 0;
  3624. memset(&tv, 0, sizeof(tv));
  3625. tv.tv_sec = milliseconds / 1000;
  3626. tv.tv_usec = (milliseconds % 1000) * 1000;
  3627. FD_ZERO(&set);
  3628. for (i = 0; i < n; i++) {
  3629. FD_SET((SOCKET)pfd[i].fd, &set);
  3630. pfd[i].revents = 0;
  3631. if (pfd[i].fd > maxfd) {
  3632. maxfd = pfd[i].fd;
  3633. }
  3634. }
  3635. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3636. for (i = 0; i < n; i++) {
  3637. if (FD_ISSET(pfd[i].fd, &set)) {
  3638. pfd[i].revents = POLLIN;
  3639. }
  3640. }
  3641. }
  3642. /* We should subtract the time used in select from remaining
  3643. * "milliseconds", in particular if called from mg_poll with a
  3644. * timeout quantum.
  3645. * Unfortunately, the remaining time is not stored in "tv" in all
  3646. * implementations, so the result in "tv" must be considered undefined.
  3647. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3648. return result;
  3649. }
  3650. #endif /* HAVE_POLL */
  3651. #if defined(__MINGW32__)
  3652. /* Enable unused function warning again */
  3653. #pragma GCC diagnostic pop
  3654. #endif
  3655. static void
  3656. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3657. {
  3658. (void)conn; /* Unused. */
  3659. #if defined(_WIN32_WCE)
  3660. (void)sock;
  3661. #else
  3662. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3663. #endif
  3664. }
  3665. int
  3666. mg_start_thread(mg_thread_func_t f, void *p)
  3667. {
  3668. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3669. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3670. */
  3671. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3672. == ((uintptr_t)(-1L)))
  3673. ? -1
  3674. : 0);
  3675. #else
  3676. return (
  3677. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3678. ? -1
  3679. : 0);
  3680. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3681. }
  3682. /* Start a thread storing the thread context. */
  3683. static int
  3684. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3685. void *p,
  3686. pthread_t *threadidptr)
  3687. {
  3688. uintptr_t uip;
  3689. HANDLE threadhandle;
  3690. int result = -1;
  3691. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3692. threadhandle = (HANDLE)uip;
  3693. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3694. *threadidptr = threadhandle;
  3695. result = 0;
  3696. }
  3697. return result;
  3698. }
  3699. /* Wait for a thread to finish. */
  3700. static int
  3701. mg_join_thread(pthread_t threadid)
  3702. {
  3703. int result;
  3704. DWORD dwevent;
  3705. result = -1;
  3706. dwevent = WaitForSingleObject(threadid, INFINITE);
  3707. if (dwevent == WAIT_FAILED) {
  3708. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3709. } else {
  3710. if (dwevent == WAIT_OBJECT_0) {
  3711. CloseHandle(threadid);
  3712. result = 0;
  3713. }
  3714. }
  3715. return result;
  3716. }
  3717. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3718. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3719. /* Create substitutes for POSIX functions in Win32. */
  3720. #if defined(__MINGW32__)
  3721. /* Show no warning in case system functions are not used. */
  3722. #pragma GCC diagnostic push
  3723. #pragma GCC diagnostic ignored "-Wunused-function"
  3724. #endif
  3725. static HANDLE
  3726. dlopen(const char *dll_name, int flags)
  3727. {
  3728. wchar_t wbuf[PATH_MAX];
  3729. (void)flags;
  3730. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3731. return LoadLibraryW(wbuf);
  3732. }
  3733. static int
  3734. dlclose(void *handle)
  3735. {
  3736. int result;
  3737. if (FreeLibrary((HMODULE)handle) != 0) {
  3738. result = 0;
  3739. } else {
  3740. result = -1;
  3741. }
  3742. return result;
  3743. }
  3744. #if defined(__MINGW32__)
  3745. /* Enable unused function warning again */
  3746. #pragma GCC diagnostic pop
  3747. #endif
  3748. #endif
  3749. #if !defined(NO_CGI)
  3750. #define SIGKILL (0)
  3751. static int
  3752. kill(pid_t pid, int sig_num)
  3753. {
  3754. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3755. (void)CloseHandle((HANDLE)pid);
  3756. return 0;
  3757. }
  3758. static void
  3759. trim_trailing_whitespaces(char *s)
  3760. {
  3761. char *e = s + strlen(s) - 1;
  3762. while (e > s && isspace(*(unsigned char *)e)) {
  3763. *e-- = '\0';
  3764. }
  3765. }
  3766. static pid_t
  3767. spawn_process(struct mg_connection *conn,
  3768. const char *prog,
  3769. char *envblk,
  3770. char *envp[],
  3771. int fdin[2],
  3772. int fdout[2],
  3773. int fderr[2],
  3774. const char *dir)
  3775. {
  3776. HANDLE me;
  3777. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3778. cmdline[PATH_MAX], buf[PATH_MAX];
  3779. int truncated;
  3780. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3781. STARTUPINFOA si;
  3782. PROCESS_INFORMATION pi = {0};
  3783. (void)envp;
  3784. memset(&si, 0, sizeof(si));
  3785. si.cb = sizeof(si);
  3786. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3787. si.wShowWindow = SW_HIDE;
  3788. me = GetCurrentProcess();
  3789. DuplicateHandle(me,
  3790. (HANDLE)_get_osfhandle(fdin[0]),
  3791. me,
  3792. &si.hStdInput,
  3793. 0,
  3794. TRUE,
  3795. DUPLICATE_SAME_ACCESS);
  3796. DuplicateHandle(me,
  3797. (HANDLE)_get_osfhandle(fdout[1]),
  3798. me,
  3799. &si.hStdOutput,
  3800. 0,
  3801. TRUE,
  3802. DUPLICATE_SAME_ACCESS);
  3803. DuplicateHandle(me,
  3804. (HANDLE)_get_osfhandle(fderr[1]),
  3805. me,
  3806. &si.hStdError,
  3807. 0,
  3808. TRUE,
  3809. DUPLICATE_SAME_ACCESS);
  3810. /* Mark handles that should not be inherited. See
  3811. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3812. */
  3813. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3814. HANDLE_FLAG_INHERIT,
  3815. 0);
  3816. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3817. HANDLE_FLAG_INHERIT,
  3818. 0);
  3819. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3820. HANDLE_FLAG_INHERIT,
  3821. 0);
  3822. /* If CGI file is a script, try to read the interpreter line */
  3823. interp = conn->ctx->config[CGI_INTERPRETER];
  3824. if (interp == NULL) {
  3825. buf[0] = buf[1] = '\0';
  3826. /* Read the first line of the script into the buffer */
  3827. mg_snprintf(
  3828. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3829. if (truncated) {
  3830. pi.hProcess = (pid_t)-1;
  3831. goto spawn_cleanup;
  3832. }
  3833. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3834. p = (char *)file.access.membuf;
  3835. mg_fgets(buf, sizeof(buf), &file, &p);
  3836. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3837. buf[sizeof(buf) - 1] = '\0';
  3838. }
  3839. if (buf[0] == '#' && buf[1] == '!') {
  3840. trim_trailing_whitespaces(buf + 2);
  3841. } else {
  3842. buf[2] = '\0';
  3843. }
  3844. interp = buf + 2;
  3845. }
  3846. if (interp[0] != '\0') {
  3847. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3848. interp = full_interp;
  3849. }
  3850. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3851. if (interp[0] != '\0') {
  3852. mg_snprintf(conn,
  3853. &truncated,
  3854. cmdline,
  3855. sizeof(cmdline),
  3856. "\"%s\" \"%s\\%s\"",
  3857. interp,
  3858. full_dir,
  3859. prog);
  3860. } else {
  3861. mg_snprintf(conn,
  3862. &truncated,
  3863. cmdline,
  3864. sizeof(cmdline),
  3865. "\"%s\\%s\"",
  3866. full_dir,
  3867. prog);
  3868. }
  3869. if (truncated) {
  3870. pi.hProcess = (pid_t)-1;
  3871. goto spawn_cleanup;
  3872. }
  3873. DEBUG_TRACE("Running [%s]", cmdline);
  3874. if (CreateProcessA(NULL,
  3875. cmdline,
  3876. NULL,
  3877. NULL,
  3878. TRUE,
  3879. CREATE_NEW_PROCESS_GROUP,
  3880. envblk,
  3881. NULL,
  3882. &si,
  3883. &pi) == 0) {
  3884. mg_cry(
  3885. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3886. pi.hProcess = (pid_t)-1;
  3887. /* goto spawn_cleanup; */
  3888. }
  3889. spawn_cleanup:
  3890. (void)CloseHandle(si.hStdOutput);
  3891. (void)CloseHandle(si.hStdError);
  3892. (void)CloseHandle(si.hStdInput);
  3893. if (pi.hThread != NULL) {
  3894. (void)CloseHandle(pi.hThread);
  3895. }
  3896. return (pid_t)pi.hProcess;
  3897. }
  3898. #endif /* !NO_CGI */
  3899. static int
  3900. set_blocking_mode(SOCKET sock, int blocking)
  3901. {
  3902. unsigned long non_blocking = !blocking;
  3903. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3904. }
  3905. #else
  3906. static int
  3907. mg_stat(const struct mg_connection *conn,
  3908. const char *path,
  3909. struct mg_file_stat *filep)
  3910. {
  3911. struct stat st;
  3912. if (!filep) {
  3913. return 0;
  3914. }
  3915. memset(filep, 0, sizeof(*filep));
  3916. if (conn && is_file_in_memory(conn, path)) {
  3917. /* Quick fix (for 1.9.x): */
  3918. /* mg_stat must fill all fields, also for files in memory */
  3919. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3920. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3921. filep->size = tmp_file.stat.size;
  3922. filep->last_modified = time(NULL);
  3923. filep->location = 2;
  3924. /* TODO: for 1.10: restructure how files in memory are handled */
  3925. return 1;
  3926. }
  3927. if (0 == stat(path, &st)) {
  3928. filep->size = (uint64_t)(st.st_size);
  3929. filep->last_modified = st.st_mtime;
  3930. filep->is_directory = S_ISDIR(st.st_mode);
  3931. return 1;
  3932. }
  3933. return 0;
  3934. }
  3935. static void
  3936. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3937. {
  3938. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3939. if (conn) {
  3940. mg_cry(conn,
  3941. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3942. __func__,
  3943. strerror(ERRNO));
  3944. }
  3945. }
  3946. }
  3947. int
  3948. mg_start_thread(mg_thread_func_t func, void *param)
  3949. {
  3950. pthread_t thread_id;
  3951. pthread_attr_t attr;
  3952. int result;
  3953. (void)pthread_attr_init(&attr);
  3954. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3955. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3956. /* Compile-time option to control stack size,
  3957. * e.g. -DUSE_STACK_SIZE=16384 */
  3958. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3959. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3960. result = pthread_create(&thread_id, &attr, func, param);
  3961. pthread_attr_destroy(&attr);
  3962. return result;
  3963. }
  3964. /* Start a thread storing the thread context. */
  3965. static int
  3966. mg_start_thread_with_id(mg_thread_func_t func,
  3967. void *param,
  3968. pthread_t *threadidptr)
  3969. {
  3970. pthread_t thread_id;
  3971. pthread_attr_t attr;
  3972. int result;
  3973. (void)pthread_attr_init(&attr);
  3974. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3975. /* Compile-time option to control stack size,
  3976. * e.g. -DUSE_STACK_SIZE=16384 */
  3977. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3978. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3979. result = pthread_create(&thread_id, &attr, func, param);
  3980. pthread_attr_destroy(&attr);
  3981. if ((result == 0) && (threadidptr != NULL)) {
  3982. *threadidptr = thread_id;
  3983. }
  3984. return result;
  3985. }
  3986. /* Wait for a thread to finish. */
  3987. static int
  3988. mg_join_thread(pthread_t threadid)
  3989. {
  3990. int result;
  3991. result = pthread_join(threadid, NULL);
  3992. return result;
  3993. }
  3994. #ifndef NO_CGI
  3995. static pid_t
  3996. spawn_process(struct mg_connection *conn,
  3997. const char *prog,
  3998. char *envblk,
  3999. char *envp[],
  4000. int fdin[2],
  4001. int fdout[2],
  4002. int fderr[2],
  4003. const char *dir)
  4004. {
  4005. pid_t pid;
  4006. const char *interp;
  4007. (void)envblk;
  4008. if (conn == NULL) {
  4009. return 0;
  4010. }
  4011. if ((pid = fork()) == -1) {
  4012. /* Parent */
  4013. mg_send_http_error(conn,
  4014. 500,
  4015. "Error: Creating CGI process\nfork(): %s",
  4016. strerror(ERRNO));
  4017. } else if (pid == 0) {
  4018. /* Child */
  4019. if (chdir(dir) != 0) {
  4020. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4021. } else if (dup2(fdin[0], 0) == -1) {
  4022. mg_cry(conn,
  4023. "%s: dup2(%d, 0): %s",
  4024. __func__,
  4025. fdin[0],
  4026. strerror(ERRNO));
  4027. } else if (dup2(fdout[1], 1) == -1) {
  4028. mg_cry(conn,
  4029. "%s: dup2(%d, 1): %s",
  4030. __func__,
  4031. fdout[1],
  4032. strerror(ERRNO));
  4033. } else if (dup2(fderr[1], 2) == -1) {
  4034. mg_cry(conn,
  4035. "%s: dup2(%d, 2): %s",
  4036. __func__,
  4037. fderr[1],
  4038. strerror(ERRNO));
  4039. } else {
  4040. /* Keep stderr and stdout in two different pipes.
  4041. * Stdout will be sent back to the client,
  4042. * stderr should go into a server error log. */
  4043. (void)close(fdin[0]);
  4044. (void)close(fdout[1]);
  4045. (void)close(fderr[1]);
  4046. /* Close write end fdin and read end fdout and fderr */
  4047. (void)close(fdin[1]);
  4048. (void)close(fdout[0]);
  4049. (void)close(fderr[0]);
  4050. /* After exec, all signal handlers are restored to their default
  4051. * values, with one exception of SIGCHLD. According to
  4052. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4053. * leave unchanged after exec if it was set to be ignored. Restore
  4054. * it to default action. */
  4055. signal(SIGCHLD, SIG_DFL);
  4056. interp = conn->ctx->config[CGI_INTERPRETER];
  4057. if (interp == NULL) {
  4058. (void)execle(prog, prog, NULL, envp);
  4059. mg_cry(conn,
  4060. "%s: execle(%s): %s",
  4061. __func__,
  4062. prog,
  4063. strerror(ERRNO));
  4064. } else {
  4065. (void)execle(interp, interp, prog, NULL, envp);
  4066. mg_cry(conn,
  4067. "%s: execle(%s %s): %s",
  4068. __func__,
  4069. interp,
  4070. prog,
  4071. strerror(ERRNO));
  4072. }
  4073. }
  4074. exit(EXIT_FAILURE);
  4075. }
  4076. return pid;
  4077. }
  4078. #endif /* !NO_CGI */
  4079. static int
  4080. set_blocking_mode(SOCKET sock, int blocking)
  4081. {
  4082. int flags;
  4083. flags = fcntl(sock, F_GETFL, 0);
  4084. if (blocking) {
  4085. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  4086. } else {
  4087. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  4088. }
  4089. return 0;
  4090. }
  4091. #endif /* _WIN32 */
  4092. /* End of initial operating system specific define block. */
  4093. /* Get a random number (independent of C rand function) */
  4094. static uint64_t
  4095. get_random(void)
  4096. {
  4097. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4098. static uint64_t lcg = 0; /* Linear congruential generator */
  4099. uint64_t now = mg_get_current_time_ns();
  4100. if (lfsr == 0) {
  4101. /* lfsr will be only 0 if has not been initialized,
  4102. * so this code is called only once. */
  4103. lfsr = mg_get_current_time_ns();
  4104. lcg = mg_get_current_time_ns();
  4105. } else {
  4106. /* Get the next step of both random number generators. */
  4107. lfsr = (lfsr >> 1)
  4108. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4109. << 63);
  4110. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  4111. }
  4112. /* Combining two pseudo-random number generators and a high resolution part
  4113. * of the current server time will make it hard (impossible?) to guess the
  4114. * next number. */
  4115. return (lfsr ^ lcg ^ now);
  4116. }
  4117. static int
  4118. mg_poll(struct pollfd *pfd,
  4119. unsigned int n,
  4120. int milliseconds,
  4121. volatile int *stop_server)
  4122. {
  4123. int ms_now, result;
  4124. /* Call poll, but only for a maximum time of a few seconds.
  4125. * This will allow to stop the server after some seconds, instead
  4126. * of having to wait for a long socket timeout. */
  4127. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4128. do {
  4129. if (*stop_server) {
  4130. /* Shut down signal */
  4131. return -2;
  4132. }
  4133. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4134. ms_now = milliseconds;
  4135. }
  4136. result = poll(pfd, n, ms_now);
  4137. if (result != 0) {
  4138. /* Poll returned either success (1) or error (-1).
  4139. * Forward both to the caller. */
  4140. return result;
  4141. }
  4142. /* Poll returned timeout (0). */
  4143. if (milliseconds > 0) {
  4144. milliseconds -= ms_now;
  4145. }
  4146. } while (milliseconds != 0);
  4147. return result;
  4148. }
  4149. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4150. * descriptor. Return number of bytes written. */
  4151. static int
  4152. push(struct mg_context *ctx,
  4153. FILE *fp,
  4154. SOCKET sock,
  4155. SSL *ssl,
  4156. const char *buf,
  4157. int len,
  4158. double timeout)
  4159. {
  4160. uint64_t start = 0, now = 0, timeout_ns = 0;
  4161. int n, err;
  4162. #ifdef _WIN32
  4163. typedef int len_t;
  4164. #else
  4165. typedef size_t len_t;
  4166. #endif
  4167. if (timeout > 0) {
  4168. start = mg_get_current_time_ns();
  4169. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4170. }
  4171. if (ctx == NULL) {
  4172. return -1;
  4173. }
  4174. #ifdef NO_SSL
  4175. if (ssl) {
  4176. return -1;
  4177. }
  4178. #endif
  4179. do {
  4180. #ifndef NO_SSL
  4181. if (ssl != NULL) {
  4182. n = SSL_write(ssl, buf, len);
  4183. if (n <= 0) {
  4184. err = SSL_get_error(ssl, n);
  4185. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4186. err = ERRNO;
  4187. } else if ((err == SSL_ERROR_WANT_READ)
  4188. || (err == SSL_ERROR_WANT_WRITE)) {
  4189. n = 0;
  4190. } else {
  4191. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4192. return -1;
  4193. }
  4194. } else {
  4195. err = 0;
  4196. }
  4197. } else
  4198. #endif
  4199. if (fp != NULL) {
  4200. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4201. if (ferror(fp)) {
  4202. n = -1;
  4203. err = ERRNO;
  4204. } else {
  4205. err = 0;
  4206. }
  4207. } else {
  4208. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4209. err = (n < 0) ? ERRNO : 0;
  4210. #ifdef _WIN32
  4211. if (err == WSAEWOULDBLOCK) {
  4212. err = 0;
  4213. n = 0;
  4214. }
  4215. #else
  4216. if (err == EWOULDBLOCK) {
  4217. err = 0;
  4218. n = 0;
  4219. }
  4220. #endif
  4221. if (n < 0) {
  4222. /* shutdown of the socket at client side */
  4223. return -1;
  4224. }
  4225. }
  4226. if (ctx->stop_flag) {
  4227. return -1;
  4228. }
  4229. if ((n > 0) || (n == 0 && len == 0)) {
  4230. /* some data has been read, or no data was requested */
  4231. return n;
  4232. }
  4233. if (n < 0) {
  4234. /* socket error - check errno */
  4235. DEBUG_TRACE("send() failed, error %d", err);
  4236. /* TODO (mid): error handling depending on the error code.
  4237. * These codes are different between Windows and Linux.
  4238. * Currently there is no problem with failing send calls,
  4239. * if there is a reproducible situation, it should be
  4240. * investigated in detail.
  4241. */
  4242. return -1;
  4243. }
  4244. /* Only in case n=0 (timeout), repeat calling the write function */
  4245. if (timeout >= 0) {
  4246. now = mg_get_current_time_ns();
  4247. }
  4248. } while ((timeout <= 0) || ((now - start) <= timeout_ns));
  4249. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4250. used */
  4251. return -1;
  4252. }
  4253. static int64_t
  4254. push_all(struct mg_context *ctx,
  4255. FILE *fp,
  4256. SOCKET sock,
  4257. SSL *ssl,
  4258. const char *buf,
  4259. int64_t len)
  4260. {
  4261. double timeout = -1.0;
  4262. int64_t n, nwritten = 0;
  4263. if (ctx == NULL) {
  4264. return -1;
  4265. }
  4266. if (ctx->config[REQUEST_TIMEOUT]) {
  4267. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4268. }
  4269. while (len > 0 && ctx->stop_flag == 0) {
  4270. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4271. if (n < 0) {
  4272. if (nwritten == 0) {
  4273. nwritten = n; /* Propagate the error */
  4274. }
  4275. break;
  4276. } else if (n == 0) {
  4277. break; /* No more data to write */
  4278. } else {
  4279. nwritten += n;
  4280. len -= n;
  4281. }
  4282. }
  4283. return nwritten;
  4284. }
  4285. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4286. * Return value:
  4287. * >=0 .. number of bytes successfully read
  4288. * -1 .. timeout
  4289. * -2 .. error
  4290. */
  4291. static int
  4292. pull_inner(FILE *fp,
  4293. struct mg_connection *conn,
  4294. char *buf,
  4295. int len,
  4296. double timeout)
  4297. {
  4298. int nread, err = 0;
  4299. #ifdef _WIN32
  4300. typedef int len_t;
  4301. #else
  4302. typedef size_t len_t;
  4303. #endif
  4304. #ifndef NO_SSL
  4305. int ssl_pending;
  4306. #endif
  4307. /* We need an additional wait loop around this, because in some cases
  4308. * with TLSwe may get data from the socket but not from SSL_read.
  4309. * In this case we need to repeat at least once.
  4310. */
  4311. if (fp != NULL) {
  4312. #if !defined(_WIN32_WCE)
  4313. /* Use read() instead of fread(), because if we're reading from the
  4314. * CGI pipe, fread() may block until IO buffer is filled up. We
  4315. * cannot afford to block and must pass all read bytes immediately
  4316. * to the client. */
  4317. nread = (int)read(fileno(fp), buf, (size_t)len);
  4318. #else
  4319. /* WinCE does not support CGI pipes */
  4320. nread = (int)fread(buf, 1, (size_t)len, fp);
  4321. #endif
  4322. err = (nread < 0) ? ERRNO : 0;
  4323. #ifndef NO_SSL
  4324. } else if ((conn->ssl != NULL)
  4325. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4326. /* We already know there is no more data buffered in conn->buf
  4327. * but there is more available in the SSL layer. So don't poll
  4328. * conn->client.sock yet. */
  4329. if (ssl_pending > len) {
  4330. ssl_pending = len;
  4331. }
  4332. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4333. if (nread <= 0) {
  4334. err = SSL_get_error(conn->ssl, nread);
  4335. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4336. err = ERRNO;
  4337. } else if ((err == SSL_ERROR_WANT_READ)
  4338. || (err == SSL_ERROR_WANT_WRITE)) {
  4339. nread = 0;
  4340. } else {
  4341. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4342. return -1;
  4343. }
  4344. } else {
  4345. err = 0;
  4346. }
  4347. } else if (conn->ssl != NULL) {
  4348. struct pollfd pfd[1];
  4349. int pollres;
  4350. pfd[0].fd = conn->client.sock;
  4351. pfd[0].events = POLLIN;
  4352. pollres =
  4353. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4354. if (conn->ctx->stop_flag) {
  4355. return -2;
  4356. }
  4357. if (pollres > 0) {
  4358. nread = SSL_read(conn->ssl, buf, len);
  4359. if (nread <= 0) {
  4360. err = SSL_get_error(conn->ssl, nread);
  4361. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4362. err = ERRNO;
  4363. } else if ((err == SSL_ERROR_WANT_READ)
  4364. || (err == SSL_ERROR_WANT_WRITE)) {
  4365. nread = 0;
  4366. } else {
  4367. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4368. return -2;
  4369. }
  4370. } else {
  4371. err = 0;
  4372. }
  4373. } else if (pollres < 0) {
  4374. /* Error */
  4375. return -2;
  4376. } else {
  4377. /* pollres = 0 means timeout */
  4378. nread = 0;
  4379. }
  4380. #endif
  4381. } else {
  4382. struct pollfd pfd[1];
  4383. int pollres;
  4384. pfd[0].fd = conn->client.sock;
  4385. pfd[0].events = POLLIN;
  4386. pollres =
  4387. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4388. if (conn->ctx->stop_flag) {
  4389. return -2;
  4390. }
  4391. if (pollres > 0) {
  4392. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4393. err = (nread < 0) ? ERRNO : 0;
  4394. if (nread <= 0) {
  4395. /* shutdown of the socket at client side */
  4396. return -2;
  4397. }
  4398. } else if (pollres < 0) {
  4399. /* error callint poll */
  4400. return -2;
  4401. } else {
  4402. /* pollres = 0 means timeout */
  4403. nread = 0;
  4404. }
  4405. }
  4406. if (conn->ctx->stop_flag) {
  4407. return -2;
  4408. }
  4409. if ((nread > 0) || (nread == 0 && len == 0)) {
  4410. /* some data has been read, or no data was requested */
  4411. return nread;
  4412. }
  4413. if (nread < 0) {
  4414. /* socket error - check errno */
  4415. #ifdef _WIN32
  4416. if (err == WSAEWOULDBLOCK) {
  4417. /* TODO (low): check if this is still required */
  4418. /* standard case if called from close_socket_gracefully */
  4419. return -2;
  4420. } else if (err == WSAETIMEDOUT) {
  4421. /* TODO (low): check if this is still required */
  4422. /* timeout is handled by the while loop */
  4423. return 0;
  4424. } else if (err == WSAECONNABORTED) {
  4425. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4426. return -2;
  4427. } else {
  4428. DEBUG_TRACE("recv() failed, error %d", err);
  4429. return -2;
  4430. }
  4431. #else
  4432. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4433. * if the timeout is reached and if the socket was set to non-
  4434. * blocking in close_socket_gracefully, so we can not distinguish
  4435. * here. We have to wait for the timeout in both cases for now.
  4436. */
  4437. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4438. /* TODO (low): check if this is still required */
  4439. /* EAGAIN/EWOULDBLOCK:
  4440. * standard case if called from close_socket_gracefully
  4441. * => should return -1 */
  4442. /* or timeout occured
  4443. * => the code must stay in the while loop */
  4444. /* EINTR can be generated on a socket with a timeout set even
  4445. * when SA_RESTART is effective for all relevant signals
  4446. * (see signal(7)).
  4447. * => stay in the while loop */
  4448. } else {
  4449. DEBUG_TRACE("recv() failed, error %d", err);
  4450. return -2;
  4451. }
  4452. #endif
  4453. }
  4454. /* Timeout occured, but no data available. */
  4455. return -1;
  4456. }
  4457. static int
  4458. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4459. {
  4460. int n, nread = 0;
  4461. double timeout = -1.0;
  4462. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4463. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4464. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4465. }
  4466. if (timeout >= 0.0) {
  4467. start_time = mg_get_current_time_ns();
  4468. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4469. }
  4470. while (len > 0 && conn->ctx->stop_flag == 0) {
  4471. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4472. if (n == -2) {
  4473. if (nread == 0) {
  4474. nread = -1; /* Propagate the error */
  4475. }
  4476. break;
  4477. } else if (n == -1) {
  4478. /* timeout */
  4479. if (timeout >= 0.0) {
  4480. now = mg_get_current_time_ns();
  4481. if ((now - start_time) <= timeout_ns) {
  4482. continue;
  4483. }
  4484. }
  4485. break;
  4486. } else if (n == 0) {
  4487. break; /* No more data to read */
  4488. } else {
  4489. conn->consumed_content += n;
  4490. nread += n;
  4491. len -= n;
  4492. }
  4493. }
  4494. return nread;
  4495. }
  4496. static void
  4497. discard_unread_request_data(struct mg_connection *conn)
  4498. {
  4499. char buf[MG_BUF_LEN];
  4500. size_t to_read;
  4501. int nread;
  4502. if (conn == NULL) {
  4503. return;
  4504. }
  4505. to_read = sizeof(buf);
  4506. if (conn->is_chunked) {
  4507. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4508. * completely */
  4509. while (conn->is_chunked == 1) {
  4510. nread = mg_read(conn, buf, to_read);
  4511. if (nread <= 0) {
  4512. break;
  4513. }
  4514. }
  4515. } else {
  4516. /* Not chunked: content length is known */
  4517. while (conn->consumed_content < conn->content_len) {
  4518. if (to_read
  4519. > (size_t)(conn->content_len - conn->consumed_content)) {
  4520. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4521. }
  4522. nread = mg_read(conn, buf, to_read);
  4523. if (nread <= 0) {
  4524. break;
  4525. }
  4526. }
  4527. }
  4528. }
  4529. static int
  4530. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4531. {
  4532. int64_t n, buffered_len, nread;
  4533. int64_t len64 =
  4534. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4535. * int, we may not read more
  4536. * bytes */
  4537. const char *body;
  4538. if (conn == NULL) {
  4539. return 0;
  4540. }
  4541. /* If Content-Length is not set for a PUT or POST request, read until
  4542. * socket is closed */
  4543. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4544. conn->content_len = INT64_MAX;
  4545. conn->must_close = 1;
  4546. }
  4547. nread = 0;
  4548. if (conn->consumed_content < conn->content_len) {
  4549. /* Adjust number of bytes to read. */
  4550. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4551. if (left_to_read < len64) {
  4552. /* Do not read more than the total content length of the request.
  4553. */
  4554. len64 = left_to_read;
  4555. }
  4556. /* Return buffered data */
  4557. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4558. - conn->consumed_content;
  4559. if (buffered_len > 0) {
  4560. if (len64 < buffered_len) {
  4561. buffered_len = len64;
  4562. }
  4563. body = conn->buf + conn->request_len + conn->consumed_content;
  4564. memcpy(buf, body, (size_t)buffered_len);
  4565. len64 -= buffered_len;
  4566. conn->consumed_content += buffered_len;
  4567. nread += buffered_len;
  4568. buf = (char *)buf + buffered_len;
  4569. }
  4570. /* We have returned all buffered data. Read new data from the remote
  4571. * socket.
  4572. */
  4573. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4574. nread += n;
  4575. } else {
  4576. nread = ((nread > 0) ? nread : n);
  4577. }
  4578. }
  4579. return (int)nread;
  4580. }
  4581. static char
  4582. mg_getc(struct mg_connection *conn)
  4583. {
  4584. char c;
  4585. if (conn == NULL) {
  4586. return 0;
  4587. }
  4588. conn->content_len++;
  4589. if (mg_read_inner(conn, &c, 1) <= 0) {
  4590. return (char)0;
  4591. }
  4592. return c;
  4593. }
  4594. int
  4595. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4596. {
  4597. if (len > INT_MAX) {
  4598. len = INT_MAX;
  4599. }
  4600. if (conn == NULL) {
  4601. return 0;
  4602. }
  4603. if (conn->is_chunked) {
  4604. size_t all_read = 0;
  4605. while (len > 0) {
  4606. if (conn->is_chunked == 2) {
  4607. /* No more data left to read */
  4608. return 0;
  4609. }
  4610. if (conn->chunk_remainder) {
  4611. /* copy from the remainder of the last received chunk */
  4612. long read_ret;
  4613. size_t read_now =
  4614. ((conn->chunk_remainder > len) ? (len)
  4615. : (conn->chunk_remainder));
  4616. conn->content_len += (int)read_now;
  4617. read_ret =
  4618. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4619. if (read_ret < 1) {
  4620. /* read error */
  4621. return -1;
  4622. }
  4623. all_read += (size_t)read_ret;
  4624. conn->chunk_remainder -= (size_t)read_ret;
  4625. len -= (size_t)read_ret;
  4626. if (conn->chunk_remainder == 0) {
  4627. /* Add data bytes in the current chunk have been read,
  4628. * so we are expecting \r\n now. */
  4629. char x1 = mg_getc(conn);
  4630. char x2 = mg_getc(conn);
  4631. if ((x1 != '\r') || (x2 != '\n')) {
  4632. /* Protocol violation */
  4633. return -1;
  4634. }
  4635. }
  4636. } else {
  4637. /* fetch a new chunk */
  4638. int i = 0;
  4639. char lenbuf[64];
  4640. char *end = 0;
  4641. unsigned long chunkSize = 0;
  4642. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4643. lenbuf[i] = mg_getc(conn);
  4644. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4645. continue;
  4646. }
  4647. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4648. lenbuf[i + 1] = 0;
  4649. chunkSize = strtoul(lenbuf, &end, 16);
  4650. if (chunkSize == 0) {
  4651. /* regular end of content */
  4652. conn->is_chunked = 2;
  4653. }
  4654. break;
  4655. }
  4656. if (!isxdigit(lenbuf[i])) {
  4657. /* illegal character for chunk length */
  4658. return -1;
  4659. }
  4660. }
  4661. if ((end == NULL) || (*end != '\r')) {
  4662. /* chunksize not set correctly */
  4663. return -1;
  4664. }
  4665. if (chunkSize == 0) {
  4666. break;
  4667. }
  4668. conn->chunk_remainder = chunkSize;
  4669. }
  4670. }
  4671. return (int)all_read;
  4672. }
  4673. return mg_read_inner(conn, buf, len);
  4674. }
  4675. int
  4676. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4677. {
  4678. time_t now;
  4679. int64_t n, total, allowed;
  4680. if (conn == NULL) {
  4681. return 0;
  4682. }
  4683. if (conn->throttle > 0) {
  4684. if ((now = time(NULL)) != conn->last_throttle_time) {
  4685. conn->last_throttle_time = now;
  4686. conn->last_throttle_bytes = 0;
  4687. }
  4688. allowed = conn->throttle - conn->last_throttle_bytes;
  4689. if (allowed > (int64_t)len) {
  4690. allowed = (int64_t)len;
  4691. }
  4692. if ((total = push_all(conn->ctx,
  4693. NULL,
  4694. conn->client.sock,
  4695. conn->ssl,
  4696. (const char *)buf,
  4697. (int64_t)allowed)) == allowed) {
  4698. buf = (const char *)buf + total;
  4699. conn->last_throttle_bytes += total;
  4700. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4701. allowed = (conn->throttle > ((int64_t)len - total))
  4702. ? (int64_t)len - total
  4703. : conn->throttle;
  4704. if ((n = push_all(conn->ctx,
  4705. NULL,
  4706. conn->client.sock,
  4707. conn->ssl,
  4708. (const char *)buf,
  4709. (int64_t)allowed)) != allowed) {
  4710. break;
  4711. }
  4712. sleep(1);
  4713. conn->last_throttle_bytes = allowed;
  4714. conn->last_throttle_time = time(NULL);
  4715. buf = (const char *)buf + n;
  4716. total += n;
  4717. }
  4718. }
  4719. } else {
  4720. total = push_all(conn->ctx,
  4721. NULL,
  4722. conn->client.sock,
  4723. conn->ssl,
  4724. (const char *)buf,
  4725. (int64_t)len);
  4726. }
  4727. return (int)total;
  4728. }
  4729. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  4730. int
  4731. mg_send_chunk(struct mg_connection *conn,
  4732. const char *chunk,
  4733. unsigned int chunk_len)
  4734. {
  4735. char lenbuf[16];
  4736. size_t lenbuf_len;
  4737. int ret;
  4738. int t;
  4739. /* First store the length information in a text buffer. */
  4740. sprintf(lenbuf, "%x\r\n", chunk_len);
  4741. lenbuf_len = strlen(lenbuf);
  4742. /* Then send length information, chunk and terminating \r\n. */
  4743. ret = mg_write(conn, lenbuf, lenbuf_len);
  4744. if (ret != (int)lenbuf_len) {
  4745. return -1;
  4746. }
  4747. t = ret;
  4748. ret = mg_write(conn, chunk, chunk_len);
  4749. if (ret != (int)chunk_len) {
  4750. return -1;
  4751. }
  4752. t += ret;
  4753. ret = mg_write(conn, "\r\n", 2);
  4754. if (ret != 2) {
  4755. return -1;
  4756. }
  4757. t += ret;
  4758. return t;
  4759. }
  4760. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4761. static int
  4762. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4763. {
  4764. va_list ap_copy;
  4765. size_t size = MG_BUF_LEN / 4;
  4766. int len = -1;
  4767. *buf = NULL;
  4768. while (len < 0) {
  4769. if (*buf) {
  4770. mg_free(*buf);
  4771. }
  4772. size *= 4;
  4773. *buf = (char *)mg_malloc(size);
  4774. if (!*buf) {
  4775. break;
  4776. }
  4777. va_copy(ap_copy, ap);
  4778. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4779. va_end(ap_copy);
  4780. (*buf)[size - 1] = 0;
  4781. }
  4782. return len;
  4783. }
  4784. /* Print message to buffer. If buffer is large enough to hold the message,
  4785. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4786. * and return allocated buffer. */
  4787. static int
  4788. alloc_vprintf(char **out_buf,
  4789. char *prealloc_buf,
  4790. size_t prealloc_size,
  4791. const char *fmt,
  4792. va_list ap)
  4793. {
  4794. va_list ap_copy;
  4795. int len;
  4796. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4797. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4798. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4799. * Therefore, we make two passes: on first pass, get required message
  4800. * length.
  4801. * On second pass, actually print the message. */
  4802. va_copy(ap_copy, ap);
  4803. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4804. va_end(ap_copy);
  4805. if (len < 0) {
  4806. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4807. * Switch to alternative code path that uses incremental allocations.
  4808. */
  4809. va_copy(ap_copy, ap);
  4810. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4811. va_end(ap_copy);
  4812. } else if ((size_t)(len) >= prealloc_size) {
  4813. /* The pre-allocated buffer not large enough. */
  4814. /* Allocate a new buffer. */
  4815. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4816. if (!*out_buf) {
  4817. /* Allocation failed. Return -1 as "out of memory" error. */
  4818. return -1;
  4819. }
  4820. /* Buffer allocation successful. Store the string there. */
  4821. va_copy(ap_copy, ap);
  4822. IGNORE_UNUSED_RESULT(
  4823. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4824. va_end(ap_copy);
  4825. } else {
  4826. /* The pre-allocated buffer is large enough.
  4827. * Use it to store the string and return the address. */
  4828. va_copy(ap_copy, ap);
  4829. IGNORE_UNUSED_RESULT(
  4830. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4831. va_end(ap_copy);
  4832. *out_buf = prealloc_buf;
  4833. }
  4834. return len;
  4835. }
  4836. static int
  4837. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4838. {
  4839. char mem[MG_BUF_LEN];
  4840. char *buf = NULL;
  4841. int len;
  4842. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4843. len = mg_write(conn, buf, (size_t)len);
  4844. }
  4845. if (buf != mem && buf != NULL) {
  4846. mg_free(buf);
  4847. }
  4848. return len;
  4849. }
  4850. int
  4851. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4852. {
  4853. va_list ap;
  4854. int result;
  4855. va_start(ap, fmt);
  4856. result = mg_vprintf(conn, fmt, ap);
  4857. va_end(ap);
  4858. return result;
  4859. }
  4860. int
  4861. mg_url_decode(const char *src,
  4862. int src_len,
  4863. char *dst,
  4864. int dst_len,
  4865. int is_form_url_encoded)
  4866. {
  4867. int i, j, a, b;
  4868. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4869. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4870. if (i < src_len - 2 && src[i] == '%'
  4871. && isxdigit(*(const unsigned char *)(src + i + 1))
  4872. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4873. a = tolower(*(const unsigned char *)(src + i + 1));
  4874. b = tolower(*(const unsigned char *)(src + i + 2));
  4875. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4876. i += 2;
  4877. } else if (is_form_url_encoded && src[i] == '+') {
  4878. dst[j] = ' ';
  4879. } else {
  4880. dst[j] = src[i];
  4881. }
  4882. }
  4883. dst[j] = '\0'; /* Null-terminate the destination */
  4884. return (i >= src_len) ? j : -1;
  4885. }
  4886. int
  4887. mg_get_var(const char *data,
  4888. size_t data_len,
  4889. const char *name,
  4890. char *dst,
  4891. size_t dst_len)
  4892. {
  4893. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4894. }
  4895. int
  4896. mg_get_var2(const char *data,
  4897. size_t data_len,
  4898. const char *name,
  4899. char *dst,
  4900. size_t dst_len,
  4901. size_t occurrence)
  4902. {
  4903. const char *p, *e, *s;
  4904. size_t name_len;
  4905. int len;
  4906. if (dst == NULL || dst_len == 0) {
  4907. len = -2;
  4908. } else if (data == NULL || name == NULL || data_len == 0) {
  4909. len = -1;
  4910. dst[0] = '\0';
  4911. } else {
  4912. name_len = strlen(name);
  4913. e = data + data_len;
  4914. len = -1;
  4915. dst[0] = '\0';
  4916. /* data is "var1=val1&var2=val2...". Find variable first */
  4917. for (p = data; p + name_len < e; p++) {
  4918. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4919. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4920. /* Point p to variable value */
  4921. p += name_len + 1;
  4922. /* Point s to the end of the value */
  4923. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4924. if (s == NULL) {
  4925. s = e;
  4926. }
  4927. /* assert(s >= p); */
  4928. if (s < p) {
  4929. return -3;
  4930. }
  4931. /* Decode variable into destination buffer */
  4932. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4933. /* Redirect error code from -1 to -2 (destination buffer too
  4934. * small). */
  4935. if (len == -1) {
  4936. len = -2;
  4937. }
  4938. break;
  4939. }
  4940. }
  4941. }
  4942. return len;
  4943. }
  4944. /* HCP24: some changes to compare hole var_name */
  4945. int
  4946. mg_get_cookie(const char *cookie_header,
  4947. const char *var_name,
  4948. char *dst,
  4949. size_t dst_size)
  4950. {
  4951. const char *s, *p, *end;
  4952. int name_len, len = -1;
  4953. if (dst == NULL || dst_size == 0) {
  4954. return -2;
  4955. }
  4956. dst[0] = '\0';
  4957. if (var_name == NULL || (s = cookie_header) == NULL) {
  4958. return -1;
  4959. }
  4960. name_len = (int)strlen(var_name);
  4961. end = s + strlen(s);
  4962. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4963. if (s[name_len] == '=') {
  4964. /* HCP24: now check is it a substring or a full cookie name */
  4965. if ((s == cookie_header) || (s[-1] == ' ')) {
  4966. s += name_len + 1;
  4967. if ((p = strchr(s, ' ')) == NULL) {
  4968. p = end;
  4969. }
  4970. if (p[-1] == ';') {
  4971. p--;
  4972. }
  4973. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4974. s++;
  4975. p--;
  4976. }
  4977. if ((size_t)(p - s) < dst_size) {
  4978. len = (int)(p - s);
  4979. mg_strlcpy(dst, s, (size_t)len + 1);
  4980. } else {
  4981. len = -3;
  4982. }
  4983. break;
  4984. }
  4985. }
  4986. }
  4987. return len;
  4988. }
  4989. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4990. static void
  4991. base64_encode(const unsigned char *src, int src_len, char *dst)
  4992. {
  4993. static const char *b64 =
  4994. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4995. int i, j, a, b, c;
  4996. for (i = j = 0; i < src_len; i += 3) {
  4997. a = src[i];
  4998. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4999. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5000. dst[j++] = b64[a >> 2];
  5001. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5002. if (i + 1 < src_len) {
  5003. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5004. }
  5005. if (i + 2 < src_len) {
  5006. dst[j++] = b64[c & 63];
  5007. }
  5008. }
  5009. while (j % 4 != 0) {
  5010. dst[j++] = '=';
  5011. }
  5012. dst[j++] = '\0';
  5013. }
  5014. #endif
  5015. #if defined(USE_LUA)
  5016. static unsigned char
  5017. b64reverse(char letter)
  5018. {
  5019. if (letter >= 'A' && letter <= 'Z') {
  5020. return letter - 'A';
  5021. }
  5022. if (letter >= 'a' && letter <= 'z') {
  5023. return letter - 'a' + 26;
  5024. }
  5025. if (letter >= '0' && letter <= '9') {
  5026. return letter - '0' + 52;
  5027. }
  5028. if (letter == '+') {
  5029. return 62;
  5030. }
  5031. if (letter == '/') {
  5032. return 63;
  5033. }
  5034. if (letter == '=') {
  5035. return 255; /* normal end */
  5036. }
  5037. return 254; /* error */
  5038. }
  5039. static int
  5040. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5041. {
  5042. int i;
  5043. unsigned char a, b, c, d;
  5044. *dst_len = 0;
  5045. for (i = 0; i < src_len; i += 4) {
  5046. a = b64reverse(src[i]);
  5047. if (a >= 254) {
  5048. return i;
  5049. }
  5050. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5051. if (b >= 254) {
  5052. return i + 1;
  5053. }
  5054. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5055. if (c == 254) {
  5056. return i + 2;
  5057. }
  5058. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5059. if (d == 254) {
  5060. return i + 3;
  5061. }
  5062. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5063. if (c != 255) {
  5064. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5065. if (d != 255) {
  5066. dst[(*dst_len)++] = (c << 6) + d;
  5067. }
  5068. }
  5069. }
  5070. return -1;
  5071. }
  5072. #endif
  5073. static int
  5074. is_put_or_delete_method(const struct mg_connection *conn)
  5075. {
  5076. if (conn) {
  5077. const char *s = conn->request_info.request_method;
  5078. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5079. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5080. }
  5081. return 0;
  5082. }
  5083. #if !defined(NO_FILES)
  5084. static int
  5085. extention_matches_script(
  5086. struct mg_connection *conn, /* in: request (must be valid) */
  5087. const char *filename /* in: filename (must be valid) */
  5088. )
  5089. {
  5090. #if !defined(NO_CGI)
  5091. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5092. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5093. filename) > 0) {
  5094. return 1;
  5095. }
  5096. #endif
  5097. #if defined(USE_LUA)
  5098. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5099. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5100. filename) > 0) {
  5101. return 1;
  5102. }
  5103. #endif
  5104. #if defined(USE_DUKTAPE)
  5105. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5106. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5107. filename) > 0) {
  5108. return 1;
  5109. }
  5110. #endif
  5111. /* filename and conn could be unused, if all preocessor conditions
  5112. * are false (no script language supported). */
  5113. (void)filename;
  5114. (void)conn;
  5115. return 0;
  5116. }
  5117. /* For given directory path, substitute it to valid index file.
  5118. * Return 1 if index file has been found, 0 if not found.
  5119. * If the file is found, it's stats is returned in stp. */
  5120. static int
  5121. substitute_index_file(struct mg_connection *conn,
  5122. char *path,
  5123. size_t path_len,
  5124. struct mg_file_stat *filestat)
  5125. {
  5126. const char *list = conn->ctx->config[INDEX_FILES];
  5127. struct vec filename_vec;
  5128. size_t n = strlen(path);
  5129. int found = 0;
  5130. /* The 'path' given to us points to the directory. Remove all trailing
  5131. * directory separator characters from the end of the path, and
  5132. * then append single directory separator character. */
  5133. while (n > 0 && path[n - 1] == '/') {
  5134. n--;
  5135. }
  5136. path[n] = '/';
  5137. /* Traverse index files list. For each entry, append it to the given
  5138. * path and see if the file exists. If it exists, break the loop */
  5139. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5140. /* Ignore too long entries that may overflow path buffer */
  5141. if (filename_vec.len > path_len - (n + 2)) {
  5142. continue;
  5143. }
  5144. /* Prepare full path to the index file */
  5145. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5146. /* Does it exist? */
  5147. if (mg_stat(conn, path, filestat)) {
  5148. /* Yes it does, break the loop */
  5149. found = 1;
  5150. break;
  5151. }
  5152. }
  5153. /* If no index file exists, restore directory path */
  5154. if (!found) {
  5155. path[n] = '\0';
  5156. }
  5157. return found;
  5158. }
  5159. #endif
  5160. static void
  5161. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5162. char *filename, /* out: filename */
  5163. size_t filename_buf_len, /* in: size of filename buffer */
  5164. struct mg_file_stat *filestat, /* out: file status structure */
  5165. int *is_found, /* out: file found (directly) */
  5166. int *is_script_resource, /* out: handled by a script? */
  5167. int *is_websocket_request, /* out: websocket connetion? */
  5168. int *is_put_or_delete_request /* out: put/delete a file? */
  5169. )
  5170. {
  5171. #if !defined(NO_FILES)
  5172. const char *uri = conn->request_info.local_uri;
  5173. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5174. const char *rewrite;
  5175. struct vec a, b;
  5176. int match_len;
  5177. char gz_path[PATH_MAX];
  5178. char const *accept_encoding;
  5179. int truncated;
  5180. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5181. char *tmp_str;
  5182. size_t tmp_str_len, sep_pos;
  5183. #endif
  5184. #else
  5185. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5186. #endif
  5187. /* Step 1: Set all initially unknown outputs to zero */
  5188. memset(filestat, 0, sizeof(*filestat));
  5189. *filename = 0;
  5190. *is_found = 0;
  5191. *is_script_resource = 0;
  5192. /* Step 2: Check if the request attempts to modify the file system */
  5193. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5194. /* Step 3: Check if it is a websocket request, and modify the document
  5195. * root if required */
  5196. #if defined(USE_WEBSOCKET)
  5197. *is_websocket_request = is_websocket_protocol(conn);
  5198. #if !defined(NO_FILES)
  5199. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5200. root = conn->ctx->config[WEBSOCKET_ROOT];
  5201. }
  5202. #endif /* !NO_FILES */
  5203. #else /* USE_WEBSOCKET */
  5204. *is_websocket_request = 0;
  5205. #endif /* USE_WEBSOCKET */
  5206. #if !defined(NO_FILES)
  5207. /* Step 4: If there is no root directory, don't look for files. */
  5208. /* Note that root == NULL is a regular use case here. This occurs,
  5209. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5210. * config is not required. */
  5211. if (root == NULL) {
  5212. /* all file related outputs have already been set to 0, just return
  5213. */
  5214. return;
  5215. }
  5216. /* Step 5: Determine the local file path from the root path and the
  5217. * request uri. */
  5218. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5219. * part of the path one byte on the right. */
  5220. mg_snprintf(
  5221. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5222. if (truncated) {
  5223. goto interpret_cleanup;
  5224. }
  5225. /* Step 6: URI rewriting */
  5226. rewrite = conn->ctx->config[REWRITE];
  5227. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5228. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5229. mg_snprintf(conn,
  5230. &truncated,
  5231. filename,
  5232. filename_buf_len - 1,
  5233. "%.*s%s",
  5234. (int)b.len,
  5235. b.ptr,
  5236. uri + match_len);
  5237. break;
  5238. }
  5239. }
  5240. if (truncated) {
  5241. goto interpret_cleanup;
  5242. }
  5243. /* Step 7: Check if the file exists at the server */
  5244. /* Local file path and name, corresponding to requested URI
  5245. * is now stored in "filename" variable. */
  5246. if (mg_stat(conn, filename, filestat)) {
  5247. /* 7.1: File exists. */
  5248. *is_found = 1;
  5249. /* 7.2: Check if it is a script type. */
  5250. if (extention_matches_script(conn, filename)) {
  5251. /* The request addresses a CGI resource, Lua script or
  5252. * server-side javascript.
  5253. * The URI corresponds to the script itself (like
  5254. * /path/script.cgi), and there is no additional resource
  5255. * path (like /path/script.cgi/something).
  5256. * Requests that modify (replace or delete) a resource, like
  5257. * PUT and DELETE requests, should replace/delete the script
  5258. * file.
  5259. * Requests that read or write from/to a resource, like GET and
  5260. * POST requests, should call the script and return the
  5261. * generated response. */
  5262. *is_script_resource = (!*is_put_or_delete_request);
  5263. }
  5264. /* 7.3: If the request target is a directory, there could be
  5265. * a substitute file (index.html, index.cgi, ...). */
  5266. if (filestat->is_directory) {
  5267. /* Use a local copy here, since substitute_index_file will
  5268. * change the content of the file status */
  5269. struct mg_file_stat tmp_filestat;
  5270. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5271. if (substitute_index_file(
  5272. conn, filename, filename_buf_len, &tmp_filestat)) {
  5273. /* Substitute file found. Copy stat to the output, then
  5274. * check if the file is a script file */
  5275. *filestat = tmp_filestat;
  5276. if (extention_matches_script(conn, filename)) {
  5277. /* Substitute file is a script file */
  5278. *is_script_resource = 1;
  5279. } else {
  5280. /* Substitute file is a regular file */
  5281. *is_script_resource = 0;
  5282. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5283. }
  5284. }
  5285. /* If there is no substitute file, the server could return
  5286. * a directory listing in a later step */
  5287. }
  5288. return;
  5289. }
  5290. /* Step 8: Check for zipped files: */
  5291. /* If we can't find the actual file, look for the file
  5292. * with the same name but a .gz extension. If we find it,
  5293. * use that and set the gzipped flag in the file struct
  5294. * to indicate that the response need to have the content-
  5295. * encoding: gzip header.
  5296. * We can only do this if the browser declares support. */
  5297. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5298. if (strstr(accept_encoding, "gzip") != NULL) {
  5299. mg_snprintf(
  5300. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5301. if (truncated) {
  5302. goto interpret_cleanup;
  5303. }
  5304. if (mg_stat(conn, gz_path, filestat)) {
  5305. if (filestat) {
  5306. filestat->is_gzipped = 1;
  5307. *is_found = 1;
  5308. }
  5309. /* Currently gz files can not be scripts. */
  5310. return;
  5311. }
  5312. }
  5313. }
  5314. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5315. /* Step 9: Script resources may handle sub-resources */
  5316. /* Support PATH_INFO for CGI scripts. */
  5317. tmp_str_len = strlen(filename);
  5318. tmp_str = mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->ctx);
  5319. if (!tmp_str) {
  5320. /* Out of memory */
  5321. goto interpret_cleanup;
  5322. }
  5323. memcpy(tmp_str, filename, tmp_str_len + 1);
  5324. sep_pos = tmp_str_len;
  5325. while (sep_pos > 0) {
  5326. sep_pos--;
  5327. if (tmp_str[sep_pos] == '/') {
  5328. int is_script = 0, does_exist = 0;
  5329. tmp_str[sep_pos] = 0;
  5330. if (tmp_str[0]) {
  5331. is_script = extention_matches_script(conn, tmp_str);
  5332. does_exist = mg_stat(conn, tmp_str, filestat);
  5333. }
  5334. if (does_exist && is_script) {
  5335. filename[sep_pos] = 0;
  5336. memmove(filename + sep_pos + 2,
  5337. filename + sep_pos + 1,
  5338. strlen(filename + sep_pos + 1) + 1);
  5339. conn->path_info = filename + sep_pos + 1;
  5340. filename[sep_pos + 1] = '/';
  5341. *is_script_resource = 1;
  5342. *is_found = 1;
  5343. break;
  5344. }
  5345. if (substitute_index_file(
  5346. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5347. /* some intermediate directory has an index file */
  5348. if (extention_matches_script(conn, tmp_str)) {
  5349. /* this index file is a script */
  5350. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5351. mg_snprintf(conn,
  5352. &truncated,
  5353. filename,
  5354. filename_buf_len,
  5355. "%s//%s",
  5356. tmp_str,
  5357. tmp_str2);
  5358. mg_free(tmp_str2);
  5359. if (truncated) {
  5360. mg_free(tmp_str);
  5361. tmp_str = NULL;
  5362. goto interpret_cleanup;
  5363. }
  5364. sep_pos = strlen(tmp_str);
  5365. filename[sep_pos] = 0;
  5366. conn->path_info = filename + sep_pos + 1;
  5367. *is_script_resource = 1;
  5368. *is_found = 1;
  5369. break;
  5370. } else {
  5371. /* non-script files will not have sub-resources */
  5372. filename[sep_pos] = 0;
  5373. conn->path_info = 0;
  5374. *is_script_resource = 0;
  5375. *is_found = 0;
  5376. break;
  5377. }
  5378. }
  5379. tmp_str[sep_pos] = '/';
  5380. }
  5381. }
  5382. mg_free(tmp_str);
  5383. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5384. #endif /* !defined(NO_FILES) */
  5385. return;
  5386. #if !defined(NO_FILES)
  5387. /* Reset all outputs */
  5388. interpret_cleanup:
  5389. memset(filestat, 0, sizeof(*filestat));
  5390. *filename = 0;
  5391. *is_found = 0;
  5392. *is_script_resource = 0;
  5393. *is_websocket_request = 0;
  5394. *is_put_or_delete_request = 0;
  5395. #endif /* !defined(NO_FILES) */
  5396. }
  5397. /* Check whether full request is buffered. Return:
  5398. * -1 if request is malformed
  5399. * 0 if request is not yet fully buffered
  5400. * >0 actual request length, including last \r\n\r\n */
  5401. static int
  5402. get_request_len(const char *buf, int buflen)
  5403. {
  5404. const char *s, *e;
  5405. int len = 0;
  5406. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  5407. /* Control characters are not allowed but >=128 is. */
  5408. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  5409. && *(const unsigned char *)s < 128) {
  5410. len = -1;
  5411. break; /* [i_a] abort scan as soon as one malformed character is
  5412. * found; */
  5413. /* don't let subsequent \r\n\r\n win us over anyhow */
  5414. } else if (s[0] == '\n' && s[1] == '\n') {
  5415. len = (int)(s - buf) + 2;
  5416. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  5417. len = (int)(s - buf) + 3;
  5418. }
  5419. return len;
  5420. }
  5421. #if !defined(NO_CACHING)
  5422. /* Convert month to the month number. Return -1 on error, or month number */
  5423. static int
  5424. get_month_index(const char *s)
  5425. {
  5426. size_t i;
  5427. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5428. if (!strcmp(s, month_names[i])) {
  5429. return (int)i;
  5430. }
  5431. }
  5432. return -1;
  5433. }
  5434. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5435. static time_t
  5436. parse_date_string(const char *datetime)
  5437. {
  5438. char month_str[32] = {0};
  5439. int second, minute, hour, day, month, year;
  5440. time_t result = (time_t)0;
  5441. struct tm tm;
  5442. if ((sscanf(datetime,
  5443. "%d/%3s/%d %d:%d:%d",
  5444. &day,
  5445. month_str,
  5446. &year,
  5447. &hour,
  5448. &minute,
  5449. &second) == 6) || (sscanf(datetime,
  5450. "%d %3s %d %d:%d:%d",
  5451. &day,
  5452. month_str,
  5453. &year,
  5454. &hour,
  5455. &minute,
  5456. &second) == 6)
  5457. || (sscanf(datetime,
  5458. "%*3s, %d %3s %d %d:%d:%d",
  5459. &day,
  5460. month_str,
  5461. &year,
  5462. &hour,
  5463. &minute,
  5464. &second) == 6) || (sscanf(datetime,
  5465. "%d-%3s-%d %d:%d:%d",
  5466. &day,
  5467. month_str,
  5468. &year,
  5469. &hour,
  5470. &minute,
  5471. &second) == 6)) {
  5472. month = get_month_index(month_str);
  5473. if ((month >= 0) && (year >= 1970)) {
  5474. memset(&tm, 0, sizeof(tm));
  5475. tm.tm_year = year - 1900;
  5476. tm.tm_mon = month;
  5477. tm.tm_mday = day;
  5478. tm.tm_hour = hour;
  5479. tm.tm_min = minute;
  5480. tm.tm_sec = second;
  5481. result = timegm(&tm);
  5482. }
  5483. }
  5484. return result;
  5485. }
  5486. #endif /* !NO_CACHING */
  5487. /* Protect against directory disclosure attack by removing '..',
  5488. * excessive '/' and '\' characters */
  5489. static void
  5490. remove_double_dots_and_double_slashes(char *s)
  5491. {
  5492. char *p = s;
  5493. while ((s[0] == '.') && (s[1] == '.')) {
  5494. s++;
  5495. }
  5496. while (*s != '\0') {
  5497. *p++ = *s++;
  5498. if (s[-1] == '/' || s[-1] == '\\') {
  5499. /* Skip all following slashes, backslashes and double-dots */
  5500. while (s[0] != '\0') {
  5501. if (s[0] == '/' || s[0] == '\\') {
  5502. s++;
  5503. } else if (s[0] == '.' && s[1] == '.') {
  5504. s += 2;
  5505. } else {
  5506. break;
  5507. }
  5508. }
  5509. }
  5510. }
  5511. *p = '\0';
  5512. }
  5513. static const struct {
  5514. const char *extension;
  5515. size_t ext_len;
  5516. const char *mime_type;
  5517. } builtin_mime_types[] = {
  5518. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5519. * application types */
  5520. {".doc", 4, "application/msword"},
  5521. {".eps", 4, "application/postscript"},
  5522. {".exe", 4, "application/octet-stream"},
  5523. {".js", 3, "application/javascript"},
  5524. {".json", 5, "application/json"},
  5525. {".pdf", 4, "application/pdf"},
  5526. {".ps", 3, "application/postscript"},
  5527. {".rtf", 4, "application/rtf"},
  5528. {".xhtml", 6, "application/xhtml+xml"},
  5529. {".xsl", 4, "application/xml"},
  5530. {".xslt", 5, "application/xml"},
  5531. /* fonts */
  5532. {".ttf", 4, "application/font-sfnt"},
  5533. {".cff", 4, "application/font-sfnt"},
  5534. {".otf", 4, "application/font-sfnt"},
  5535. {".aat", 4, "application/font-sfnt"},
  5536. {".sil", 4, "application/font-sfnt"},
  5537. {".pfr", 4, "application/font-tdpfr"},
  5538. {".woff", 5, "application/font-woff"},
  5539. /* audio */
  5540. {".mp3", 4, "audio/mpeg"},
  5541. {".oga", 4, "audio/ogg"},
  5542. {".ogg", 4, "audio/ogg"},
  5543. /* image */
  5544. {".gif", 4, "image/gif"},
  5545. {".ief", 4, "image/ief"},
  5546. {".jpeg", 5, "image/jpeg"},
  5547. {".jpg", 4, "image/jpeg"},
  5548. {".jpm", 4, "image/jpm"},
  5549. {".jpx", 4, "image/jpx"},
  5550. {".png", 4, "image/png"},
  5551. {".svg", 4, "image/svg+xml"},
  5552. {".tif", 4, "image/tiff"},
  5553. {".tiff", 5, "image/tiff"},
  5554. /* model */
  5555. {".wrl", 4, "model/vrml"},
  5556. /* text */
  5557. {".css", 4, "text/css"},
  5558. {".csv", 4, "text/csv"},
  5559. {".htm", 4, "text/html"},
  5560. {".html", 5, "text/html"},
  5561. {".sgm", 4, "text/sgml"},
  5562. {".shtm", 5, "text/html"},
  5563. {".shtml", 6, "text/html"},
  5564. {".txt", 4, "text/plain"},
  5565. {".xml", 4, "text/xml"},
  5566. /* video */
  5567. {".mov", 4, "video/quicktime"},
  5568. {".mp4", 4, "video/mp4"},
  5569. {".mpeg", 5, "video/mpeg"},
  5570. {".mpg", 4, "video/mpeg"},
  5571. {".ogv", 4, "video/ogg"},
  5572. {".qt", 3, "video/quicktime"},
  5573. /* not registered types
  5574. * (http://reference.sitepoint.com/html/mime-types-full,
  5575. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5576. {".arj", 4, "application/x-arj-compressed"},
  5577. {".gz", 3, "application/x-gunzip"},
  5578. {".rar", 4, "application/x-arj-compressed"},
  5579. {".swf", 4, "application/x-shockwave-flash"},
  5580. {".tar", 4, "application/x-tar"},
  5581. {".tgz", 4, "application/x-tar-gz"},
  5582. {".torrent", 8, "application/x-bittorrent"},
  5583. {".ppt", 4, "application/x-mspowerpoint"},
  5584. {".xls", 4, "application/x-msexcel"},
  5585. {".zip", 4, "application/x-zip-compressed"},
  5586. {".aac",
  5587. 4,
  5588. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5589. {".aif", 4, "audio/x-aif"},
  5590. {".m3u", 4, "audio/x-mpegurl"},
  5591. {".mid", 4, "audio/x-midi"},
  5592. {".ra", 3, "audio/x-pn-realaudio"},
  5593. {".ram", 4, "audio/x-pn-realaudio"},
  5594. {".wav", 4, "audio/x-wav"},
  5595. {".bmp", 4, "image/bmp"},
  5596. {".ico", 4, "image/x-icon"},
  5597. {".pct", 4, "image/x-pct"},
  5598. {".pict", 5, "image/pict"},
  5599. {".rgb", 4, "image/x-rgb"},
  5600. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5601. {".asf", 4, "video/x-ms-asf"},
  5602. {".avi", 4, "video/x-msvideo"},
  5603. {".m4v", 4, "video/x-m4v"},
  5604. {NULL, 0, NULL}};
  5605. const char *
  5606. mg_get_builtin_mime_type(const char *path)
  5607. {
  5608. const char *ext;
  5609. size_t i, path_len;
  5610. path_len = strlen(path);
  5611. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5612. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5613. if (path_len > builtin_mime_types[i].ext_len
  5614. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5615. return builtin_mime_types[i].mime_type;
  5616. }
  5617. }
  5618. return "text/plain";
  5619. }
  5620. /* Look at the "path" extension and figure what mime type it has.
  5621. * Store mime type in the vector. */
  5622. static void
  5623. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5624. {
  5625. struct vec ext_vec, mime_vec;
  5626. const char *list, *ext;
  5627. size_t path_len;
  5628. path_len = strlen(path);
  5629. if (ctx == NULL || vec == NULL) {
  5630. return;
  5631. }
  5632. /* Scan user-defined mime types first, in case user wants to
  5633. * override default mime types. */
  5634. list = ctx->config[EXTRA_MIME_TYPES];
  5635. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5636. /* ext now points to the path suffix */
  5637. ext = path + path_len - ext_vec.len;
  5638. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5639. *vec = mime_vec;
  5640. return;
  5641. }
  5642. }
  5643. vec->ptr = mg_get_builtin_mime_type(path);
  5644. vec->len = strlen(vec->ptr);
  5645. }
  5646. /* Stringify binary data. Output buffer must be twice as big as input,
  5647. * because each byte takes 2 bytes in string representation */
  5648. static void
  5649. bin2str(char *to, const unsigned char *p, size_t len)
  5650. {
  5651. static const char *hex = "0123456789abcdef";
  5652. for (; len--; p++) {
  5653. *to++ = hex[p[0] >> 4];
  5654. *to++ = hex[p[0] & 0x0f];
  5655. }
  5656. *to = '\0';
  5657. }
  5658. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5659. char *
  5660. mg_md5(char buf[33], ...)
  5661. {
  5662. md5_byte_t hash[16];
  5663. const char *p;
  5664. va_list ap;
  5665. md5_state_t ctx;
  5666. md5_init(&ctx);
  5667. va_start(ap, buf);
  5668. while ((p = va_arg(ap, const char *)) != NULL) {
  5669. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5670. }
  5671. va_end(ap);
  5672. md5_finish(&ctx, hash);
  5673. bin2str(buf, hash, sizeof(hash));
  5674. return buf;
  5675. }
  5676. /* Check the user's password, return 1 if OK */
  5677. static int
  5678. check_password(const char *method,
  5679. const char *ha1,
  5680. const char *uri,
  5681. const char *nonce,
  5682. const char *nc,
  5683. const char *cnonce,
  5684. const char *qop,
  5685. const char *response)
  5686. {
  5687. char ha2[32 + 1], expected_response[32 + 1];
  5688. /* Some of the parameters may be NULL */
  5689. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5690. || qop == NULL
  5691. || response == NULL) {
  5692. return 0;
  5693. }
  5694. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5695. if (strlen(response) != 32) {
  5696. return 0;
  5697. }
  5698. mg_md5(ha2, method, ":", uri, NULL);
  5699. mg_md5(expected_response,
  5700. ha1,
  5701. ":",
  5702. nonce,
  5703. ":",
  5704. nc,
  5705. ":",
  5706. cnonce,
  5707. ":",
  5708. qop,
  5709. ":",
  5710. ha2,
  5711. NULL);
  5712. return mg_strcasecmp(response, expected_response) == 0;
  5713. }
  5714. /* Use the global passwords file, if specified by auth_gpass option,
  5715. * or search for .htpasswd in the requested directory. */
  5716. static void
  5717. open_auth_file(struct mg_connection *conn,
  5718. const char *path,
  5719. struct mg_file *filep)
  5720. {
  5721. if (conn != NULL && conn->ctx != NULL) {
  5722. char name[PATH_MAX];
  5723. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5724. int truncated;
  5725. if (gpass != NULL) {
  5726. /* Use global passwords file */
  5727. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5728. #ifdef DEBUG
  5729. /* Use mg_cry here, since gpass has been configured. */
  5730. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5731. #endif
  5732. }
  5733. /* Important: using local struct mg_file to test path for
  5734. * is_directory flag. If filep is used, mg_stat() makes it
  5735. * appear as if auth file was opened.
  5736. * TODO(mid): Check if this is still required after rewriting
  5737. * mg_stat */
  5738. } else if (mg_stat(conn, path, &filep->stat)
  5739. && filep->stat.is_directory) {
  5740. mg_snprintf(conn,
  5741. &truncated,
  5742. name,
  5743. sizeof(name),
  5744. "%s/%s",
  5745. path,
  5746. PASSWORDS_FILE_NAME);
  5747. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5748. #ifdef DEBUG
  5749. /* Don't use mg_cry here, but only a trace, since this is
  5750. * a typical case. It will occur for every directory
  5751. * without a password file. */
  5752. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5753. #endif
  5754. }
  5755. } else {
  5756. /* Try to find .htpasswd in requested directory. */
  5757. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5758. if (e[0] == '/') {
  5759. break;
  5760. }
  5761. }
  5762. mg_snprintf(conn,
  5763. &truncated,
  5764. name,
  5765. sizeof(name),
  5766. "%.*s/%s",
  5767. (int)(e - p),
  5768. p,
  5769. PASSWORDS_FILE_NAME);
  5770. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5771. #ifdef DEBUG
  5772. /* Don't use mg_cry here, but only a trace, since this is
  5773. * a typical case. It will occur for every directory
  5774. * without a password file. */
  5775. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5776. #endif
  5777. }
  5778. }
  5779. }
  5780. }
  5781. /* Parsed Authorization header */
  5782. struct ah {
  5783. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5784. };
  5785. /* Return 1 on success. Always initializes the ah structure. */
  5786. static int
  5787. parse_auth_header(struct mg_connection *conn,
  5788. char *buf,
  5789. size_t buf_size,
  5790. struct ah *ah)
  5791. {
  5792. char *name, *value, *s;
  5793. const char *auth_header;
  5794. uint64_t nonce;
  5795. if (!ah || !conn) {
  5796. return 0;
  5797. }
  5798. (void)memset(ah, 0, sizeof(*ah));
  5799. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5800. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5801. return 0;
  5802. }
  5803. /* Make modifiable copy of the auth header */
  5804. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5805. s = buf;
  5806. /* Parse authorization header */
  5807. for (;;) {
  5808. /* Gobble initial spaces */
  5809. while (isspace(*(unsigned char *)s)) {
  5810. s++;
  5811. }
  5812. name = skip_quoted(&s, "=", " ", 0);
  5813. /* Value is either quote-delimited, or ends at first comma or space. */
  5814. if (s[0] == '\"') {
  5815. s++;
  5816. value = skip_quoted(&s, "\"", " ", '\\');
  5817. if (s[0] == ',') {
  5818. s++;
  5819. }
  5820. } else {
  5821. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5822. * spaces */
  5823. }
  5824. if (*name == '\0') {
  5825. break;
  5826. }
  5827. if (!strcmp(name, "username")) {
  5828. ah->user = value;
  5829. } else if (!strcmp(name, "cnonce")) {
  5830. ah->cnonce = value;
  5831. } else if (!strcmp(name, "response")) {
  5832. ah->response = value;
  5833. } else if (!strcmp(name, "uri")) {
  5834. ah->uri = value;
  5835. } else if (!strcmp(name, "qop")) {
  5836. ah->qop = value;
  5837. } else if (!strcmp(name, "nc")) {
  5838. ah->nc = value;
  5839. } else if (!strcmp(name, "nonce")) {
  5840. ah->nonce = value;
  5841. }
  5842. }
  5843. #ifndef NO_NONCE_CHECK
  5844. /* Read the nonce from the response. */
  5845. if (ah->nonce == NULL) {
  5846. return 0;
  5847. }
  5848. s = NULL;
  5849. nonce = strtoull(ah->nonce, &s, 10);
  5850. if ((s == NULL) || (*s != 0)) {
  5851. return 0;
  5852. }
  5853. /* Convert the nonce from the client to a number. */
  5854. nonce ^= conn->ctx->auth_nonce_mask;
  5855. /* The converted number corresponds to the time the nounce has been
  5856. * created. This should not be earlier than the server start. */
  5857. /* Server side nonce check is valuable in all situations but one:
  5858. * if the server restarts frequently, but the client should not see
  5859. * that, so the server should accept nonces from previous starts. */
  5860. /* However, the reasonable default is to not accept a nonce from a
  5861. * previous start, so if anyone changed the access rights between
  5862. * two restarts, a new login is required. */
  5863. if (nonce < (uint64_t)conn->ctx->start_time) {
  5864. /* nonce is from a previous start of the server and no longer valid
  5865. * (replay attack?) */
  5866. return 0;
  5867. }
  5868. /* Check if the nonce is too high, so it has not (yet) been used by the
  5869. * server. */
  5870. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5871. return 0;
  5872. }
  5873. #else
  5874. (void)nonce;
  5875. #endif
  5876. /* CGI needs it as REMOTE_USER */
  5877. if (ah->user != NULL) {
  5878. conn->request_info.remote_user = mg_strdup(ah->user);
  5879. } else {
  5880. return 0;
  5881. }
  5882. return 1;
  5883. }
  5884. static const char *
  5885. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5886. {
  5887. const char *eof;
  5888. size_t len;
  5889. const char *memend;
  5890. if (!filep) {
  5891. return NULL;
  5892. }
  5893. if (filep->access.membuf != NULL && *p != NULL) {
  5894. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5895. /* Search for \n from p till the end of stream */
  5896. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5897. if (eof != NULL) {
  5898. eof += 1; /* Include \n */
  5899. } else {
  5900. eof = memend; /* Copy remaining data */
  5901. }
  5902. len =
  5903. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5904. memcpy(buf, *p, len);
  5905. buf[len] = '\0';
  5906. *p += len;
  5907. return len ? eof : NULL;
  5908. } else if (filep->access.fp != NULL) {
  5909. return fgets(buf, (int)size, filep->access.fp);
  5910. } else {
  5911. return NULL;
  5912. }
  5913. }
  5914. /* Define the initial recursion depth for procesesing htpasswd files that
  5915. * include other htpasswd
  5916. * (or even the same) files. It is not difficult to provide a file or files
  5917. * s.t. they force civetweb
  5918. * to infinitely recurse and then crash.
  5919. */
  5920. #define INITIAL_DEPTH 9
  5921. #if INITIAL_DEPTH <= 0
  5922. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5923. #endif
  5924. struct read_auth_file_struct {
  5925. struct mg_connection *conn;
  5926. struct ah ah;
  5927. char *domain;
  5928. char buf[256 + 256 + 40];
  5929. char *f_user;
  5930. char *f_domain;
  5931. char *f_ha1;
  5932. };
  5933. static int
  5934. read_auth_file(struct mg_file *filep,
  5935. struct read_auth_file_struct *workdata,
  5936. int depth)
  5937. {
  5938. char *p;
  5939. int is_authorized = 0;
  5940. struct mg_file fp;
  5941. size_t l;
  5942. if (!filep || !workdata || 0 == depth) {
  5943. return 0;
  5944. }
  5945. /* Loop over passwords file */
  5946. p = (char *)filep->access.membuf;
  5947. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5948. l = strlen(workdata->buf);
  5949. while (l > 0) {
  5950. if (isspace(workdata->buf[l - 1])
  5951. || iscntrl(workdata->buf[l - 1])) {
  5952. l--;
  5953. workdata->buf[l] = 0;
  5954. } else
  5955. break;
  5956. }
  5957. if (l < 1) {
  5958. continue;
  5959. }
  5960. workdata->f_user = workdata->buf;
  5961. if (workdata->f_user[0] == ':') {
  5962. /* user names may not contain a ':' and may not be empty,
  5963. * so lines starting with ':' may be used for a special purpose */
  5964. if (workdata->f_user[1] == '#') {
  5965. /* :# is a comment */
  5966. continue;
  5967. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5968. if (mg_fopen(workdata->conn,
  5969. workdata->f_user + 9,
  5970. MG_FOPEN_MODE_READ,
  5971. &fp)) {
  5972. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5973. (void)mg_fclose(
  5974. &fp.access); /* ignore error on read only file */
  5975. /* No need to continue processing files once we have a
  5976. * match, since nothing will reset it back
  5977. * to 0.
  5978. */
  5979. if (is_authorized) {
  5980. return is_authorized;
  5981. }
  5982. } else {
  5983. mg_cry(workdata->conn,
  5984. "%s: cannot open authorization file: %s",
  5985. __func__,
  5986. workdata->buf);
  5987. }
  5988. continue;
  5989. }
  5990. /* everything is invalid for the moment (might change in the
  5991. * future) */
  5992. mg_cry(workdata->conn,
  5993. "%s: syntax error in authorization file: %s",
  5994. __func__,
  5995. workdata->buf);
  5996. continue;
  5997. }
  5998. workdata->f_domain = strchr(workdata->f_user, ':');
  5999. if (workdata->f_domain == NULL) {
  6000. mg_cry(workdata->conn,
  6001. "%s: syntax error in authorization file: %s",
  6002. __func__,
  6003. workdata->buf);
  6004. continue;
  6005. }
  6006. *(workdata->f_domain) = 0;
  6007. (workdata->f_domain)++;
  6008. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6009. if (workdata->f_ha1 == NULL) {
  6010. mg_cry(workdata->conn,
  6011. "%s: syntax error in authorization file: %s",
  6012. __func__,
  6013. workdata->buf);
  6014. continue;
  6015. }
  6016. *(workdata->f_ha1) = 0;
  6017. (workdata->f_ha1)++;
  6018. if (!strcmp(workdata->ah.user, workdata->f_user)
  6019. && !strcmp(workdata->domain, workdata->f_domain)) {
  6020. return check_password(workdata->conn->request_info.request_method,
  6021. workdata->f_ha1,
  6022. workdata->ah.uri,
  6023. workdata->ah.nonce,
  6024. workdata->ah.nc,
  6025. workdata->ah.cnonce,
  6026. workdata->ah.qop,
  6027. workdata->ah.response);
  6028. }
  6029. }
  6030. return is_authorized;
  6031. }
  6032. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6033. static int
  6034. authorize(struct mg_connection *conn, struct mg_file *filep)
  6035. {
  6036. struct read_auth_file_struct workdata;
  6037. char buf[MG_BUF_LEN];
  6038. if (!conn || !conn->ctx) {
  6039. return 0;
  6040. }
  6041. memset(&workdata, 0, sizeof(workdata));
  6042. workdata.conn = conn;
  6043. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6044. return 0;
  6045. }
  6046. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6047. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6048. }
  6049. /* Return 1 if request is authorised, 0 otherwise. */
  6050. static int
  6051. check_authorization(struct mg_connection *conn, const char *path)
  6052. {
  6053. char fname[PATH_MAX];
  6054. struct vec uri_vec, filename_vec;
  6055. const char *list;
  6056. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6057. int authorized = 1, truncated;
  6058. if (!conn || !conn->ctx) {
  6059. return 0;
  6060. }
  6061. list = conn->ctx->config[PROTECT_URI];
  6062. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6063. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6064. mg_snprintf(conn,
  6065. &truncated,
  6066. fname,
  6067. sizeof(fname),
  6068. "%.*s",
  6069. (int)filename_vec.len,
  6070. filename_vec.ptr);
  6071. if (truncated
  6072. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6073. mg_cry(conn,
  6074. "%s: cannot open %s: %s",
  6075. __func__,
  6076. fname,
  6077. strerror(errno));
  6078. }
  6079. break;
  6080. }
  6081. }
  6082. if (!is_file_opened(&file.access)) {
  6083. open_auth_file(conn, path, &file);
  6084. }
  6085. if (is_file_opened(&file.access)) {
  6086. authorized = authorize(conn, &file);
  6087. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6088. }
  6089. return authorized;
  6090. }
  6091. static void
  6092. send_authorization_request(struct mg_connection *conn)
  6093. {
  6094. char date[64];
  6095. time_t curtime = time(NULL);
  6096. if (conn && conn->ctx) {
  6097. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6098. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6099. nonce += conn->ctx->nonce_count;
  6100. ++conn->ctx->nonce_count;
  6101. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6102. nonce ^= conn->ctx->auth_nonce_mask;
  6103. conn->status_code = 401;
  6104. conn->must_close = 1;
  6105. gmt_time_string(date, sizeof(date), &curtime);
  6106. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6107. send_no_cache_header(conn);
  6108. send_additional_header(conn);
  6109. mg_printf(conn,
  6110. "Date: %s\r\n"
  6111. "Connection: %s\r\n"
  6112. "Content-Length: 0\r\n"
  6113. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6114. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6115. date,
  6116. suggest_connection_header(conn),
  6117. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6118. nonce);
  6119. }
  6120. }
  6121. #if !defined(NO_FILES)
  6122. static int
  6123. is_authorized_for_put(struct mg_connection *conn)
  6124. {
  6125. if (conn) {
  6126. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6127. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6128. int ret = 0;
  6129. if (passfile != NULL
  6130. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6131. ret = authorize(conn, &file);
  6132. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6133. }
  6134. return ret;
  6135. }
  6136. return 0;
  6137. }
  6138. #endif
  6139. int
  6140. mg_modify_passwords_file(const char *fname,
  6141. const char *domain,
  6142. const char *user,
  6143. const char *pass)
  6144. {
  6145. int found, i;
  6146. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6147. FILE *fp, *fp2;
  6148. found = 0;
  6149. fp = fp2 = NULL;
  6150. /* Regard empty password as no password - remove user record. */
  6151. if (pass != NULL && pass[0] == '\0') {
  6152. pass = NULL;
  6153. }
  6154. /* Other arguments must not be empty */
  6155. if (fname == NULL || domain == NULL || user == NULL) {
  6156. return 0;
  6157. }
  6158. /* Using the given file format, user name and domain must not contain ':'
  6159. */
  6160. if (strchr(user, ':') != NULL) {
  6161. return 0;
  6162. }
  6163. if (strchr(domain, ':') != NULL) {
  6164. return 0;
  6165. }
  6166. /* Do not allow control characters like newline in user name and domain.
  6167. * Do not allow excessively long names either. */
  6168. for (i = 0; i < 255 && user[i] != 0; i++) {
  6169. if (iscntrl(user[i])) {
  6170. return 0;
  6171. }
  6172. }
  6173. if (user[i]) {
  6174. return 0;
  6175. }
  6176. for (i = 0; i < 255 && domain[i] != 0; i++) {
  6177. if (iscntrl(domain[i])) {
  6178. return 0;
  6179. }
  6180. }
  6181. if (domain[i]) {
  6182. return 0;
  6183. }
  6184. /* The maximum length of the path to the password file is limited */
  6185. if ((strlen(fname) + 4) >= PATH_MAX) {
  6186. return 0;
  6187. }
  6188. /* Create a temporary file name. Length has been checked before. */
  6189. strcpy(tmp, fname);
  6190. strcat(tmp, ".tmp");
  6191. /* Create the file if does not exist */
  6192. /* Use of fopen here is OK, since fname is only ASCII */
  6193. if ((fp = fopen(fname, "a+")) != NULL) {
  6194. (void)fclose(fp);
  6195. }
  6196. /* Open the given file and temporary file */
  6197. if ((fp = fopen(fname, "r")) == NULL) {
  6198. return 0;
  6199. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6200. fclose(fp);
  6201. return 0;
  6202. }
  6203. /* Copy the stuff to temporary file */
  6204. while (fgets(line, sizeof(line), fp) != NULL) {
  6205. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6206. continue;
  6207. }
  6208. u[255] = 0;
  6209. d[255] = 0;
  6210. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6211. found++;
  6212. if (pass != NULL) {
  6213. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6214. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6215. }
  6216. } else {
  6217. fprintf(fp2, "%s", line);
  6218. }
  6219. }
  6220. /* If new user, just add it */
  6221. if (!found && pass != NULL) {
  6222. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6223. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6224. }
  6225. /* Close files */
  6226. fclose(fp);
  6227. fclose(fp2);
  6228. /* Put the temp file in place of real file */
  6229. IGNORE_UNUSED_RESULT(remove(fname));
  6230. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6231. return 1;
  6232. }
  6233. static int
  6234. is_valid_port(unsigned long port)
  6235. {
  6236. return (port <= 0xffff);
  6237. }
  6238. static int
  6239. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6240. {
  6241. struct addrinfo hints, *res, *ressave;
  6242. int func_ret = 0;
  6243. int gai_ret;
  6244. memset(&hints, 0, sizeof(struct addrinfo));
  6245. hints.ai_family = af;
  6246. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6247. if (gai_ret != 0) {
  6248. /* gai_strerror could be used to convert gai_ret to a string */
  6249. /* POSIX return values: see
  6250. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6251. */
  6252. /* Windows return values: see
  6253. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6254. */
  6255. return 0;
  6256. }
  6257. ressave = res;
  6258. while (res) {
  6259. if (dstlen >= res->ai_addrlen) {
  6260. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6261. func_ret = 1;
  6262. }
  6263. res = res->ai_next;
  6264. }
  6265. freeaddrinfo(ressave);
  6266. return func_ret;
  6267. }
  6268. static int
  6269. connect_socket(struct mg_context *ctx /* may be NULL */,
  6270. const char *host,
  6271. int port,
  6272. int use_ssl,
  6273. char *ebuf,
  6274. size_t ebuf_len,
  6275. SOCKET *sock /* output: socket, must not be NULL */,
  6276. union usa *sa /* output: socket address, must not be NULL */
  6277. )
  6278. {
  6279. int ip_ver = 0;
  6280. *sock = INVALID_SOCKET;
  6281. memset(sa, 0, sizeof(*sa));
  6282. if (ebuf_len > 0) {
  6283. *ebuf = 0;
  6284. }
  6285. if (host == NULL) {
  6286. mg_snprintf(NULL,
  6287. NULL, /* No truncation check for ebuf */
  6288. ebuf,
  6289. ebuf_len,
  6290. "%s",
  6291. "NULL host");
  6292. return 0;
  6293. }
  6294. if (port <= 0 || !is_valid_port((unsigned)port)) {
  6295. mg_snprintf(NULL,
  6296. NULL, /* No truncation check for ebuf */
  6297. ebuf,
  6298. ebuf_len,
  6299. "%s",
  6300. "invalid port");
  6301. return 0;
  6302. }
  6303. #if !defined(NO_SSL)
  6304. #if !defined(NO_SSL_DL)
  6305. #ifdef OPENSSL_API_1_1
  6306. if (use_ssl && (TLS_client_method == NULL)) {
  6307. mg_snprintf(NULL,
  6308. NULL, /* No truncation check for ebuf */
  6309. ebuf,
  6310. ebuf_len,
  6311. "%s",
  6312. "SSL is not initialized");
  6313. return 0;
  6314. }
  6315. #else
  6316. if (use_ssl && (SSLv23_client_method == NULL)) {
  6317. mg_snprintf(NULL,
  6318. NULL, /* No truncation check for ebuf */
  6319. ebuf,
  6320. ebuf_len,
  6321. "%s",
  6322. "SSL is not initialized");
  6323. return 0;
  6324. }
  6325. #endif /* OPENSSL_API_1_1 */
  6326. #else
  6327. (void)use_ssl;
  6328. #endif /* NO_SSL_DL */
  6329. #else
  6330. (void)use_ssl;
  6331. #endif /* !defined(NO_SSL) */
  6332. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6333. sa->sin.sin_port = htons((uint16_t)port);
  6334. ip_ver = 4;
  6335. #ifdef USE_IPV6
  6336. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6337. sa->sin6.sin6_port = htons((uint16_t)port);
  6338. ip_ver = 6;
  6339. } else if (host[0] == '[') {
  6340. /* While getaddrinfo on Windows will work with [::1],
  6341. * getaddrinfo on Linux only works with ::1 (without []). */
  6342. size_t l = strlen(host + 1);
  6343. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6344. if (h) {
  6345. h[l - 1] = 0;
  6346. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6347. sa->sin6.sin6_port = htons((uint16_t)port);
  6348. ip_ver = 6;
  6349. }
  6350. mg_free(h);
  6351. }
  6352. #endif
  6353. }
  6354. if (ip_ver == 0) {
  6355. mg_snprintf(NULL,
  6356. NULL, /* No truncation check for ebuf */
  6357. ebuf,
  6358. ebuf_len,
  6359. "%s",
  6360. "host not found");
  6361. return 0;
  6362. }
  6363. if (ip_ver == 4) {
  6364. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6365. }
  6366. #ifdef USE_IPV6
  6367. else if (ip_ver == 6) {
  6368. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6369. }
  6370. #endif
  6371. if (*sock == INVALID_SOCKET) {
  6372. mg_snprintf(NULL,
  6373. NULL, /* No truncation check for ebuf */
  6374. ebuf,
  6375. ebuf_len,
  6376. "socket(): %s",
  6377. strerror(ERRNO));
  6378. return 0;
  6379. }
  6380. set_close_on_exec(*sock, fc(ctx));
  6381. if ((ip_ver == 4)
  6382. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6383. == 0)) {
  6384. /* connected with IPv4 */
  6385. set_blocking_mode(*sock, 0);
  6386. return 1;
  6387. }
  6388. #ifdef USE_IPV6
  6389. if ((ip_ver == 6)
  6390. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6391. == 0)) {
  6392. /* connected with IPv6 */
  6393. set_blocking_mode(*sock, 0);
  6394. return 1;
  6395. }
  6396. #endif
  6397. /* Not connected */
  6398. mg_snprintf(NULL,
  6399. NULL, /* No truncation check for ebuf */
  6400. ebuf,
  6401. ebuf_len,
  6402. "connect(%s:%d): %s",
  6403. host,
  6404. port,
  6405. strerror(ERRNO));
  6406. closesocket(*sock);
  6407. *sock = INVALID_SOCKET;
  6408. return 0;
  6409. }
  6410. int
  6411. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6412. {
  6413. static const char *dont_escape = "._-$,;~()";
  6414. static const char *hex = "0123456789abcdef";
  6415. char *pos = dst;
  6416. const char *end = dst + dst_len - 1;
  6417. for (; *src != '\0' && pos < end; src++, pos++) {
  6418. if (isalnum(*(const unsigned char *)src)
  6419. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  6420. *pos = *src;
  6421. } else if (pos + 2 < end) {
  6422. pos[0] = '%';
  6423. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6424. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6425. pos += 2;
  6426. } else {
  6427. break;
  6428. }
  6429. }
  6430. *pos = '\0';
  6431. return (*src == '\0') ? (int)(pos - dst) : -1;
  6432. }
  6433. static void
  6434. print_dir_entry(struct de *de)
  6435. {
  6436. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6437. struct tm *tm;
  6438. if (de->file.is_directory) {
  6439. mg_snprintf(de->conn,
  6440. NULL, /* Buffer is big enough */
  6441. size,
  6442. sizeof(size),
  6443. "%s",
  6444. "[DIRECTORY]");
  6445. } else {
  6446. /* We use (signed) cast below because MSVC 6 compiler cannot
  6447. * convert unsigned __int64 to double. Sigh. */
  6448. if (de->file.size < 1024) {
  6449. mg_snprintf(de->conn,
  6450. NULL, /* Buffer is big enough */
  6451. size,
  6452. sizeof(size),
  6453. "%d",
  6454. (int)de->file.size);
  6455. } else if (de->file.size < 0x100000) {
  6456. mg_snprintf(de->conn,
  6457. NULL, /* Buffer is big enough */
  6458. size,
  6459. sizeof(size),
  6460. "%.1fk",
  6461. (double)de->file.size / 1024.0);
  6462. } else if (de->file.size < 0x40000000) {
  6463. mg_snprintf(de->conn,
  6464. NULL, /* Buffer is big enough */
  6465. size,
  6466. sizeof(size),
  6467. "%.1fM",
  6468. (double)de->file.size / 1048576);
  6469. } else {
  6470. mg_snprintf(de->conn,
  6471. NULL, /* Buffer is big enough */
  6472. size,
  6473. sizeof(size),
  6474. "%.1fG",
  6475. (double)de->file.size / 1073741824);
  6476. }
  6477. }
  6478. /* Note: mg_snprintf will not cause a buffer overflow above.
  6479. * So, string truncation checks are not required here. */
  6480. tm = localtime(&de->file.last_modified);
  6481. if (tm != NULL) {
  6482. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6483. } else {
  6484. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6485. mod[sizeof(mod) - 1] = '\0';
  6486. }
  6487. mg_url_encode(de->file_name, href, sizeof(href));
  6488. de->conn->num_bytes_sent +=
  6489. mg_printf(de->conn,
  6490. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6491. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6492. de->conn->request_info.local_uri,
  6493. href,
  6494. de->file.is_directory ? "/" : "",
  6495. de->file_name,
  6496. de->file.is_directory ? "/" : "",
  6497. mod,
  6498. size);
  6499. }
  6500. /* This function is called from send_directory() and used for
  6501. * sorting directory entries by size, or name, or modification time.
  6502. * On windows, __cdecl specification is needed in case if project is built
  6503. * with __stdcall convention. qsort always requires __cdels callback. */
  6504. static int WINCDECL
  6505. compare_dir_entries(const void *p1, const void *p2)
  6506. {
  6507. if (p1 && p2) {
  6508. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6509. const char *query_string = a->conn->request_info.query_string;
  6510. int cmp_result = 0;
  6511. if (query_string == NULL) {
  6512. query_string = "na";
  6513. }
  6514. if (a->file.is_directory && !b->file.is_directory) {
  6515. return -1; /* Always put directories on top */
  6516. } else if (!a->file.is_directory && b->file.is_directory) {
  6517. return 1; /* Always put directories on top */
  6518. } else if (*query_string == 'n') {
  6519. cmp_result = strcmp(a->file_name, b->file_name);
  6520. } else if (*query_string == 's') {
  6521. cmp_result = (a->file.size == b->file.size)
  6522. ? 0
  6523. : ((a->file.size > b->file.size) ? 1 : -1);
  6524. } else if (*query_string == 'd') {
  6525. cmp_result =
  6526. (a->file.last_modified == b->file.last_modified)
  6527. ? 0
  6528. : ((a->file.last_modified > b->file.last_modified) ? 1
  6529. : -1);
  6530. }
  6531. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6532. }
  6533. return 0;
  6534. }
  6535. static int
  6536. must_hide_file(struct mg_connection *conn, const char *path)
  6537. {
  6538. if (conn && conn->ctx) {
  6539. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6540. const char *pattern = conn->ctx->config[HIDE_FILES];
  6541. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6542. || (pattern != NULL
  6543. && match_prefix(pattern, strlen(pattern), path) > 0);
  6544. }
  6545. return 0;
  6546. }
  6547. static int
  6548. scan_directory(struct mg_connection *conn,
  6549. const char *dir,
  6550. void *data,
  6551. void (*cb)(struct de *, void *))
  6552. {
  6553. char path[PATH_MAX];
  6554. struct dirent *dp;
  6555. DIR *dirp;
  6556. struct de de;
  6557. int truncated;
  6558. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6559. return 0;
  6560. } else {
  6561. de.conn = conn;
  6562. while ((dp = mg_readdir(dirp)) != NULL) {
  6563. /* Do not show current dir and hidden files */
  6564. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6565. || must_hide_file(conn, dp->d_name)) {
  6566. continue;
  6567. }
  6568. mg_snprintf(
  6569. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6570. /* If we don't memset stat structure to zero, mtime will have
  6571. * garbage and strftime() will segfault later on in
  6572. * print_dir_entry(). memset is required only if mg_stat()
  6573. * fails. For more details, see
  6574. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6575. memset(&de.file, 0, sizeof(de.file));
  6576. if (truncated) {
  6577. /* If the path is not complete, skip processing. */
  6578. continue;
  6579. }
  6580. if (!mg_stat(conn, path, &de.file)) {
  6581. mg_cry(conn,
  6582. "%s: mg_stat(%s) failed: %s",
  6583. __func__,
  6584. path,
  6585. strerror(ERRNO));
  6586. }
  6587. de.file_name = dp->d_name;
  6588. cb(&de, data);
  6589. }
  6590. (void)mg_closedir(dirp);
  6591. }
  6592. return 1;
  6593. }
  6594. #if !defined(NO_FILES)
  6595. static int
  6596. remove_directory(struct mg_connection *conn, const char *dir)
  6597. {
  6598. char path[PATH_MAX];
  6599. struct dirent *dp;
  6600. DIR *dirp;
  6601. struct de de;
  6602. int truncated;
  6603. int ok = 1;
  6604. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6605. return 0;
  6606. } else {
  6607. de.conn = conn;
  6608. while ((dp = mg_readdir(dirp)) != NULL) {
  6609. /* Do not show current dir (but show hidden files as they will
  6610. * also be removed) */
  6611. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6612. continue;
  6613. }
  6614. mg_snprintf(
  6615. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6616. /* If we don't memset stat structure to zero, mtime will have
  6617. * garbage and strftime() will segfault later on in
  6618. * print_dir_entry(). memset is required only if mg_stat()
  6619. * fails. For more details, see
  6620. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6621. memset(&de.file, 0, sizeof(de.file));
  6622. if (truncated) {
  6623. /* Do not delete anything shorter */
  6624. ok = 0;
  6625. continue;
  6626. }
  6627. if (!mg_stat(conn, path, &de.file)) {
  6628. mg_cry(conn,
  6629. "%s: mg_stat(%s) failed: %s",
  6630. __func__,
  6631. path,
  6632. strerror(ERRNO));
  6633. ok = 0;
  6634. }
  6635. if (de.file.is_directory) {
  6636. if (remove_directory(conn, path) == 0) {
  6637. ok = 0;
  6638. }
  6639. } else {
  6640. /* This will fail file is the file is in memory */
  6641. if (mg_remove(conn, path) == 0) {
  6642. ok = 0;
  6643. }
  6644. }
  6645. }
  6646. (void)mg_closedir(dirp);
  6647. IGNORE_UNUSED_RESULT(rmdir(dir));
  6648. }
  6649. return ok;
  6650. }
  6651. #endif
  6652. struct dir_scan_data {
  6653. struct de *entries;
  6654. unsigned int num_entries;
  6655. unsigned int arr_size;
  6656. };
  6657. /* Behaves like realloc(), but frees original pointer on failure */
  6658. static void *
  6659. realloc2(void *ptr, size_t size)
  6660. {
  6661. void *new_ptr = mg_realloc(ptr, size);
  6662. if (new_ptr == NULL) {
  6663. mg_free(ptr);
  6664. }
  6665. return new_ptr;
  6666. }
  6667. static void
  6668. dir_scan_callback(struct de *de, void *data)
  6669. {
  6670. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6671. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6672. dsd->arr_size *= 2;
  6673. dsd->entries =
  6674. (struct de *)realloc2(dsd->entries,
  6675. dsd->arr_size * sizeof(dsd->entries[0]));
  6676. }
  6677. if (dsd->entries == NULL) {
  6678. /* TODO(lsm, low): propagate an error to the caller */
  6679. dsd->num_entries = 0;
  6680. } else {
  6681. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6682. dsd->entries[dsd->num_entries].file = de->file;
  6683. dsd->entries[dsd->num_entries].conn = de->conn;
  6684. dsd->num_entries++;
  6685. }
  6686. }
  6687. static void
  6688. handle_directory_request(struct mg_connection *conn, const char *dir)
  6689. {
  6690. unsigned int i;
  6691. int sort_direction;
  6692. struct dir_scan_data data = {NULL, 0, 128};
  6693. char date[64];
  6694. time_t curtime = time(NULL);
  6695. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6696. mg_send_http_error(conn,
  6697. 500,
  6698. "Error: Cannot open directory\nopendir(%s): %s",
  6699. dir,
  6700. strerror(ERRNO));
  6701. return;
  6702. }
  6703. gmt_time_string(date, sizeof(date), &curtime);
  6704. if (!conn) {
  6705. return;
  6706. }
  6707. sort_direction = ((conn->request_info.query_string != NULL)
  6708. && (conn->request_info.query_string[1] == 'd'))
  6709. ? 'a'
  6710. : 'd';
  6711. conn->must_close = 1;
  6712. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6713. send_static_cache_header(conn);
  6714. send_additional_header(conn);
  6715. mg_printf(conn,
  6716. "Date: %s\r\n"
  6717. "Connection: close\r\n"
  6718. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6719. date);
  6720. conn->num_bytes_sent +=
  6721. mg_printf(conn,
  6722. "<html><head><title>Index of %s</title>"
  6723. "<style>th {text-align: left;}</style></head>"
  6724. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6725. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6726. "<th><a href=\"?d%c\">Modified</a></th>"
  6727. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6728. "<tr><td colspan=\"3\"><hr></td></tr>",
  6729. conn->request_info.local_uri,
  6730. conn->request_info.local_uri,
  6731. sort_direction,
  6732. sort_direction,
  6733. sort_direction);
  6734. /* Print first entry - link to a parent directory */
  6735. conn->num_bytes_sent +=
  6736. mg_printf(conn,
  6737. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6738. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6739. conn->request_info.local_uri,
  6740. "..",
  6741. "Parent directory",
  6742. "-",
  6743. "-");
  6744. /* Sort and print directory entries */
  6745. if (data.entries != NULL) {
  6746. qsort(data.entries,
  6747. (size_t)data.num_entries,
  6748. sizeof(data.entries[0]),
  6749. compare_dir_entries);
  6750. for (i = 0; i < data.num_entries; i++) {
  6751. print_dir_entry(&data.entries[i]);
  6752. mg_free(data.entries[i].file_name);
  6753. }
  6754. mg_free(data.entries);
  6755. }
  6756. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6757. conn->status_code = 200;
  6758. }
  6759. /* Send len bytes from the opened file to the client. */
  6760. static void
  6761. send_file_data(struct mg_connection *conn,
  6762. struct mg_file *filep,
  6763. int64_t offset,
  6764. int64_t len)
  6765. {
  6766. char buf[MG_BUF_LEN];
  6767. int to_read, num_read, num_written;
  6768. int64_t size;
  6769. if (!filep || !conn) {
  6770. return;
  6771. }
  6772. /* Sanity check the offset */
  6773. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6774. : (int64_t)(filep->stat.size);
  6775. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6776. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6777. /* file stored in memory */
  6778. if (len > size - offset) {
  6779. len = size - offset;
  6780. }
  6781. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6782. } else if (len > 0 && filep->access.fp != NULL) {
  6783. /* file stored on disk */
  6784. #if defined(__linux__)
  6785. /* sendfile is only available for Linux */
  6786. if ((conn->ssl == 0) && (conn->throttle == 0)
  6787. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6788. "yes"))) {
  6789. off_t sf_offs = (off_t)offset;
  6790. ssize_t sf_sent;
  6791. int sf_file = fileno(filep->access.fp);
  6792. int loop_cnt = 0;
  6793. do {
  6794. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6795. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6796. size_t sf_tosend =
  6797. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6798. sf_sent =
  6799. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6800. if (sf_sent > 0) {
  6801. conn->num_bytes_sent += sf_sent;
  6802. len -= sf_sent;
  6803. offset += sf_sent;
  6804. } else if (loop_cnt == 0) {
  6805. /* This file can not be sent using sendfile.
  6806. * This might be the case for pseudo-files in the
  6807. * /sys/ and /proc/ file system.
  6808. * Use the regular user mode copy code instead. */
  6809. break;
  6810. } else if (sf_sent == 0) {
  6811. /* No error, but 0 bytes sent. May be EOF? */
  6812. return;
  6813. }
  6814. loop_cnt++;
  6815. } while ((len > 0) && (sf_sent >= 0));
  6816. if (sf_sent > 0) {
  6817. return; /* OK */
  6818. }
  6819. /* sf_sent<0 means error, thus fall back to the classic way */
  6820. /* This is always the case, if sf_file is not a "normal" file,
  6821. * e.g., for sending data from the output of a CGI process. */
  6822. offset = (int64_t)sf_offs;
  6823. }
  6824. #endif
  6825. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6826. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6827. mg_send_http_error(
  6828. conn,
  6829. 500,
  6830. "%s",
  6831. "Error: Unable to access file at requested position.");
  6832. } else {
  6833. while (len > 0) {
  6834. /* Calculate how much to read from the file in the buffer */
  6835. to_read = sizeof(buf);
  6836. if ((int64_t)to_read > len) {
  6837. to_read = (int)len;
  6838. }
  6839. /* Read from file, exit the loop on error */
  6840. if ((num_read =
  6841. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6842. <= 0) {
  6843. break;
  6844. }
  6845. /* Send read bytes to the client, exit the loop on error */
  6846. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6847. != num_read) {
  6848. break;
  6849. }
  6850. /* Both read and were successful, adjust counters */
  6851. conn->num_bytes_sent += num_written;
  6852. len -= num_written;
  6853. }
  6854. }
  6855. }
  6856. }
  6857. static int
  6858. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6859. {
  6860. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6861. }
  6862. static void
  6863. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6864. {
  6865. if (filestat != NULL && buf != NULL) {
  6866. mg_snprintf(NULL,
  6867. NULL, /* All calls to construct_etag use 64 byte buffer */
  6868. buf,
  6869. buf_len,
  6870. "\"%lx.%" INT64_FMT "\"",
  6871. (unsigned long)filestat->last_modified,
  6872. filestat->size);
  6873. }
  6874. }
  6875. static void
  6876. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6877. {
  6878. if (filep != NULL && filep->fp != NULL) {
  6879. #ifdef _WIN32
  6880. (void)conn; /* Unused. */
  6881. #else
  6882. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6883. mg_cry(conn,
  6884. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6885. __func__,
  6886. strerror(ERRNO));
  6887. }
  6888. #endif
  6889. }
  6890. }
  6891. static void
  6892. handle_static_file_request(struct mg_connection *conn,
  6893. const char *path,
  6894. struct mg_file *filep,
  6895. const char *mime_type,
  6896. const char *additional_headers)
  6897. {
  6898. char date[64], lm[64], etag[64];
  6899. char range[128]; /* large enough, so there will be no overflow */
  6900. const char *msg = "OK", *hdr;
  6901. time_t curtime = time(NULL);
  6902. int64_t cl, r1, r2;
  6903. struct vec mime_vec;
  6904. int n, truncated;
  6905. char gz_path[PATH_MAX];
  6906. const char *encoding = "";
  6907. const char *cors1, *cors2, *cors3;
  6908. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6909. return;
  6910. }
  6911. if (mime_type == NULL) {
  6912. get_mime_type(conn->ctx, path, &mime_vec);
  6913. } else {
  6914. mime_vec.ptr = mime_type;
  6915. mime_vec.len = strlen(mime_type);
  6916. }
  6917. if (filep->stat.size > INT64_MAX) {
  6918. mg_send_http_error(conn,
  6919. 500,
  6920. "Error: File size is too large to send\n%" INT64_FMT,
  6921. filep->stat.size);
  6922. }
  6923. cl = (int64_t)filep->stat.size;
  6924. conn->status_code = 200;
  6925. range[0] = '\0';
  6926. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6927. * it's important to rewrite the filename after resolving
  6928. * the mime type from it, to preserve the actual file's type */
  6929. if (filep->stat.is_gzipped) {
  6930. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6931. if (truncated) {
  6932. mg_send_http_error(conn,
  6933. 500,
  6934. "Error: Path of zipped file too long (%s)",
  6935. path);
  6936. return;
  6937. }
  6938. path = gz_path;
  6939. encoding = "Content-Encoding: gzip\r\n";
  6940. }
  6941. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6942. mg_send_http_error(conn,
  6943. 500,
  6944. "Error: Cannot open file\nfopen(%s): %s",
  6945. path,
  6946. strerror(ERRNO));
  6947. return;
  6948. }
  6949. fclose_on_exec(&filep->access, conn);
  6950. /* If Range: header specified, act accordingly */
  6951. r1 = r2 = 0;
  6952. hdr = mg_get_header(conn, "Range");
  6953. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6954. && r2 >= 0) {
  6955. /* actually, range requests don't play well with a pre-gzipped
  6956. * file (since the range is specified in the uncompressed space) */
  6957. if (filep->stat.is_gzipped) {
  6958. mg_send_http_error(
  6959. conn,
  6960. 416, /* 416 = Range Not Satisfiable */
  6961. "%s",
  6962. "Error: Range requests in gzipped files are not supported");
  6963. (void)mg_fclose(
  6964. &filep->access); /* ignore error on read only file */
  6965. return;
  6966. }
  6967. conn->status_code = 206;
  6968. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6969. mg_snprintf(conn,
  6970. NULL, /* range buffer is big enough */
  6971. range,
  6972. sizeof(range),
  6973. "Content-Range: bytes "
  6974. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6975. r1,
  6976. r1 + cl - 1,
  6977. filep->stat.size);
  6978. msg = "Partial Content";
  6979. }
  6980. hdr = mg_get_header(conn, "Origin");
  6981. if (hdr) {
  6982. /* Cross-origin resource sharing (CORS), see
  6983. * http://www.html5rocks.com/en/tutorials/cors/,
  6984. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6985. * preflight is not supported for files. */
  6986. cors1 = "Access-Control-Allow-Origin: ";
  6987. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6988. cors3 = "\r\n";
  6989. } else {
  6990. cors1 = cors2 = cors3 = "";
  6991. }
  6992. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6993. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6994. gmt_time_string(date, sizeof(date), &curtime);
  6995. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6996. construct_etag(etag, sizeof(etag), &filep->stat);
  6997. (void)mg_printf(conn,
  6998. "HTTP/1.1 %d %s\r\n"
  6999. "%s%s%s"
  7000. "Date: %s\r\n",
  7001. conn->status_code,
  7002. msg,
  7003. cors1,
  7004. cors2,
  7005. cors3,
  7006. date);
  7007. send_static_cache_header(conn);
  7008. send_additional_header(conn);
  7009. (void)mg_printf(conn,
  7010. "Last-Modified: %s\r\n"
  7011. "Etag: %s\r\n"
  7012. "Content-Type: %.*s\r\n"
  7013. "Content-Length: %" INT64_FMT "\r\n"
  7014. "Connection: %s\r\n"
  7015. "Accept-Ranges: bytes\r\n"
  7016. "%s%s",
  7017. lm,
  7018. etag,
  7019. (int)mime_vec.len,
  7020. mime_vec.ptr,
  7021. cl,
  7022. suggest_connection_header(conn),
  7023. range,
  7024. encoding);
  7025. /* The previous code must not add any header starting with X- to make
  7026. * sure no one of the additional_headers is included twice */
  7027. if (additional_headers != NULL) {
  7028. (void)mg_printf(conn,
  7029. "%.*s\r\n\r\n",
  7030. (int)strlen(additional_headers),
  7031. additional_headers);
  7032. } else {
  7033. (void)mg_printf(conn, "\r\n");
  7034. }
  7035. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7036. send_file_data(conn, filep, r1, cl);
  7037. }
  7038. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7039. }
  7040. #if !defined(NO_CACHING)
  7041. static void
  7042. handle_not_modified_static_file_request(struct mg_connection *conn,
  7043. struct mg_file *filep)
  7044. {
  7045. char date[64], lm[64], etag[64];
  7046. time_t curtime = time(NULL);
  7047. if (conn == NULL || filep == NULL) {
  7048. return;
  7049. }
  7050. conn->status_code = 304;
  7051. gmt_time_string(date, sizeof(date), &curtime);
  7052. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7053. construct_etag(etag, sizeof(etag), &filep->stat);
  7054. (void)mg_printf(conn,
  7055. "HTTP/1.1 %d %s\r\n"
  7056. "Date: %s\r\n",
  7057. conn->status_code,
  7058. mg_get_response_code_text(conn, conn->status_code),
  7059. date);
  7060. send_static_cache_header(conn);
  7061. send_additional_header(conn);
  7062. (void)mg_printf(conn,
  7063. "Last-Modified: %s\r\n"
  7064. "Etag: %s\r\n"
  7065. "Connection: %s\r\n"
  7066. "\r\n",
  7067. lm,
  7068. etag,
  7069. suggest_connection_header(conn));
  7070. }
  7071. #endif
  7072. void
  7073. mg_send_file(struct mg_connection *conn, const char *path)
  7074. {
  7075. mg_send_mime_file(conn, path, NULL);
  7076. }
  7077. void
  7078. mg_send_mime_file(struct mg_connection *conn,
  7079. const char *path,
  7080. const char *mime_type)
  7081. {
  7082. mg_send_mime_file2(conn, path, mime_type, NULL);
  7083. }
  7084. void
  7085. mg_send_mime_file2(struct mg_connection *conn,
  7086. const char *path,
  7087. const char *mime_type,
  7088. const char *additional_headers)
  7089. {
  7090. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7091. if (mg_stat(conn, path, &file.stat)) {
  7092. if (file.stat.is_directory) {
  7093. if (!conn) {
  7094. return;
  7095. }
  7096. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7097. "yes")) {
  7098. handle_directory_request(conn, path);
  7099. } else {
  7100. mg_send_http_error(conn,
  7101. 403,
  7102. "%s",
  7103. "Error: Directory listing denied");
  7104. }
  7105. } else {
  7106. handle_static_file_request(
  7107. conn, path, &file, mime_type, additional_headers);
  7108. }
  7109. } else {
  7110. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7111. }
  7112. }
  7113. /* For a given PUT path, create all intermediate subdirectories.
  7114. * Return 0 if the path itself is a directory.
  7115. * Return 1 if the path leads to a file.
  7116. * Return -1 for if the path is too long.
  7117. * Return -2 if path can not be created.
  7118. */
  7119. static int
  7120. put_dir(struct mg_connection *conn, const char *path)
  7121. {
  7122. char buf[PATH_MAX];
  7123. const char *s, *p;
  7124. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7125. size_t len;
  7126. int res = 1;
  7127. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7128. len = (size_t)(p - path);
  7129. if (len >= sizeof(buf)) {
  7130. /* path too long */
  7131. res = -1;
  7132. break;
  7133. }
  7134. memcpy(buf, path, len);
  7135. buf[len] = '\0';
  7136. /* Try to create intermediate directory */
  7137. DEBUG_TRACE("mkdir(%s)", buf);
  7138. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7139. /* path does not exixt and can not be created */
  7140. res = -2;
  7141. break;
  7142. }
  7143. /* Is path itself a directory? */
  7144. if (p[1] == '\0') {
  7145. res = 0;
  7146. }
  7147. }
  7148. return res;
  7149. }
  7150. static void
  7151. remove_bad_file(const struct mg_connection *conn, const char *path)
  7152. {
  7153. int r = mg_remove(conn, path);
  7154. if (r != 0) {
  7155. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7156. }
  7157. }
  7158. long long
  7159. mg_store_body(struct mg_connection *conn, const char *path)
  7160. {
  7161. char buf[MG_BUF_LEN];
  7162. long long len = 0;
  7163. int ret, n;
  7164. struct mg_file fi;
  7165. if (conn->consumed_content != 0) {
  7166. mg_cry(conn, "%s: Contents already consumed", __func__);
  7167. return -11;
  7168. }
  7169. ret = put_dir(conn, path);
  7170. if (ret < 0) {
  7171. /* -1 for path too long,
  7172. * -2 for path can not be created. */
  7173. return ret;
  7174. }
  7175. if (ret != 1) {
  7176. /* Return 0 means, path itself is a directory. */
  7177. return 0;
  7178. }
  7179. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7180. return -12;
  7181. }
  7182. ret = mg_read(conn, buf, sizeof(buf));
  7183. while (ret > 0) {
  7184. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7185. if (n != ret) {
  7186. (void)mg_fclose(
  7187. &fi.access); /* File is bad and will be removed anyway. */
  7188. remove_bad_file(conn, path);
  7189. return -13;
  7190. }
  7191. len += ret;
  7192. ret = mg_read(conn, buf, sizeof(buf));
  7193. }
  7194. /* File is open for writing. If fclose fails, there was probably an
  7195. * error flushing the buffer to disk, so the file on disk might be
  7196. * broken. Delete it and return an error to the caller. */
  7197. if (mg_fclose(&fi.access) != 0) {
  7198. remove_bad_file(conn, path);
  7199. return -14;
  7200. }
  7201. return len;
  7202. }
  7203. /* Parse HTTP headers from the given buffer, advance buf pointer
  7204. * to the point where parsing stopped.
  7205. * All parameters must be valid pointers (not NULL).
  7206. * Return <0 on error. */
  7207. static int
  7208. parse_http_headers(char **buf, struct mg_request_info *ri)
  7209. {
  7210. int i;
  7211. ri->num_headers = 0;
  7212. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  7213. char *dp = *buf;
  7214. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7215. dp++;
  7216. }
  7217. if (dp == *buf) {
  7218. /* End of headers reached. */
  7219. break;
  7220. }
  7221. if (*dp != ':') {
  7222. /* This is not a valid field. */
  7223. return -1;
  7224. }
  7225. /* End of header key (*dp == ':') */
  7226. /* Truncate here and set the key name */
  7227. *dp = 0;
  7228. ri->http_headers[i].name = *buf;
  7229. do {
  7230. dp++;
  7231. } while (*dp == ' ');
  7232. /* The rest of the line is the value */
  7233. ri->http_headers[i].value = dp;
  7234. *buf = dp + strcspn(dp, "\r\n");
  7235. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7236. *buf = NULL;
  7237. }
  7238. ri->num_headers = i + 1;
  7239. if (*buf) {
  7240. (*buf)[0] = 0;
  7241. (*buf)[1] = 0;
  7242. *buf += 2;
  7243. } else {
  7244. *buf = dp;
  7245. break;
  7246. }
  7247. if ((*buf)[0] == '\r') {
  7248. /* This is the end of the header */
  7249. break;
  7250. }
  7251. }
  7252. return ri->num_headers;
  7253. }
  7254. static int
  7255. is_valid_http_method(const char *method)
  7256. {
  7257. /* Check if the method is known to the server. The list of all known
  7258. * HTTP methods can be found here at
  7259. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7260. */
  7261. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7262. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7263. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7264. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7265. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7266. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7267. /* TRACE method (RFC 2616) is not supported for security reasons */
  7268. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7269. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7270. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7271. /* Unsupported WEBDAV Methods: */
  7272. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7273. /* + 11 methods from RFC 3253 */
  7274. /* ORDERPATCH (RFC 3648) */
  7275. /* ACL (RFC 3744) */
  7276. /* SEARCH (RFC 5323) */
  7277. /* + MicroSoft extensions
  7278. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7279. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7280. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7281. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7282. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7283. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7284. * to be useful for REST in case a "GET request with body" is
  7285. * required. */
  7286. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7287. ;
  7288. }
  7289. /* Parse HTTP request, fill in mg_request_info structure.
  7290. * This function modifies the buffer by NUL-terminating
  7291. * HTTP request components, header names and header values.
  7292. * Parameters:
  7293. * buf (in/out): pointer to the HTTP header to parse and split
  7294. * len (in): length of HTTP header buffer
  7295. * re (out): parsed header as mg_request_info
  7296. * buf and ri must be valid pointers (not NULL), len>0.
  7297. * Returns <0 on error. */
  7298. static int
  7299. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  7300. {
  7301. int is_request, request_length;
  7302. char *start_line;
  7303. request_length = get_request_len(buf, len);
  7304. if (request_length > 0) {
  7305. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7306. * remote_port */
  7307. ri->remote_user = ri->request_method = ri->request_uri =
  7308. ri->http_version = NULL;
  7309. ri->num_headers = 0;
  7310. buf[request_length - 1] = '\0';
  7311. /* RFC says that all initial whitespaces should be ingored */
  7312. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  7313. buf++;
  7314. }
  7315. start_line = skip(&buf, "\r\n");
  7316. ri->request_method = skip(&start_line, " ");
  7317. ri->request_uri = skip(&start_line, " ");
  7318. ri->http_version = start_line;
  7319. /* HTTP message could be either HTTP request:
  7320. * "GET / HTTP/1.0 ..."
  7321. * or a HTTP response:
  7322. * "HTTP/1.0 200 OK ..."
  7323. * otherwise it is invalid.
  7324. */
  7325. is_request = is_valid_http_method(ri->request_method);
  7326. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  7327. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  7328. /* Not a valid request or response: invalid */
  7329. return -1;
  7330. }
  7331. if (is_request) {
  7332. ri->http_version += 5;
  7333. }
  7334. if (parse_http_headers(&buf, ri) < 0) {
  7335. /* Error while parsing headers */
  7336. return -1;
  7337. }
  7338. }
  7339. return request_length;
  7340. }
  7341. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7342. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7343. * buffer (which marks the end of HTTP request). Buffer buf may already
  7344. * have some data. The length of the data is stored in nread.
  7345. * Upon every read operation, increase nread by the number of bytes read. */
  7346. static int
  7347. read_request(FILE *fp,
  7348. struct mg_connection *conn,
  7349. char *buf,
  7350. int bufsiz,
  7351. int *nread)
  7352. {
  7353. int request_len, n = 0;
  7354. struct timespec last_action_time;
  7355. double request_timeout;
  7356. if (!conn) {
  7357. return 0;
  7358. }
  7359. memset(&last_action_time, 0, sizeof(last_action_time));
  7360. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7361. /* value of request_timeout is in seconds, config in milliseconds */
  7362. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7363. } else {
  7364. request_timeout = -1.0;
  7365. }
  7366. if (conn->handled_requests > 0) {
  7367. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7368. request_timeout =
  7369. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7370. }
  7371. }
  7372. request_len = get_request_len(buf, *nread);
  7373. /* first time reading from this connection */
  7374. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7375. while (request_len == 0) {
  7376. /* Full request not yet received */
  7377. if (conn->ctx->stop_flag != 0) {
  7378. /* Server is to be stopped. */
  7379. return -1;
  7380. }
  7381. if (*nread >= bufsiz) {
  7382. /* Request too long */
  7383. return -2;
  7384. }
  7385. n = pull_inner(
  7386. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7387. if (n == -2) {
  7388. /* Receive error */
  7389. return -1;
  7390. }
  7391. if (n > 0) {
  7392. *nread += n;
  7393. request_len = get_request_len(buf, *nread);
  7394. } else {
  7395. request_len = 0;
  7396. }
  7397. if ((request_len == 0) && (request_timeout >= 0)) {
  7398. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7399. > request_timeout) {
  7400. /* Timeout */
  7401. return -1;
  7402. }
  7403. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7404. }
  7405. }
  7406. return request_len;
  7407. }
  7408. #if !defined(NO_CACHING)
  7409. /* Return True if we should reply 304 Not Modified. */
  7410. static int
  7411. is_not_modified(const struct mg_connection *conn,
  7412. const struct mg_file_stat *filestat)
  7413. {
  7414. char etag[64];
  7415. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7416. const char *inm = mg_get_header(conn, "If-None-Match");
  7417. construct_etag(etag, sizeof(etag), filestat);
  7418. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7419. || ((ims != NULL)
  7420. && (filestat->last_modified <= parse_date_string(ims)));
  7421. }
  7422. #endif /* !NO_CACHING */
  7423. #if !defined(NO_CGI) || !defined(NO_FILES)
  7424. static int
  7425. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7426. {
  7427. const char *expect, *body;
  7428. char buf[MG_BUF_LEN];
  7429. int to_read, nread, success = 0;
  7430. int64_t buffered_len;
  7431. double timeout = -1.0;
  7432. if (!conn) {
  7433. return 0;
  7434. }
  7435. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7436. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7437. }
  7438. expect = mg_get_header(conn, "Expect");
  7439. /* assert(fp != NULL); */
  7440. if (!fp) {
  7441. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  7442. return 0;
  7443. }
  7444. if (conn->content_len == -1 && !conn->is_chunked) {
  7445. /* Content length is not specified by the client. */
  7446. mg_send_http_error(conn,
  7447. 411,
  7448. "%s",
  7449. "Error: Client did not specify content length");
  7450. } else if ((expect != NULL)
  7451. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7452. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7453. mg_send_http_error(conn,
  7454. 417,
  7455. "Error: Can not fulfill expectation %s",
  7456. expect);
  7457. } else {
  7458. if (expect != NULL) {
  7459. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7460. conn->status_code = 100;
  7461. } else {
  7462. conn->status_code = 200;
  7463. }
  7464. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7465. - conn->consumed_content;
  7466. /* assert(buffered_len >= 0); */
  7467. /* assert(conn->consumed_content == 0); */
  7468. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7469. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7470. return 0;
  7471. }
  7472. if (buffered_len > 0) {
  7473. if ((int64_t)buffered_len > conn->content_len) {
  7474. buffered_len = (int)conn->content_len;
  7475. }
  7476. body = conn->buf + conn->request_len + conn->consumed_content;
  7477. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7478. conn->consumed_content += buffered_len;
  7479. }
  7480. nread = 0;
  7481. while (conn->consumed_content < conn->content_len) {
  7482. to_read = sizeof(buf);
  7483. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7484. to_read = (int)(conn->content_len - conn->consumed_content);
  7485. }
  7486. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7487. if (nread == -2) {
  7488. /* error */
  7489. break;
  7490. }
  7491. if (nread > 0) {
  7492. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7493. break;
  7494. }
  7495. }
  7496. conn->consumed_content += nread;
  7497. }
  7498. if (conn->consumed_content == conn->content_len) {
  7499. success = (nread >= 0);
  7500. }
  7501. /* Each error code path in this function must send an error */
  7502. if (!success) {
  7503. /* NOTE: Maybe some data has already been sent. */
  7504. /* TODO (low): If some data has been sent, a correct error
  7505. * reply can no longer be sent, so just close the connection */
  7506. mg_send_http_error(conn, 500, "%s", "");
  7507. }
  7508. }
  7509. return success;
  7510. }
  7511. #endif
  7512. #if !defined(NO_CGI)
  7513. /* This structure helps to create an environment for the spawned CGI program.
  7514. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7515. * last element must be NULL.
  7516. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7517. * strings must reside in a contiguous buffer. The end of the buffer is
  7518. * marked by two '\0' characters.
  7519. * We satisfy both worlds: we create an envp array (which is vars), all
  7520. * entries are actually pointers inside buf. */
  7521. struct cgi_environment {
  7522. struct mg_connection *conn;
  7523. /* Data block */
  7524. char *buf; /* Environment buffer */
  7525. size_t buflen; /* Space available in buf */
  7526. size_t bufused; /* Space taken in buf */
  7527. /* Index block */
  7528. char **var; /* char **envp */
  7529. size_t varlen; /* Number of variables available in var */
  7530. size_t varused; /* Number of variables stored in var */
  7531. };
  7532. static void addenv(struct cgi_environment *env,
  7533. PRINTF_FORMAT_STRING(const char *fmt),
  7534. ...) PRINTF_ARGS(2, 3);
  7535. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7536. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7537. static void
  7538. addenv(struct cgi_environment *env, const char *fmt, ...)
  7539. {
  7540. size_t n, space;
  7541. int truncated = 0;
  7542. char *added;
  7543. va_list ap;
  7544. /* Calculate how much space is left in the buffer */
  7545. space = (env->buflen - env->bufused);
  7546. /* Calculate an estimate for the required space */
  7547. n = strlen(fmt) + 2 + 128;
  7548. do {
  7549. if (space <= n) {
  7550. /* Allocate new buffer */
  7551. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7552. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  7553. if (!added) {
  7554. /* Out of memory */
  7555. mg_cry(env->conn,
  7556. "%s: Cannot allocate memory for CGI variable [%s]",
  7557. __func__,
  7558. fmt);
  7559. return;
  7560. }
  7561. env->buf = added;
  7562. env->buflen = n;
  7563. space = (env->buflen - env->bufused);
  7564. }
  7565. /* Make a pointer to the free space int the buffer */
  7566. added = env->buf + env->bufused;
  7567. /* Copy VARIABLE=VALUE\0 string into the free space */
  7568. va_start(ap, fmt);
  7569. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7570. va_end(ap);
  7571. /* Do not add truncated strings to the environment */
  7572. if (truncated) {
  7573. /* Reallocate the buffer */
  7574. space = 0;
  7575. n = 1;
  7576. }
  7577. } while (truncated);
  7578. /* Calculate number of bytes added to the environment */
  7579. n = strlen(added) + 1;
  7580. env->bufused += n;
  7581. /* Now update the variable index */
  7582. space = (env->varlen - env->varused);
  7583. if (space < 2) {
  7584. mg_cry(env->conn,
  7585. "%s: Cannot register CGI variable [%s]",
  7586. __func__,
  7587. fmt);
  7588. return;
  7589. }
  7590. /* Append a pointer to the added string into the envp array */
  7591. env->var[env->varused] = added;
  7592. env->varused++;
  7593. }
  7594. static void
  7595. prepare_cgi_environment(struct mg_connection *conn,
  7596. const char *prog,
  7597. struct cgi_environment *env)
  7598. {
  7599. const char *s;
  7600. struct vec var_vec;
  7601. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7602. int i, truncated, uri_len;
  7603. if (conn == NULL || prog == NULL || env == NULL) {
  7604. return;
  7605. }
  7606. env->conn = conn;
  7607. env->buflen = CGI_ENVIRONMENT_SIZE;
  7608. env->bufused = 0;
  7609. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  7610. env->varlen = MAX_CGI_ENVIR_VARS;
  7611. env->varused = 0;
  7612. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  7613. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7614. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7615. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7616. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7617. /* Prepare the environment block */
  7618. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7619. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7620. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7621. #if defined(USE_IPV6)
  7622. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7623. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7624. } else
  7625. #endif
  7626. {
  7627. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7628. }
  7629. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7630. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7631. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7632. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7633. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7634. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7635. /* SCRIPT_NAME */
  7636. uri_len = (int)strlen(conn->request_info.local_uri);
  7637. if (conn->path_info == NULL) {
  7638. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7639. /* URI: /path_to_script/script.cgi */
  7640. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7641. } else {
  7642. /* URI: /path_to_script/ ... using index.cgi */
  7643. const char *index_file = strrchr(prog, '/');
  7644. if (index_file) {
  7645. addenv(env,
  7646. "SCRIPT_NAME=%s%s",
  7647. conn->request_info.local_uri,
  7648. index_file + 1);
  7649. }
  7650. }
  7651. } else {
  7652. /* URI: /path_to_script/script.cgi/path_info */
  7653. addenv(env,
  7654. "SCRIPT_NAME=%.*s",
  7655. uri_len - (int)strlen(conn->path_info),
  7656. conn->request_info.local_uri);
  7657. }
  7658. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7659. if (conn->path_info == NULL) {
  7660. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7661. } else {
  7662. addenv(env,
  7663. "PATH_TRANSLATED=%s%s",
  7664. conn->ctx->config[DOCUMENT_ROOT],
  7665. conn->path_info);
  7666. }
  7667. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7668. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7669. addenv(env, "CONTENT_TYPE=%s", s);
  7670. }
  7671. if (conn->request_info.query_string != NULL) {
  7672. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7673. }
  7674. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7675. addenv(env, "CONTENT_LENGTH=%s", s);
  7676. }
  7677. if ((s = getenv("PATH")) != NULL) {
  7678. addenv(env, "PATH=%s", s);
  7679. }
  7680. if (conn->path_info != NULL) {
  7681. addenv(env, "PATH_INFO=%s", conn->path_info);
  7682. }
  7683. if (conn->status_code > 0) {
  7684. /* CGI error handler should show the status code */
  7685. addenv(env, "STATUS=%d", conn->status_code);
  7686. }
  7687. #if defined(_WIN32)
  7688. if ((s = getenv("COMSPEC")) != NULL) {
  7689. addenv(env, "COMSPEC=%s", s);
  7690. }
  7691. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7692. addenv(env, "SYSTEMROOT=%s", s);
  7693. }
  7694. if ((s = getenv("SystemDrive")) != NULL) {
  7695. addenv(env, "SystemDrive=%s", s);
  7696. }
  7697. if ((s = getenv("ProgramFiles")) != NULL) {
  7698. addenv(env, "ProgramFiles=%s", s);
  7699. }
  7700. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7701. addenv(env, "ProgramFiles(x86)=%s", s);
  7702. }
  7703. #else
  7704. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7705. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7706. }
  7707. #endif /* _WIN32 */
  7708. if ((s = getenv("PERLLIB")) != NULL) {
  7709. addenv(env, "PERLLIB=%s", s);
  7710. }
  7711. if (conn->request_info.remote_user != NULL) {
  7712. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7713. addenv(env, "%s", "AUTH_TYPE=Digest");
  7714. }
  7715. /* Add all headers as HTTP_* variables */
  7716. for (i = 0; i < conn->request_info.num_headers; i++) {
  7717. (void)mg_snprintf(conn,
  7718. &truncated,
  7719. http_var_name,
  7720. sizeof(http_var_name),
  7721. "HTTP_%s",
  7722. conn->request_info.http_headers[i].name);
  7723. if (truncated) {
  7724. mg_cry(conn,
  7725. "%s: HTTP header variable too long [%s]",
  7726. __func__,
  7727. conn->request_info.http_headers[i].name);
  7728. continue;
  7729. }
  7730. /* Convert variable name into uppercase, and change - to _ */
  7731. for (p = http_var_name; *p != '\0'; p++) {
  7732. if (*p == '-') {
  7733. *p = '_';
  7734. }
  7735. *p = (char)toupper(*(unsigned char *)p);
  7736. }
  7737. addenv(env,
  7738. "%s=%s",
  7739. http_var_name,
  7740. conn->request_info.http_headers[i].value);
  7741. }
  7742. /* Add user-specified variables */
  7743. s = conn->ctx->config[CGI_ENVIRONMENT];
  7744. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7745. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7746. }
  7747. env->var[env->varused] = NULL;
  7748. env->buf[env->bufused] = '\0';
  7749. }
  7750. static void
  7751. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7752. {
  7753. char *buf;
  7754. size_t buflen;
  7755. int headers_len, data_len, i, truncated;
  7756. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7757. const char *status, *status_text, *connection_state;
  7758. char *pbuf, dir[PATH_MAX], *p;
  7759. struct mg_request_info ri;
  7760. struct cgi_environment blk;
  7761. FILE *in = NULL, *out = NULL, *err = NULL;
  7762. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7763. pid_t pid = (pid_t)-1;
  7764. if (conn == NULL) {
  7765. return;
  7766. }
  7767. buf = NULL;
  7768. buflen = 16384;
  7769. prepare_cgi_environment(conn, prog, &blk);
  7770. /* CGI must be executed in its own directory. 'dir' must point to the
  7771. * directory containing executable program, 'p' must point to the
  7772. * executable program name relative to 'dir'. */
  7773. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7774. if (truncated) {
  7775. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7776. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7777. goto done;
  7778. }
  7779. if ((p = strrchr(dir, '/')) != NULL) {
  7780. *p++ = '\0';
  7781. } else {
  7782. dir[0] = '.', dir[1] = '\0';
  7783. p = (char *)prog;
  7784. }
  7785. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7786. status = strerror(ERRNO);
  7787. mg_cry(conn,
  7788. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7789. prog,
  7790. status);
  7791. mg_send_http_error(conn,
  7792. 500,
  7793. "Error: Cannot create CGI pipe: %s",
  7794. status);
  7795. goto done;
  7796. }
  7797. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7798. if (pid == (pid_t)-1) {
  7799. status = strerror(ERRNO);
  7800. mg_cry(conn,
  7801. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7802. prog,
  7803. status);
  7804. mg_send_http_error(conn,
  7805. 500,
  7806. "Error: Cannot spawn CGI process [%s]: %s",
  7807. prog,
  7808. status);
  7809. goto done;
  7810. }
  7811. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7812. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7813. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7814. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7815. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7816. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7817. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7818. /* Parent closes only one side of the pipes.
  7819. * If we don't mark them as closed, close() attempt before
  7820. * return from this function throws an exception on Windows.
  7821. * Windows does not like when closed descriptor is closed again. */
  7822. (void)close(fdin[0]);
  7823. (void)close(fdout[1]);
  7824. (void)close(fderr[1]);
  7825. fdin[0] = fdout[1] = fderr[1] = -1;
  7826. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7827. status = strerror(ERRNO);
  7828. mg_cry(conn,
  7829. "Error: CGI program \"%s\": Can not open stdin: %s",
  7830. prog,
  7831. status);
  7832. mg_send_http_error(conn,
  7833. 500,
  7834. "Error: CGI can not open fdin\nfopen: %s",
  7835. status);
  7836. goto done;
  7837. }
  7838. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7839. status = strerror(ERRNO);
  7840. mg_cry(conn,
  7841. "Error: CGI program \"%s\": Can not open stdout: %s",
  7842. prog,
  7843. status);
  7844. mg_send_http_error(conn,
  7845. 500,
  7846. "Error: CGI can not open fdout\nfopen: %s",
  7847. status);
  7848. goto done;
  7849. }
  7850. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7851. status = strerror(ERRNO);
  7852. mg_cry(conn,
  7853. "Error: CGI program \"%s\": Can not open stderr: %s",
  7854. prog,
  7855. status);
  7856. mg_send_http_error(conn,
  7857. 500,
  7858. "Error: CGI can not open fdout\nfopen: %s",
  7859. status);
  7860. goto done;
  7861. }
  7862. setbuf(in, NULL);
  7863. setbuf(out, NULL);
  7864. setbuf(err, NULL);
  7865. fout.access.fp = out;
  7866. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7867. /* This is a POST/PUT request, or another request with body data. */
  7868. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7869. /* Error sending the body data */
  7870. mg_cry(conn,
  7871. "Error: CGI program \"%s\": Forward body data failed",
  7872. prog);
  7873. goto done;
  7874. }
  7875. }
  7876. /* Close so child gets an EOF. */
  7877. fclose(in);
  7878. in = NULL;
  7879. fdin[1] = -1;
  7880. /* Now read CGI reply into a buffer. We need to set correct
  7881. * status code, thus we need to see all HTTP headers first.
  7882. * Do not send anything back to client, until we buffer in all
  7883. * HTTP headers. */
  7884. data_len = 0;
  7885. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  7886. if (buf == NULL) {
  7887. mg_send_http_error(conn,
  7888. 500,
  7889. "Error: Not enough memory for CGI buffer (%u bytes)",
  7890. (unsigned int)buflen);
  7891. mg_cry(conn,
  7892. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7893. "bytes)",
  7894. prog,
  7895. (unsigned int)buflen);
  7896. goto done;
  7897. }
  7898. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7899. if (headers_len <= 0) {
  7900. /* Could not parse the CGI response. Check if some error message on
  7901. * stderr. */
  7902. i = pull_all(err, conn, buf, (int)buflen);
  7903. if (i > 0) {
  7904. mg_cry(conn,
  7905. "Error: CGI program \"%s\" sent error "
  7906. "message: [%.*s]",
  7907. prog,
  7908. i,
  7909. buf);
  7910. mg_send_http_error(conn,
  7911. 500,
  7912. "Error: CGI program \"%s\" sent error "
  7913. "message: [%.*s]",
  7914. prog,
  7915. i,
  7916. buf);
  7917. } else {
  7918. mg_cry(conn,
  7919. "Error: CGI program sent malformed or too big "
  7920. "(>%u bytes) HTTP headers: [%.*s]",
  7921. (unsigned)buflen,
  7922. data_len,
  7923. buf);
  7924. mg_send_http_error(conn,
  7925. 500,
  7926. "Error: CGI program sent malformed or too big "
  7927. "(>%u bytes) HTTP headers: [%.*s]",
  7928. (unsigned)buflen,
  7929. data_len,
  7930. buf);
  7931. }
  7932. goto done;
  7933. }
  7934. pbuf = buf;
  7935. buf[headers_len - 1] = '\0';
  7936. parse_http_headers(&pbuf, &ri);
  7937. /* Make up and send the status line */
  7938. status_text = "OK";
  7939. if ((status = get_header(&ri, "Status")) != NULL) {
  7940. conn->status_code = atoi(status);
  7941. status_text = status;
  7942. while (isdigit(*(const unsigned char *)status_text)
  7943. || *status_text == ' ') {
  7944. status_text++;
  7945. }
  7946. } else if (get_header(&ri, "Location") != NULL) {
  7947. conn->status_code = 302;
  7948. } else {
  7949. conn->status_code = 200;
  7950. }
  7951. connection_state = get_header(&ri, "Connection");
  7952. if (!header_has_option(connection_state, "keep-alive")) {
  7953. conn->must_close = 1;
  7954. }
  7955. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7956. /* Send headers */
  7957. for (i = 0; i < ri.num_headers; i++) {
  7958. mg_printf(conn,
  7959. "%s: %s\r\n",
  7960. ri.http_headers[i].name,
  7961. ri.http_headers[i].value);
  7962. }
  7963. mg_write(conn, "\r\n", 2);
  7964. /* Send chunk of data that may have been read after the headers */
  7965. conn->num_bytes_sent +=
  7966. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7967. /* Read the rest of CGI output and send to the client */
  7968. send_file_data(conn, &fout, 0, INT64_MAX);
  7969. done:
  7970. mg_free(blk.var);
  7971. mg_free(blk.buf);
  7972. if (pid != (pid_t)-1) {
  7973. kill(pid, SIGKILL);
  7974. #if !defined(_WIN32)
  7975. {
  7976. int st;
  7977. while (waitpid(pid, &st, 0) != -1)
  7978. ; /* clean zombies */
  7979. }
  7980. #endif
  7981. }
  7982. if (fdin[0] != -1) {
  7983. close(fdin[0]);
  7984. }
  7985. if (fdout[1] != -1) {
  7986. close(fdout[1]);
  7987. }
  7988. if (in != NULL) {
  7989. fclose(in);
  7990. } else if (fdin[1] != -1) {
  7991. close(fdin[1]);
  7992. }
  7993. if (out != NULL) {
  7994. fclose(out);
  7995. } else if (fdout[0] != -1) {
  7996. close(fdout[0]);
  7997. }
  7998. if (err != NULL) {
  7999. fclose(err);
  8000. } else if (fderr[0] != -1) {
  8001. close(fderr[0]);
  8002. }
  8003. if (buf != NULL) {
  8004. mg_free(buf);
  8005. }
  8006. }
  8007. #endif /* !NO_CGI */
  8008. #if !defined(NO_FILES)
  8009. static void
  8010. mkcol(struct mg_connection *conn, const char *path)
  8011. {
  8012. int rc, body_len;
  8013. struct de de;
  8014. char date[64];
  8015. time_t curtime = time(NULL);
  8016. if (conn == NULL) {
  8017. return;
  8018. }
  8019. /* TODO (mid): Check the mg_send_http_error situations in this function */
  8020. memset(&de.file, 0, sizeof(de.file));
  8021. if (!mg_stat(conn, path, &de.file)) {
  8022. mg_cry(conn,
  8023. "%s: mg_stat(%s) failed: %s",
  8024. __func__,
  8025. path,
  8026. strerror(ERRNO));
  8027. }
  8028. if (de.file.last_modified) {
  8029. /* TODO (mid): This check does not seem to make any sense ! */
  8030. /* TODO (mid): Add a webdav unit test first, before changing
  8031. * anything here. */
  8032. mg_send_http_error(
  8033. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8034. return;
  8035. }
  8036. body_len = conn->data_len - conn->request_len;
  8037. if (body_len > 0) {
  8038. mg_send_http_error(
  8039. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8040. return;
  8041. }
  8042. rc = mg_mkdir(conn, path, 0755);
  8043. if (rc == 0) {
  8044. conn->status_code = 201;
  8045. gmt_time_string(date, sizeof(date), &curtime);
  8046. mg_printf(conn,
  8047. "HTTP/1.1 %d Created\r\n"
  8048. "Date: %s\r\n",
  8049. conn->status_code,
  8050. date);
  8051. send_static_cache_header(conn);
  8052. send_additional_header(conn);
  8053. mg_printf(conn,
  8054. "Content-Length: 0\r\n"
  8055. "Connection: %s\r\n\r\n",
  8056. suggest_connection_header(conn));
  8057. } else if (rc == -1) {
  8058. if (errno == EEXIST) {
  8059. mg_send_http_error(
  8060. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8061. } else if (errno == EACCES) {
  8062. mg_send_http_error(
  8063. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8064. } else if (errno == ENOENT) {
  8065. mg_send_http_error(
  8066. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8067. } else {
  8068. mg_send_http_error(
  8069. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8070. }
  8071. }
  8072. }
  8073. static void
  8074. put_file(struct mg_connection *conn, const char *path)
  8075. {
  8076. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8077. const char *range;
  8078. int64_t r1, r2;
  8079. int rc;
  8080. char date[64];
  8081. time_t curtime = time(NULL);
  8082. if (conn == NULL) {
  8083. return;
  8084. }
  8085. if (mg_stat(conn, path, &file.stat)) {
  8086. /* File already exists */
  8087. conn->status_code = 200;
  8088. if (file.stat.is_directory) {
  8089. /* This is an already existing directory,
  8090. * so there is nothing to do for the server. */
  8091. rc = 0;
  8092. } else {
  8093. /* File exists and is not a directory. */
  8094. /* Can it be replaced? */
  8095. if (file.access.membuf != NULL) {
  8096. /* This is an "in-memory" file, that can not be replaced */
  8097. mg_send_http_error(
  8098. conn,
  8099. 405,
  8100. "Error: Put not possible\nReplacing %s is not supported",
  8101. path);
  8102. return;
  8103. }
  8104. /* Check if the server may write this file */
  8105. if (access(path, W_OK) == 0) {
  8106. /* Access granted */
  8107. conn->status_code = 200;
  8108. rc = 1;
  8109. } else {
  8110. mg_send_http_error(
  8111. conn,
  8112. 403,
  8113. "Error: Put not possible\nReplacing %s is not allowed",
  8114. path);
  8115. return;
  8116. }
  8117. }
  8118. } else {
  8119. /* File should be created */
  8120. conn->status_code = 201;
  8121. rc = put_dir(conn, path);
  8122. }
  8123. if (rc == 0) {
  8124. /* put_dir returns 0 if path is a directory */
  8125. gmt_time_string(date, sizeof(date), &curtime);
  8126. mg_printf(conn,
  8127. "HTTP/1.1 %d %s\r\n",
  8128. conn->status_code,
  8129. mg_get_response_code_text(NULL, conn->status_code));
  8130. send_no_cache_header(conn);
  8131. send_additional_header(conn);
  8132. mg_printf(conn,
  8133. "Date: %s\r\n"
  8134. "Content-Length: 0\r\n"
  8135. "Connection: %s\r\n\r\n",
  8136. date,
  8137. suggest_connection_header(conn));
  8138. /* Request to create a directory has been fulfilled successfully.
  8139. * No need to put a file. */
  8140. return;
  8141. }
  8142. if (rc == -1) {
  8143. /* put_dir returns -1 if the path is too long */
  8144. mg_send_http_error(conn,
  8145. 414,
  8146. "Error: Path too long\nput_dir(%s): %s",
  8147. path,
  8148. strerror(ERRNO));
  8149. return;
  8150. }
  8151. if (rc == -2) {
  8152. /* put_dir returns -2 if the directory can not be created */
  8153. mg_send_http_error(conn,
  8154. 500,
  8155. "Error: Can not create directory\nput_dir(%s): %s",
  8156. path,
  8157. strerror(ERRNO));
  8158. return;
  8159. }
  8160. /* A file should be created or overwritten. */
  8161. /* Currently CivetWeb does not nead read+write access. */
  8162. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8163. || file.access.fp == NULL) {
  8164. (void)mg_fclose(&file.access);
  8165. mg_send_http_error(conn,
  8166. 500,
  8167. "Error: Can not create file\nfopen(%s): %s",
  8168. path,
  8169. strerror(ERRNO));
  8170. return;
  8171. }
  8172. fclose_on_exec(&file.access, conn);
  8173. range = mg_get_header(conn, "Content-Range");
  8174. r1 = r2 = 0;
  8175. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  8176. conn->status_code = 206; /* Partial content */
  8177. fseeko(file.access.fp, r1, SEEK_SET);
  8178. }
  8179. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8180. /* forward_body_data failed.
  8181. * The error code has already been sent to the client,
  8182. * and conn->status_code is already set. */
  8183. (void)mg_fclose(&file.access);
  8184. return;
  8185. }
  8186. if (mg_fclose(&file.access) != 0) {
  8187. /* fclose failed. This might have different reasons, but a likely
  8188. * one is "no space on disk", http 507. */
  8189. conn->status_code = 507;
  8190. }
  8191. gmt_time_string(date, sizeof(date), &curtime);
  8192. mg_printf(conn,
  8193. "HTTP/1.1 %d %s\r\n",
  8194. conn->status_code,
  8195. mg_get_response_code_text(NULL, conn->status_code));
  8196. send_no_cache_header(conn);
  8197. send_additional_header(conn);
  8198. mg_printf(conn,
  8199. "Date: %s\r\n"
  8200. "Content-Length: 0\r\n"
  8201. "Connection: %s\r\n\r\n",
  8202. date,
  8203. suggest_connection_header(conn));
  8204. }
  8205. static void
  8206. delete_file(struct mg_connection *conn, const char *path)
  8207. {
  8208. struct de de;
  8209. memset(&de.file, 0, sizeof(de.file));
  8210. if (!mg_stat(conn, path, &de.file)) {
  8211. /* mg_stat returns 0 if the file does not exist */
  8212. mg_send_http_error(conn,
  8213. 404,
  8214. "Error: Cannot delete file\nFile %s not found",
  8215. path);
  8216. return;
  8217. }
  8218. #if 0 /* Ignore if a file in memory is inside a folder */
  8219. if (de.access.membuf != NULL) {
  8220. /* the file is cached in memory */
  8221. mg_send_http_error(
  8222. conn,
  8223. 405,
  8224. "Error: Delete not possible\nDeleting %s is not supported",
  8225. path);
  8226. return;
  8227. }
  8228. #endif
  8229. if (de.file.is_directory) {
  8230. if (remove_directory(conn, path)) {
  8231. /* Delete is successful: Return 204 without content. */
  8232. mg_send_http_error(conn, 204, "%s", "");
  8233. } else {
  8234. /* Delete is not successful: Return 500 (Server error). */
  8235. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8236. }
  8237. return;
  8238. }
  8239. /* This is an existing file (not a directory).
  8240. * Check if write permission is granted. */
  8241. if (access(path, W_OK) != 0) {
  8242. /* File is read only */
  8243. mg_send_http_error(
  8244. conn,
  8245. 403,
  8246. "Error: Delete not possible\nDeleting %s is not allowed",
  8247. path);
  8248. return;
  8249. }
  8250. /* Try to delete it. */
  8251. if (mg_remove(conn, path) == 0) {
  8252. /* Delete was successful: Return 204 without content. */
  8253. mg_send_http_error(conn, 204, "%s", "");
  8254. } else {
  8255. /* Delete not successful (file locked). */
  8256. mg_send_http_error(conn,
  8257. 423,
  8258. "Error: Cannot delete file\nremove(%s): %s",
  8259. path,
  8260. strerror(ERRNO));
  8261. }
  8262. }
  8263. #endif /* !NO_FILES */
  8264. static void
  8265. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8266. static void
  8267. do_ssi_include(struct mg_connection *conn,
  8268. const char *ssi,
  8269. char *tag,
  8270. int include_level)
  8271. {
  8272. char file_name[MG_BUF_LEN], path[512], *p;
  8273. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8274. size_t len;
  8275. int truncated = 0;
  8276. if (conn == NULL) {
  8277. return;
  8278. }
  8279. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8280. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8281. * always < MG_BUF_LEN. */
  8282. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8283. /* File name is relative to the webserver root */
  8284. file_name[511] = 0;
  8285. (void)mg_snprintf(conn,
  8286. &truncated,
  8287. path,
  8288. sizeof(path),
  8289. "%s/%s",
  8290. conn->ctx->config[DOCUMENT_ROOT],
  8291. file_name);
  8292. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8293. /* File name is relative to the webserver working directory
  8294. * or it is absolute system path */
  8295. file_name[511] = 0;
  8296. (void)
  8297. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8298. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  8299. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  8300. /* File name is relative to the currect document */
  8301. file_name[511] = 0;
  8302. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8303. if (!truncated) {
  8304. if ((p = strrchr(path, '/')) != NULL) {
  8305. p[1] = '\0';
  8306. }
  8307. len = strlen(path);
  8308. (void)mg_snprintf(conn,
  8309. &truncated,
  8310. path + len,
  8311. sizeof(path) - len,
  8312. "%s",
  8313. file_name);
  8314. }
  8315. } else {
  8316. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8317. return;
  8318. }
  8319. if (truncated) {
  8320. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8321. return;
  8322. }
  8323. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8324. mg_cry(conn,
  8325. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8326. tag,
  8327. path,
  8328. strerror(ERRNO));
  8329. } else {
  8330. fclose_on_exec(&file.access, conn);
  8331. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8332. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8333. path) > 0) {
  8334. send_ssi_file(conn, path, &file, include_level + 1);
  8335. } else {
  8336. send_file_data(conn, &file, 0, INT64_MAX);
  8337. }
  8338. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8339. }
  8340. }
  8341. #if !defined(NO_POPEN)
  8342. static void
  8343. do_ssi_exec(struct mg_connection *conn, char *tag)
  8344. {
  8345. char cmd[1024] = "";
  8346. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8347. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8348. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8349. } else {
  8350. cmd[1023] = 0;
  8351. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8352. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8353. } else {
  8354. send_file_data(conn, &file, 0, INT64_MAX);
  8355. pclose(file.access.fp);
  8356. }
  8357. }
  8358. }
  8359. #endif /* !NO_POPEN */
  8360. static int
  8361. mg_fgetc(struct mg_file *filep, int offset)
  8362. {
  8363. if (filep == NULL) {
  8364. return EOF;
  8365. }
  8366. if (filep->access.membuf != NULL && offset >= 0
  8367. && ((unsigned int)(offset)) < filep->stat.size) {
  8368. return ((const unsigned char *)filep->access.membuf)[offset];
  8369. } else if (filep->access.fp != NULL) {
  8370. return fgetc(filep->access.fp);
  8371. } else {
  8372. return EOF;
  8373. }
  8374. }
  8375. static void
  8376. send_ssi_file(struct mg_connection *conn,
  8377. const char *path,
  8378. struct mg_file *filep,
  8379. int include_level)
  8380. {
  8381. char buf[MG_BUF_LEN];
  8382. int ch, offset, len, in_ssi_tag;
  8383. if (include_level > 10) {
  8384. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8385. return;
  8386. }
  8387. in_ssi_tag = len = offset = 0;
  8388. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  8389. if (in_ssi_tag && ch == '>') {
  8390. in_ssi_tag = 0;
  8391. buf[len++] = (char)ch;
  8392. buf[len] = '\0';
  8393. /* assert(len <= (int) sizeof(buf)); */
  8394. if (len > (int)sizeof(buf)) {
  8395. break;
  8396. }
  8397. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  8398. /* Not an SSI tag, pass it */
  8399. (void)mg_write(conn, buf, (size_t)len);
  8400. } else {
  8401. if (!memcmp(buf + 5, "include", 7)) {
  8402. do_ssi_include(conn, path, buf + 12, include_level);
  8403. #if !defined(NO_POPEN)
  8404. } else if (!memcmp(buf + 5, "exec", 4)) {
  8405. do_ssi_exec(conn, buf + 9);
  8406. #endif /* !NO_POPEN */
  8407. } else {
  8408. mg_cry(conn,
  8409. "%s: unknown SSI "
  8410. "command: \"%s\"",
  8411. path,
  8412. buf);
  8413. }
  8414. }
  8415. len = 0;
  8416. } else if (in_ssi_tag) {
  8417. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8418. /* Not an SSI tag */
  8419. in_ssi_tag = 0;
  8420. } else if (len == (int)sizeof(buf) - 2) {
  8421. mg_cry(conn, "%s: SSI tag is too large", path);
  8422. len = 0;
  8423. }
  8424. buf[len++] = (char)(ch & 0xff);
  8425. } else if (ch == '<') {
  8426. in_ssi_tag = 1;
  8427. if (len > 0) {
  8428. mg_write(conn, buf, (size_t)len);
  8429. }
  8430. len = 0;
  8431. buf[len++] = (char)(ch & 0xff);
  8432. } else {
  8433. buf[len++] = (char)(ch & 0xff);
  8434. if (len == (int)sizeof(buf)) {
  8435. mg_write(conn, buf, (size_t)len);
  8436. len = 0;
  8437. }
  8438. }
  8439. }
  8440. /* Send the rest of buffered data */
  8441. if (len > 0) {
  8442. mg_write(conn, buf, (size_t)len);
  8443. }
  8444. }
  8445. static void
  8446. handle_ssi_file_request(struct mg_connection *conn,
  8447. const char *path,
  8448. struct mg_file *filep)
  8449. {
  8450. char date[64];
  8451. time_t curtime = time(NULL);
  8452. const char *cors1, *cors2, *cors3;
  8453. if (conn == NULL || path == NULL || filep == NULL) {
  8454. return;
  8455. }
  8456. if (mg_get_header(conn, "Origin")) {
  8457. /* Cross-origin resource sharing (CORS). */
  8458. cors1 = "Access-Control-Allow-Origin: ";
  8459. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8460. cors3 = "\r\n";
  8461. } else {
  8462. cors1 = cors2 = cors3 = "";
  8463. }
  8464. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8465. /* File exists (precondition for calling this function),
  8466. * but can not be opened by the server. */
  8467. mg_send_http_error(conn,
  8468. 500,
  8469. "Error: Cannot read file\nfopen(%s): %s",
  8470. path,
  8471. strerror(ERRNO));
  8472. } else {
  8473. conn->must_close = 1;
  8474. gmt_time_string(date, sizeof(date), &curtime);
  8475. fclose_on_exec(&filep->access, conn);
  8476. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8477. send_no_cache_header(conn);
  8478. send_additional_header(conn);
  8479. mg_printf(conn,
  8480. "%s%s%s"
  8481. "Date: %s\r\n"
  8482. "Content-Type: text/html\r\n"
  8483. "Connection: %s\r\n\r\n",
  8484. cors1,
  8485. cors2,
  8486. cors3,
  8487. date,
  8488. suggest_connection_header(conn));
  8489. send_ssi_file(conn, path, filep, 0);
  8490. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8491. }
  8492. }
  8493. #if !defined(NO_FILES)
  8494. static void
  8495. send_options(struct mg_connection *conn)
  8496. {
  8497. char date[64];
  8498. time_t curtime = time(NULL);
  8499. if (!conn) {
  8500. return;
  8501. }
  8502. conn->status_code = 200;
  8503. conn->must_close = 1;
  8504. gmt_time_string(date, sizeof(date), &curtime);
  8505. /* We do not set a "Cache-Control" header here, but leave the default.
  8506. * Since browsers do not send an OPTIONS request, we can not test the
  8507. * effect anyway. */
  8508. mg_printf(conn,
  8509. "HTTP/1.1 200 OK\r\n"
  8510. "Date: %s\r\n"
  8511. "Connection: %s\r\n"
  8512. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8513. "PROPFIND, MKCOL\r\n"
  8514. "DAV: 1\r\n",
  8515. date,
  8516. suggest_connection_header(conn));
  8517. send_additional_header(conn);
  8518. mg_printf(conn, "\r\n");
  8519. }
  8520. /* Writes PROPFIND properties for a collection element */
  8521. static void
  8522. print_props(struct mg_connection *conn,
  8523. const char *uri,
  8524. struct mg_file_stat *filep)
  8525. {
  8526. char mtime[64];
  8527. if (conn == NULL || uri == NULL || filep == NULL) {
  8528. return;
  8529. }
  8530. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8531. conn->num_bytes_sent +=
  8532. mg_printf(conn,
  8533. "<d:response>"
  8534. "<d:href>%s</d:href>"
  8535. "<d:propstat>"
  8536. "<d:prop>"
  8537. "<d:resourcetype>%s</d:resourcetype>"
  8538. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8539. "<d:getlastmodified>%s</d:getlastmodified>"
  8540. "</d:prop>"
  8541. "<d:status>HTTP/1.1 200 OK</d:status>"
  8542. "</d:propstat>"
  8543. "</d:response>\n",
  8544. uri,
  8545. filep->is_directory ? "<d:collection/>" : "",
  8546. filep->size,
  8547. mtime);
  8548. }
  8549. static void
  8550. print_dav_dir_entry(struct de *de, void *data)
  8551. {
  8552. char href[PATH_MAX];
  8553. char href_encoded[PATH_MAX * 3 /* worst case */];
  8554. int truncated;
  8555. struct mg_connection *conn = (struct mg_connection *)data;
  8556. if (!de || !conn) {
  8557. return;
  8558. }
  8559. mg_snprintf(conn,
  8560. &truncated,
  8561. href,
  8562. sizeof(href),
  8563. "%s%s",
  8564. conn->request_info.local_uri,
  8565. de->file_name);
  8566. if (!truncated) {
  8567. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8568. print_props(conn, href_encoded, &de->file);
  8569. }
  8570. }
  8571. static void
  8572. handle_propfind(struct mg_connection *conn,
  8573. const char *path,
  8574. struct mg_file_stat *filep)
  8575. {
  8576. const char *depth = mg_get_header(conn, "Depth");
  8577. char date[64];
  8578. time_t curtime = time(NULL);
  8579. gmt_time_string(date, sizeof(date), &curtime);
  8580. if (!conn || !path || !filep || !conn->ctx) {
  8581. return;
  8582. }
  8583. conn->must_close = 1;
  8584. conn->status_code = 207;
  8585. mg_printf(conn,
  8586. "HTTP/1.1 207 Multi-Status\r\n"
  8587. "Date: %s\r\n",
  8588. date);
  8589. send_static_cache_header(conn);
  8590. send_additional_header(conn);
  8591. mg_printf(conn,
  8592. "Connection: %s\r\n"
  8593. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8594. suggest_connection_header(conn));
  8595. conn->num_bytes_sent +=
  8596. mg_printf(conn,
  8597. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8598. "<d:multistatus xmlns:d='DAV:'>\n");
  8599. /* Print properties for the requested resource itself */
  8600. print_props(conn, conn->request_info.local_uri, filep);
  8601. /* If it is a directory, print directory entries too if Depth is not 0 */
  8602. if (filep && filep->is_directory
  8603. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8604. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8605. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8606. }
  8607. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8608. }
  8609. #endif
  8610. void
  8611. mg_lock_connection(struct mg_connection *conn)
  8612. {
  8613. if (conn) {
  8614. (void)pthread_mutex_lock(&conn->mutex);
  8615. }
  8616. }
  8617. void
  8618. mg_unlock_connection(struct mg_connection *conn)
  8619. {
  8620. if (conn) {
  8621. (void)pthread_mutex_unlock(&conn->mutex);
  8622. }
  8623. }
  8624. void
  8625. mg_lock_context(struct mg_context *ctx)
  8626. {
  8627. if (ctx) {
  8628. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8629. }
  8630. }
  8631. void
  8632. mg_unlock_context(struct mg_context *ctx)
  8633. {
  8634. if (ctx) {
  8635. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8636. }
  8637. }
  8638. #if defined(USE_TIMERS)
  8639. #define TIMER_API static
  8640. #include "timer.inl"
  8641. #endif /* USE_TIMERS */
  8642. #ifdef USE_LUA
  8643. #include "mod_lua.inl"
  8644. #endif /* USE_LUA */
  8645. #ifdef USE_DUKTAPE
  8646. #include "mod_duktape.inl"
  8647. #endif /* USE_DUKTAPE */
  8648. #if defined(USE_WEBSOCKET)
  8649. #if !defined(NO_SSL_DL)
  8650. #define SHA_API static
  8651. #include "sha1.inl"
  8652. #endif
  8653. static int
  8654. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8655. {
  8656. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8657. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8658. SHA_CTX sha_ctx;
  8659. int truncated;
  8660. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8661. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8662. if (truncated) {
  8663. conn->must_close = 1;
  8664. return 0;
  8665. }
  8666. SHA1_Init(&sha_ctx);
  8667. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8668. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8669. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8670. mg_printf(conn,
  8671. "HTTP/1.1 101 Switching Protocols\r\n"
  8672. "Upgrade: websocket\r\n"
  8673. "Connection: Upgrade\r\n"
  8674. "Sec-WebSocket-Accept: %s\r\n",
  8675. b64_sha);
  8676. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8677. mg_printf(conn,
  8678. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8679. conn->request_info.acceptedWebSocketSubprotocol);
  8680. } else {
  8681. mg_printf(conn, "%s", "\r\n");
  8682. }
  8683. return 1;
  8684. }
  8685. static void
  8686. read_websocket(struct mg_connection *conn,
  8687. mg_websocket_data_handler ws_data_handler,
  8688. void *callback_data)
  8689. {
  8690. /* Pointer to the beginning of the portion of the incoming websocket
  8691. * message queue.
  8692. * The original websocket upgrade request is never removed, so the queue
  8693. * begins after it. */
  8694. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8695. int n, error, exit_by_callback;
  8696. /* body_len is the length of the entire queue in bytes
  8697. * len is the length of the current message
  8698. * data_len is the length of the current message's data payload
  8699. * header_len is the length of the current message's header */
  8700. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8701. /* "The masking key is a 32-bit value chosen at random by the client."
  8702. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8703. */
  8704. unsigned char mask[4];
  8705. /* data points to the place where the message is stored when passed to
  8706. * the
  8707. * websocket_data callback. This is either mem on the stack, or a
  8708. * dynamically allocated buffer if it is too large. */
  8709. unsigned char mem[4096];
  8710. unsigned char *data = mem;
  8711. unsigned char mop; /* mask flag and opcode */
  8712. double timeout = -1.0;
  8713. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8714. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8715. }
  8716. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8717. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8718. }
  8719. mg_set_thread_name("wsock");
  8720. /* Loop continuously, reading messages from the socket, invoking the
  8721. * callback, and waiting repeatedly until an error occurs. */
  8722. while (!conn->ctx->stop_flag) {
  8723. header_len = 0;
  8724. assert(conn->data_len >= conn->request_len);
  8725. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8726. len = buf[1] & 127;
  8727. mask_len = (buf[1] & 128) ? 4 : 0;
  8728. if ((len < 126) && (body_len >= mask_len)) {
  8729. /* inline 7-bit length field */
  8730. data_len = len;
  8731. header_len = 2 + mask_len;
  8732. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8733. /* 16-bit length field */
  8734. header_len = 4 + mask_len;
  8735. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8736. } else if (body_len >= (10 + mask_len)) {
  8737. /* 64-bit length field */
  8738. uint32_t l1, l2;
  8739. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  8740. memcpy(&l2, &buf[6], 4);
  8741. header_len = 10 + mask_len;
  8742. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  8743. }
  8744. }
  8745. if (header_len > 0 && body_len >= header_len) {
  8746. /* Allocate space to hold websocket payload */
  8747. data = mem;
  8748. if (data_len > sizeof(mem)) {
  8749. data = (unsigned char *)mg_malloc_ctx(data_len, conn->ctx);
  8750. if (data == NULL) {
  8751. /* Allocation failed, exit the loop and then close the
  8752. * connection */
  8753. mg_cry(conn, "websocket out of memory; closing connection");
  8754. break;
  8755. }
  8756. }
  8757. /* Copy the mask before we shift the queue and destroy it */
  8758. if (mask_len > 0) {
  8759. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8760. } else {
  8761. memset(mask, 0, sizeof(mask));
  8762. }
  8763. /* Read frame payload from the first message in the queue into
  8764. * data and advance the queue by moving the memory in place. */
  8765. assert(body_len >= header_len);
  8766. if (data_len + header_len > body_len) {
  8767. mop = buf[0]; /* current mask and opcode */
  8768. /* Overflow case */
  8769. len = body_len - header_len;
  8770. memcpy(data, buf + header_len, len);
  8771. error = 0;
  8772. while (len < data_len) {
  8773. n = pull_inner(NULL,
  8774. conn,
  8775. (char *)(data + len),
  8776. (int)(data_len - len),
  8777. timeout);
  8778. if (n <= -2) {
  8779. error = 1;
  8780. break;
  8781. } else if (n > 0) {
  8782. len += (size_t)n;
  8783. } else {
  8784. /* Timeout: should retry */
  8785. /* TODO: retry condition */
  8786. }
  8787. }
  8788. if (error) {
  8789. mg_cry(conn, "Websocket pull failed; closing connection");
  8790. break;
  8791. }
  8792. conn->data_len = conn->request_len;
  8793. } else {
  8794. mop = buf[0]; /* current mask and opcode, overwritten by
  8795. * memmove() */
  8796. /* Length of the message being read at the front of the
  8797. * queue */
  8798. len = data_len + header_len;
  8799. /* Copy the data payload into the data pointer for the
  8800. * callback */
  8801. memcpy(data, buf + header_len, data_len);
  8802. /* Move the queue forward len bytes */
  8803. memmove(buf, buf + len, body_len - len);
  8804. /* Mark the queue as advanced */
  8805. conn->data_len -= (int)len;
  8806. }
  8807. /* Apply mask if necessary */
  8808. if (mask_len > 0) {
  8809. for (i = 0; i < data_len; ++i) {
  8810. data[i] ^= mask[i & 3];
  8811. }
  8812. }
  8813. /* Exit the loop if callback signals to exit (server side),
  8814. * or "connection close" opcode received (client side). */
  8815. exit_by_callback = 0;
  8816. if ((ws_data_handler != NULL)
  8817. && !ws_data_handler(
  8818. conn, mop, (char *)data, data_len, callback_data)) {
  8819. exit_by_callback = 1;
  8820. }
  8821. if (data != mem) {
  8822. mg_free(data);
  8823. }
  8824. if (exit_by_callback
  8825. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8826. /* Opcode == 8, connection close */
  8827. break;
  8828. }
  8829. /* Not breaking the loop, process next websocket frame. */
  8830. } else {
  8831. /* Read from the socket into the next available location in the
  8832. * message queue. */
  8833. n = pull_inner(NULL,
  8834. conn,
  8835. conn->buf + conn->data_len,
  8836. conn->buf_size - conn->data_len,
  8837. timeout);
  8838. if (n <= -2) {
  8839. /* Error, no bytes read */
  8840. break;
  8841. }
  8842. if (n > 0) {
  8843. conn->data_len += n;
  8844. } else {
  8845. /* Timeout: should retry */
  8846. /* TODO: get timeout def */
  8847. }
  8848. }
  8849. }
  8850. mg_set_thread_name("worker");
  8851. }
  8852. static int
  8853. mg_websocket_write_exec(struct mg_connection *conn,
  8854. int opcode,
  8855. const char *data,
  8856. size_t dataLen,
  8857. uint32_t masking_key)
  8858. {
  8859. unsigned char header[14];
  8860. size_t headerLen = 1;
  8861. int retval = -1;
  8862. #if defined(__GNUC__) || defined(__MINGW32__)
  8863. /* Disable spurious conversion warning for GCC */
  8864. #pragma GCC diagnostic push
  8865. #pragma GCC diagnostic ignored "-Wconversion"
  8866. #endif
  8867. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8868. #if defined(__GNUC__) || defined(__MINGW32__)
  8869. #pragma GCC diagnostic pop
  8870. #endif
  8871. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8872. if (dataLen < 126) {
  8873. /* inline 7-bit length field */
  8874. header[1] = (unsigned char)dataLen;
  8875. headerLen = 2;
  8876. } else if (dataLen <= 0xFFFF) {
  8877. /* 16-bit length field */
  8878. uint16_t len = htons((uint16_t)dataLen);
  8879. header[1] = 126;
  8880. memcpy(header + 2, &len, 2);
  8881. headerLen = 4;
  8882. } else {
  8883. /* 64-bit length field */
  8884. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8885. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8886. header[1] = 127;
  8887. memcpy(header + 2, &len1, 4);
  8888. memcpy(header + 6, &len2, 4);
  8889. headerLen = 10;
  8890. }
  8891. if (masking_key) {
  8892. /* add mask */
  8893. header[1] |= 0x80;
  8894. memcpy(header + headerLen, &masking_key, 4);
  8895. headerLen += 4;
  8896. }
  8897. /* Note that POSIX/Winsock's send() is threadsafe
  8898. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8899. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8900. * push(), although that is only a problem if the packet is large or
  8901. * outgoing buffer is full). */
  8902. /* TODO: Check if this lock should be moved to user land.
  8903. * Currently the server sets this lock for websockets, but
  8904. * not for any other connection. It must be set for every
  8905. * conn read/written by more than one thread, no matter if
  8906. * it is a websocket or regular connection. */
  8907. (void)mg_lock_connection(conn);
  8908. retval = mg_write(conn, header, headerLen);
  8909. if (dataLen > 0) {
  8910. retval = mg_write(conn, data, dataLen);
  8911. }
  8912. /* TODO: Remove this unlock as well, when lock is moved. */
  8913. mg_unlock_connection(conn);
  8914. return retval;
  8915. }
  8916. int
  8917. mg_websocket_write(struct mg_connection *conn,
  8918. int opcode,
  8919. const char *data,
  8920. size_t dataLen)
  8921. {
  8922. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8923. }
  8924. static void
  8925. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8926. {
  8927. size_t i = 0;
  8928. i = 0;
  8929. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8930. /* Convert in 32 bit words, if data is 4 byte aligned */
  8931. while (i < (in_len - 3)) {
  8932. *(uint32_t *)(void *)(out + i) =
  8933. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8934. i += 4;
  8935. }
  8936. }
  8937. if (i != in_len) {
  8938. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8939. while (i < in_len) {
  8940. *(uint8_t *)(void *)(out + i) =
  8941. *(uint8_t *)(void *)(in + i)
  8942. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8943. i++;
  8944. }
  8945. }
  8946. }
  8947. int
  8948. mg_websocket_client_write(struct mg_connection *conn,
  8949. int opcode,
  8950. const char *data,
  8951. size_t dataLen)
  8952. {
  8953. int retval = -1;
  8954. char *masked_data =
  8955. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  8956. uint32_t masking_key = (uint32_t)get_random();
  8957. if (masked_data == NULL) {
  8958. /* Return -1 in an error case */
  8959. mg_cry(conn,
  8960. "Cannot allocate buffer for masked websocket response: "
  8961. "Out of memory");
  8962. return -1;
  8963. }
  8964. mask_data(data, dataLen, masking_key, masked_data);
  8965. retval = mg_websocket_write_exec(
  8966. conn, opcode, masked_data, dataLen, masking_key);
  8967. mg_free(masked_data);
  8968. return retval;
  8969. }
  8970. static void
  8971. handle_websocket_request(struct mg_connection *conn,
  8972. const char *path,
  8973. int is_callback_resource,
  8974. struct mg_websocket_subprotocols *subprotocols,
  8975. mg_websocket_connect_handler ws_connect_handler,
  8976. mg_websocket_ready_handler ws_ready_handler,
  8977. mg_websocket_data_handler ws_data_handler,
  8978. mg_websocket_close_handler ws_close_handler,
  8979. void *cbData)
  8980. {
  8981. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8982. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8983. int lua_websock = 0;
  8984. #if !defined(USE_LUA)
  8985. (void)path;
  8986. #endif
  8987. /* Step 1: Check websocket protocol version. */
  8988. /* Step 1.1: Check Sec-WebSocket-Key. */
  8989. if (!websock_key) {
  8990. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8991. * requires a Sec-WebSocket-Key header.
  8992. */
  8993. /* It could be the hixie draft version
  8994. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8995. */
  8996. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8997. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8998. char key3[8];
  8999. if ((key1 != NULL) && (key2 != NULL)) {
  9000. /* This version uses 8 byte body data in a GET request */
  9001. conn->content_len = 8;
  9002. if (8 == mg_read(conn, key3, 8)) {
  9003. /* This is the hixie version */
  9004. mg_send_http_error(conn,
  9005. 426,
  9006. "%s",
  9007. "Protocol upgrade to RFC 6455 required");
  9008. return;
  9009. }
  9010. }
  9011. /* This is an unknown version */
  9012. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  9013. return;
  9014. }
  9015. /* Step 1.2: Check websocket protocol version. */
  9016. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  9017. if (version == NULL || strcmp(version, "13") != 0) {
  9018. /* Reject wrong versions */
  9019. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  9020. return;
  9021. }
  9022. /* Step 1.3: Could check for "Host", but we do not really nead this
  9023. * value for anything, so just ignore it. */
  9024. /* Step 2: If a callback is responsible, call it. */
  9025. if (is_callback_resource) {
  9026. /* Step 2.1 check and select subprotocol */
  9027. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  9028. if (protocol && subprotocols) {
  9029. int idx;
  9030. unsigned long len;
  9031. const char *sep, *curSubProtocol,
  9032. *acceptedWebSocketSubprotocol = NULL;
  9033. /* look for matching subprotocol */
  9034. do {
  9035. sep = strchr(protocol, ',');
  9036. curSubProtocol = protocol;
  9037. len = sep ? (unsigned long)(sep - protocol)
  9038. : (unsigned long)strlen(protocol);
  9039. while (sep && isspace(*++sep)) {
  9040. ; /* ignore leading whitespaces */
  9041. }
  9042. protocol = sep;
  9043. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  9044. if ((strlen(subprotocols->subprotocols[idx]) == len)
  9045. && (strncmp(curSubProtocol,
  9046. subprotocols->subprotocols[idx],
  9047. len) == 0)) {
  9048. acceptedWebSocketSubprotocol =
  9049. subprotocols->subprotocols[idx];
  9050. break;
  9051. }
  9052. }
  9053. } while (sep && !acceptedWebSocketSubprotocol);
  9054. conn->request_info.acceptedWebSocketSubprotocol =
  9055. acceptedWebSocketSubprotocol;
  9056. } else if (protocol) {
  9057. /* keep legacy behavior */
  9058. /* The protocol is a comma seperated list of names. */
  9059. /* The server must only return one value from this list. */
  9060. /* First check if it is a list or just a single value. */
  9061. const char *sep = strrchr(protocol, ',');
  9062. if (sep == NULL) {
  9063. /* Just a single protocol -> accept it. */
  9064. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  9065. } else {
  9066. /* Multiple protocols -> accept the last one. */
  9067. /* This is just a quick fix if the client offers multiple
  9068. * protocols. The handler should have a list of accepted
  9069. * protocols on his own
  9070. * and use it to select one protocol among those the client has
  9071. * offered.
  9072. */
  9073. while (isspace(*++sep)) {
  9074. ; /* ignore leading whitespaces */
  9075. }
  9076. conn->request_info.acceptedWebSocketSubprotocol = sep;
  9077. }
  9078. }
  9079. if (ws_connect_handler != NULL
  9080. && ws_connect_handler(conn, cbData) != 0) {
  9081. /* C callback has returned non-zero, do not proceed with
  9082. * handshake.
  9083. */
  9084. /* Note that C callbacks are no longer called when Lua is
  9085. * responsible, so C can no longer filter callbacks for Lua. */
  9086. return;
  9087. }
  9088. }
  9089. #if defined(USE_LUA)
  9090. /* Step 3: No callback. Check if Lua is responsible. */
  9091. else {
  9092. /* Step 3.1: Check if Lua is responsible. */
  9093. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  9094. lua_websock =
  9095. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  9096. strlen(
  9097. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  9098. path);
  9099. }
  9100. if (lua_websock) {
  9101. /* Step 3.2: Lua is responsible: call it. */
  9102. conn->lua_websocket_state = lua_websocket_new(path, conn);
  9103. if (!conn->lua_websocket_state) {
  9104. /* Lua rejected the new client */
  9105. return;
  9106. }
  9107. }
  9108. }
  9109. #endif
  9110. /* Step 4: Check if there is a responsible websocket handler. */
  9111. if (!is_callback_resource && !lua_websock) {
  9112. /* There is no callback, and Lua is not responsible either. */
  9113. /* Reply with a 404 Not Found. We are still at a standard
  9114. * HTTP request here, before the websocket handshake, so
  9115. * we can still send standard HTTP error replies. */
  9116. mg_send_http_error(conn, 404, "%s", "Not found");
  9117. return;
  9118. }
  9119. /* Step 5: The websocket connection has been accepted */
  9120. if (!send_websocket_handshake(conn, websock_key)) {
  9121. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  9122. return;
  9123. }
  9124. /* Step 6: Call the ready handler */
  9125. if (is_callback_resource) {
  9126. if (ws_ready_handler != NULL) {
  9127. ws_ready_handler(conn, cbData);
  9128. }
  9129. #if defined(USE_LUA)
  9130. } else if (lua_websock) {
  9131. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9132. /* the ready handler returned false */
  9133. return;
  9134. }
  9135. #endif
  9136. }
  9137. /* Step 7: Enter the read loop */
  9138. if (is_callback_resource) {
  9139. read_websocket(conn, ws_data_handler, cbData);
  9140. #if defined(USE_LUA)
  9141. } else if (lua_websock) {
  9142. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9143. #endif
  9144. }
  9145. /* Step 8: Call the close handler */
  9146. if (ws_close_handler) {
  9147. ws_close_handler(conn, cbData);
  9148. }
  9149. }
  9150. static int
  9151. is_websocket_protocol(const struct mg_connection *conn)
  9152. {
  9153. const char *upgrade, *connection;
  9154. /* A websocket protocoll has the following HTTP headers:
  9155. *
  9156. * Connection: Upgrade
  9157. * Upgrade: Websocket
  9158. */
  9159. upgrade = mg_get_header(conn, "Upgrade");
  9160. if (upgrade == NULL) {
  9161. return 0; /* fail early, don't waste time checking other header
  9162. * fields
  9163. */
  9164. }
  9165. if (!mg_strcasestr(upgrade, "websocket")) {
  9166. return 0;
  9167. }
  9168. connection = mg_get_header(conn, "Connection");
  9169. if (connection == NULL) {
  9170. return 0;
  9171. }
  9172. if (!mg_strcasestr(connection, "upgrade")) {
  9173. return 0;
  9174. }
  9175. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9176. * "Sec-WebSocket-Version" are also required.
  9177. * Don't check them here, since even an unsupported websocket protocol
  9178. * request still IS a websocket request (in contrast to a standard HTTP
  9179. * request). It will fail later in handle_websocket_request.
  9180. */
  9181. return 1;
  9182. }
  9183. #endif /* !USE_WEBSOCKET */
  9184. static int
  9185. isbyte(int n)
  9186. {
  9187. return n >= 0 && n <= 255;
  9188. }
  9189. static int
  9190. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9191. {
  9192. int n, a, b, c, d, slash = 32, len = 0;
  9193. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  9194. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  9195. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  9196. && slash < 33) {
  9197. len = n;
  9198. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9199. | (uint32_t)d;
  9200. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9201. }
  9202. return len;
  9203. }
  9204. static int
  9205. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9206. {
  9207. int throttle = 0;
  9208. struct vec vec, val;
  9209. uint32_t net, mask;
  9210. char mult;
  9211. double v;
  9212. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9213. mult = ',';
  9214. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9215. || (v < 0) || ((lowercase(&mult) != 'k')
  9216. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9217. continue;
  9218. }
  9219. v *= (lowercase(&mult) == 'k')
  9220. ? 1024
  9221. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9222. if (vec.len == 1 && vec.ptr[0] == '*') {
  9223. throttle = (int)v;
  9224. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9225. if ((remote_ip & mask) == net) {
  9226. throttle = (int)v;
  9227. }
  9228. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9229. throttle = (int)v;
  9230. }
  9231. }
  9232. return throttle;
  9233. }
  9234. static uint32_t
  9235. get_remote_ip(const struct mg_connection *conn)
  9236. {
  9237. if (!conn) {
  9238. return 0;
  9239. }
  9240. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9241. }
  9242. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9243. #include "handle_form.inl"
  9244. #if defined(MG_LEGACY_INTERFACE)
  9245. /* Implement the deprecated mg_upload function by calling the new
  9246. * mg_handle_form_request function. While mg_upload could only handle
  9247. * HTML forms sent as POST request in multipart/form-data format
  9248. * containing only file input elements, mg_handle_form_request can
  9249. * handle all form input elements and all standard request methods. */
  9250. struct mg_upload_user_data {
  9251. struct mg_connection *conn;
  9252. const char *destination_dir;
  9253. int num_uploaded_files;
  9254. };
  9255. /* Helper function for deprecated mg_upload. */
  9256. static int
  9257. mg_upload_field_found(const char *key,
  9258. const char *filename,
  9259. char *path,
  9260. size_t pathlen,
  9261. void *user_data)
  9262. {
  9263. int truncated = 0;
  9264. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9265. (void)key;
  9266. if (!filename) {
  9267. mg_cry(fud->conn, "%s: No filename set", __func__);
  9268. return FORM_FIELD_STORAGE_ABORT;
  9269. }
  9270. mg_snprintf(fud->conn,
  9271. &truncated,
  9272. path,
  9273. pathlen - 1,
  9274. "%s/%s",
  9275. fud->destination_dir,
  9276. filename);
  9277. if (!truncated) {
  9278. mg_cry(fud->conn, "%s: File path too long", __func__);
  9279. return FORM_FIELD_STORAGE_ABORT;
  9280. }
  9281. return FORM_FIELD_STORAGE_STORE;
  9282. }
  9283. /* Helper function for deprecated mg_upload. */
  9284. static int
  9285. mg_upload_field_get(const char *key,
  9286. const char *value,
  9287. size_t value_size,
  9288. void *user_data)
  9289. {
  9290. /* Function should never be called */
  9291. (void)key;
  9292. (void)value;
  9293. (void)value_size;
  9294. (void)user_data;
  9295. return 0;
  9296. }
  9297. /* Helper function for deprecated mg_upload. */
  9298. static int
  9299. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9300. {
  9301. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9302. (void)file_size;
  9303. fud->num_uploaded_files++;
  9304. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9305. return 0;
  9306. }
  9307. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9308. int
  9309. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9310. {
  9311. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9312. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9313. mg_upload_field_get,
  9314. mg_upload_field_stored,
  9315. 0};
  9316. int ret;
  9317. fdh.user_data = (void *)&fud;
  9318. ret = mg_handle_form_request(conn, &fdh);
  9319. if (ret < 0) {
  9320. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9321. }
  9322. return fud.num_uploaded_files;
  9323. }
  9324. #endif
  9325. static int
  9326. get_first_ssl_listener_index(const struct mg_context *ctx)
  9327. {
  9328. unsigned int i;
  9329. int idx = -1;
  9330. if (ctx) {
  9331. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  9332. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9333. }
  9334. }
  9335. return idx;
  9336. }
  9337. static void
  9338. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9339. {
  9340. char host[1025];
  9341. const char *host_header;
  9342. size_t hostlen;
  9343. host_header = mg_get_header(conn, "Host");
  9344. hostlen = sizeof(host);
  9345. if (host_header != NULL) {
  9346. char *pos;
  9347. mg_strlcpy(host, host_header, hostlen);
  9348. host[hostlen - 1] = '\0';
  9349. pos = strchr(host, ':');
  9350. if (pos != NULL) {
  9351. *pos = '\0';
  9352. }
  9353. } else {
  9354. /* Cannot get host from the Host: header.
  9355. * Fallback to our IP address. */
  9356. if (conn) {
  9357. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9358. }
  9359. }
  9360. /* Send host, port, uri and (if it exists) ?query_string */
  9361. if (conn) {
  9362. mg_printf(conn,
  9363. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9364. host,
  9365. #if defined(USE_IPV6)
  9366. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9367. == AF_INET6)
  9368. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9369. .lsa.sin6.sin6_port)
  9370. :
  9371. #endif
  9372. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9373. .lsa.sin.sin_port),
  9374. conn->request_info.local_uri,
  9375. (conn->request_info.query_string == NULL) ? "" : "?",
  9376. (conn->request_info.query_string == NULL)
  9377. ? ""
  9378. : conn->request_info.query_string);
  9379. }
  9380. }
  9381. static void
  9382. mg_set_handler_type(struct mg_context *ctx,
  9383. const char *uri,
  9384. int handler_type,
  9385. int is_delete_request,
  9386. mg_request_handler handler,
  9387. struct mg_websocket_subprotocols *subprotocols,
  9388. mg_websocket_connect_handler connect_handler,
  9389. mg_websocket_ready_handler ready_handler,
  9390. mg_websocket_data_handler data_handler,
  9391. mg_websocket_close_handler close_handler,
  9392. mg_authorization_handler auth_handler,
  9393. void *cbdata)
  9394. {
  9395. struct mg_handler_info *tmp_rh, **lastref;
  9396. size_t urilen = strlen(uri);
  9397. if (handler_type == WEBSOCKET_HANDLER) {
  9398. /* assert(handler == NULL); */
  9399. /* assert(is_delete_request || connect_handler!=NULL ||
  9400. * ready_handler!=NULL || data_handler!=NULL ||
  9401. * close_handler!=NULL);
  9402. */
  9403. /* assert(auth_handler == NULL); */
  9404. if (handler != NULL) {
  9405. return;
  9406. }
  9407. if (!is_delete_request && connect_handler == NULL
  9408. && ready_handler == NULL
  9409. && data_handler == NULL
  9410. && close_handler == NULL) {
  9411. return;
  9412. }
  9413. if (auth_handler != NULL) {
  9414. return;
  9415. }
  9416. } else if (handler_type == REQUEST_HANDLER) {
  9417. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9418. * data_handler==NULL && close_handler==NULL); */
  9419. /* assert(is_delete_request || (handler!=NULL));
  9420. */
  9421. /* assert(auth_handler == NULL); */
  9422. if (connect_handler != NULL || ready_handler != NULL
  9423. || data_handler != NULL
  9424. || close_handler != NULL) {
  9425. return;
  9426. }
  9427. if (!is_delete_request && (handler == NULL)) {
  9428. return;
  9429. }
  9430. if (auth_handler != NULL) {
  9431. return;
  9432. }
  9433. } else { /* AUTH_HANDLER */
  9434. /* assert(handler == NULL); */
  9435. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9436. * data_handler==NULL && close_handler==NULL); */
  9437. /* assert(auth_handler != NULL); */
  9438. if (handler != NULL) {
  9439. return;
  9440. }
  9441. if (connect_handler != NULL || ready_handler != NULL
  9442. || data_handler != NULL
  9443. || close_handler != NULL) {
  9444. return;
  9445. }
  9446. if (!is_delete_request && (auth_handler == NULL)) {
  9447. return;
  9448. }
  9449. }
  9450. if (!ctx) {
  9451. return;
  9452. }
  9453. mg_lock_context(ctx);
  9454. /* first try to find an existing handler */
  9455. lastref = &(ctx->handlers);
  9456. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9457. if (tmp_rh->handler_type == handler_type) {
  9458. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9459. if (!is_delete_request) {
  9460. /* update existing handler */
  9461. if (handler_type == REQUEST_HANDLER) {
  9462. tmp_rh->handler = handler;
  9463. } else if (handler_type == WEBSOCKET_HANDLER) {
  9464. tmp_rh->subprotocols = subprotocols;
  9465. tmp_rh->connect_handler = connect_handler;
  9466. tmp_rh->ready_handler = ready_handler;
  9467. tmp_rh->data_handler = data_handler;
  9468. tmp_rh->close_handler = close_handler;
  9469. } else { /* AUTH_HANDLER */
  9470. tmp_rh->auth_handler = auth_handler;
  9471. }
  9472. tmp_rh->cbdata = cbdata;
  9473. } else {
  9474. /* remove existing handler */
  9475. *lastref = tmp_rh->next;
  9476. mg_free(tmp_rh->uri);
  9477. mg_free(tmp_rh);
  9478. }
  9479. mg_unlock_context(ctx);
  9480. return;
  9481. }
  9482. }
  9483. lastref = &(tmp_rh->next);
  9484. }
  9485. if (is_delete_request) {
  9486. /* no handler to set, this was a remove request to a non-existing
  9487. * handler */
  9488. mg_unlock_context(ctx);
  9489. return;
  9490. }
  9491. tmp_rh =
  9492. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  9493. 1,
  9494. ctx);
  9495. if (tmp_rh == NULL) {
  9496. mg_unlock_context(ctx);
  9497. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9498. return;
  9499. }
  9500. tmp_rh->uri = mg_strdup(uri);
  9501. if (!tmp_rh->uri) {
  9502. mg_unlock_context(ctx);
  9503. mg_free(tmp_rh);
  9504. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9505. return;
  9506. }
  9507. tmp_rh->uri_len = urilen;
  9508. if (handler_type == REQUEST_HANDLER) {
  9509. tmp_rh->handler = handler;
  9510. } else if (handler_type == WEBSOCKET_HANDLER) {
  9511. tmp_rh->subprotocols = subprotocols;
  9512. tmp_rh->connect_handler = connect_handler;
  9513. tmp_rh->ready_handler = ready_handler;
  9514. tmp_rh->data_handler = data_handler;
  9515. tmp_rh->close_handler = close_handler;
  9516. } else { /* AUTH_HANDLER */
  9517. tmp_rh->auth_handler = auth_handler;
  9518. }
  9519. tmp_rh->cbdata = cbdata;
  9520. tmp_rh->handler_type = handler_type;
  9521. tmp_rh->next = NULL;
  9522. *lastref = tmp_rh;
  9523. mg_unlock_context(ctx);
  9524. }
  9525. void
  9526. mg_set_request_handler(struct mg_context *ctx,
  9527. const char *uri,
  9528. mg_request_handler handler,
  9529. void *cbdata)
  9530. {
  9531. mg_set_handler_type(ctx,
  9532. uri,
  9533. REQUEST_HANDLER,
  9534. handler == NULL,
  9535. handler,
  9536. NULL,
  9537. NULL,
  9538. NULL,
  9539. NULL,
  9540. NULL,
  9541. NULL,
  9542. cbdata);
  9543. }
  9544. void
  9545. mg_set_websocket_handler(struct mg_context *ctx,
  9546. const char *uri,
  9547. mg_websocket_connect_handler connect_handler,
  9548. mg_websocket_ready_handler ready_handler,
  9549. mg_websocket_data_handler data_handler,
  9550. mg_websocket_close_handler close_handler,
  9551. void *cbdata)
  9552. {
  9553. mg_set_websocket_handler_with_subprotocols(ctx,
  9554. uri,
  9555. NULL,
  9556. connect_handler,
  9557. ready_handler,
  9558. data_handler,
  9559. close_handler,
  9560. cbdata);
  9561. }
  9562. void
  9563. mg_set_websocket_handler_with_subprotocols(
  9564. struct mg_context *ctx,
  9565. const char *uri,
  9566. struct mg_websocket_subprotocols *subprotocols,
  9567. mg_websocket_connect_handler connect_handler,
  9568. mg_websocket_ready_handler ready_handler,
  9569. mg_websocket_data_handler data_handler,
  9570. mg_websocket_close_handler close_handler,
  9571. void *cbdata)
  9572. {
  9573. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9574. && (data_handler == NULL)
  9575. && (close_handler == NULL);
  9576. mg_set_handler_type(ctx,
  9577. uri,
  9578. WEBSOCKET_HANDLER,
  9579. is_delete_request,
  9580. NULL,
  9581. subprotocols,
  9582. connect_handler,
  9583. ready_handler,
  9584. data_handler,
  9585. close_handler,
  9586. NULL,
  9587. cbdata);
  9588. }
  9589. void
  9590. mg_set_auth_handler(struct mg_context *ctx,
  9591. const char *uri,
  9592. mg_request_handler handler,
  9593. void *cbdata)
  9594. {
  9595. mg_set_handler_type(ctx,
  9596. uri,
  9597. AUTH_HANDLER,
  9598. handler == NULL,
  9599. NULL,
  9600. NULL,
  9601. NULL,
  9602. NULL,
  9603. NULL,
  9604. NULL,
  9605. handler,
  9606. cbdata);
  9607. }
  9608. static int
  9609. get_request_handler(struct mg_connection *conn,
  9610. int handler_type,
  9611. mg_request_handler *handler,
  9612. struct mg_websocket_subprotocols **subprotocols,
  9613. mg_websocket_connect_handler *connect_handler,
  9614. mg_websocket_ready_handler *ready_handler,
  9615. mg_websocket_data_handler *data_handler,
  9616. mg_websocket_close_handler *close_handler,
  9617. mg_authorization_handler *auth_handler,
  9618. void **cbdata)
  9619. {
  9620. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9621. if (request_info) {
  9622. const char *uri = request_info->local_uri;
  9623. size_t urilen = strlen(uri);
  9624. struct mg_handler_info *tmp_rh;
  9625. if (!conn || !conn->ctx) {
  9626. return 0;
  9627. }
  9628. mg_lock_context(conn->ctx);
  9629. /* first try for an exact match */
  9630. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9631. tmp_rh = tmp_rh->next) {
  9632. if (tmp_rh->handler_type == handler_type) {
  9633. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9634. if (handler_type == WEBSOCKET_HANDLER) {
  9635. *subprotocols = tmp_rh->subprotocols;
  9636. *connect_handler = tmp_rh->connect_handler;
  9637. *ready_handler = tmp_rh->ready_handler;
  9638. *data_handler = tmp_rh->data_handler;
  9639. *close_handler = tmp_rh->close_handler;
  9640. } else if (handler_type == REQUEST_HANDLER) {
  9641. *handler = tmp_rh->handler;
  9642. } else { /* AUTH_HANDLER */
  9643. *auth_handler = tmp_rh->auth_handler;
  9644. }
  9645. *cbdata = tmp_rh->cbdata;
  9646. mg_unlock_context(conn->ctx);
  9647. return 1;
  9648. }
  9649. }
  9650. }
  9651. /* next try for a partial match, we will accept uri/something */
  9652. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9653. tmp_rh = tmp_rh->next) {
  9654. if (tmp_rh->handler_type == handler_type) {
  9655. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9656. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9657. if (handler_type == WEBSOCKET_HANDLER) {
  9658. *subprotocols = tmp_rh->subprotocols;
  9659. *connect_handler = tmp_rh->connect_handler;
  9660. *ready_handler = tmp_rh->ready_handler;
  9661. *data_handler = tmp_rh->data_handler;
  9662. *close_handler = tmp_rh->close_handler;
  9663. } else if (handler_type == REQUEST_HANDLER) {
  9664. *handler = tmp_rh->handler;
  9665. } else { /* AUTH_HANDLER */
  9666. *auth_handler = tmp_rh->auth_handler;
  9667. }
  9668. *cbdata = tmp_rh->cbdata;
  9669. mg_unlock_context(conn->ctx);
  9670. return 1;
  9671. }
  9672. }
  9673. }
  9674. /* finally try for pattern match */
  9675. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9676. tmp_rh = tmp_rh->next) {
  9677. if (tmp_rh->handler_type == handler_type) {
  9678. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9679. if (handler_type == WEBSOCKET_HANDLER) {
  9680. *subprotocols = tmp_rh->subprotocols;
  9681. *connect_handler = tmp_rh->connect_handler;
  9682. *ready_handler = tmp_rh->ready_handler;
  9683. *data_handler = tmp_rh->data_handler;
  9684. *close_handler = tmp_rh->close_handler;
  9685. } else if (handler_type == REQUEST_HANDLER) {
  9686. *handler = tmp_rh->handler;
  9687. } else { /* AUTH_HANDLER */
  9688. *auth_handler = tmp_rh->auth_handler;
  9689. }
  9690. *cbdata = tmp_rh->cbdata;
  9691. mg_unlock_context(conn->ctx);
  9692. return 1;
  9693. }
  9694. }
  9695. }
  9696. mg_unlock_context(conn->ctx);
  9697. }
  9698. return 0; /* none found */
  9699. }
  9700. /* Check if the script file is in a path, allowed for script files.
  9701. * This can be used if uploading files is possible not only for the server
  9702. * admin, and the upload mechanism does not check the file extension.
  9703. */
  9704. static int
  9705. is_in_script_path(const struct mg_connection *conn, const char *path)
  9706. {
  9707. /* TODO (Feature): Add config value for allowed script path.
  9708. * Default: All allowed. */
  9709. (void)conn;
  9710. (void)path;
  9711. return 1;
  9712. }
  9713. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9714. static int
  9715. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9716. void *cbdata)
  9717. {
  9718. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9719. if (pcallbacks->websocket_connect) {
  9720. return pcallbacks->websocket_connect(conn);
  9721. }
  9722. /* No handler set - assume "OK" */
  9723. return 0;
  9724. }
  9725. static void
  9726. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9727. {
  9728. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9729. if (pcallbacks->websocket_ready) {
  9730. pcallbacks->websocket_ready(conn);
  9731. }
  9732. }
  9733. static int
  9734. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9735. int bits,
  9736. char *data,
  9737. size_t len,
  9738. void *cbdata)
  9739. {
  9740. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9741. if (pcallbacks->websocket_data) {
  9742. return pcallbacks->websocket_data(conn, bits, data, len);
  9743. }
  9744. /* No handler set - assume "OK" */
  9745. return 1;
  9746. }
  9747. #endif
  9748. /* This is the heart of the Civetweb's logic.
  9749. * This function is called when the request is read, parsed and validated,
  9750. * and Civetweb must decide what action to take: serve a file, or
  9751. * a directory, or call embedded function, etcetera. */
  9752. static void
  9753. handle_request(struct mg_connection *conn)
  9754. {
  9755. struct mg_request_info *ri = &conn->request_info;
  9756. char path[PATH_MAX];
  9757. int uri_len, ssl_index;
  9758. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9759. is_put_or_delete_request = 0, is_callback_resource = 0;
  9760. int i;
  9761. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9762. mg_request_handler callback_handler = NULL;
  9763. struct mg_websocket_subprotocols *subprotocols;
  9764. mg_websocket_connect_handler ws_connect_handler = NULL;
  9765. mg_websocket_ready_handler ws_ready_handler = NULL;
  9766. mg_websocket_data_handler ws_data_handler = NULL;
  9767. mg_websocket_close_handler ws_close_handler = NULL;
  9768. void *callback_data = NULL;
  9769. mg_authorization_handler auth_handler = NULL;
  9770. void *auth_callback_data = NULL;
  9771. #if !defined(NO_FILES)
  9772. time_t curtime = time(NULL);
  9773. char date[64];
  9774. #endif
  9775. path[0] = 0;
  9776. /* 1. get the request url */
  9777. /* 1.1. split into url and query string */
  9778. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9779. != NULL) {
  9780. *((char *)conn->request_info.query_string++) = '\0';
  9781. }
  9782. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9783. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9784. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9785. if (ssl_index >= 0) {
  9786. redirect_to_https_port(conn, ssl_index);
  9787. } else {
  9788. /* A http to https forward port has been specified,
  9789. * but no https port to forward to. */
  9790. mg_send_http_error(conn,
  9791. 503,
  9792. "%s",
  9793. "Error: SSL forward not configured properly");
  9794. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9795. }
  9796. return;
  9797. }
  9798. uri_len = (int)strlen(ri->local_uri);
  9799. /* 1.3. decode url (if config says so) */
  9800. if (should_decode_url(conn)) {
  9801. mg_url_decode(
  9802. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9803. }
  9804. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9805. * not possible */
  9806. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9807. /* step 1. completed, the url is known now */
  9808. uri_len = (int)strlen(ri->local_uri);
  9809. DEBUG_TRACE("URL: %s", ri->local_uri);
  9810. /* 3. if this ip has limited speed, set it for this connection */
  9811. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9812. get_remote_ip(conn),
  9813. ri->local_uri);
  9814. /* 4. call a "handle everything" callback, if registered */
  9815. if (conn->ctx->callbacks.begin_request != NULL) {
  9816. /* Note that since V1.7 the "begin_request" function is called
  9817. * before an authorization check. If an authorization check is
  9818. * required, use a request_handler instead. */
  9819. i = conn->ctx->callbacks.begin_request(conn);
  9820. if (i > 0) {
  9821. /* callback already processed the request. Store the
  9822. return value as a status code for the access log. */
  9823. conn->status_code = i;
  9824. discard_unread_request_data(conn);
  9825. return;
  9826. } else if (i == 0) {
  9827. /* civetweb should process the request */
  9828. } else {
  9829. /* unspecified - may change with the next version */
  9830. return;
  9831. }
  9832. }
  9833. /* request not yet handled by a handler or redirect, so the request
  9834. * is processed here */
  9835. /* 5. interpret the url to find out how the request must be handled
  9836. */
  9837. /* 5.1. first test, if the request targets the regular http(s)://
  9838. * protocol namespace or the websocket ws(s):// protocol namespace.
  9839. */
  9840. is_websocket_request = is_websocket_protocol(conn);
  9841. /* 5.2. check if the request will be handled by a callback */
  9842. if (get_request_handler(conn,
  9843. is_websocket_request ? WEBSOCKET_HANDLER
  9844. : REQUEST_HANDLER,
  9845. &callback_handler,
  9846. &subprotocols,
  9847. &ws_connect_handler,
  9848. &ws_ready_handler,
  9849. &ws_data_handler,
  9850. &ws_close_handler,
  9851. NULL,
  9852. &callback_data)) {
  9853. /* 5.2.1. A callback will handle this request. All requests
  9854. * handled
  9855. * by a callback have to be considered as requests to a script
  9856. * resource. */
  9857. is_callback_resource = 1;
  9858. is_script_resource = 1;
  9859. is_put_or_delete_request = is_put_or_delete_method(conn);
  9860. } else {
  9861. no_callback_resource:
  9862. /* 5.2.2. No callback is responsible for this request. The URI
  9863. * addresses a file based resource (static content or Lua/cgi
  9864. * scripts in the file system). */
  9865. is_callback_resource = 0;
  9866. interpret_uri(conn,
  9867. path,
  9868. sizeof(path),
  9869. &file.stat,
  9870. &is_found,
  9871. &is_script_resource,
  9872. &is_websocket_request,
  9873. &is_put_or_delete_request);
  9874. }
  9875. /* 6. authorization check */
  9876. /* 6.1. a custom authorization handler is installed */
  9877. if (get_request_handler(conn,
  9878. AUTH_HANDLER,
  9879. NULL,
  9880. NULL,
  9881. NULL,
  9882. NULL,
  9883. NULL,
  9884. NULL,
  9885. &auth_handler,
  9886. &auth_callback_data)) {
  9887. if (!auth_handler(conn, auth_callback_data)) {
  9888. return;
  9889. }
  9890. } else if (is_put_or_delete_request && !is_script_resource
  9891. && !is_callback_resource) {
  9892. /* 6.2. this request is a PUT/DELETE to a real file */
  9893. /* 6.2.1. thus, the server must have real files */
  9894. #if defined(NO_FILES)
  9895. if (1) {
  9896. #else
  9897. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9898. #endif
  9899. /* This server does not have any real files, thus the
  9900. * PUT/DELETE methods are not valid. */
  9901. mg_send_http_error(conn,
  9902. 405,
  9903. "%s method not allowed",
  9904. conn->request_info.request_method);
  9905. return;
  9906. }
  9907. #if !defined(NO_FILES)
  9908. /* 6.2.2. Check if put authorization for static files is
  9909. * available.
  9910. */
  9911. if (!is_authorized_for_put(conn)) {
  9912. send_authorization_request(conn);
  9913. return;
  9914. }
  9915. #endif
  9916. } else {
  9917. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9918. * or it is a PUT or DELETE request to a resource that does not
  9919. * correspond to a file. Check authorization. */
  9920. if (!check_authorization(conn, path)) {
  9921. send_authorization_request(conn);
  9922. return;
  9923. }
  9924. }
  9925. /* request is authorized or does not need authorization */
  9926. /* 7. check if there are request handlers for this uri */
  9927. if (is_callback_resource) {
  9928. if (!is_websocket_request) {
  9929. i = callback_handler(conn, callback_data);
  9930. if (i > 0) {
  9931. /* Do nothing, callback has served the request. Store
  9932. * then return value as status code for the log and discard
  9933. * all data from the client not used by the callback. */
  9934. conn->status_code = i;
  9935. discard_unread_request_data(conn);
  9936. } else {
  9937. /* The handler did NOT handle the request. */
  9938. /* Some proper reactions would be:
  9939. * a) close the connections without sending anything
  9940. * b) send a 404 not found
  9941. * c) try if there is a file matching the URI
  9942. * It would be possible to do a, b or c in the callback
  9943. * implementation, and return 1 - we cannot do anything
  9944. * here, that is not possible in the callback.
  9945. *
  9946. * TODO: What would be the best reaction here?
  9947. * (Note: The reaction may change, if there is a better idea.)
  9948. */
  9949. /* For the moment, use option c: We look for a proper file,
  9950. * but since a file request is not always a script resource,
  9951. * the authorization check might be different. */
  9952. interpret_uri(conn,
  9953. path,
  9954. sizeof(path),
  9955. &file.stat,
  9956. &is_found,
  9957. &is_script_resource,
  9958. &is_websocket_request,
  9959. &is_put_or_delete_request);
  9960. callback_handler = NULL;
  9961. /* Here we are at a dead end:
  9962. * According to URI matching, a callback should be
  9963. * responsible for handling the request,
  9964. * we called it, but the callback declared itself
  9965. * not responsible.
  9966. * We use a goto here, to get out of this dead end,
  9967. * and continue with the default handling.
  9968. * A goto here is simpler and better to understand
  9969. * than some curious loop. */
  9970. goto no_callback_resource;
  9971. }
  9972. } else {
  9973. #if defined(USE_WEBSOCKET)
  9974. handle_websocket_request(conn,
  9975. path,
  9976. is_callback_resource,
  9977. subprotocols,
  9978. ws_connect_handler,
  9979. ws_ready_handler,
  9980. ws_data_handler,
  9981. ws_close_handler,
  9982. callback_data);
  9983. #endif
  9984. }
  9985. return;
  9986. }
  9987. /* 8. handle websocket requests */
  9988. #if defined(USE_WEBSOCKET)
  9989. if (is_websocket_request) {
  9990. if (is_script_resource) {
  9991. if (is_in_script_path(conn, path)) {
  9992. /* Websocket Lua script */
  9993. handle_websocket_request(conn,
  9994. path,
  9995. 0 /* Lua Script */,
  9996. NULL,
  9997. NULL,
  9998. NULL,
  9999. NULL,
  10000. NULL,
  10001. &conn->ctx->callbacks);
  10002. } else {
  10003. /* Script was in an illegal path */
  10004. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10005. }
  10006. } else {
  10007. #if defined(MG_LEGACY_INTERFACE)
  10008. handle_websocket_request(
  10009. conn,
  10010. path,
  10011. !is_script_resource /* could be deprecated global callback */,
  10012. NULL,
  10013. deprecated_websocket_connect_wrapper,
  10014. deprecated_websocket_ready_wrapper,
  10015. deprecated_websocket_data_wrapper,
  10016. NULL,
  10017. &conn->ctx->callbacks);
  10018. #else
  10019. mg_send_http_error(conn, 404, "%s", "Not found");
  10020. #endif
  10021. }
  10022. return;
  10023. } else
  10024. #endif
  10025. #if defined(NO_FILES)
  10026. /* 9a. In case the server uses only callbacks, this uri is
  10027. * unknown.
  10028. * Then, all request handling ends here. */
  10029. mg_send_http_error(conn, 404, "%s", "Not Found");
  10030. #else
  10031. /* 9b. This request is either for a static file or resource handled
  10032. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  10033. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10034. mg_send_http_error(conn, 404, "%s", "Not Found");
  10035. return;
  10036. }
  10037. /* 10. Request is handled by a script */
  10038. if (is_script_resource) {
  10039. handle_file_based_request(conn, path, &file);
  10040. return;
  10041. }
  10042. /* 11. Handle put/delete/mkcol requests */
  10043. if (is_put_or_delete_request) {
  10044. /* 11.1. PUT method */
  10045. if (!strcmp(ri->request_method, "PUT")) {
  10046. put_file(conn, path);
  10047. return;
  10048. }
  10049. /* 11.2. DELETE method */
  10050. if (!strcmp(ri->request_method, "DELETE")) {
  10051. delete_file(conn, path);
  10052. return;
  10053. }
  10054. /* 11.3. MKCOL method */
  10055. if (!strcmp(ri->request_method, "MKCOL")) {
  10056. mkcol(conn, path);
  10057. return;
  10058. }
  10059. /* 11.4. PATCH method
  10060. * This method is not supported for static resources,
  10061. * only for scripts (Lua, CGI) and callbacks. */
  10062. mg_send_http_error(conn,
  10063. 405,
  10064. "%s method not allowed",
  10065. conn->request_info.request_method);
  10066. return;
  10067. }
  10068. /* 11. File does not exist, or it was configured that it should be
  10069. * hidden */
  10070. if (!is_found || (must_hide_file(conn, path))) {
  10071. mg_send_http_error(conn, 404, "%s", "Not found");
  10072. return;
  10073. }
  10074. /* 12. Directory uris should end with a slash */
  10075. if (file.stat.is_directory && (uri_len > 0)
  10076. && (ri->local_uri[uri_len - 1] != '/')) {
  10077. gmt_time_string(date, sizeof(date), &curtime);
  10078. mg_printf(conn,
  10079. "HTTP/1.1 301 Moved Permanently\r\n"
  10080. "Location: %s/\r\n"
  10081. "Date: %s\r\n"
  10082. /* "Cache-Control: private\r\n" (= default) */
  10083. "Content-Length: 0\r\n"
  10084. "Connection: %s\r\n",
  10085. ri->request_uri,
  10086. date,
  10087. suggest_connection_header(conn));
  10088. send_additional_header(conn);
  10089. mg_printf(conn, "\r\n");
  10090. return;
  10091. }
  10092. /* 13. Handle other methods than GET/HEAD */
  10093. /* 13.1. Handle PROPFIND */
  10094. if (!strcmp(ri->request_method, "PROPFIND")) {
  10095. handle_propfind(conn, path, &file.stat);
  10096. return;
  10097. }
  10098. /* 13.2. Handle OPTIONS for files */
  10099. if (!strcmp(ri->request_method, "OPTIONS")) {
  10100. /* This standard handler is only used for real files.
  10101. * Scripts should support the OPTIONS method themselves, to allow a
  10102. * maximum flexibility.
  10103. * Lua and CGI scripts may fully support CORS this way (including
  10104. * preflights). */
  10105. send_options(conn);
  10106. return;
  10107. }
  10108. /* 13.3. everything but GET and HEAD (e.g. POST) */
  10109. if (0 != strcmp(ri->request_method, "GET")
  10110. && 0 != strcmp(ri->request_method, "HEAD")) {
  10111. mg_send_http_error(conn,
  10112. 405,
  10113. "%s method not allowed",
  10114. conn->request_info.request_method);
  10115. return;
  10116. }
  10117. /* 14. directories */
  10118. if (file.stat.is_directory) {
  10119. /* Substitute files have already been handled above. */
  10120. /* Here we can either generate and send a directory listing,
  10121. * or send an "access denied" error. */
  10122. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  10123. "yes")) {
  10124. handle_directory_request(conn, path);
  10125. } else {
  10126. mg_send_http_error(conn,
  10127. 403,
  10128. "%s",
  10129. "Error: Directory listing denied");
  10130. }
  10131. return;
  10132. }
  10133. handle_file_based_request(conn, path, &file);
  10134. #endif /* !defined(NO_FILES) */
  10135. #if 0
  10136. /* Perform redirect and auth checks before calling begin_request()
  10137. * handler.
  10138. * Otherwise, begin_request() would need to perform auth checks and
  10139. * redirects. */
  10140. #endif
  10141. }
  10142. static void
  10143. handle_file_based_request(struct mg_connection *conn,
  10144. const char *path,
  10145. struct mg_file *file)
  10146. {
  10147. if (!conn || !conn->ctx) {
  10148. return;
  10149. }
  10150. if (0) {
  10151. #ifdef USE_LUA
  10152. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10153. strlen(
  10154. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10155. path) > 0) {
  10156. if (is_in_script_path(conn, path)) {
  10157. /* Lua server page: an SSI like page containing mostly plain html
  10158. * code
  10159. * plus some tags with server generated contents. */
  10160. handle_lsp_request(conn, path, file, NULL);
  10161. } else {
  10162. /* Script was in an illegal path */
  10163. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10164. }
  10165. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10166. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10167. path) > 0) {
  10168. if (is_in_script_path(conn, path)) {
  10169. /* Lua in-server module script: a CGI like script used to generate
  10170. * the
  10171. * entire reply. */
  10172. mg_exec_lua_script(conn, path, NULL);
  10173. } else {
  10174. /* Script was in an illegal path */
  10175. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10176. }
  10177. #endif
  10178. #if defined(USE_DUKTAPE)
  10179. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10180. strlen(
  10181. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10182. path) > 0) {
  10183. if (is_in_script_path(conn, path)) {
  10184. /* Call duktape to generate the page */
  10185. mg_exec_duktape_script(conn, path);
  10186. } else {
  10187. /* Script was in an illegal path */
  10188. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10189. }
  10190. #endif
  10191. #if !defined(NO_CGI)
  10192. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10193. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10194. path) > 0) {
  10195. if (is_in_script_path(conn, path)) {
  10196. /* CGI scripts may support all HTTP methods */
  10197. handle_cgi_request(conn, path);
  10198. } else {
  10199. /* Script was in an illegal path */
  10200. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10201. }
  10202. #endif /* !NO_CGI */
  10203. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10204. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10205. path) > 0) {
  10206. if (is_in_script_path(conn, path)) {
  10207. handle_ssi_file_request(conn, path, file);
  10208. } else {
  10209. /* Script was in an illegal path */
  10210. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10211. }
  10212. #if !defined(NO_CACHING)
  10213. } else if ((!conn->in_error_handler)
  10214. && is_not_modified(conn, &file->stat)) {
  10215. /* Send 304 "Not Modified" - this must not send any body data */
  10216. handle_not_modified_static_file_request(conn, file);
  10217. #endif /* !NO_CACHING */
  10218. } else {
  10219. handle_static_file_request(conn, path, file, NULL, NULL);
  10220. }
  10221. }
  10222. static void
  10223. close_all_listening_sockets(struct mg_context *ctx)
  10224. {
  10225. unsigned int i;
  10226. if (!ctx) {
  10227. return;
  10228. }
  10229. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10230. closesocket(ctx->listening_sockets[i].sock);
  10231. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10232. }
  10233. mg_free(ctx->listening_sockets);
  10234. ctx->listening_sockets = NULL;
  10235. mg_free(ctx->listening_socket_fds);
  10236. ctx->listening_socket_fds = NULL;
  10237. }
  10238. /* Valid listening port specification is: [ip_address:]port[s]
  10239. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10240. * Examples for IPv6: [::]:80, [::1]:80,
  10241. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10242. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10243. * In order to bind to both, IPv4 and IPv6, you can either add
  10244. * both ports using 8080,[::]:8080, or the short form +8080.
  10245. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10246. * one only accepting IPv4 the other only IPv6. +8080 creates
  10247. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10248. * environment, they might work differently, or might not work
  10249. * at all - it must be tested what options work best in the
  10250. * relevant network environment.
  10251. */
  10252. static int
  10253. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10254. {
  10255. unsigned int a, b, c, d, port;
  10256. int ch, len;
  10257. #if defined(USE_IPV6)
  10258. char buf[100] = {0};
  10259. #endif
  10260. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10261. * Also, all-zeroes in the socket address means binding to all addresses
  10262. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10263. memset(so, 0, sizeof(*so));
  10264. so->lsa.sin.sin_family = AF_INET;
  10265. *ip_version = 0;
  10266. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10267. == 5) {
  10268. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10269. so->lsa.sin.sin_addr.s_addr =
  10270. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10271. so->lsa.sin.sin_port = htons((uint16_t)port);
  10272. *ip_version = 4;
  10273. #if defined(USE_IPV6)
  10274. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10275. && mg_inet_pton(
  10276. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10277. /* IPv6 address, examples: see above */
  10278. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10279. */
  10280. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10281. *ip_version = 6;
  10282. #endif
  10283. } else if ((vec->ptr[0] == '+')
  10284. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10285. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10286. /* Add 1 to len for the + character we skipped before */
  10287. len++;
  10288. #if defined(USE_IPV6)
  10289. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10290. so->lsa.sin6.sin6_family = AF_INET6;
  10291. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10292. *ip_version = 4 + 6;
  10293. #else
  10294. /* Bind to IPv4 only, since IPv6 is not built in. */
  10295. so->lsa.sin.sin_port = htons((uint16_t)port);
  10296. *ip_version = 4;
  10297. #endif
  10298. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10299. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10300. so->lsa.sin.sin_port = htons((uint16_t)port);
  10301. *ip_version = 4;
  10302. } else {
  10303. /* Parsing failure. Make port invalid. */
  10304. port = 0;
  10305. len = 0;
  10306. }
  10307. /* sscanf and the option splitting code ensure the following condition
  10308. */
  10309. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  10310. *ip_version = 0;
  10311. return 0;
  10312. }
  10313. ch = vec->ptr[len]; /* Next character after the port number */
  10314. so->is_ssl = (ch == 's');
  10315. so->ssl_redir = (ch == 'r');
  10316. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  10317. if (is_valid_port(port)
  10318. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  10319. return 1;
  10320. }
  10321. /* Reset ip_version to 0 of there is an error */
  10322. *ip_version = 0;
  10323. return 0;
  10324. }
  10325. static int
  10326. set_ports_option(struct mg_context *ctx)
  10327. {
  10328. const char *list;
  10329. int on = 1;
  10330. #if defined(USE_IPV6)
  10331. int off = 0;
  10332. #endif
  10333. struct vec vec;
  10334. struct socket so, *ptr;
  10335. struct pollfd *pfd;
  10336. union usa usa;
  10337. socklen_t len;
  10338. int ip_version;
  10339. int portsTotal = 0;
  10340. int portsOk = 0;
  10341. if (!ctx) {
  10342. return 0;
  10343. }
  10344. memset(&so, 0, sizeof(so));
  10345. memset(&usa, 0, sizeof(usa));
  10346. len = sizeof(usa);
  10347. list = ctx->config[LISTENING_PORTS];
  10348. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10349. portsTotal++;
  10350. if (!parse_port_string(&vec, &so, &ip_version)) {
  10351. mg_cry(fc(ctx),
  10352. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  10353. (int)vec.len,
  10354. vec.ptr,
  10355. portsTotal,
  10356. "[IP_ADDRESS:]PORT[s|r]");
  10357. continue;
  10358. }
  10359. #if !defined(NO_SSL)
  10360. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10361. mg_cry(fc(ctx),
  10362. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10363. "option set?",
  10364. portsTotal);
  10365. continue;
  10366. }
  10367. #endif
  10368. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10369. == INVALID_SOCKET) {
  10370. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10371. continue;
  10372. }
  10373. #ifdef _WIN32
  10374. /* Windows SO_REUSEADDR lets many procs binds to a
  10375. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10376. * if someone already has the socket -- DTL */
  10377. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10378. * Windows might need a few seconds before
  10379. * the same port can be used again in the
  10380. * same process, so a short Sleep may be
  10381. * required between mg_stop and mg_start.
  10382. */
  10383. if (setsockopt(so.sock,
  10384. SOL_SOCKET,
  10385. SO_EXCLUSIVEADDRUSE,
  10386. (SOCK_OPT_TYPE)&on,
  10387. sizeof(on)) != 0) {
  10388. /* Set reuse option, but don't abort on errors. */
  10389. mg_cry(fc(ctx),
  10390. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10391. portsTotal);
  10392. }
  10393. #else
  10394. if (setsockopt(so.sock,
  10395. SOL_SOCKET,
  10396. SO_REUSEADDR,
  10397. (SOCK_OPT_TYPE)&on,
  10398. sizeof(on)) != 0) {
  10399. /* Set reuse option, but don't abort on errors. */
  10400. mg_cry(fc(ctx),
  10401. "cannot set socket option SO_REUSEADDR (entry %i)",
  10402. portsTotal);
  10403. }
  10404. #endif
  10405. if (ip_version > 4) {
  10406. #if defined(USE_IPV6)
  10407. if (ip_version == 6) {
  10408. if (so.lsa.sa.sa_family == AF_INET6
  10409. && setsockopt(so.sock,
  10410. IPPROTO_IPV6,
  10411. IPV6_V6ONLY,
  10412. (void *)&off,
  10413. sizeof(off)) != 0) {
  10414. /* Set IPv6 only option, but don't abort on errors. */
  10415. mg_cry(fc(ctx),
  10416. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10417. portsTotal);
  10418. }
  10419. }
  10420. #else
  10421. mg_cry(fc(ctx), "IPv6 not available");
  10422. closesocket(so.sock);
  10423. so.sock = INVALID_SOCKET;
  10424. continue;
  10425. #endif
  10426. }
  10427. if (so.lsa.sa.sa_family == AF_INET) {
  10428. len = sizeof(so.lsa.sin);
  10429. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10430. mg_cry(fc(ctx),
  10431. "cannot bind to %.*s: %d (%s)",
  10432. (int)vec.len,
  10433. vec.ptr,
  10434. (int)ERRNO,
  10435. strerror(errno));
  10436. closesocket(so.sock);
  10437. so.sock = INVALID_SOCKET;
  10438. continue;
  10439. }
  10440. }
  10441. #if defined(USE_IPV6)
  10442. else if (so.lsa.sa.sa_family == AF_INET6) {
  10443. len = sizeof(so.lsa.sin6);
  10444. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10445. mg_cry(fc(ctx),
  10446. "cannot bind to IPv6 %.*s: %d (%s)",
  10447. (int)vec.len,
  10448. vec.ptr,
  10449. (int)ERRNO,
  10450. strerror(errno));
  10451. closesocket(so.sock);
  10452. so.sock = INVALID_SOCKET;
  10453. continue;
  10454. }
  10455. }
  10456. #endif
  10457. else {
  10458. mg_cry(fc(ctx),
  10459. "cannot bind: address family not supported (entry %i)",
  10460. portsTotal);
  10461. continue;
  10462. }
  10463. if (listen(so.sock, SOMAXCONN) != 0) {
  10464. mg_cry(fc(ctx),
  10465. "cannot listen to %.*s: %d (%s)",
  10466. (int)vec.len,
  10467. vec.ptr,
  10468. (int)ERRNO,
  10469. strerror(errno));
  10470. closesocket(so.sock);
  10471. so.sock = INVALID_SOCKET;
  10472. continue;
  10473. }
  10474. if (getsockname(so.sock, &(usa.sa), &len) != 0
  10475. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  10476. int err = (int)ERRNO;
  10477. mg_cry(fc(ctx),
  10478. "call to getsockname failed %.*s: %d (%s)",
  10479. (int)vec.len,
  10480. vec.ptr,
  10481. err,
  10482. strerror(errno));
  10483. closesocket(so.sock);
  10484. so.sock = INVALID_SOCKET;
  10485. continue;
  10486. }
  10487. /* Update lsa port in case of random free ports */
  10488. #if defined(USE_IPV6)
  10489. if (so.lsa.sa.sa_family == AF_INET6) {
  10490. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10491. } else
  10492. #endif
  10493. {
  10494. so.lsa.sin.sin_port = usa.sin.sin_port;
  10495. }
  10496. if ((ptr = (struct socket *)
  10497. mg_realloc_ctx(ctx->listening_sockets,
  10498. (ctx->num_listening_sockets + 1)
  10499. * sizeof(ctx->listening_sockets[0]),
  10500. ctx)) == NULL) {
  10501. mg_cry(fc(ctx), "%s", "Out of memory");
  10502. closesocket(so.sock);
  10503. so.sock = INVALID_SOCKET;
  10504. continue;
  10505. }
  10506. if ((pfd = (struct pollfd *)
  10507. mg_realloc_ctx(ctx->listening_socket_fds,
  10508. (ctx->num_listening_sockets + 1)
  10509. * sizeof(ctx->listening_socket_fds[0]),
  10510. ctx)) == NULL) {
  10511. mg_cry(fc(ctx), "%s", "Out of memory");
  10512. closesocket(so.sock);
  10513. so.sock = INVALID_SOCKET;
  10514. mg_free(ptr);
  10515. continue;
  10516. }
  10517. set_close_on_exec(so.sock, fc(ctx));
  10518. ctx->listening_sockets = ptr;
  10519. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10520. ctx->listening_socket_fds = pfd;
  10521. ctx->num_listening_sockets++;
  10522. portsOk++;
  10523. }
  10524. if (portsOk != portsTotal) {
  10525. close_all_listening_sockets(ctx);
  10526. portsOk = 0;
  10527. }
  10528. return portsOk;
  10529. }
  10530. static const char *
  10531. header_val(const struct mg_connection *conn, const char *header)
  10532. {
  10533. const char *header_value;
  10534. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10535. return "-";
  10536. } else {
  10537. return header_value;
  10538. }
  10539. }
  10540. static void
  10541. log_access(const struct mg_connection *conn)
  10542. {
  10543. const struct mg_request_info *ri;
  10544. struct mg_file fi;
  10545. char date[64], src_addr[IP_ADDR_STR_LEN];
  10546. struct tm *tm;
  10547. const char *referer;
  10548. const char *user_agent;
  10549. char buf[4096];
  10550. if (!conn || !conn->ctx) {
  10551. return;
  10552. }
  10553. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10554. if (mg_fopen(conn,
  10555. conn->ctx->config[ACCESS_LOG_FILE],
  10556. MG_FOPEN_MODE_APPEND,
  10557. &fi) == 0) {
  10558. fi.access.fp = NULL;
  10559. }
  10560. } else {
  10561. fi.access.fp = NULL;
  10562. }
  10563. /* Log is written to a file and/or a callback. If both are not set,
  10564. * executing the rest of the function is pointless. */
  10565. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10566. return;
  10567. }
  10568. tm = localtime(&conn->conn_birth_time);
  10569. if (tm != NULL) {
  10570. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10571. } else {
  10572. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10573. date[sizeof(date) - 1] = '\0';
  10574. }
  10575. ri = &conn->request_info;
  10576. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10577. referer = header_val(conn, "Referer");
  10578. user_agent = header_val(conn, "User-Agent");
  10579. mg_snprintf(conn,
  10580. NULL, /* Ignore truncation in access log */
  10581. buf,
  10582. sizeof(buf),
  10583. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10584. src_addr,
  10585. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10586. date,
  10587. ri->request_method ? ri->request_method : "-",
  10588. ri->request_uri ? ri->request_uri : "-",
  10589. ri->query_string ? "?" : "",
  10590. ri->query_string ? ri->query_string : "",
  10591. ri->http_version,
  10592. conn->status_code,
  10593. conn->num_bytes_sent,
  10594. referer,
  10595. user_agent);
  10596. if (conn->ctx->callbacks.log_access) {
  10597. conn->ctx->callbacks.log_access(conn, buf);
  10598. }
  10599. if (fi.access.fp) {
  10600. int ok = 1;
  10601. flockfile(fi.access.fp);
  10602. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10603. ok = 0;
  10604. }
  10605. if (fflush(fi.access.fp) != 0) {
  10606. ok = 0;
  10607. }
  10608. funlockfile(fi.access.fp);
  10609. if (mg_fclose(&fi.access) != 0) {
  10610. ok = 0;
  10611. }
  10612. if (!ok) {
  10613. mg_cry(conn,
  10614. "Error writing log file %s",
  10615. conn->ctx->config[ACCESS_LOG_FILE]);
  10616. }
  10617. }
  10618. }
  10619. /* Verify given socket address against the ACL.
  10620. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10621. */
  10622. static int
  10623. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10624. {
  10625. int allowed, flag;
  10626. uint32_t net, mask;
  10627. struct vec vec;
  10628. if (ctx) {
  10629. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10630. /* If any ACL is set, deny by default */
  10631. allowed = (list == NULL) ? '+' : '-';
  10632. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10633. flag = vec.ptr[0];
  10634. if ((flag != '+' && flag != '-')
  10635. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10636. mg_cry(fc(ctx),
  10637. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10638. __func__);
  10639. return -1;
  10640. }
  10641. if (net == (remote_ip & mask)) {
  10642. allowed = flag;
  10643. }
  10644. }
  10645. return allowed == '+';
  10646. }
  10647. return -1;
  10648. }
  10649. #if !defined(_WIN32)
  10650. static int
  10651. set_uid_option(struct mg_context *ctx)
  10652. {
  10653. struct passwd *pw;
  10654. if (ctx) {
  10655. const char *uid = ctx->config[RUN_AS_USER];
  10656. int success = 0;
  10657. if (uid == NULL) {
  10658. success = 1;
  10659. } else {
  10660. if ((pw = getpwnam(uid)) == NULL) {
  10661. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10662. } else if (setgid(pw->pw_gid) == -1) {
  10663. mg_cry(fc(ctx),
  10664. "%s: setgid(%s): %s",
  10665. __func__,
  10666. uid,
  10667. strerror(errno));
  10668. } else if (setgroups(0, NULL)) {
  10669. mg_cry(fc(ctx),
  10670. "%s: setgroups(): %s",
  10671. __func__,
  10672. strerror(errno));
  10673. } else if (setuid(pw->pw_uid) == -1) {
  10674. mg_cry(fc(ctx),
  10675. "%s: setuid(%s): %s",
  10676. __func__,
  10677. uid,
  10678. strerror(errno));
  10679. } else {
  10680. success = 1;
  10681. }
  10682. }
  10683. return success;
  10684. }
  10685. return 0;
  10686. }
  10687. #endif /* !_WIN32 */
  10688. static void
  10689. tls_dtor(void *key)
  10690. {
  10691. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10692. /* key == pthread_getspecific(sTlsKey); */
  10693. if (tls) {
  10694. if (tls->is_master == 2) {
  10695. tls->is_master = -3; /* Mark memory as dead */
  10696. mg_free(tls);
  10697. }
  10698. }
  10699. pthread_setspecific(sTlsKey, NULL);
  10700. }
  10701. #if !defined(NO_SSL)
  10702. static int
  10703. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  10704. static const char *ssl_error(void);
  10705. static int
  10706. refresh_trust(struct mg_connection *conn)
  10707. {
  10708. static int reload_lock = 0;
  10709. static long int data_check = 0;
  10710. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10711. struct stat cert_buf;
  10712. long int t;
  10713. const char *pem;
  10714. const char *chain;
  10715. int should_verify_peer;
  10716. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10717. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10718. * refresh_trust still can not work. */
  10719. return 0;
  10720. }
  10721. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  10722. if (chain == NULL) {
  10723. chain = pem;
  10724. }
  10725. if ((chain != NULL) && (*chain == 0)) {
  10726. chain = NULL;
  10727. }
  10728. t = data_check;
  10729. if (stat(pem, &cert_buf) != -1) {
  10730. t = (long int)cert_buf.st_mtime;
  10731. }
  10732. if (data_check != t) {
  10733. data_check = t;
  10734. should_verify_peer = 0;
  10735. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  10736. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10737. == 0) {
  10738. should_verify_peer = 1;
  10739. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  10740. "optional") == 0) {
  10741. should_verify_peer = 1;
  10742. }
  10743. }
  10744. if (should_verify_peer) {
  10745. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10746. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10747. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10748. ca_file,
  10749. ca_path) != 1) {
  10750. mg_cry(fc(conn->ctx),
  10751. "SSL_CTX_load_verify_locations error: %s "
  10752. "ssl_verify_peer requires setting "
  10753. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10754. "present in "
  10755. "the .conf file?",
  10756. ssl_error());
  10757. return 0;
  10758. }
  10759. }
  10760. if (1 == mg_atomic_inc(p_reload_lock)) {
  10761. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  10762. return 0;
  10763. }
  10764. *p_reload_lock = 0;
  10765. }
  10766. }
  10767. /* lock while cert is reloading */
  10768. while (*p_reload_lock) {
  10769. sleep(1);
  10770. }
  10771. return 1;
  10772. }
  10773. #ifdef OPENSSL_API_1_1
  10774. #else
  10775. static pthread_mutex_t *ssl_mutexes;
  10776. #endif /* OPENSSL_API_1_1 */
  10777. static int
  10778. sslize(struct mg_connection *conn,
  10779. SSL_CTX *s,
  10780. int (*func)(SSL *),
  10781. volatile int *stop_server)
  10782. {
  10783. int ret, err;
  10784. int short_trust;
  10785. unsigned i;
  10786. if (!conn) {
  10787. return 0;
  10788. }
  10789. short_trust =
  10790. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10791. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10792. if (short_trust) {
  10793. int trust_ret = refresh_trust(conn);
  10794. if (!trust_ret) {
  10795. return trust_ret;
  10796. }
  10797. }
  10798. conn->ssl = SSL_new(s);
  10799. if (conn->ssl == NULL) {
  10800. return 0;
  10801. }
  10802. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10803. if (ret != 1) {
  10804. err = SSL_get_error(conn->ssl, ret);
  10805. (void)err; /* TODO: set some error message */
  10806. SSL_free(conn->ssl);
  10807. conn->ssl = NULL;
  10808. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10809. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10810. #ifndef OPENSSL_API_1_1
  10811. ERR_remove_state(0);
  10812. #endif
  10813. return 0;
  10814. }
  10815. /* SSL functions may fail and require to be called again:
  10816. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10817. * Here "func" could be SSL_connect or SSL_accept. */
  10818. for (i = 16; i <= 1024; i *= 2) {
  10819. ret = func(conn->ssl);
  10820. if (ret != 1) {
  10821. err = SSL_get_error(conn->ssl, ret);
  10822. if ((err == SSL_ERROR_WANT_CONNECT)
  10823. || (err == SSL_ERROR_WANT_ACCEPT)
  10824. || (err == SSL_ERROR_WANT_READ)
  10825. || (err == SSL_ERROR_WANT_WRITE)) {
  10826. /* Need to retry the function call "later".
  10827. * See https://linux.die.net/man/3/ssl_get_error
  10828. * This is typical for non-blocking sockets. */
  10829. if (*stop_server) {
  10830. /* Don't wait if the server is going to be stopped. */
  10831. break;
  10832. }
  10833. mg_sleep(i);
  10834. } else if (err == SSL_ERROR_SYSCALL) {
  10835. /* This is an IO error. Look at errno. */
  10836. err = errno;
  10837. /* TODO: set some error message */
  10838. (void)err;
  10839. break;
  10840. } else {
  10841. /* This is an SSL specific error */
  10842. /* TODO: set some error message */
  10843. break;
  10844. }
  10845. } else {
  10846. /* success */
  10847. break;
  10848. }
  10849. }
  10850. if (ret != 1) {
  10851. SSL_free(conn->ssl);
  10852. conn->ssl = NULL;
  10853. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10854. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10855. #ifndef OPENSSL_API_1_1
  10856. ERR_remove_state(0);
  10857. #endif
  10858. return 0;
  10859. }
  10860. return 1;
  10861. }
  10862. /* Return OpenSSL error message (from CRYPTO lib) */
  10863. static const char *
  10864. ssl_error(void)
  10865. {
  10866. unsigned long err;
  10867. err = ERR_get_error();
  10868. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10869. }
  10870. static int
  10871. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10872. {
  10873. int i;
  10874. const char hexdigit[] = "0123456789abcdef";
  10875. if (memlen <= 0 || buflen <= 0) {
  10876. return 0;
  10877. }
  10878. if (buflen < (3 * memlen)) {
  10879. return 0;
  10880. }
  10881. for (i = 0; i < memlen; i++) {
  10882. if (i > 0) {
  10883. buf[3 * i - 1] = ' ';
  10884. }
  10885. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10886. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10887. }
  10888. buf[3 * memlen - 1] = 0;
  10889. return 1;
  10890. }
  10891. static void
  10892. ssl_get_client_cert_info(struct mg_connection *conn)
  10893. {
  10894. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10895. if (cert) {
  10896. char str_subject[1024];
  10897. char str_issuer[1024];
  10898. char str_finger[1024];
  10899. unsigned char buf[256];
  10900. char *str_serial = NULL;
  10901. unsigned int ulen;
  10902. int ilen;
  10903. unsigned char *tmp_buf;
  10904. unsigned char *tmp_p;
  10905. /* Handle to algorithm used for fingerprint */
  10906. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10907. /* Get Subject and issuer */
  10908. X509_NAME *subj = X509_get_subject_name(cert);
  10909. X509_NAME *iss = X509_get_issuer_name(cert);
  10910. /* Get serial number */
  10911. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10912. /* Translate serial number to a hex string */
  10913. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10914. str_serial = BN_bn2hex(serial_bn);
  10915. BN_free(serial_bn);
  10916. /* Translate subject and issuer to a string */
  10917. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10918. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10919. /* Calculate SHA1 fingerprint and store as a hex string */
  10920. ulen = 0;
  10921. /* ASN1_digest is deprecated. Do the calculation manually,
  10922. * using EVP_Digest. */
  10923. ilen = i2d_X509((void *)cert, NULL);
  10924. tmp_buf =
  10925. (ilen > 0)
  10926. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  10927. : NULL;
  10928. if (tmp_buf) {
  10929. tmp_p = tmp_buf;
  10930. (void)i2d_X509((void *)cert, &tmp_p);
  10931. if (!EVP_Digest(
  10932. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  10933. ulen = 0;
  10934. }
  10935. mg_free(tmp_buf);
  10936. }
  10937. if (!hexdump2string(
  10938. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10939. *str_finger = 0;
  10940. }
  10941. conn->request_info.client_cert =
  10942. (struct client_cert *)mg_malloc_ctx(sizeof(struct client_cert),
  10943. conn->ctx);
  10944. if (conn->request_info.client_cert) {
  10945. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10946. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10947. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10948. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10949. } else {
  10950. /* TODO: write some OOM message */
  10951. }
  10952. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10953. * see https://linux.die.net/man/3/bn_bn2hex */
  10954. OPENSSL_free(str_serial);
  10955. /* Free certificate memory */
  10956. X509_free(cert);
  10957. }
  10958. }
  10959. #ifdef OPENSSL_API_1_1
  10960. #else
  10961. static void
  10962. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10963. {
  10964. (void)line;
  10965. (void)file;
  10966. if (mode & 1) {
  10967. /* 1 is CRYPTO_LOCK */
  10968. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10969. } else {
  10970. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10971. }
  10972. }
  10973. #endif /* OPENSSL_API_1_1 */
  10974. #if !defined(NO_SSL_DL)
  10975. static void *
  10976. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  10977. {
  10978. union {
  10979. void *p;
  10980. void (*fp)(void);
  10981. } u;
  10982. void *dll_handle;
  10983. struct ssl_func *fp;
  10984. int ok;
  10985. int truncated = 0;
  10986. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10987. mg_snprintf(NULL,
  10988. NULL, /* No truncation check for ebuf */
  10989. ebuf,
  10990. ebuf_len,
  10991. "%s: cannot load %s",
  10992. __func__,
  10993. dll_name);
  10994. return NULL;
  10995. }
  10996. ok = 1;
  10997. for (fp = sw; fp->name != NULL; fp++) {
  10998. #ifdef _WIN32
  10999. /* GetProcAddress() returns pointer to function */
  11000. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  11001. #else
  11002. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  11003. * pointers to function pointers. We need to use a union to make a
  11004. * cast. */
  11005. u.p = dlsym(dll_handle, fp->name);
  11006. #endif /* _WIN32 */
  11007. if (u.fp == NULL) {
  11008. if (ok) {
  11009. mg_snprintf(NULL,
  11010. &truncated,
  11011. ebuf,
  11012. ebuf_len,
  11013. "%s: %s: cannot find %s",
  11014. __func__,
  11015. dll_name,
  11016. fp->name);
  11017. ok = 0;
  11018. } else {
  11019. size_t cur_len = strlen(ebuf);
  11020. if (!truncated) {
  11021. mg_snprintf(NULL,
  11022. &truncated,
  11023. ebuf + cur_len,
  11024. ebuf_len - cur_len - 3,
  11025. ", %s",
  11026. fp->name);
  11027. if (truncated) {
  11028. /* If truncated, add "..." */
  11029. strcat(ebuf, "...");
  11030. }
  11031. }
  11032. }
  11033. /* Debug:
  11034. * printf("Missing function: %s\n", fp->name); */
  11035. } else {
  11036. fp->ptr = u.fp;
  11037. }
  11038. }
  11039. if (!ok) {
  11040. (void)dlclose(dll_handle);
  11041. return NULL;
  11042. }
  11043. return dll_handle;
  11044. }
  11045. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  11046. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  11047. #endif /* NO_SSL_DL */
  11048. #if defined(SSL_ALREADY_INITIALIZED)
  11049. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  11050. #else
  11051. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  11052. #endif
  11053. static int
  11054. initialize_ssl(char *ebuf, size_t ebuf_len)
  11055. {
  11056. #ifdef OPENSSL_API_1_1
  11057. if (ebuf_len > 0) {
  11058. ebuf[0] = 0;
  11059. }
  11060. #if !defined(NO_SSL_DL)
  11061. if (!cryptolib_dll_handle) {
  11062. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11063. if (!cryptolib_dll_handle) {
  11064. return 0;
  11065. }
  11066. }
  11067. #endif /* NO_SSL_DL */
  11068. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11069. return 1;
  11070. }
  11071. #else /* not OPENSSL_API_1_1 */
  11072. int i;
  11073. size_t size;
  11074. if (ebuf_len > 0) {
  11075. ebuf[0] = 0;
  11076. }
  11077. #if !defined(NO_SSL_DL)
  11078. if (!cryptolib_dll_handle) {
  11079. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11080. if (!cryptolib_dll_handle) {
  11081. return 0;
  11082. }
  11083. }
  11084. #endif /* NO_SSL_DL */
  11085. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11086. return 1;
  11087. }
  11088. /* Initialize locking callbacks, needed for thread safety.
  11089. * http://www.openssl.org/support/faq.html#PROG1
  11090. */
  11091. i = CRYPTO_num_locks();
  11092. if (i < 0) {
  11093. i = 0;
  11094. }
  11095. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  11096. if (size == 0) {
  11097. ssl_mutexes = NULL;
  11098. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  11099. mg_snprintf(NULL,
  11100. NULL, /* No truncation check for ebuf */
  11101. ebuf,
  11102. ebuf_len,
  11103. "%s: cannot allocate mutexes: %s",
  11104. __func__,
  11105. ssl_error());
  11106. return 0;
  11107. }
  11108. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11109. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  11110. }
  11111. CRYPTO_set_locking_callback(&ssl_locking_callback);
  11112. CRYPTO_set_id_callback(&mg_current_thread_id);
  11113. #endif /* OPENSSL_API_1_1 */
  11114. return 1;
  11115. }
  11116. static int
  11117. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  11118. {
  11119. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  11120. mg_cry(fc(ctx),
  11121. "%s: cannot open certificate file %s: %s",
  11122. __func__,
  11123. pem,
  11124. ssl_error());
  11125. return 0;
  11126. }
  11127. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  11128. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  11129. mg_cry(fc(ctx),
  11130. "%s: cannot open private key file %s: %s",
  11131. __func__,
  11132. pem,
  11133. ssl_error());
  11134. return 0;
  11135. }
  11136. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  11137. mg_cry(fc(ctx),
  11138. "%s: certificate and private key do not match: %s",
  11139. __func__,
  11140. pem);
  11141. return 0;
  11142. }
  11143. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11144. * chain files that contain private keys and certificates in
  11145. * SSL_CTX_use_certificate_chain_file.
  11146. * The CivetWeb-Server used pem-Files that contained both information.
  11147. * In order to make wolfSSL work, it is split in two files.
  11148. * One file that contains key and certificate used by the server and
  11149. * an optional chain file for the ssl stack.
  11150. */
  11151. if (chain) {
  11152. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11153. mg_cry(fc(ctx),
  11154. "%s: cannot use certificate chain file %s: %s",
  11155. __func__,
  11156. pem,
  11157. ssl_error());
  11158. return 0;
  11159. }
  11160. }
  11161. return 1;
  11162. }
  11163. #ifdef OPENSSL_API_1_1
  11164. static unsigned long
  11165. ssl_get_protocol(int version_id)
  11166. {
  11167. long unsigned ret = SSL_OP_ALL;
  11168. if (version_id > 0)
  11169. ret |= SSL_OP_NO_SSLv2;
  11170. if (version_id > 1)
  11171. ret |= SSL_OP_NO_SSLv3;
  11172. if (version_id > 2)
  11173. ret |= SSL_OP_NO_TLSv1;
  11174. if (version_id > 3)
  11175. ret |= SSL_OP_NO_TLSv1_1;
  11176. return ret;
  11177. }
  11178. #else
  11179. static long
  11180. ssl_get_protocol(int version_id)
  11181. {
  11182. long ret = SSL_OP_ALL;
  11183. if (version_id > 0)
  11184. ret |= SSL_OP_NO_SSLv2;
  11185. if (version_id > 1)
  11186. ret |= SSL_OP_NO_SSLv3;
  11187. if (version_id > 2)
  11188. ret |= SSL_OP_NO_TLSv1;
  11189. if (version_id > 3)
  11190. ret |= SSL_OP_NO_TLSv1_1;
  11191. return ret;
  11192. }
  11193. #endif /* OPENSSL_API_1_1 */
  11194. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11195. static int
  11196. set_ssl_option(struct mg_context *ctx)
  11197. {
  11198. const char *pem;
  11199. const char *chain;
  11200. int callback_ret;
  11201. int should_verify_peer;
  11202. int peer_certificate_optional;
  11203. const char *ca_path;
  11204. const char *ca_file;
  11205. int use_default_verify_paths;
  11206. int verify_depth;
  11207. time_t now_rt = time(NULL);
  11208. struct timespec now_mt;
  11209. md5_byte_t ssl_context_id[16];
  11210. md5_state_t md5state;
  11211. int protocol_ver;
  11212. char ebuf[128];
  11213. /* If PEM file is not specified and the init_ssl callback
  11214. * is not specified, skip SSL initialization. */
  11215. if (!ctx) {
  11216. return 0;
  11217. }
  11218. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11219. && ctx->callbacks.init_ssl == NULL) {
  11220. return 1;
  11221. }
  11222. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11223. if (chain == NULL) {
  11224. chain = pem;
  11225. }
  11226. if ((chain != NULL) && (*chain == 0)) {
  11227. chain = NULL;
  11228. }
  11229. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11230. mg_cry(fc(ctx), "%s", ebuf);
  11231. return 0;
  11232. }
  11233. #if !defined(NO_SSL_DL)
  11234. if (!ssllib_dll_handle) {
  11235. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11236. if (!ssllib_dll_handle) {
  11237. mg_cry(fc(ctx), "%s", ebuf);
  11238. return 0;
  11239. }
  11240. }
  11241. #endif /* NO_SSL_DL */
  11242. #ifdef OPENSSL_API_1_1
  11243. /* Initialize SSL library */
  11244. OPENSSL_init_ssl(0, NULL);
  11245. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11246. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11247. NULL);
  11248. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11249. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11250. return 0;
  11251. }
  11252. #else
  11253. /* Initialize SSL library */
  11254. SSL_library_init();
  11255. SSL_load_error_strings();
  11256. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11257. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11258. return 0;
  11259. }
  11260. #endif /* OPENSSL_API_1_1 */
  11261. SSL_CTX_clear_options(ctx->ssl_ctx,
  11262. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11263. | SSL_OP_NO_TLSv1_1);
  11264. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11265. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11266. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11267. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11268. #if !defined(NO_SSL_DL)
  11269. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11270. #endif /* NO_SSL_DL */
  11271. /* If a callback has been specified, call it. */
  11272. callback_ret =
  11273. (ctx->callbacks.init_ssl == NULL)
  11274. ? 0
  11275. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11276. /* If callback returns 0, civetweb sets up the SSL certificate.
  11277. * If it returns 1, civetweb assumes the calback already did this.
  11278. * If it returns -1, initializing ssl fails. */
  11279. if (callback_ret < 0) {
  11280. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11281. return 0;
  11282. }
  11283. if (callback_ret > 0) {
  11284. if (pem != NULL) {
  11285. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11286. }
  11287. return 1;
  11288. }
  11289. /* Use some UID as session context ID. */
  11290. md5_init(&md5state);
  11291. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  11292. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  11293. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  11294. md5_append(&md5state,
  11295. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  11296. strlen(ctx->config[LISTENING_PORTS]));
  11297. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  11298. md5_finish(&md5state, ssl_context_id);
  11299. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  11300. (const unsigned char *)&ssl_context_id,
  11301. sizeof(ssl_context_id));
  11302. if (pem != NULL) {
  11303. if (!ssl_use_pem_file(ctx, pem, chain)) {
  11304. return 0;
  11305. }
  11306. }
  11307. /* Should we support client certificates? */
  11308. /* Default is "no". */
  11309. should_verify_peer = 0;
  11310. peer_certificate_optional = 0;
  11311. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11312. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  11313. /* Yes, they are mandatory */
  11314. should_verify_peer = 1;
  11315. peer_certificate_optional = 0;
  11316. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  11317. == 0) {
  11318. /* Yes, they are optional */
  11319. should_verify_peer = 1;
  11320. peer_certificate_optional = 1;
  11321. }
  11322. }
  11323. use_default_verify_paths =
  11324. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  11325. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  11326. if (should_verify_peer) {
  11327. ca_path = ctx->config[SSL_CA_PATH];
  11328. ca_file = ctx->config[SSL_CA_FILE];
  11329. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  11330. != 1) {
  11331. mg_cry(fc(ctx),
  11332. "SSL_CTX_load_verify_locations error: %s "
  11333. "ssl_verify_peer requires setting "
  11334. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11335. "present in "
  11336. "the .conf file?",
  11337. ssl_error());
  11338. return 0;
  11339. }
  11340. if (peer_certificate_optional) {
  11341. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  11342. } else {
  11343. SSL_CTX_set_verify(ctx->ssl_ctx,
  11344. SSL_VERIFY_PEER
  11345. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11346. NULL);
  11347. }
  11348. if (use_default_verify_paths
  11349. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  11350. mg_cry(fc(ctx),
  11351. "SSL_CTX_set_default_verify_paths error: %s",
  11352. ssl_error());
  11353. return 0;
  11354. }
  11355. if (ctx->config[SSL_VERIFY_DEPTH]) {
  11356. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  11357. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  11358. }
  11359. }
  11360. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  11361. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  11362. != 1) {
  11363. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  11364. }
  11365. }
  11366. return 1;
  11367. }
  11368. static void
  11369. uninitialize_ssl(void)
  11370. {
  11371. #ifdef OPENSSL_API_1_1
  11372. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11373. /* Shutdown according to
  11374. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11375. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11376. */
  11377. CONF_modules_unload(1);
  11378. #else
  11379. int i;
  11380. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11381. /* Shutdown according to
  11382. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11383. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11384. */
  11385. CRYPTO_set_locking_callback(NULL);
  11386. CRYPTO_set_id_callback(NULL);
  11387. ENGINE_cleanup();
  11388. CONF_modules_unload(1);
  11389. ERR_free_strings();
  11390. EVP_cleanup();
  11391. CRYPTO_cleanup_all_ex_data();
  11392. ERR_remove_state(0);
  11393. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11394. pthread_mutex_destroy(&ssl_mutexes[i]);
  11395. }
  11396. mg_free(ssl_mutexes);
  11397. ssl_mutexes = NULL;
  11398. #endif /* OPENSSL_API_1_1 */
  11399. }
  11400. }
  11401. #endif /* !NO_SSL */
  11402. static int
  11403. set_gpass_option(struct mg_context *ctx)
  11404. {
  11405. if (ctx) {
  11406. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11407. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  11408. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  11409. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  11410. return 0;
  11411. }
  11412. return 1;
  11413. }
  11414. return 0;
  11415. }
  11416. static int
  11417. set_acl_option(struct mg_context *ctx)
  11418. {
  11419. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  11420. }
  11421. static void
  11422. reset_per_request_attributes(struct mg_connection *conn)
  11423. {
  11424. if (!conn) {
  11425. return;
  11426. }
  11427. conn->path_info = NULL;
  11428. conn->num_bytes_sent = conn->consumed_content = 0;
  11429. conn->status_code = -1;
  11430. conn->is_chunked = 0;
  11431. conn->must_close = conn->request_len = conn->throttle = 0;
  11432. conn->request_info.content_length = -1;
  11433. conn->request_info.remote_user = NULL;
  11434. conn->request_info.request_method = NULL;
  11435. conn->request_info.request_uri = NULL;
  11436. conn->request_info.local_uri = NULL;
  11437. #if defined(MG_LEGACY_INTERFACE)
  11438. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  11439. * local_uri and request_uri */
  11440. #endif
  11441. conn->request_info.http_version = NULL;
  11442. conn->request_info.num_headers = 0;
  11443. conn->data_len = 0;
  11444. conn->chunk_remainder = 0;
  11445. }
  11446. #if 0
  11447. /* Note: set_sock_timeout is not required for non-blocking sockets.
  11448. * Leave this function here (commented out) for reference until
  11449. * CivetWeb 1.9 is tested, and the tests confirme this function is
  11450. * no longer required.
  11451. */
  11452. static int
  11453. set_sock_timeout(SOCKET sock, int milliseconds)
  11454. {
  11455. int r0 = 0, r1, r2;
  11456. #ifdef _WIN32
  11457. /* Windows specific */
  11458. DWORD tv = (DWORD)milliseconds;
  11459. #else
  11460. /* Linux, ... (not Windows) */
  11461. struct timeval tv;
  11462. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  11463. * max. time waiting for the acknowledged of TCP data before the connection
  11464. * will be forcefully closed and ETIMEDOUT is returned to the application.
  11465. * If this option is not set, the default timeout of 20-30 minutes is used.
  11466. */
  11467. /* #define TCP_USER_TIMEOUT (18) */
  11468. #if defined(TCP_USER_TIMEOUT)
  11469. unsigned int uto = (unsigned int)milliseconds;
  11470. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  11471. #endif
  11472. memset(&tv, 0, sizeof(tv));
  11473. tv.tv_sec = milliseconds / 1000;
  11474. tv.tv_usec = (milliseconds * 1000) % 1000000;
  11475. #endif /* _WIN32 */
  11476. r1 = setsockopt(
  11477. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11478. r2 = setsockopt(
  11479. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11480. return r0 || r1 || r2;
  11481. }
  11482. #endif
  11483. static int
  11484. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11485. {
  11486. if (setsockopt(sock,
  11487. IPPROTO_TCP,
  11488. TCP_NODELAY,
  11489. (SOCK_OPT_TYPE)&nodelay_on,
  11490. sizeof(nodelay_on)) != 0) {
  11491. /* Error */
  11492. return 1;
  11493. }
  11494. /* OK */
  11495. return 0;
  11496. }
  11497. static void
  11498. close_socket_gracefully(struct mg_connection *conn)
  11499. {
  11500. #if defined(_WIN32)
  11501. char buf[MG_BUF_LEN];
  11502. int n;
  11503. #endif
  11504. struct linger linger;
  11505. int error_code = 0;
  11506. int linger_timeout = -2;
  11507. socklen_t opt_len = sizeof(error_code);
  11508. if (!conn) {
  11509. return;
  11510. }
  11511. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  11512. * "Note that enabling a nonzero timeout on a nonblocking socket
  11513. * is not recommended.", so set it to blocking now */
  11514. set_blocking_mode(conn->client.sock, 1);
  11515. /* Send FIN to the client */
  11516. shutdown(conn->client.sock, SHUTDOWN_WR);
  11517. #if defined(_WIN32)
  11518. /* Read and discard pending incoming data. If we do not do that and
  11519. * close
  11520. * the socket, the data in the send buffer may be discarded. This
  11521. * behaviour is seen on Windows, when client keeps sending data
  11522. * when server decides to close the connection; then when client
  11523. * does recv() it gets no data back. */
  11524. do {
  11525. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  11526. } while (n > 0);
  11527. #endif
  11528. if (conn->ctx->config[LINGER_TIMEOUT]) {
  11529. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  11530. }
  11531. /* Set linger option according to configuration */
  11532. if (linger_timeout >= 0) {
  11533. /* Set linger option to avoid socket hanging out after close. This
  11534. * prevent ephemeral port exhaust problem under high QPS. */
  11535. linger.l_onoff = 1;
  11536. #if defined(_MSC_VER)
  11537. #pragma warning(push)
  11538. #pragma warning(disable : 4244)
  11539. #endif
  11540. linger.l_linger = (linger_timeout + 999) / 1000;
  11541. #if defined(_MSC_VER)
  11542. #pragma warning(pop)
  11543. #endif
  11544. } else {
  11545. linger.l_onoff = 0;
  11546. linger.l_linger = 0;
  11547. }
  11548. if (linger_timeout < -1) {
  11549. /* Default: don't configure any linger */
  11550. } else if (getsockopt(conn->client.sock,
  11551. SOL_SOCKET,
  11552. SO_ERROR,
  11553. (char *)&error_code,
  11554. &opt_len) != 0) {
  11555. /* Cannot determine if socket is already closed. This should
  11556. * not occur and never did in a test. Log an error message
  11557. * and continue. */
  11558. mg_cry(conn,
  11559. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  11560. __func__,
  11561. strerror(ERRNO));
  11562. } else if (error_code == ECONNRESET) {
  11563. /* Socket already closed by client/peer, close socket without linger */
  11564. } else {
  11565. /* Set linger timeout */
  11566. if (setsockopt(conn->client.sock,
  11567. SOL_SOCKET,
  11568. SO_LINGER,
  11569. (char *)&linger,
  11570. sizeof(linger)) != 0) {
  11571. mg_cry(conn,
  11572. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  11573. __func__,
  11574. linger.l_onoff,
  11575. linger.l_linger,
  11576. strerror(ERRNO));
  11577. }
  11578. }
  11579. /* Now we know that our FIN is ACK-ed, safe to close */
  11580. closesocket(conn->client.sock);
  11581. conn->client.sock = INVALID_SOCKET;
  11582. }
  11583. static void
  11584. close_connection(struct mg_connection *conn)
  11585. {
  11586. if (!conn || !conn->ctx) {
  11587. return;
  11588. }
  11589. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11590. if (conn->lua_websocket_state) {
  11591. lua_websocket_close(conn, conn->lua_websocket_state);
  11592. conn->lua_websocket_state = NULL;
  11593. }
  11594. #endif
  11595. /* call the connection_close callback if assigned */
  11596. if ((conn->ctx->callbacks.connection_close != NULL)
  11597. && (conn->ctx->context_type == 1)) {
  11598. conn->ctx->callbacks.connection_close(conn);
  11599. }
  11600. mg_lock_connection(conn);
  11601. conn->must_close = 1;
  11602. #ifndef NO_SSL
  11603. if (conn->ssl != NULL) {
  11604. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11605. */
  11606. SSL_shutdown(conn->ssl);
  11607. SSL_free(conn->ssl);
  11608. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11609. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11610. #ifndef OPENSSL_API_1_1
  11611. ERR_remove_state(0);
  11612. #endif
  11613. conn->ssl = NULL;
  11614. }
  11615. #endif
  11616. if (conn->client.sock != INVALID_SOCKET) {
  11617. close_socket_gracefully(conn);
  11618. conn->client.sock = INVALID_SOCKET;
  11619. }
  11620. mg_unlock_connection(conn);
  11621. }
  11622. void
  11623. mg_close_connection(struct mg_connection *conn)
  11624. {
  11625. struct mg_context *client_ctx = NULL;
  11626. if (conn == NULL) {
  11627. return;
  11628. }
  11629. #if defined(USE_WEBSOCKET)
  11630. if (conn->ctx->context_type == 2) {
  11631. unsigned int i;
  11632. /* ws/wss client */
  11633. client_ctx = conn->ctx;
  11634. /* client context: loops must end */
  11635. conn->ctx->stop_flag = 1;
  11636. /* We need to get the client thread out of the select/recv call here. */
  11637. /* Since we use a sleep quantum of some seconds to check for recv
  11638. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11639. /* join worker thread */
  11640. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11641. if (client_ctx->worker_threadids[i] != 0) {
  11642. mg_join_thread(client_ctx->worker_threadids[i]);
  11643. }
  11644. }
  11645. }
  11646. #else
  11647. (void)client_ctx;
  11648. #endif
  11649. close_connection(conn);
  11650. #ifndef NO_SSL
  11651. if (conn->client_ssl_ctx != NULL) {
  11652. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11653. }
  11654. #endif
  11655. if (client_ctx != NULL) {
  11656. /* free context */
  11657. mg_free(client_ctx->worker_threadids);
  11658. mg_free(client_ctx);
  11659. (void)pthread_mutex_destroy(&conn->mutex);
  11660. mg_free(conn);
  11661. } else if (conn->ctx->context_type == 0) { // Client
  11662. mg_free(conn);
  11663. }
  11664. }
  11665. static struct mg_context common_client_context;
  11666. static struct mg_connection *
  11667. mg_connect_client_impl(const struct mg_client_options *client_options,
  11668. int use_ssl,
  11669. char *ebuf,
  11670. size_t ebuf_len)
  11671. {
  11672. struct mg_connection *conn = NULL;
  11673. SOCKET sock;
  11674. union usa sa;
  11675. if (!connect_socket(&common_client_context,
  11676. client_options->host,
  11677. client_options->port,
  11678. use_ssl,
  11679. ebuf,
  11680. ebuf_len,
  11681. &sock,
  11682. &sa)) {
  11683. return NULL;
  11684. }
  11685. if ((conn = (struct mg_connection *)mg_calloc_ctx(
  11686. 1, sizeof(*conn) + MAX_REQUEST_SIZE, &common_client_context))
  11687. == NULL) {
  11688. mg_snprintf(NULL,
  11689. NULL, /* No truncation check for ebuf */
  11690. ebuf,
  11691. ebuf_len,
  11692. "calloc(): %s",
  11693. strerror(ERRNO));
  11694. closesocket(sock);
  11695. return NULL;
  11696. }
  11697. #ifndef NO_SSL
  11698. #ifdef OPENSSL_API_1_1
  11699. if (use_ssl
  11700. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  11701. mg_snprintf(NULL,
  11702. NULL, /* No truncation check for ebuf */
  11703. ebuf,
  11704. ebuf_len,
  11705. "SSL_CTX_new error");
  11706. closesocket(sock);
  11707. mg_free(conn);
  11708. return NULL;
  11709. }
  11710. #else
  11711. if (use_ssl
  11712. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11713. == NULL) {
  11714. mg_snprintf(NULL,
  11715. NULL, /* No truncation check for ebuf */
  11716. ebuf,
  11717. ebuf_len,
  11718. "SSL_CTX_new error");
  11719. closesocket(sock);
  11720. mg_free(conn);
  11721. return NULL;
  11722. }
  11723. #endif /* OPENSSL_API_1_1 */
  11724. #endif /* NO_SSL */
  11725. #ifdef USE_IPV6
  11726. socklen_t len = (sa.sa.sa_family == AF_INET)
  11727. ? sizeof(conn->client.rsa.sin)
  11728. : sizeof(conn->client.rsa.sin6);
  11729. struct sockaddr *psa = (sa.sa.sa_family == AF_INET)
  11730. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11731. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11732. #else
  11733. socklen_t len = sizeof(conn->client.rsa.sin);
  11734. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11735. #endif
  11736. conn->buf_size = MAX_REQUEST_SIZE;
  11737. conn->buf = (char *)(conn + 1);
  11738. conn->ctx = &common_client_context;
  11739. conn->client.sock = sock;
  11740. conn->client.lsa = sa;
  11741. if (getsockname(sock, psa, &len) != 0) {
  11742. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  11743. }
  11744. conn->client.is_ssl = use_ssl ? 1 : 0;
  11745. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11746. #ifndef NO_SSL
  11747. if (use_ssl) {
  11748. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  11749. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11750. * SSL_CTX_set_verify call is needed to switch off server
  11751. * certificate checking, which is off by default in OpenSSL and
  11752. * on in yaSSL. */
  11753. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11754. * SSL_VERIFY_PEER, verify_ssl_server); */
  11755. if (client_options->client_cert) {
  11756. if (!ssl_use_pem_file(&common_client_context,
  11757. client_options->client_cert,
  11758. NULL)) {
  11759. mg_snprintf(NULL,
  11760. NULL, /* No truncation check for ebuf */
  11761. ebuf,
  11762. ebuf_len,
  11763. "Can not use SSL client certificate");
  11764. SSL_CTX_free(conn->client_ssl_ctx);
  11765. closesocket(sock);
  11766. mg_free(conn);
  11767. return NULL;
  11768. }
  11769. }
  11770. if (client_options->server_cert) {
  11771. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11772. client_options->server_cert,
  11773. NULL);
  11774. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11775. } else {
  11776. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11777. }
  11778. if (!sslize(conn,
  11779. conn->client_ssl_ctx,
  11780. SSL_connect,
  11781. &(conn->ctx->stop_flag))) {
  11782. mg_snprintf(NULL,
  11783. NULL, /* No truncation check for ebuf */
  11784. ebuf,
  11785. ebuf_len,
  11786. "SSL connection error");
  11787. SSL_CTX_free(conn->client_ssl_ctx);
  11788. closesocket(sock);
  11789. mg_free(conn);
  11790. return NULL;
  11791. }
  11792. }
  11793. #endif
  11794. set_blocking_mode(sock, 0);
  11795. return conn;
  11796. }
  11797. CIVETWEB_API struct mg_connection *
  11798. mg_connect_client_secure(const struct mg_client_options *client_options,
  11799. char *error_buffer,
  11800. size_t error_buffer_size)
  11801. {
  11802. return mg_connect_client_impl(client_options,
  11803. 1,
  11804. error_buffer,
  11805. error_buffer_size);
  11806. }
  11807. struct mg_connection *
  11808. mg_connect_client(const char *host,
  11809. int port,
  11810. int use_ssl,
  11811. char *error_buffer,
  11812. size_t error_buffer_size)
  11813. {
  11814. struct mg_client_options opts;
  11815. memset(&opts, 0, sizeof(opts));
  11816. opts.host = host;
  11817. opts.port = port;
  11818. return mg_connect_client_impl(&opts,
  11819. use_ssl,
  11820. error_buffer,
  11821. error_buffer_size);
  11822. }
  11823. static const struct {
  11824. const char *proto;
  11825. size_t proto_len;
  11826. unsigned default_port;
  11827. } abs_uri_protocols[] = {{"http://", 7, 80},
  11828. {"https://", 8, 443},
  11829. {"ws://", 5, 80},
  11830. {"wss://", 6, 443},
  11831. {NULL, 0, 0}};
  11832. /* Check if the uri is valid.
  11833. * return 0 for invalid uri,
  11834. * return 1 for *,
  11835. * return 2 for relative uri,
  11836. * return 3 for absolute uri without port,
  11837. * return 4 for absolute uri with port */
  11838. static int
  11839. get_uri_type(const char *uri)
  11840. {
  11841. int i;
  11842. const char *hostend, *portbegin;
  11843. char *portend;
  11844. unsigned long port;
  11845. /* According to the HTTP standard
  11846. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11847. * URI can be an asterisk (*) or should start with slash (relative uri),
  11848. * or it should start with the protocol (absolute uri). */
  11849. if (uri[0] == '*' && uri[1] == '\0') {
  11850. /* asterisk */
  11851. return 1;
  11852. }
  11853. /* Valid URIs according to RFC 3986
  11854. * (https://www.ietf.org/rfc/rfc3986.txt)
  11855. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11856. * and unreserved characters A-Z a-z 0-9 and -._~
  11857. * and % encoded symbols.
  11858. */
  11859. for (i = 0; uri[i] != 0; i++) {
  11860. if (uri[i] < 33) {
  11861. /* control characters and spaces are invalid */
  11862. return 0;
  11863. }
  11864. if (uri[i] > 126) {
  11865. /* non-ascii characters must be % encoded */
  11866. return 0;
  11867. } else {
  11868. switch (uri[i]) {
  11869. case '"': /* 34 */
  11870. case '<': /* 60 */
  11871. case '>': /* 62 */
  11872. case '\\': /* 92 */
  11873. case '^': /* 94 */
  11874. case '`': /* 96 */
  11875. case '{': /* 123 */
  11876. case '|': /* 124 */
  11877. case '}': /* 125 */
  11878. return 0;
  11879. default:
  11880. /* character is ok */
  11881. break;
  11882. }
  11883. }
  11884. }
  11885. /* A relative uri starts with a / character */
  11886. if (uri[0] == '/') {
  11887. /* relative uri */
  11888. return 2;
  11889. }
  11890. /* It could be an absolute uri: */
  11891. /* This function only checks if the uri is valid, not if it is
  11892. * addressing the current server. So civetweb can also be used
  11893. * as a proxy server. */
  11894. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11895. if (mg_strncasecmp(uri,
  11896. abs_uri_protocols[i].proto,
  11897. abs_uri_protocols[i].proto_len) == 0) {
  11898. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11899. if (!hostend) {
  11900. return 0;
  11901. }
  11902. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11903. if (!portbegin) {
  11904. return 3;
  11905. }
  11906. port = strtoul(portbegin + 1, &portend, 10);
  11907. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11908. return 0;
  11909. }
  11910. return 4;
  11911. }
  11912. }
  11913. return 0;
  11914. }
  11915. /* Return NULL or the relative uri at the current server */
  11916. static const char *
  11917. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11918. {
  11919. const char *server_domain;
  11920. size_t server_domain_len;
  11921. size_t request_domain_len = 0;
  11922. unsigned long port = 0;
  11923. int i, auth_domain_check_enabled;
  11924. const char *hostbegin = NULL;
  11925. const char *hostend = NULL;
  11926. const char *portbegin;
  11927. char *portend;
  11928. auth_domain_check_enabled =
  11929. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  11930. if (!auth_domain_check_enabled) {
  11931. return 0;
  11932. }
  11933. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11934. if (!server_domain) {
  11935. return 0;
  11936. }
  11937. server_domain_len = strlen(server_domain);
  11938. if (!server_domain_len) {
  11939. return 0;
  11940. }
  11941. /* DNS is case insensitive, so use case insensitive string compare here
  11942. */
  11943. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11944. if (mg_strncasecmp(uri,
  11945. abs_uri_protocols[i].proto,
  11946. abs_uri_protocols[i].proto_len) == 0) {
  11947. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11948. hostend = strchr(hostbegin, '/');
  11949. if (!hostend) {
  11950. return 0;
  11951. }
  11952. portbegin = strchr(hostbegin, ':');
  11953. if ((!portbegin) || (portbegin > hostend)) {
  11954. port = abs_uri_protocols[i].default_port;
  11955. request_domain_len = (size_t)(hostend - hostbegin);
  11956. } else {
  11957. port = strtoul(portbegin + 1, &portend, 10);
  11958. if ((portend != hostend) || (port <= 0)
  11959. || !is_valid_port(port)) {
  11960. return 0;
  11961. }
  11962. request_domain_len = (size_t)(portbegin - hostbegin);
  11963. }
  11964. /* protocol found, port set */
  11965. break;
  11966. }
  11967. }
  11968. if (!port) {
  11969. /* port remains 0 if the protocol is not found */
  11970. return 0;
  11971. }
  11972. /* Check if the request is directed to a different server. */
  11973. /* First check if the port is the same (IPv4 and IPv6). */
  11974. #if defined(USE_IPV6)
  11975. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11976. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11977. /* Request is directed to a different port */
  11978. return 0;
  11979. }
  11980. } else
  11981. #endif
  11982. {
  11983. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11984. /* Request is directed to a different port */
  11985. return 0;
  11986. }
  11987. }
  11988. /* Finally check if the server corresponds to the authentication
  11989. * domain of the server (the server domain).
  11990. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11991. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11992. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11993. * or http://mydomain.com.fake/path/file.ext).
  11994. */
  11995. if (auth_domain_check_enabled) {
  11996. if ((request_domain_len == server_domain_len)
  11997. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11998. /* Request is directed to this server - full name match. */
  11999. } else {
  12000. if (request_domain_len < (server_domain_len + 2)) {
  12001. /* Request is directed to another server: The server name is
  12002. * longer
  12003. * than
  12004. * the request name. Drop this case here to avoid overflows in
  12005. * the
  12006. * following checks. */
  12007. return 0;
  12008. }
  12009. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  12010. /* Request is directed to another server: It could be a
  12011. * substring
  12012. * like notmyserver.com */
  12013. return 0;
  12014. }
  12015. if (0 != memcmp(server_domain,
  12016. hostbegin + request_domain_len - server_domain_len,
  12017. server_domain_len)) {
  12018. /* Request is directed to another server:
  12019. * The server name is different. */
  12020. return 0;
  12021. }
  12022. }
  12023. }
  12024. return hostend;
  12025. }
  12026. static int
  12027. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12028. {
  12029. const char *cl;
  12030. if (ebuf_len > 0) {
  12031. ebuf[0] = '\0';
  12032. }
  12033. *err = 0;
  12034. reset_per_request_attributes(conn);
  12035. if (!conn) {
  12036. mg_snprintf(conn,
  12037. NULL, /* No truncation check for ebuf */
  12038. ebuf,
  12039. ebuf_len,
  12040. "%s",
  12041. "Internal error");
  12042. *err = 500;
  12043. return 0;
  12044. }
  12045. /* Set the time the request was received. This value should be used for
  12046. * timeouts. */
  12047. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  12048. conn->request_len =
  12049. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  12050. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  12051. */
  12052. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  12053. mg_snprintf(conn,
  12054. NULL, /* No truncation check for ebuf */
  12055. ebuf,
  12056. ebuf_len,
  12057. "%s",
  12058. "Invalid request size");
  12059. *err = 500;
  12060. return 0;
  12061. }
  12062. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  12063. mg_snprintf(conn,
  12064. NULL, /* No truncation check for ebuf */
  12065. ebuf,
  12066. ebuf_len,
  12067. "%s",
  12068. "Request Too Large");
  12069. *err = 413;
  12070. return 0;
  12071. } else if (conn->request_len <= 0) {
  12072. if (conn->data_len > 0) {
  12073. mg_snprintf(conn,
  12074. NULL, /* No truncation check for ebuf */
  12075. ebuf,
  12076. ebuf_len,
  12077. "%s",
  12078. "Client sent malformed request");
  12079. *err = 400;
  12080. } else {
  12081. /* Server did not recv anything -> just close the connection */
  12082. conn->must_close = 1;
  12083. mg_snprintf(conn,
  12084. NULL, /* No truncation check for ebuf */
  12085. ebuf,
  12086. ebuf_len,
  12087. "%s",
  12088. "Client did not send a request");
  12089. *err = 0;
  12090. }
  12091. return 0;
  12092. } else if (parse_http_message(conn->buf,
  12093. conn->buf_size,
  12094. &conn->request_info) <= 0) {
  12095. mg_snprintf(conn,
  12096. NULL, /* No truncation check for ebuf */
  12097. ebuf,
  12098. ebuf_len,
  12099. "%s",
  12100. "Bad Request");
  12101. *err = 400;
  12102. return 0;
  12103. } else {
  12104. /* Message is a valid request or response */
  12105. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  12106. /* Request/response has content length set */
  12107. char *endptr = NULL;
  12108. conn->content_len = strtoll(cl, &endptr, 10);
  12109. if (endptr == cl) {
  12110. mg_snprintf(conn,
  12111. NULL, /* No truncation check for ebuf */
  12112. ebuf,
  12113. ebuf_len,
  12114. "%s",
  12115. "Bad Request");
  12116. *err = 411;
  12117. return 0;
  12118. }
  12119. /* Publish the content length back to the request info. */
  12120. conn->request_info.content_length = conn->content_len;
  12121. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  12122. != NULL
  12123. && !mg_strcasecmp(cl, "chunked")) {
  12124. conn->is_chunked = 1;
  12125. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  12126. || !mg_strcasecmp(conn->request_info.request_method,
  12127. "PUT")) {
  12128. /* POST or PUT request without content length set */
  12129. conn->content_len = -1;
  12130. } else if (!mg_strncasecmp(conn->request_info.request_method,
  12131. "HTTP/",
  12132. 5)) {
  12133. /* Response without content length set */
  12134. conn->content_len = -1;
  12135. } else {
  12136. /* Other request */
  12137. conn->content_len = 0;
  12138. }
  12139. }
  12140. return 1;
  12141. }
  12142. int
  12143. mg_get_response(struct mg_connection *conn,
  12144. char *ebuf,
  12145. size_t ebuf_len,
  12146. int timeout)
  12147. {
  12148. if (conn) {
  12149. /* Implementation of API function for HTTP clients */
  12150. int err, ret;
  12151. struct mg_context *octx = conn->ctx;
  12152. struct mg_context rctx = *(conn->ctx);
  12153. char txt[32]; /* will not overflow */
  12154. if (timeout >= 0) {
  12155. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  12156. rctx.config[REQUEST_TIMEOUT] = txt;
  12157. /* Not required for non-blocking sockets.
  12158. set_sock_timeout(conn->client.sock, timeout);
  12159. */
  12160. } else {
  12161. rctx.config[REQUEST_TIMEOUT] = NULL;
  12162. }
  12163. conn->ctx = &rctx;
  12164. ret = getreq(conn, ebuf, ebuf_len, &err);
  12165. conn->ctx = octx;
  12166. #if defined(MG_LEGACY_INTERFACE)
  12167. /* TODO: 1) uri is deprecated;
  12168. * 2) here, ri.uri is the http response code */
  12169. conn->request_info.uri = conn->request_info.request_uri;
  12170. #endif
  12171. conn->request_info.local_uri = conn->request_info.request_uri;
  12172. /* TODO (mid): Define proper return values - maybe return length?
  12173. * For the first test use <0 for error and >0 for OK */
  12174. return (ret == 0) ? -1 : +1;
  12175. }
  12176. return -1;
  12177. }
  12178. struct mg_connection *
  12179. mg_download(const char *host,
  12180. int port,
  12181. int use_ssl,
  12182. char *ebuf,
  12183. size_t ebuf_len,
  12184. const char *fmt,
  12185. ...)
  12186. {
  12187. struct mg_connection *conn;
  12188. va_list ap;
  12189. int i;
  12190. int reqerr;
  12191. va_start(ap, fmt);
  12192. ebuf[0] = '\0';
  12193. /* open a connection */
  12194. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  12195. if (conn != NULL) {
  12196. i = mg_vprintf(conn, fmt, ap);
  12197. if (i <= 0) {
  12198. mg_snprintf(conn,
  12199. NULL, /* No truncation check for ebuf */
  12200. ebuf,
  12201. ebuf_len,
  12202. "%s",
  12203. "Error sending request");
  12204. } else {
  12205. getreq(conn, ebuf, ebuf_len, &reqerr);
  12206. #if defined(MG_LEGACY_INTERFACE)
  12207. /* TODO: 1) uri is deprecated;
  12208. * 2) here, ri.uri is the http response code */
  12209. conn->request_info.uri = conn->request_info.request_uri;
  12210. #endif
  12211. conn->request_info.local_uri = conn->request_info.request_uri;
  12212. }
  12213. }
  12214. /* if an error occured, close the connection */
  12215. if (ebuf[0] != '\0' && conn != NULL) {
  12216. mg_close_connection(conn);
  12217. conn = NULL;
  12218. }
  12219. va_end(ap);
  12220. return conn;
  12221. }
  12222. struct websocket_client_thread_data {
  12223. struct mg_connection *conn;
  12224. mg_websocket_data_handler data_handler;
  12225. mg_websocket_close_handler close_handler;
  12226. void *callback_data;
  12227. };
  12228. #if defined(USE_WEBSOCKET)
  12229. #ifdef _WIN32
  12230. static unsigned __stdcall websocket_client_thread(void *data)
  12231. #else
  12232. static void *
  12233. websocket_client_thread(void *data)
  12234. #endif
  12235. {
  12236. struct websocket_client_thread_data *cdata =
  12237. (struct websocket_client_thread_data *)data;
  12238. mg_set_thread_name("ws-clnt");
  12239. if (cdata->conn->ctx) {
  12240. if (cdata->conn->ctx->callbacks.init_thread) {
  12241. /* 3 indicates a websocket client thread */
  12242. /* TODO: check if conn->ctx can be set */
  12243. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  12244. }
  12245. }
  12246. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  12247. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  12248. if (cdata->close_handler != NULL) {
  12249. cdata->close_handler(cdata->conn, cdata->callback_data);
  12250. }
  12251. /* The websocket_client context has only this thread. If it runs out,
  12252. set the stop_flag to 2 (= "stopped"). */
  12253. cdata->conn->ctx->stop_flag = 2;
  12254. mg_free((void *)cdata);
  12255. #ifdef _WIN32
  12256. return 0;
  12257. #else
  12258. return NULL;
  12259. #endif
  12260. }
  12261. #endif
  12262. struct mg_connection *
  12263. mg_connect_websocket_client(const char *host,
  12264. int port,
  12265. int use_ssl,
  12266. char *error_buffer,
  12267. size_t error_buffer_size,
  12268. const char *path,
  12269. const char *origin,
  12270. mg_websocket_data_handler data_func,
  12271. mg_websocket_close_handler close_func,
  12272. void *user_data)
  12273. {
  12274. struct mg_connection *conn = NULL;
  12275. #if defined(USE_WEBSOCKET)
  12276. struct mg_context *newctx = NULL;
  12277. struct websocket_client_thread_data *thread_data;
  12278. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  12279. static const char *handshake_req;
  12280. if (origin != NULL) {
  12281. handshake_req = "GET %s HTTP/1.1\r\n"
  12282. "Host: %s\r\n"
  12283. "Upgrade: websocket\r\n"
  12284. "Connection: Upgrade\r\n"
  12285. "Sec-WebSocket-Key: %s\r\n"
  12286. "Sec-WebSocket-Version: 13\r\n"
  12287. "Origin: %s\r\n"
  12288. "\r\n";
  12289. } else {
  12290. handshake_req = "GET %s HTTP/1.1\r\n"
  12291. "Host: %s\r\n"
  12292. "Upgrade: websocket\r\n"
  12293. "Connection: Upgrade\r\n"
  12294. "Sec-WebSocket-Key: %s\r\n"
  12295. "Sec-WebSocket-Version: 13\r\n"
  12296. "\r\n";
  12297. }
  12298. /* Establish the client connection and request upgrade */
  12299. conn = mg_download(host,
  12300. port,
  12301. use_ssl,
  12302. error_buffer,
  12303. error_buffer_size,
  12304. handshake_req,
  12305. path,
  12306. host,
  12307. magic,
  12308. origin);
  12309. /* Connection object will be null if something goes wrong */
  12310. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  12311. if (!*error_buffer) {
  12312. /* if there is a connection, but it did not return 101,
  12313. * error_buffer is not yet set */
  12314. mg_snprintf(conn,
  12315. NULL, /* No truncation check for ebuf */
  12316. error_buffer,
  12317. error_buffer_size,
  12318. "Unexpected server reply");
  12319. }
  12320. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  12321. if (conn != NULL) {
  12322. mg_free(conn);
  12323. conn = NULL;
  12324. }
  12325. return conn;
  12326. }
  12327. /* For client connections, mg_context is fake. Since we need to set a
  12328. * callback function, we need to create a copy and modify it. */
  12329. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  12330. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  12331. newctx->user_data = user_data;
  12332. newctx->context_type = 2; /* ws/wss client context type */
  12333. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  12334. newctx->worker_threadids =
  12335. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  12336. sizeof(pthread_t),
  12337. newctx);
  12338. conn->ctx = newctx;
  12339. thread_data = (struct websocket_client_thread_data *)
  12340. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  12341. thread_data->conn = conn;
  12342. thread_data->data_handler = data_func;
  12343. thread_data->close_handler = close_func;
  12344. thread_data->callback_data = user_data;
  12345. /* Start a thread to read the websocket client connection
  12346. * This thread will automatically stop when mg_disconnect is
  12347. * called on the client connection */
  12348. if (mg_start_thread_with_id(websocket_client_thread,
  12349. (void *)thread_data,
  12350. newctx->worker_threadids) != 0) {
  12351. mg_free((void *)thread_data);
  12352. mg_free((void *)newctx->worker_threadids);
  12353. mg_free((void *)newctx);
  12354. mg_free((void *)conn);
  12355. conn = NULL;
  12356. DEBUG_TRACE("%s",
  12357. "Websocket client connect thread could not be started\r\n");
  12358. }
  12359. #else
  12360. /* Appease "unused parameter" warnings */
  12361. (void)host;
  12362. (void)port;
  12363. (void)use_ssl;
  12364. (void)error_buffer;
  12365. (void)error_buffer_size;
  12366. (void)path;
  12367. (void)origin;
  12368. (void)user_data;
  12369. (void)data_func;
  12370. (void)close_func;
  12371. #endif
  12372. return conn;
  12373. }
  12374. static void
  12375. process_new_connection(struct mg_connection *conn)
  12376. {
  12377. if (conn && conn->ctx) {
  12378. struct mg_request_info *ri = &conn->request_info;
  12379. int keep_alive_enabled, keep_alive, discard_len;
  12380. char ebuf[100];
  12381. const char *hostend;
  12382. int reqerr, uri_type;
  12383. #if defined(USE_SERVER_STATS)
  12384. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  12385. mg_atomic_add(&(conn->ctx->total_connections), 1);
  12386. if (mcon > (conn->ctx->max_connections)) {
  12387. /* could use atomic compare exchange, but this
  12388. * seems overkill for statistics data */
  12389. conn->ctx->max_connections = mcon;
  12390. }
  12391. #endif
  12392. keep_alive_enabled =
  12393. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  12394. /* Important: on new connection, reset the receiving buffer. Credit
  12395. * goes to crule42. */
  12396. conn->data_len = 0;
  12397. conn->handled_requests = 0;
  12398. do {
  12399. DEBUG_TRACE("calling getreq (%i times for this connection)",
  12400. conn->handled_requests + 1);
  12401. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  12402. /* The request sent by the client could not be understood by
  12403. * the server, or it was incomplete or a timeout. Send an
  12404. * error message and close the connection. */
  12405. if (reqerr > 0) {
  12406. /*assert(ebuf[0] != '\0');*/
  12407. mg_send_http_error(conn, reqerr, "%s", ebuf);
  12408. }
  12409. } else if (strcmp(ri->http_version, "1.0")
  12410. && strcmp(ri->http_version, "1.1")) {
  12411. mg_snprintf(conn,
  12412. NULL, /* No truncation check for ebuf */
  12413. ebuf,
  12414. sizeof(ebuf),
  12415. "Bad HTTP version: [%s]",
  12416. ri->http_version);
  12417. mg_send_http_error(conn, 505, "%s", ebuf);
  12418. }
  12419. if (ebuf[0] == '\0') {
  12420. uri_type = get_uri_type(conn->request_info.request_uri);
  12421. switch (uri_type) {
  12422. case 1:
  12423. /* Asterisk */
  12424. conn->request_info.local_uri = NULL;
  12425. break;
  12426. case 2:
  12427. /* relative uri */
  12428. conn->request_info.local_uri =
  12429. conn->request_info.request_uri;
  12430. break;
  12431. case 3:
  12432. case 4:
  12433. /* absolute uri (with/without port) */
  12434. hostend = get_rel_url_at_current_server(
  12435. conn->request_info.request_uri, conn);
  12436. if (hostend) {
  12437. conn->request_info.local_uri = hostend;
  12438. } else {
  12439. conn->request_info.local_uri = NULL;
  12440. }
  12441. break;
  12442. default:
  12443. mg_snprintf(conn,
  12444. NULL, /* No truncation check for ebuf */
  12445. ebuf,
  12446. sizeof(ebuf),
  12447. "Invalid URI");
  12448. mg_send_http_error(conn, 400, "%s", ebuf);
  12449. conn->request_info.local_uri = NULL;
  12450. break;
  12451. }
  12452. #if defined(MG_LEGACY_INTERFACE)
  12453. /* TODO: cleanup uri, local_uri and request_uri */
  12454. conn->request_info.uri = conn->request_info.local_uri;
  12455. #endif
  12456. }
  12457. DEBUG_TRACE("http: %s, error: %s",
  12458. (ri->http_version ? ri->http_version : "none"),
  12459. (ebuf[0] ? ebuf : "none"));
  12460. if (ebuf[0] == '\0') {
  12461. if (conn->request_info.local_uri) {
  12462. /* handle request to local server */
  12463. handle_request(conn);
  12464. DEBUG_TRACE("%s", "handle_request done");
  12465. if (conn->ctx->callbacks.end_request != NULL) {
  12466. conn->ctx->callbacks.end_request(conn,
  12467. conn->status_code);
  12468. DEBUG_TRACE("%s", "end_request callback done");
  12469. }
  12470. log_access(conn);
  12471. } else {
  12472. /* TODO: handle non-local request (PROXY) */
  12473. conn->must_close = 1;
  12474. }
  12475. } else {
  12476. conn->must_close = 1;
  12477. }
  12478. if (ri->remote_user != NULL) {
  12479. mg_free((void *)ri->remote_user);
  12480. /* Important! When having connections with and without auth
  12481. * would cause double free and then crash */
  12482. ri->remote_user = NULL;
  12483. }
  12484. /* NOTE(lsm): order is important here. should_keep_alive() call
  12485. * is
  12486. * using parsed request, which will be invalid after memmove's
  12487. * below.
  12488. * Therefore, memorize should_keep_alive() result now for later
  12489. * use
  12490. * in loop exit condition. */
  12491. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  12492. && (conn->content_len >= 0) && should_keep_alive(conn);
  12493. /* Discard all buffered data for this request */
  12494. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  12495. && ((conn->request_len + conn->content_len)
  12496. < (int64_t)conn->data_len))
  12497. ? (int)(conn->request_len + conn->content_len)
  12498. : conn->data_len;
  12499. /*assert(discard_len >= 0);*/
  12500. if (discard_len < 0) {
  12501. DEBUG_TRACE("internal error: discard_len = %li",
  12502. (long int)discard_len);
  12503. break;
  12504. }
  12505. conn->data_len -= discard_len;
  12506. if (conn->data_len > 0) {
  12507. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  12508. memmove(conn->buf,
  12509. conn->buf + discard_len,
  12510. (size_t)conn->data_len);
  12511. }
  12512. /* assert(conn->data_len >= 0); */
  12513. /* assert(conn->data_len <= conn->buf_size); */
  12514. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  12515. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  12516. (long int)conn->data_len,
  12517. (long int)conn->buf_size);
  12518. break;
  12519. }
  12520. conn->handled_requests++;
  12521. } while (keep_alive);
  12522. #if defined(USE_SERVER_STATS)
  12523. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  12524. mg_atomic_dec(&(conn->ctx->active_connections));
  12525. #endif
  12526. }
  12527. }
  12528. #if defined(ALTERNATIVE_QUEUE)
  12529. static void
  12530. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12531. {
  12532. unsigned int i;
  12533. for (;;) {
  12534. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12535. /* find a free worker slot and signal it */
  12536. if (ctx->client_socks[i].in_use == 0) {
  12537. ctx->client_socks[i] = *sp;
  12538. ctx->client_socks[i].in_use = 1;
  12539. event_signal(ctx->client_wait_events[i]);
  12540. return;
  12541. }
  12542. }
  12543. /* queue is full */
  12544. mg_sleep(1);
  12545. }
  12546. }
  12547. static int
  12548. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12549. {
  12550. DEBUG_TRACE("%s", "going idle");
  12551. ctx->client_socks[thread_index].in_use = 0;
  12552. event_wait(ctx->client_wait_events[thread_index]);
  12553. *sp = ctx->client_socks[thread_index];
  12554. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12555. return !ctx->stop_flag;
  12556. }
  12557. #else /* ALTERNATIVE_QUEUE */
  12558. /* Worker threads take accepted socket from the queue */
  12559. static int
  12560. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12561. {
  12562. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12563. (void)thread_index;
  12564. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12565. DEBUG_TRACE("%s", "going idle");
  12566. /* If the queue is empty, wait. We're idle at this point. */
  12567. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  12568. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  12569. }
  12570. /* If we're stopping, sq_head may be equal to sq_tail. */
  12571. if (ctx->sq_head > ctx->sq_tail) {
  12572. /* Copy socket from the queue and increment tail */
  12573. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  12574. ctx->sq_tail++;
  12575. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12576. /* Wrap pointers if needed */
  12577. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  12578. ctx->sq_tail -= QUEUE_SIZE(ctx);
  12579. ctx->sq_head -= QUEUE_SIZE(ctx);
  12580. }
  12581. }
  12582. (void)pthread_cond_signal(&ctx->sq_empty);
  12583. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12584. return !ctx->stop_flag;
  12585. #undef QUEUE_SIZE
  12586. }
  12587. /* Master thread adds accepted socket to a queue */
  12588. static void
  12589. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12590. {
  12591. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12592. if (!ctx) {
  12593. return;
  12594. }
  12595. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12596. /* If the queue is full, wait */
  12597. while (ctx->stop_flag == 0
  12598. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  12599. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  12600. }
  12601. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  12602. /* Copy socket to the queue and increment head */
  12603. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  12604. ctx->sq_head++;
  12605. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12606. }
  12607. (void)pthread_cond_signal(&ctx->sq_full);
  12608. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12609. #undef QUEUE_SIZE
  12610. }
  12611. #endif /* ALTERNATIVE_QUEUE */
  12612. struct worker_thread_args {
  12613. struct mg_context *ctx;
  12614. int index;
  12615. };
  12616. static void *
  12617. worker_thread_run(struct worker_thread_args *thread_args)
  12618. {
  12619. struct mg_context *ctx = thread_args->ctx;
  12620. struct mg_connection *conn;
  12621. struct mg_workerTLS tls;
  12622. #if defined(MG_LEGACY_INTERFACE)
  12623. uint32_t addr;
  12624. #endif
  12625. mg_set_thread_name("worker");
  12626. tls.is_master = 0;
  12627. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12628. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12629. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12630. #endif
  12631. /* Initialize thread local storage before calling any callback */
  12632. pthread_setspecific(sTlsKey, &tls);
  12633. if (ctx->callbacks.init_thread) {
  12634. /* call init_thread for a worker thread (type 1) */
  12635. ctx->callbacks.init_thread(ctx, 1);
  12636. }
  12637. /* Connection structure has been pre-allocated */
  12638. if (((int)thread_args->index < 0)
  12639. || ((unsigned)thread_args->index
  12640. >= (unsigned)ctx->cfg_worker_threads)) {
  12641. mg_cry(fc(ctx),
  12642. "Internal error: Invalid worker index %i",
  12643. (int)thread_args->index);
  12644. return NULL;
  12645. }
  12646. conn = ctx->worker_connections + thread_args->index;
  12647. /* Request buffers are not pre-allocated. They are private to the
  12648. * request and do not contain any state information that might be
  12649. * of interest to anyone observing a server status. */
  12650. conn->buf = (char *)mg_malloc_ctx(MAX_REQUEST_SIZE, conn->ctx);
  12651. if (conn->buf == NULL) {
  12652. mg_cry(fc(ctx),
  12653. "Out of memory: Cannot allocate buffer for worker %i",
  12654. (int)thread_args->index);
  12655. return NULL;
  12656. }
  12657. conn->buf_size = MAX_REQUEST_SIZE;
  12658. conn->ctx = ctx;
  12659. conn->thread_index = thread_args->index;
  12660. conn->request_info.user_data = ctx->user_data;
  12661. /* Allocate a mutex for this connection to allow communication both
  12662. * within the request handler and from elsewhere in the application
  12663. */
  12664. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12665. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12666. * signal sq_empty condvar to wake up the master waiting in
  12667. * produce_socket() */
  12668. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12669. conn->conn_birth_time = time(NULL);
  12670. /* Fill in IP, port info early so even if SSL setup below fails,
  12671. * error handler would have the corresponding info.
  12672. * Thanks to Johannes Winkelmann for the patch.
  12673. */
  12674. #if defined(USE_IPV6)
  12675. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12676. conn->request_info.remote_port =
  12677. ntohs(conn->client.rsa.sin6.sin6_port);
  12678. } else
  12679. #endif
  12680. {
  12681. conn->request_info.remote_port =
  12682. ntohs(conn->client.rsa.sin.sin_port);
  12683. }
  12684. sockaddr_to_string(conn->request_info.remote_addr,
  12685. sizeof(conn->request_info.remote_addr),
  12686. &conn->client.rsa);
  12687. DEBUG_TRACE("Start processing connection from %s",
  12688. conn->request_info.remote_addr);
  12689. #if defined(MG_LEGACY_INTERFACE)
  12690. /* This legacy interface only works for the IPv4 case */
  12691. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12692. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12693. #endif
  12694. conn->request_info.is_ssl = conn->client.is_ssl;
  12695. if (conn->client.is_ssl) {
  12696. #ifndef NO_SSL
  12697. /* HTTPS connection */
  12698. if (sslize(conn,
  12699. conn->ctx->ssl_ctx,
  12700. SSL_accept,
  12701. &(conn->ctx->stop_flag))) {
  12702. /* Get SSL client certificate information (if set) */
  12703. ssl_get_client_cert_info(conn);
  12704. /* process HTTPS connection */
  12705. process_new_connection(conn);
  12706. /* Free client certificate info */
  12707. if (conn->request_info.client_cert) {
  12708. mg_free((void *)(conn->request_info.client_cert->subject));
  12709. mg_free((void *)(conn->request_info.client_cert->issuer));
  12710. mg_free((void *)(conn->request_info.client_cert->serial));
  12711. mg_free((void *)(conn->request_info.client_cert->finger));
  12712. conn->request_info.client_cert->subject = 0;
  12713. conn->request_info.client_cert->issuer = 0;
  12714. conn->request_info.client_cert->serial = 0;
  12715. conn->request_info.client_cert->finger = 0;
  12716. mg_free(conn->request_info.client_cert);
  12717. conn->request_info.client_cert = 0;
  12718. }
  12719. }
  12720. #endif
  12721. } else {
  12722. /* process HTTP connection */
  12723. process_new_connection(conn);
  12724. }
  12725. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12726. conn->request_info.remote_addr,
  12727. difftime(time(NULL), conn->conn_birth_time));
  12728. close_connection(conn);
  12729. DEBUG_TRACE("%s", "Connection closed");
  12730. }
  12731. pthread_setspecific(sTlsKey, NULL);
  12732. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12733. CloseHandle(tls.pthread_cond_helper_mutex);
  12734. #endif
  12735. pthread_mutex_destroy(&conn->mutex);
  12736. /* Free the request buffer. */
  12737. conn->buf_size = 0;
  12738. mg_free(conn->buf);
  12739. conn->buf = NULL;
  12740. DEBUG_TRACE("%s", "exiting");
  12741. return NULL;
  12742. }
  12743. /* Threads have different return types on Windows and Unix. */
  12744. #ifdef _WIN32
  12745. static unsigned __stdcall worker_thread(void *thread_func_param)
  12746. {
  12747. struct worker_thread_args *pwta =
  12748. (struct worker_thread_args *)thread_func_param;
  12749. worker_thread_run(pwta);
  12750. mg_free(thread_func_param);
  12751. return 0;
  12752. }
  12753. #else
  12754. static void *
  12755. worker_thread(void *thread_func_param)
  12756. {
  12757. struct worker_thread_args *pwta =
  12758. (struct worker_thread_args *)thread_func_param;
  12759. worker_thread_run(pwta);
  12760. mg_free(thread_func_param);
  12761. return NULL;
  12762. }
  12763. #endif /* _WIN32 */
  12764. static void
  12765. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12766. {
  12767. struct socket so;
  12768. char src_addr[IP_ADDR_STR_LEN];
  12769. socklen_t len = sizeof(so.rsa);
  12770. int on = 1;
  12771. if (!listener) {
  12772. return;
  12773. }
  12774. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12775. == INVALID_SOCKET) {
  12776. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12777. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12778. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12779. closesocket(so.sock);
  12780. so.sock = INVALID_SOCKET;
  12781. } else {
  12782. /* Put so socket structure into the queue */
  12783. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12784. set_close_on_exec(so.sock, fc(ctx));
  12785. so.is_ssl = listener->is_ssl;
  12786. so.ssl_redir = listener->ssl_redir;
  12787. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12788. mg_cry(fc(ctx),
  12789. "%s: getsockname() failed: %s",
  12790. __func__,
  12791. strerror(ERRNO));
  12792. }
  12793. /* Set TCP keep-alive. This is needed because if HTTP-level
  12794. * keep-alive
  12795. * is enabled, and client resets the connection, server won't get
  12796. * TCP FIN or RST and will keep the connection open forever. With
  12797. * TCP keep-alive, next keep-alive handshake will figure out that
  12798. * the client is down and will close the server end.
  12799. * Thanks to Igor Klopov who suggested the patch. */
  12800. if (setsockopt(so.sock,
  12801. SOL_SOCKET,
  12802. SO_KEEPALIVE,
  12803. (SOCK_OPT_TYPE)&on,
  12804. sizeof(on)) != 0) {
  12805. mg_cry(fc(ctx),
  12806. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12807. __func__,
  12808. strerror(ERRNO));
  12809. }
  12810. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12811. * to effectively fill up the underlying IP packet payload and
  12812. * reduce the overhead of sending lots of small buffers. However
  12813. * this hurts the server's throughput (ie. operations per second)
  12814. * when HTTP 1.1 persistent connections are used and the responses
  12815. * are relatively small (eg. less than 1400 bytes).
  12816. */
  12817. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12818. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12819. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12820. mg_cry(fc(ctx),
  12821. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12822. __func__,
  12823. strerror(ERRNO));
  12824. }
  12825. }
  12826. /* We are using non-blocking sockets. Thus, the
  12827. * set_sock_timeout(so.sock, timeout);
  12828. * call is no longer required. */
  12829. set_blocking_mode(so.sock, 0);
  12830. produce_socket(ctx, &so);
  12831. }
  12832. }
  12833. static void
  12834. master_thread_run(void *thread_func_param)
  12835. {
  12836. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12837. struct mg_workerTLS tls;
  12838. struct pollfd *pfd;
  12839. unsigned int i;
  12840. unsigned int workerthreadcount;
  12841. if (!ctx) {
  12842. return;
  12843. }
  12844. mg_set_thread_name("master");
  12845. /* Increase priority of the master thread */
  12846. #if defined(_WIN32)
  12847. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12848. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12849. int min_prio = sched_get_priority_min(SCHED_RR);
  12850. int max_prio = sched_get_priority_max(SCHED_RR);
  12851. if ((min_prio >= 0) && (max_prio >= 0)
  12852. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12853. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12854. struct sched_param sched_param = {0};
  12855. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12856. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12857. }
  12858. #endif
  12859. /* Initialize thread local storage */
  12860. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12861. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12862. #endif
  12863. tls.is_master = 1;
  12864. pthread_setspecific(sTlsKey, &tls);
  12865. if (ctx->callbacks.init_thread) {
  12866. /* Callback for the master thread (type 0) */
  12867. ctx->callbacks.init_thread(ctx, 0);
  12868. }
  12869. /* Server starts *now* */
  12870. ctx->start_time = time(NULL);
  12871. /* Start the server */
  12872. pfd = ctx->listening_socket_fds;
  12873. while (ctx->stop_flag == 0) {
  12874. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12875. pfd[i].fd = ctx->listening_sockets[i].sock;
  12876. pfd[i].events = POLLIN;
  12877. }
  12878. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12879. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12880. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12881. * successful poll, and POLLIN is defined as
  12882. * (POLLRDNORM | POLLRDBAND)
  12883. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12884. * pfd[i].revents == POLLIN. */
  12885. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12886. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12887. }
  12888. }
  12889. }
  12890. }
  12891. /* Here stop_flag is 1 - Initiate shutdown. */
  12892. DEBUG_TRACE("%s", "stopping workers");
  12893. /* Stop signal received: somebody called mg_stop. Quit. */
  12894. close_all_listening_sockets(ctx);
  12895. /* Wakeup workers that are waiting for connections to handle. */
  12896. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12897. #if defined(ALTERNATIVE_QUEUE)
  12898. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12899. event_signal(ctx->client_wait_events[i]);
  12900. /* Since we know all sockets, we can shutdown the connections. */
  12901. if (ctx->client_socks[i].in_use) {
  12902. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12903. }
  12904. }
  12905. #else
  12906. pthread_cond_broadcast(&ctx->sq_full);
  12907. #endif
  12908. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12909. /* Join all worker threads to avoid leaking threads. */
  12910. workerthreadcount = ctx->cfg_worker_threads;
  12911. for (i = 0; i < workerthreadcount; i++) {
  12912. if (ctx->worker_threadids[i] != 0) {
  12913. mg_join_thread(ctx->worker_threadids[i]);
  12914. }
  12915. }
  12916. #if defined(USE_LUA)
  12917. /* Free Lua state of lua background task */
  12918. if (ctx->lua_background_state) {
  12919. lua_close((lua_State *)ctx->lua_background_state);
  12920. ctx->lua_background_state = 0;
  12921. }
  12922. #endif
  12923. #if !defined(NO_SSL)
  12924. if (ctx->ssl_ctx != NULL) {
  12925. uninitialize_ssl();
  12926. }
  12927. #endif
  12928. DEBUG_TRACE("%s", "exiting");
  12929. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12930. CloseHandle(tls.pthread_cond_helper_mutex);
  12931. #endif
  12932. pthread_setspecific(sTlsKey, NULL);
  12933. /* Signal mg_stop() that we're done.
  12934. * WARNING: This must be the very last thing this
  12935. * thread does, as ctx becomes invalid after this line. */
  12936. ctx->stop_flag = 2;
  12937. }
  12938. /* Threads have different return types on Windows and Unix. */
  12939. #ifdef _WIN32
  12940. static unsigned __stdcall master_thread(void *thread_func_param)
  12941. {
  12942. master_thread_run(thread_func_param);
  12943. return 0;
  12944. }
  12945. #else
  12946. static void *
  12947. master_thread(void *thread_func_param)
  12948. {
  12949. master_thread_run(thread_func_param);
  12950. return NULL;
  12951. }
  12952. #endif /* _WIN32 */
  12953. static void
  12954. free_context(struct mg_context *ctx)
  12955. {
  12956. int i;
  12957. struct mg_handler_info *tmp_rh;
  12958. if (ctx == NULL) {
  12959. return;
  12960. }
  12961. if (ctx->callbacks.exit_context) {
  12962. ctx->callbacks.exit_context(ctx);
  12963. }
  12964. /* All threads exited, no sync is needed. Destroy thread mutex and
  12965. * condvars
  12966. */
  12967. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12968. #if defined(ALTERNATIVE_QUEUE)
  12969. mg_free(ctx->client_socks);
  12970. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12971. event_destroy(ctx->client_wait_events[i]);
  12972. }
  12973. mg_free(ctx->client_wait_events);
  12974. #else
  12975. (void)pthread_cond_destroy(&ctx->sq_empty);
  12976. (void)pthread_cond_destroy(&ctx->sq_full);
  12977. #endif
  12978. /* Destroy other context global data structures mutex */
  12979. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12980. #if defined(USE_TIMERS)
  12981. timers_exit(ctx);
  12982. #endif
  12983. /* Deallocate config parameters */
  12984. for (i = 0; i < NUM_OPTIONS; i++) {
  12985. if (ctx->config[i] != NULL) {
  12986. #if defined(_MSC_VER)
  12987. #pragma warning(suppress : 6001)
  12988. #endif
  12989. mg_free(ctx->config[i]);
  12990. }
  12991. }
  12992. /* Deallocate request handlers */
  12993. while (ctx->handlers) {
  12994. tmp_rh = ctx->handlers;
  12995. ctx->handlers = tmp_rh->next;
  12996. mg_free(tmp_rh->uri);
  12997. mg_free(tmp_rh);
  12998. }
  12999. #ifndef NO_SSL
  13000. /* Deallocate SSL context */
  13001. if (ctx->ssl_ctx != NULL) {
  13002. SSL_CTX_free(ctx->ssl_ctx);
  13003. }
  13004. #endif /* !NO_SSL */
  13005. /* Deallocate worker thread ID array */
  13006. if (ctx->worker_threadids != NULL) {
  13007. mg_free(ctx->worker_threadids);
  13008. }
  13009. /* Deallocate worker thread ID array */
  13010. if (ctx->worker_connections != NULL) {
  13011. mg_free(ctx->worker_connections);
  13012. }
  13013. /* Deallocate the tls variable */
  13014. if (mg_atomic_dec(&sTlsInit) == 0) {
  13015. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13016. DeleteCriticalSection(&global_log_file_lock);
  13017. #endif /* _WIN32 && !__SYMBIAN32__ */
  13018. #if !defined(_WIN32)
  13019. pthread_mutexattr_destroy(&pthread_mutex_attr);
  13020. #endif
  13021. pthread_key_delete(sTlsKey);
  13022. #if defined(USE_LUA)
  13023. lua_exit_optional_libraries();
  13024. #endif
  13025. }
  13026. /* deallocate system name string */
  13027. mg_free(ctx->systemName);
  13028. /* Deallocate context itself */
  13029. mg_free(ctx);
  13030. }
  13031. void
  13032. mg_stop(struct mg_context *ctx)
  13033. {
  13034. pthread_t mt;
  13035. if (!ctx) {
  13036. return;
  13037. }
  13038. /* We don't use a lock here. Calling mg_stop with the same ctx from
  13039. * two threads is not allowed. */
  13040. mt = ctx->masterthreadid;
  13041. if (mt == 0) {
  13042. return;
  13043. }
  13044. ctx->masterthreadid = 0;
  13045. /* Set stop flag, so all threads know they have to exit. */
  13046. ctx->stop_flag = 1;
  13047. /* Wait until everything has stopped. */
  13048. while (ctx->stop_flag != 2) {
  13049. (void)mg_sleep(10);
  13050. }
  13051. mg_join_thread(mt);
  13052. free_context(ctx);
  13053. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13054. (void)WSACleanup();
  13055. #endif /* _WIN32 && !__SYMBIAN32__ */
  13056. }
  13057. static void
  13058. get_system_name(char **sysName)
  13059. {
  13060. #if defined(_WIN32)
  13061. #if !defined(__SYMBIAN32__)
  13062. #if defined(_WIN32_WCE)
  13063. *sysName = mg_strdup("WinCE");
  13064. #else
  13065. char name[128];
  13066. DWORD dwVersion = 0;
  13067. DWORD dwMajorVersion = 0;
  13068. DWORD dwMinorVersion = 0;
  13069. DWORD dwBuild = 0;
  13070. BOOL wowRet, isWoW = FALSE;
  13071. #ifdef _MSC_VER
  13072. #pragma warning(push)
  13073. /* GetVersion was declared deprecated */
  13074. #pragma warning(disable : 4996)
  13075. #endif
  13076. dwVersion = GetVersion();
  13077. #ifdef _MSC_VER
  13078. #pragma warning(pop)
  13079. #endif
  13080. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13081. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13082. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  13083. (void)dwBuild;
  13084. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  13085. sprintf(name,
  13086. "Windows %u.%u%s",
  13087. (unsigned)dwMajorVersion,
  13088. (unsigned)dwMinorVersion,
  13089. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  13090. *sysName = mg_strdup(name);
  13091. #endif
  13092. #else
  13093. *sysName = mg_strdup("Symbian");
  13094. #endif
  13095. #else
  13096. struct utsname name;
  13097. memset(&name, 0, sizeof(name));
  13098. uname(&name);
  13099. *sysName = mg_strdup(name.sysname);
  13100. #endif
  13101. }
  13102. struct mg_context *
  13103. mg_start(const struct mg_callbacks *callbacks,
  13104. void *user_data,
  13105. const char **options)
  13106. {
  13107. struct mg_context *ctx;
  13108. const char *name, *value, *default_value;
  13109. int idx, ok, workerthreadcount;
  13110. unsigned int i;
  13111. void (*exit_callback)(const struct mg_context *ctx) = 0;
  13112. struct mg_workerTLS tls;
  13113. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13114. WSADATA data;
  13115. WSAStartup(MAKEWORD(2, 2), &data);
  13116. #endif /* _WIN32 && !__SYMBIAN32__ */
  13117. /* Allocate context and initialize reasonable general case defaults. */
  13118. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  13119. return NULL;
  13120. }
  13121. /* Random number generator will initialize at the first call */
  13122. ctx->auth_nonce_mask =
  13123. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  13124. if (mg_atomic_inc(&sTlsInit) == 1) {
  13125. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13126. InitializeCriticalSection(&global_log_file_lock);
  13127. #endif /* _WIN32 && !__SYMBIAN32__ */
  13128. #if !defined(_WIN32)
  13129. pthread_mutexattr_init(&pthread_mutex_attr);
  13130. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  13131. #endif
  13132. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  13133. /* Fatal error - abort start. However, this situation should
  13134. * never occur in practice. */
  13135. mg_atomic_dec(&sTlsInit);
  13136. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  13137. mg_free(ctx);
  13138. return NULL;
  13139. }
  13140. #if defined(USE_LUA)
  13141. lua_init_optional_libraries();
  13142. #endif
  13143. } else {
  13144. /* TODO (low): instead of sleeping, check if sTlsKey is already
  13145. * initialized. */
  13146. mg_sleep(1);
  13147. }
  13148. tls.is_master = -1;
  13149. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13150. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13151. tls.pthread_cond_helper_mutex = NULL;
  13152. #endif
  13153. pthread_setspecific(sTlsKey, &tls);
  13154. /* Dummy use this function - in some #ifdef combinations it's used,
  13155. * while it's not used in others, but GCC seems to stupid to understand
  13156. * #pragma GCC diagnostic ignored "-Wunused-function"
  13157. * in cases the function is unused, and it also complains on
  13158. * __attribute((unused))__ in cases it is used.
  13159. * So dummy use it, to have our peace. */
  13160. (void)mg_current_thread_id();
  13161. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  13162. #if !defined(ALTERNATIVE_QUEUE)
  13163. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  13164. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  13165. #endif
  13166. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  13167. if (!ok) {
  13168. /* Fatal error - abort start. However, this situation should never
  13169. * occur in practice. */
  13170. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  13171. mg_free(ctx);
  13172. pthread_setspecific(sTlsKey, NULL);
  13173. return NULL;
  13174. }
  13175. if (callbacks) {
  13176. ctx->callbacks = *callbacks;
  13177. exit_callback = callbacks->exit_context;
  13178. ctx->callbacks.exit_context = 0;
  13179. }
  13180. ctx->user_data = user_data;
  13181. ctx->handlers = NULL;
  13182. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13183. ctx->shared_lua_websockets = 0;
  13184. #endif
  13185. while (options && (name = *options++) != NULL) {
  13186. if ((idx = get_option_index(name)) == -1) {
  13187. mg_cry(fc(ctx), "Invalid option: %s", name);
  13188. free_context(ctx);
  13189. pthread_setspecific(sTlsKey, NULL);
  13190. return NULL;
  13191. } else if ((value = *options++) == NULL) {
  13192. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  13193. free_context(ctx);
  13194. pthread_setspecific(sTlsKey, NULL);
  13195. return NULL;
  13196. }
  13197. if (ctx->config[idx] != NULL) {
  13198. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  13199. mg_free(ctx->config[idx]);
  13200. }
  13201. ctx->config[idx] = mg_strdup(value);
  13202. DEBUG_TRACE("[%s] -> [%s]", name, value);
  13203. }
  13204. /* Set default value if needed */
  13205. for (i = 0; config_options[i].name != NULL; i++) {
  13206. default_value = config_options[i].default_value;
  13207. if (ctx->config[i] == NULL && default_value != NULL) {
  13208. ctx->config[i] = mg_strdup(default_value);
  13209. }
  13210. }
  13211. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  13212. if (workerthreadcount > MAX_WORKER_THREADS) {
  13213. mg_cry(fc(ctx), "Too many worker threads");
  13214. free_context(ctx);
  13215. pthread_setspecific(sTlsKey, NULL);
  13216. return NULL;
  13217. }
  13218. if (workerthreadcount <= 0) {
  13219. mg_cry(fc(ctx), "Invalid number of worker threads");
  13220. free_context(ctx);
  13221. pthread_setspecific(sTlsKey, NULL);
  13222. return NULL;
  13223. }
  13224. #if defined(NO_FILES)
  13225. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  13226. mg_cry(fc(ctx), "%s", "Document root must not be set");
  13227. free_context(ctx);
  13228. pthread_setspecific(sTlsKey, NULL);
  13229. return NULL;
  13230. }
  13231. #endif
  13232. get_system_name(&ctx->systemName);
  13233. #if defined(USE_LUA)
  13234. /* If a Lua background script has been configured, start it. */
  13235. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  13236. char ebuf[256];
  13237. void *state = (void *)mg_prepare_lua_context_script(
  13238. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  13239. if (!state) {
  13240. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  13241. free_context(ctx);
  13242. pthread_setspecific(sTlsKey, NULL);
  13243. return NULL;
  13244. }
  13245. ctx->lua_background_state = state;
  13246. } else {
  13247. ctx->lua_background_state = 0;
  13248. }
  13249. #endif
  13250. /* NOTE(lsm): order is important here. SSL certificates must
  13251. * be initialized before listening ports. UID must be set last. */
  13252. if (!set_gpass_option(ctx) ||
  13253. #if !defined(NO_SSL)
  13254. !set_ssl_option(ctx) ||
  13255. #endif
  13256. !set_ports_option(ctx) ||
  13257. #if !defined(_WIN32)
  13258. !set_uid_option(ctx) ||
  13259. #endif
  13260. !set_acl_option(ctx)) {
  13261. free_context(ctx);
  13262. pthread_setspecific(sTlsKey, NULL);
  13263. return NULL;
  13264. }
  13265. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  13266. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  13267. * won't kill the whole process. */
  13268. (void)signal(SIGPIPE, SIG_IGN);
  13269. #endif /* !_WIN32 && !__SYMBIAN32__ */
  13270. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  13271. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13272. sizeof(pthread_t),
  13273. ctx);
  13274. if (ctx->worker_threadids == NULL) {
  13275. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  13276. free_context(ctx);
  13277. pthread_setspecific(sTlsKey, NULL);
  13278. return NULL;
  13279. }
  13280. ctx->worker_connections =
  13281. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13282. sizeof(struct mg_connection),
  13283. ctx);
  13284. if (ctx->worker_connections == NULL) {
  13285. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  13286. free_context(ctx);
  13287. pthread_setspecific(sTlsKey, NULL);
  13288. return NULL;
  13289. }
  13290. #if defined(ALTERNATIVE_QUEUE)
  13291. ctx->client_wait_events = mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  13292. ctx->cfg_worker_threads,
  13293. ctx);
  13294. if (ctx->client_wait_events == NULL) {
  13295. mg_cry(fc(ctx), "Not enough memory for worker event array");
  13296. mg_free(ctx->worker_threadids);
  13297. free_context(ctx);
  13298. pthread_setspecific(sTlsKey, NULL);
  13299. return NULL;
  13300. }
  13301. ctx->client_socks = mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  13302. ctx->cfg_worker_threads,
  13303. ctx);
  13304. if (ctx->client_wait_events == NULL) {
  13305. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  13306. mg_free(ctx->client_socks);
  13307. mg_free(ctx->worker_threadids);
  13308. free_context(ctx);
  13309. pthread_setspecific(sTlsKey, NULL);
  13310. return NULL;
  13311. }
  13312. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13313. ctx->client_wait_events[i] = event_create();
  13314. if (ctx->client_wait_events[i] == 0) {
  13315. mg_cry(fc(ctx), "Error creating worker event %i", i);
  13316. while (i > 0) {
  13317. i--;
  13318. event_destroy(ctx->client_wait_events[i]);
  13319. }
  13320. mg_free(ctx->client_socks);
  13321. mg_free(ctx->worker_threadids);
  13322. free_context(ctx);
  13323. pthread_setspecific(sTlsKey, NULL);
  13324. return NULL;
  13325. }
  13326. }
  13327. #endif
  13328. #if defined(USE_TIMERS)
  13329. if (timers_init(ctx) != 0) {
  13330. mg_cry(fc(ctx), "Error creating timers");
  13331. free_context(ctx);
  13332. pthread_setspecific(sTlsKey, NULL);
  13333. return NULL;
  13334. }
  13335. #endif
  13336. /* Context has been created - init user libraries */
  13337. if (ctx->callbacks.init_context) {
  13338. ctx->callbacks.init_context(ctx);
  13339. }
  13340. ctx->callbacks.exit_context = exit_callback;
  13341. ctx->context_type = 1; /* server context */
  13342. /* Start master (listening) thread */
  13343. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  13344. /* Start worker threads */
  13345. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13346. struct worker_thread_args *wta = (struct worker_thread_args *)
  13347. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  13348. if (wta) {
  13349. wta->ctx = ctx;
  13350. wta->index = (int)i;
  13351. }
  13352. if ((wta == NULL)
  13353. || (mg_start_thread_with_id(worker_thread,
  13354. wta,
  13355. &ctx->worker_threadids[i]) != 0)) {
  13356. /* thread was not created */
  13357. if (wta != NULL) {
  13358. mg_free(wta);
  13359. }
  13360. if (i > 0) {
  13361. mg_cry(fc(ctx),
  13362. "Cannot start worker thread %i: error %ld",
  13363. i + 1,
  13364. (long)ERRNO);
  13365. } else {
  13366. mg_cry(fc(ctx),
  13367. "Cannot create threads: error %ld",
  13368. (long)ERRNO);
  13369. free_context(ctx);
  13370. pthread_setspecific(sTlsKey, NULL);
  13371. return NULL;
  13372. }
  13373. break;
  13374. }
  13375. }
  13376. pthread_setspecific(sTlsKey, NULL);
  13377. return ctx;
  13378. }
  13379. /* Feature check API function */
  13380. unsigned
  13381. mg_check_feature(unsigned feature)
  13382. {
  13383. static const unsigned feature_set = 0
  13384. /* Set bits for available features according to API documentation.
  13385. * This bit mask is created at compile time, according to the active
  13386. * preprocessor defines. It is a single const value at runtime. */
  13387. #if !defined(NO_FILES)
  13388. | 0x0001u
  13389. #endif
  13390. #if !defined(NO_SSL)
  13391. | 0x0002u
  13392. #endif
  13393. #if !defined(NO_CGI)
  13394. | 0x0004u
  13395. #endif
  13396. #if defined(USE_IPV6)
  13397. | 0x0008u
  13398. #endif
  13399. #if defined(USE_WEBSOCKET)
  13400. | 0x0010u
  13401. #endif
  13402. #if defined(USE_LUA)
  13403. | 0x0020u
  13404. #endif
  13405. #if defined(USE_DUKTAPE)
  13406. | 0x0040u
  13407. #endif
  13408. #if !defined(NO_CACHING)
  13409. | 0x0080u
  13410. #endif
  13411. #if defined(USE_SERVER_STATS)
  13412. | 0x0100u
  13413. #endif
  13414. /* Set some extra bits not defined in the API documentation.
  13415. * These bits may change without further notice. */
  13416. #if defined(MG_LEGACY_INTERFACE)
  13417. | 0x8000u
  13418. #endif
  13419. #if defined(MEMORY_DEBUGGING)
  13420. | 0x0100u
  13421. #endif
  13422. #if defined(USE_TIMERS)
  13423. | 0x0200u
  13424. #endif
  13425. #if !defined(NO_NONCE_CHECK)
  13426. | 0x0400u
  13427. #endif
  13428. #if !defined(NO_POPEN)
  13429. | 0x0800u
  13430. #endif
  13431. ;
  13432. return (feature & feature_set);
  13433. }
  13434. /* Get system information. It can be printed or stored by the caller.
  13435. * Return the size of available information. */
  13436. static int
  13437. mg_get_system_info_impl(char *buffer, int buflen)
  13438. {
  13439. char block[256];
  13440. int system_info_length = 0;
  13441. #if defined(_WIN32)
  13442. const char *eol = "\r\n";
  13443. #else
  13444. const char *eol = "\n";
  13445. #endif
  13446. if (buffer == NULL) {
  13447. /* Avoid some warning (although, if some dillweed supplies
  13448. * buffer==NULL combined with buflen>0, he deserves a crash).
  13449. */
  13450. buflen = 0;
  13451. }
  13452. /* Server version */
  13453. {
  13454. const char *version = mg_version();
  13455. mg_snprintf(NULL,
  13456. NULL,
  13457. block,
  13458. sizeof(block),
  13459. "Server Version: %s%s",
  13460. version,
  13461. eol);
  13462. system_info_length += (int)strlen(block);
  13463. if (system_info_length < buflen) {
  13464. strcat(buffer, block);
  13465. }
  13466. }
  13467. /* System info */
  13468. {
  13469. #if defined(_WIN32)
  13470. #if !defined(__SYMBIAN32__)
  13471. DWORD dwVersion = 0;
  13472. DWORD dwMajorVersion = 0;
  13473. DWORD dwMinorVersion = 0;
  13474. SYSTEM_INFO si;
  13475. GetSystemInfo(&si);
  13476. #ifdef _MSC_VER
  13477. #pragma warning(push)
  13478. /* GetVersion was declared deprecated */
  13479. #pragma warning(disable : 4996)
  13480. #endif
  13481. dwVersion = GetVersion();
  13482. #ifdef _MSC_VER
  13483. #pragma warning(pop)
  13484. #endif
  13485. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13486. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13487. mg_snprintf(NULL,
  13488. NULL,
  13489. block,
  13490. sizeof(block),
  13491. "Windows %u.%u%s",
  13492. (unsigned)dwMajorVersion,
  13493. (unsigned)dwMinorVersion,
  13494. eol);
  13495. system_info_length += (int)strlen(block);
  13496. if (system_info_length < buflen) {
  13497. strcat(buffer, block);
  13498. }
  13499. mg_snprintf(NULL,
  13500. NULL,
  13501. block,
  13502. sizeof(block),
  13503. "CPU: type %u, cores %u, mask %x%s",
  13504. (unsigned)si.wProcessorArchitecture,
  13505. (unsigned)si.dwNumberOfProcessors,
  13506. (unsigned)si.dwActiveProcessorMask,
  13507. eol);
  13508. system_info_length += (int)strlen(block);
  13509. if (system_info_length < buflen) {
  13510. strcat(buffer, block);
  13511. }
  13512. #else
  13513. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  13514. system_info_length += (int)strlen(block);
  13515. if (system_info_length < buflen) {
  13516. strcat(buffer, block);
  13517. }
  13518. #endif
  13519. #else
  13520. struct utsname name;
  13521. memset(&name, 0, sizeof(name));
  13522. uname(&name);
  13523. mg_snprintf(NULL,
  13524. NULL,
  13525. block,
  13526. sizeof(block),
  13527. "%s %s (%s) - %s%s",
  13528. name.sysname,
  13529. name.version,
  13530. name.release,
  13531. name.machine,
  13532. eol);
  13533. system_info_length += (int)strlen(block);
  13534. if (system_info_length < buflen) {
  13535. strcat(buffer, block);
  13536. }
  13537. #endif
  13538. }
  13539. /* Features */
  13540. {
  13541. mg_snprintf(NULL,
  13542. NULL,
  13543. block,
  13544. sizeof(block),
  13545. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  13546. mg_check_feature(0xFFFFFFFFu),
  13547. eol,
  13548. mg_check_feature(1) ? " Files" : "",
  13549. mg_check_feature(2) ? " HTTPS" : "",
  13550. mg_check_feature(4) ? " CGI" : "",
  13551. mg_check_feature(8) ? " IPv6" : "",
  13552. mg_check_feature(16) ? " WebSockets" : "",
  13553. mg_check_feature(32) ? " Lua" : "",
  13554. mg_check_feature(64) ? " JavaScript" : "",
  13555. mg_check_feature(128) ? " Cache" : "",
  13556. eol);
  13557. system_info_length += (int)strlen(block);
  13558. if (system_info_length < buflen) {
  13559. strcat(buffer, block);
  13560. }
  13561. #ifdef USE_LUA
  13562. mg_snprintf(NULL,
  13563. NULL,
  13564. block,
  13565. sizeof(block),
  13566. "Lua Version: %u (%s)%s",
  13567. (unsigned)LUA_VERSION_NUM,
  13568. LUA_RELEASE,
  13569. eol);
  13570. system_info_length += (int)strlen(block);
  13571. if (system_info_length < buflen) {
  13572. strcat(buffer, block);
  13573. }
  13574. #endif
  13575. #if defined(USE_DUKTAPE)
  13576. mg_snprintf(NULL,
  13577. NULL,
  13578. block,
  13579. sizeof(block),
  13580. "JavaScript: Duktape %u.%u.%u%s",
  13581. (unsigned)DUK_VERSION / 10000,
  13582. ((unsigned)DUK_VERSION / 100) % 100,
  13583. (unsigned)DUK_VERSION % 100,
  13584. eol);
  13585. system_info_length += (int)strlen(block);
  13586. if (system_info_length < buflen) {
  13587. strcat(buffer, block);
  13588. }
  13589. #endif
  13590. }
  13591. /* Build date */
  13592. {
  13593. mg_snprintf(
  13594. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  13595. system_info_length += (int)strlen(block);
  13596. if (system_info_length < buflen) {
  13597. strcat(buffer, block);
  13598. }
  13599. }
  13600. /* Compiler information */
  13601. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  13602. {
  13603. #if defined(_MSC_VER)
  13604. mg_snprintf(NULL,
  13605. NULL,
  13606. block,
  13607. sizeof(block),
  13608. "MSC: %u (%u)%s",
  13609. (unsigned)_MSC_VER,
  13610. (unsigned)_MSC_FULL_VER,
  13611. eol);
  13612. system_info_length += (int)strlen(block);
  13613. if (system_info_length < buflen) {
  13614. strcat(buffer, block);
  13615. }
  13616. #elif defined(__MINGW64__)
  13617. mg_snprintf(NULL,
  13618. NULL,
  13619. block,
  13620. sizeof(block),
  13621. "MinGW64: %u.%u%s",
  13622. (unsigned)__MINGW64_VERSION_MAJOR,
  13623. (unsigned)__MINGW64_VERSION_MINOR,
  13624. eol);
  13625. system_info_length += (int)strlen(block);
  13626. if (system_info_length < buflen) {
  13627. strcat(buffer, block);
  13628. }
  13629. mg_snprintf(NULL,
  13630. NULL,
  13631. block,
  13632. sizeof(block),
  13633. "MinGW32: %u.%u%s",
  13634. (unsigned)__MINGW32_MAJOR_VERSION,
  13635. (unsigned)__MINGW32_MINOR_VERSION,
  13636. eol);
  13637. system_info_length += (int)strlen(block);
  13638. if (system_info_length < buflen) {
  13639. strcat(buffer, block);
  13640. }
  13641. #elif defined(__MINGW32__)
  13642. mg_snprintf(NULL,
  13643. NULL,
  13644. block,
  13645. sizeof(block),
  13646. "MinGW32: %u.%u%s",
  13647. (unsigned)__MINGW32_MAJOR_VERSION,
  13648. (unsigned)__MINGW32_MINOR_VERSION,
  13649. eol);
  13650. system_info_length += (int)strlen(block);
  13651. if (system_info_length < buflen) {
  13652. strcat(buffer, block);
  13653. }
  13654. #elif defined(__clang__)
  13655. mg_snprintf(NULL,
  13656. NULL,
  13657. block,
  13658. sizeof(block),
  13659. "clang: %u.%u.%u (%s)%s",
  13660. __clang_major__,
  13661. __clang_minor__,
  13662. __clang_patchlevel__,
  13663. __clang_version__,
  13664. eol);
  13665. system_info_length += (int)strlen(block);
  13666. if (system_info_length < buflen) {
  13667. strcat(buffer, block);
  13668. }
  13669. #elif defined(__GNUC__)
  13670. mg_snprintf(NULL,
  13671. NULL,
  13672. block,
  13673. sizeof(block),
  13674. "gcc: %u.%u.%u%s",
  13675. (unsigned)__GNUC__,
  13676. (unsigned)__GNUC_MINOR__,
  13677. (unsigned)__GNUC_PATCHLEVEL__,
  13678. eol);
  13679. system_info_length += (int)strlen(block);
  13680. if (system_info_length < buflen) {
  13681. strcat(buffer, block);
  13682. }
  13683. #elif defined(__INTEL_COMPILER)
  13684. mg_snprintf(NULL,
  13685. NULL,
  13686. block,
  13687. sizeof(block),
  13688. "Intel C/C++: %u%s",
  13689. (unsigned)__INTEL_COMPILER,
  13690. eol);
  13691. system_info_length += (int)strlen(block);
  13692. if (system_info_length < buflen) {
  13693. strcat(buffer, block);
  13694. }
  13695. #elif defined(__BORLANDC__)
  13696. mg_snprintf(NULL,
  13697. NULL,
  13698. block,
  13699. sizeof(block),
  13700. "Borland C: 0x%x%s",
  13701. (unsigned)__BORLANDC__,
  13702. eol);
  13703. system_info_length += (int)strlen(block);
  13704. if (system_info_length < buflen) {
  13705. strcat(buffer, block);
  13706. }
  13707. #elif defined(__SUNPRO_C)
  13708. mg_snprintf(NULL,
  13709. NULL,
  13710. block,
  13711. sizeof(block),
  13712. "Solaris: 0x%x%s",
  13713. (unsigned)__SUNPRO_C,
  13714. eol);
  13715. system_info_length += (int)strlen(block);
  13716. if (system_info_length < buflen) {
  13717. strcat(buffer, block);
  13718. }
  13719. #else
  13720. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13721. system_info_length += (int)strlen(block);
  13722. if (system_info_length < buflen) {
  13723. strcat(buffer, block);
  13724. }
  13725. #endif
  13726. }
  13727. /* Determine 32/64 bit data mode.
  13728. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13729. {
  13730. mg_snprintf(NULL,
  13731. NULL,
  13732. block,
  13733. sizeof(block),
  13734. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13735. "ptr:%u, size:%u, time:%u%s",
  13736. (unsigned)sizeof(short),
  13737. (unsigned)sizeof(int),
  13738. (unsigned)sizeof(long),
  13739. (unsigned)sizeof(long long),
  13740. (unsigned)sizeof(float),
  13741. (unsigned)sizeof(double),
  13742. (unsigned)sizeof(long double),
  13743. (unsigned)sizeof(char),
  13744. (unsigned)sizeof(wchar_t),
  13745. (unsigned)sizeof(void *),
  13746. (unsigned)sizeof(size_t),
  13747. (unsigned)sizeof(time_t),
  13748. eol);
  13749. system_info_length += (int)strlen(block);
  13750. if (system_info_length < buflen) {
  13751. strcat(buffer, block);
  13752. }
  13753. }
  13754. return system_info_length;
  13755. }
  13756. #if defined(USE_SERVER_STATS)
  13757. /* Get context information. It can be printed or stored by the caller.
  13758. * Return the size of available information. */
  13759. static int
  13760. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  13761. {
  13762. char block[256];
  13763. int context_info_length = 0;
  13764. #if defined(_WIN32)
  13765. const char *eol = "\r\n";
  13766. #else
  13767. const char *eol = "\n";
  13768. #endif
  13769. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  13770. const char *eoobj = "}";
  13771. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  13772. if ((buffer == NULL) || (buflen < 10)) {
  13773. buflen = 0;
  13774. }
  13775. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  13776. context_info_length += (int)strlen(block);
  13777. if (context_info_length < buflen) {
  13778. strcat(buffer, block);
  13779. }
  13780. /* Memory information */
  13781. if (ms) {
  13782. mg_snprintf(NULL,
  13783. NULL,
  13784. block,
  13785. sizeof(block),
  13786. "\"memory\" : {%s"
  13787. "\"blocks\" : %i,%s"
  13788. "\"used\" : %" INT64_FMT ",%s"
  13789. "\"maxUsed\" : %" INT64_FMT "%s"
  13790. "}%s%s",
  13791. eol,
  13792. ms->blockCount,
  13793. eol,
  13794. ms->totalMemUsed,
  13795. eol,
  13796. ms->maxMemUsed,
  13797. eol,
  13798. (ctx ? "," : ""),
  13799. eol);
  13800. context_info_length += (int)strlen(block);
  13801. if (context_info_length + reserved_len < buflen) {
  13802. strcat(buffer, block);
  13803. }
  13804. }
  13805. /* Connections information */
  13806. if (ctx) {
  13807. mg_snprintf(NULL,
  13808. NULL,
  13809. block,
  13810. sizeof(block),
  13811. "\"connections\" : {%s"
  13812. "\"active\" : %i,%s"
  13813. "\"maxActive\" : %i,%s"
  13814. "\"total\" : %" INT64_FMT "%s"
  13815. "},%s",
  13816. eol,
  13817. ctx->active_connections,
  13818. eol,
  13819. ctx->max_connections,
  13820. eol,
  13821. ctx->total_connections,
  13822. eol,
  13823. eol);
  13824. context_info_length += (int)strlen(block);
  13825. if (context_info_length + reserved_len < buflen) {
  13826. strcat(buffer, block);
  13827. }
  13828. }
  13829. /* Requests information */
  13830. if (ctx) {
  13831. mg_snprintf(NULL,
  13832. NULL,
  13833. block,
  13834. sizeof(block),
  13835. "\"requests\" : {%s"
  13836. "\"total\" : %" INT64_FMT "%s"
  13837. "}%s",
  13838. eol,
  13839. ctx->total_requests,
  13840. eol,
  13841. eol);
  13842. context_info_length += (int)strlen(block);
  13843. if (context_info_length + reserved_len < buflen) {
  13844. strcat(buffer, block);
  13845. }
  13846. }
  13847. if ((buflen > 0) && buffer && buffer[0]) {
  13848. if (context_info_length < buflen) {
  13849. strcat(buffer, eoobj);
  13850. strcat(buffer, eol);
  13851. context_info_length += reserved_len;
  13852. }
  13853. }
  13854. return context_info_length;
  13855. }
  13856. #endif
  13857. /* Get system information. It can be printed or stored by the caller.
  13858. * Return the size of available information. */
  13859. int
  13860. mg_get_system_info(char *buffer, int buflen)
  13861. {
  13862. if ((buffer == NULL) || (buflen < 1)) {
  13863. return mg_get_system_info_impl(NULL, 0);
  13864. } else {
  13865. /* Reset buffer, so we can always use strcat. */
  13866. buffer[0] = 0;
  13867. return mg_get_system_info_impl(buffer, buflen);
  13868. }
  13869. }
  13870. /* Get context information. It can be printed or stored by the caller.
  13871. * Return the size of available information. */
  13872. int
  13873. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  13874. {
  13875. #if defined(USE_SERVER_STATS)
  13876. if ((buffer == NULL) || (buflen < 1)) {
  13877. return mg_get_context_info_impl(ctx, NULL, 0);
  13878. } else {
  13879. /* Reset buffer, so we can always use strcat. */
  13880. buffer[0] = 0;
  13881. return mg_get_context_info_impl(ctx, buffer, buflen);
  13882. }
  13883. #else
  13884. (void)ctx;
  13885. if ((buffer != NULL) && (buflen > 0)) {
  13886. buffer[0] = 0;
  13887. }
  13888. return 0;
  13889. #endif
  13890. }
  13891. /* mg_init_library counter */
  13892. static int mg_init_library_called = 0;
  13893. #if !defined(NO_SSL)
  13894. static int mg_ssl_initialized = 0;
  13895. #endif
  13896. /* Initialize this library. This function does not need to be thread safe. */
  13897. unsigned
  13898. mg_init_library(unsigned features)
  13899. {
  13900. #if !defined(NO_SSL)
  13901. char ebuf[128];
  13902. #endif
  13903. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  13904. unsigned features_inited = features_to_init;
  13905. #if !defined(NO_SSL)
  13906. if (features_to_init & 2) {
  13907. if (!mg_ssl_initialized) {
  13908. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  13909. mg_ssl_initialized = 1;
  13910. } else {
  13911. (void)ebuf;
  13912. /* TODO: print error */
  13913. features_inited &= ~(2u);
  13914. }
  13915. } else {
  13916. /* ssl already initialized */
  13917. }
  13918. }
  13919. #endif
  13920. /* Start Windows. */
  13921. if (mg_init_library_called <= 0) {
  13922. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13923. WSADATA data;
  13924. WSAStartup(MAKEWORD(2, 2), &data);
  13925. #endif /* _WIN32 && !__SYMBIAN32__ */
  13926. mg_init_library_called = 1;
  13927. } else {
  13928. mg_init_library_called++;
  13929. }
  13930. return features_inited;
  13931. }
  13932. /* Un-initialize this library. */
  13933. unsigned
  13934. mg_exit_library(void)
  13935. {
  13936. if (mg_init_library_called <= 0) {
  13937. return 0;
  13938. }
  13939. mg_init_library_called--;
  13940. if (mg_init_library_called == 0) {
  13941. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13942. (void)WSACleanup();
  13943. #endif /* _WIN32 && !__SYMBIAN32__ */
  13944. #if !defined(NO_SSL)
  13945. if (mg_ssl_initialized) {
  13946. uninitialize_ssl();
  13947. mg_ssl_initialized = 0;
  13948. }
  13949. #endif
  13950. }
  13951. return 1;
  13952. }
  13953. /* End of civetweb.c */