civetweb.c 425 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126
  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(NO_SSL)
  1627. STRICT_HTTPS_MAX_AGE,
  1628. #endif
  1629. #if defined(__linux__)
  1630. ALLOW_SENDFILE_CALL,
  1631. #endif
  1632. #if defined(_WIN32)
  1633. CASE_SENSITIVE_FILES,
  1634. #endif
  1635. #if defined(USE_LUA)
  1636. LUA_BACKGROUND_SCRIPT,
  1637. #endif
  1638. NUM_OPTIONS
  1639. };
  1640. /* Config option name, config types, default value */
  1641. static struct mg_option config_options[] = {
  1642. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1643. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1644. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1645. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1646. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1647. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1648. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1649. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1650. {"throttle", CONFIG_TYPE_STRING, NULL},
  1651. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1652. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1653. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1654. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1655. {"index_files",
  1656. CONFIG_TYPE_STRING,
  1657. #ifdef USE_LUA
  1658. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1659. "index.shtml,index.php"},
  1660. #else
  1661. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1662. #endif
  1663. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1664. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1665. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1666. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1667. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1668. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1669. {"ssl_certificate_chain", CONFIG_TYPE_FILE, NULL},
  1670. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1671. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1672. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1673. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1674. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1675. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1676. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1677. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1678. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1679. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1680. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1681. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1682. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1683. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1684. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1685. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1686. #if defined(USE_WEBSOCKET)
  1687. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1688. #endif
  1689. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1690. #if defined(USE_LUA)
  1691. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1692. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1693. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1694. #endif
  1695. #if defined(USE_DUKTAPE)
  1696. /* The support for duktape is still in alpha version state.
  1697. * The name of this config option might change. */
  1698. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1699. #endif
  1700. #if defined(USE_WEBSOCKET)
  1701. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1702. #endif
  1703. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1704. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1705. #endif
  1706. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1707. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1708. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1709. #if !defined(NO_CACHING)
  1710. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1711. #endif
  1712. #if !defined(NO_SSL)
  1713. {"strict_transport_security_max_age", CONFIG_TYPE_NUMBER, NULL},
  1714. #endif
  1715. #if defined(__linux__)
  1716. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1717. #endif
  1718. #if defined(_WIN32)
  1719. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1720. #endif
  1721. #if defined(USE_LUA)
  1722. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1723. #endif
  1724. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1725. /* Check if the config_options and the corresponding enum have compatible
  1726. * sizes. */
  1727. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1728. == (NUM_OPTIONS + 1),
  1729. "config_options and enum not sync");
  1730. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1731. struct mg_handler_info {
  1732. /* Name/Pattern of the URI. */
  1733. char *uri;
  1734. size_t uri_len;
  1735. /* handler type */
  1736. int handler_type;
  1737. /* Handler for http/https or authorization requests. */
  1738. mg_request_handler handler;
  1739. /* Handler for ws/wss (websocket) requests. */
  1740. mg_websocket_connect_handler connect_handler;
  1741. mg_websocket_ready_handler ready_handler;
  1742. mg_websocket_data_handler data_handler;
  1743. mg_websocket_close_handler close_handler;
  1744. /* accepted subprotocols for ws/wss requests. */
  1745. struct mg_websocket_subprotocols *subprotocols;
  1746. /* Handler for authorization requests */
  1747. mg_authorization_handler auth_handler;
  1748. /* User supplied argument for the handler function. */
  1749. void *cbdata;
  1750. /* next handler in a linked list */
  1751. struct mg_handler_info *next;
  1752. };
  1753. struct mg_context {
  1754. volatile int stop_flag; /* Should we stop event loop */
  1755. SSL_CTX *ssl_ctx; /* SSL context */
  1756. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1757. struct mg_callbacks callbacks; /* User-defined callback function */
  1758. void *user_data; /* User-defined data */
  1759. int context_type; /* 1 = server context,
  1760. * 2 = ws/wss client context,
  1761. */
  1762. struct socket *listening_sockets;
  1763. struct pollfd *listening_socket_fds;
  1764. unsigned int num_listening_sockets;
  1765. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1766. #ifdef ALTERNATIVE_QUEUE
  1767. struct socket *client_socks;
  1768. void **client_wait_events;
  1769. #else
  1770. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1771. volatile int sq_head; /* Head of the socket queue */
  1772. volatile int sq_tail; /* Tail of the socket queue */
  1773. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1774. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1775. #endif
  1776. pthread_t masterthreadid; /* The master thread ID */
  1777. unsigned int
  1778. cfg_worker_threads; /* The number of configured worker threads. */
  1779. pthread_t *worker_threadids; /* The worker thread IDs */
  1780. struct mg_connection *worker_connections; /* The connection struct, pre-
  1781. * allocated for each worker */
  1782. time_t start_time; /* Server start time, used for authentication */
  1783. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1784. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1785. unsigned long nonce_count; /* Used nonces, used for authentication */
  1786. char *systemName; /* What operating system is running */
  1787. /* linked list of uri handlers */
  1788. struct mg_handler_info *handlers;
  1789. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1790. /* linked list of shared lua websockets */
  1791. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1792. #endif
  1793. #if defined(USE_TIMERS)
  1794. struct ttimers *timers;
  1795. #endif
  1796. #if defined(USE_LUA)
  1797. void *lua_background_state;
  1798. #endif
  1799. #if defined(USE_SERVER_STATS)
  1800. int active_connections;
  1801. int max_connections;
  1802. int64_t total_connections;
  1803. int64_t total_requests;
  1804. struct mg_memory_stat ctx_memory;
  1805. #endif
  1806. };
  1807. #if defined(USE_SERVER_STATS)
  1808. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  1809. static struct mg_memory_stat *
  1810. get_memory_stat(struct mg_context *ctx)
  1811. {
  1812. if (ctx) {
  1813. return &(ctx->ctx_memory);
  1814. }
  1815. return &mg_common_memory;
  1816. }
  1817. #endif
  1818. struct mg_connection {
  1819. struct mg_request_info request_info;
  1820. struct mg_context *ctx;
  1821. SSL *ssl; /* SSL descriptor */
  1822. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1823. struct socket client; /* Connected client */
  1824. time_t conn_birth_time; /* Time (wall clock) when connection was
  1825. * established */
  1826. struct timespec req_time; /* Time (since system start) when the request
  1827. * was received */
  1828. int64_t num_bytes_sent; /* Total bytes sent to client */
  1829. int64_t content_len; /* Content-Length header value */
  1830. int64_t consumed_content; /* How many bytes of content have been read */
  1831. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1832. * data available, 2: all data read */
  1833. size_t chunk_remainder; /* Unread data from the last chunk */
  1834. char *buf; /* Buffer for received data */
  1835. char *path_info; /* PATH_INFO part of the URL */
  1836. int must_close; /* 1 if connection must be closed */
  1837. int in_error_handler; /* 1 if in handler for user defined error
  1838. * pages */
  1839. int handled_requests; /* Number of requests handled by this connection */
  1840. int buf_size; /* Buffer size */
  1841. int request_len; /* Size of the request + headers in a buffer */
  1842. int data_len; /* Total size of data in a buffer */
  1843. int status_code; /* HTTP reply status code, e.g. 200 */
  1844. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1845. * throttle */
  1846. time_t last_throttle_time; /* Last time throttled data was sent */
  1847. int64_t last_throttle_bytes; /* Bytes sent this second */
  1848. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1849. * atomic transmissions for websockets */
  1850. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1851. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1852. #endif
  1853. int thread_index; /* Thread index within ctx */
  1854. };
  1855. /* Directory entry */
  1856. struct de {
  1857. struct mg_connection *conn;
  1858. char *file_name;
  1859. struct mg_file_stat file;
  1860. };
  1861. #if defined(USE_WEBSOCKET)
  1862. static int is_websocket_protocol(const struct mg_connection *conn);
  1863. #else
  1864. #define is_websocket_protocol(conn) (0)
  1865. #endif
  1866. #if !defined(NO_THREAD_NAME)
  1867. #if defined(_WIN32) && defined(_MSC_VER)
  1868. /* Set the thread name for debugging purposes in Visual Studio
  1869. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1870. */
  1871. #pragma pack(push, 8)
  1872. typedef struct tagTHREADNAME_INFO {
  1873. DWORD dwType; /* Must be 0x1000. */
  1874. LPCSTR szName; /* Pointer to name (in user addr space). */
  1875. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1876. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1877. } THREADNAME_INFO;
  1878. #pragma pack(pop)
  1879. #elif defined(__linux__)
  1880. #include <sys/prctl.h>
  1881. #include <sys/sendfile.h>
  1882. #include <sys/eventfd.h>
  1883. #if defined(ALTERNATIVE_QUEUE)
  1884. static void *
  1885. event_create(void)
  1886. {
  1887. int ret = eventfd(0, EFD_CLOEXEC);
  1888. if (ret == -1) {
  1889. /* Linux uses -1 on error, Windows NULL. */
  1890. /* However, Linux does not return 0 on success either. */
  1891. return 0;
  1892. }
  1893. return (void *)ret;
  1894. }
  1895. static int
  1896. event_wait(void *eventhdl)
  1897. {
  1898. uint64_t u;
  1899. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1900. if (s != sizeof(uint64_t)) {
  1901. /* error */
  1902. return 0;
  1903. }
  1904. (void)u; /* the value is not required */
  1905. return 1;
  1906. }
  1907. static int
  1908. event_signal(void *eventhdl)
  1909. {
  1910. uint64_t u = 1;
  1911. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1912. if (s != sizeof(uint64_t)) {
  1913. /* error */
  1914. return 0;
  1915. }
  1916. return 1;
  1917. }
  1918. static void
  1919. event_destroy(void *eventhdl)
  1920. {
  1921. close((int)eventhdl);
  1922. }
  1923. #endif
  1924. #endif
  1925. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1926. struct posix_event {
  1927. pthread_mutex_t mutex;
  1928. pthread_cond_t cond;
  1929. };
  1930. static void *
  1931. event_create(void)
  1932. {
  1933. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1934. if (ret == 0) {
  1935. /* out of memory */
  1936. return 0;
  1937. }
  1938. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1939. /* pthread mutex not available */
  1940. mg_free(ret);
  1941. return 0;
  1942. }
  1943. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1944. /* pthread cond not available */
  1945. pthread_mutex_destroy(&(ret->mutex));
  1946. mg_free(ret);
  1947. return 0;
  1948. }
  1949. return (void *)ret;
  1950. }
  1951. static int
  1952. event_wait(void *eventhdl)
  1953. {
  1954. struct posix_event *ev = (struct posix_event *)eventhdl;
  1955. pthread_mutex_lock(&(ev->mutex));
  1956. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1957. pthread_mutex_unlock(&(ev->mutex));
  1958. return 1;
  1959. }
  1960. static int
  1961. event_signal(void *eventhdl)
  1962. {
  1963. struct posix_event *ev = (struct posix_event *)eventhdl;
  1964. pthread_mutex_lock(&(ev->mutex));
  1965. pthread_cond_signal(&(ev->cond));
  1966. pthread_mutex_unlock(&(ev->mutex));
  1967. return 1;
  1968. }
  1969. static void
  1970. event_destroy(void *eventhdl)
  1971. {
  1972. struct posix_event *ev = (struct posix_event *)eventhdl;
  1973. pthread_cond_destroy(&(ev->cond));
  1974. pthread_mutex_destroy(&(ev->mutex));
  1975. mg_free(ev);
  1976. }
  1977. #endif
  1978. static void
  1979. mg_set_thread_name(const char *name)
  1980. {
  1981. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1982. mg_snprintf(
  1983. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1984. #if defined(_WIN32)
  1985. #if defined(_MSC_VER)
  1986. /* Windows and Visual Studio Compiler */
  1987. __try
  1988. {
  1989. THREADNAME_INFO info;
  1990. info.dwType = 0x1000;
  1991. info.szName = threadName;
  1992. info.dwThreadID = ~0U;
  1993. info.dwFlags = 0;
  1994. RaiseException(0x406D1388,
  1995. 0,
  1996. sizeof(info) / sizeof(ULONG_PTR),
  1997. (ULONG_PTR *)&info);
  1998. }
  1999. __except(EXCEPTION_EXECUTE_HANDLER)
  2000. {
  2001. }
  2002. #elif defined(__MINGW32__)
  2003. /* No option known to set thread name for MinGW */
  2004. #endif
  2005. #elif defined(__GLIBC__) \
  2006. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2007. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2008. (void)pthread_setname_np(pthread_self(), threadName);
  2009. #elif defined(__linux__)
  2010. /* on linux we can use the old prctl function */
  2011. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2012. #endif
  2013. }
  2014. #else /* !defined(NO_THREAD_NAME) */
  2015. void
  2016. mg_set_thread_name(const char *threadName)
  2017. {
  2018. }
  2019. #endif
  2020. #if defined(MG_LEGACY_INTERFACE)
  2021. const char **
  2022. mg_get_valid_option_names(void)
  2023. {
  2024. /* This function is deprecated. Use mg_get_valid_options instead. */
  2025. static const char *
  2026. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2027. int i;
  2028. for (i = 0; config_options[i].name != NULL; i++) {
  2029. data[i * 2] = config_options[i].name;
  2030. data[i * 2 + 1] = config_options[i].default_value;
  2031. }
  2032. return data;
  2033. }
  2034. #endif
  2035. const struct mg_option *
  2036. mg_get_valid_options(void)
  2037. {
  2038. return config_options;
  2039. }
  2040. /* Do not open file (used in is_file_in_memory) */
  2041. #define MG_FOPEN_MODE_NONE (0)
  2042. /* Open file for read only access */
  2043. #define MG_FOPEN_MODE_READ (1)
  2044. /* Open file for writing, create and overwrite */
  2045. #define MG_FOPEN_MODE_WRITE (2)
  2046. /* Open file for writing, create and append */
  2047. #define MG_FOPEN_MODE_APPEND (4)
  2048. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2049. * output filep and return 1, otherwise return 0 and don't modify anything. */
  2050. static int
  2051. open_file_in_memory(const struct mg_connection *conn,
  2052. const char *path,
  2053. struct mg_file *filep,
  2054. int mode)
  2055. {
  2056. #if defined(MG_USE_OPEN_FILE)
  2057. size_t size = 0;
  2058. const char *buf = NULL;
  2059. if (!conn) {
  2060. return 0;
  2061. }
  2062. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2063. return 0;
  2064. }
  2065. if (conn->ctx->callbacks.open_file) {
  2066. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2067. if (buf != NULL) {
  2068. if (filep == NULL) {
  2069. /* This is a file in memory, but we cannot store the properties
  2070. * now.
  2071. * Called from "is_file_in_memory" function. */
  2072. return 1;
  2073. }
  2074. /* NOTE: override filep->size only on success. Otherwise, it might
  2075. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2076. filep->access.membuf = buf;
  2077. filep->access.fp = NULL;
  2078. /* Size was set by the callback */
  2079. filep->stat.size = size;
  2080. /* Assume the data may change during runtime by setting
  2081. * last_modified = now */
  2082. filep->stat.last_modified = time(NULL);
  2083. filep->stat.is_directory = 0;
  2084. filep->stat.is_gzipped = 0;
  2085. }
  2086. }
  2087. return (buf != NULL);
  2088. #else
  2089. (void)conn;
  2090. (void)path;
  2091. (void)filep;
  2092. (void)mode;
  2093. return 0;
  2094. #endif
  2095. }
  2096. static int
  2097. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2098. {
  2099. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2100. }
  2101. static int
  2102. is_file_opened(const struct mg_file_access *fileacc)
  2103. {
  2104. if (!fileacc) {
  2105. return 0;
  2106. }
  2107. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2108. }
  2109. static int mg_stat(const struct mg_connection *conn,
  2110. const char *path,
  2111. struct mg_file_stat *filep);
  2112. /* mg_fopen will open a file either in memory or on the disk.
  2113. * The input parameter path is a string in UTF-8 encoding.
  2114. * The input parameter mode is MG_FOPEN_MODE_*
  2115. * On success, either fp or membuf will be set in the output
  2116. * struct file. All status members will also be set.
  2117. * The function returns 1 on success, 0 on error. */
  2118. static int
  2119. mg_fopen(const struct mg_connection *conn,
  2120. const char *path,
  2121. int mode,
  2122. struct mg_file *filep)
  2123. {
  2124. int found;
  2125. if (!filep) {
  2126. return 0;
  2127. }
  2128. filep->access.fp = NULL;
  2129. filep->access.membuf = NULL;
  2130. if (!is_file_in_memory(conn, path)) {
  2131. /* filep is initialized in mg_stat: all fields with memset to,
  2132. * some fields like size and modification date with values */
  2133. found = mg_stat(conn, path, &(filep->stat));
  2134. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2135. /* file does not exist and will not be created */
  2136. return 0;
  2137. }
  2138. #ifdef _WIN32
  2139. {
  2140. wchar_t wbuf[PATH_MAX];
  2141. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2142. switch (mode) {
  2143. case MG_FOPEN_MODE_READ:
  2144. filep->access.fp = _wfopen(wbuf, L"rb");
  2145. break;
  2146. case MG_FOPEN_MODE_WRITE:
  2147. filep->access.fp = _wfopen(wbuf, L"wb");
  2148. break;
  2149. case MG_FOPEN_MODE_APPEND:
  2150. filep->access.fp = _wfopen(wbuf, L"ab");
  2151. break;
  2152. }
  2153. }
  2154. #else
  2155. /* Linux et al already use unicode. No need to convert. */
  2156. switch (mode) {
  2157. case MG_FOPEN_MODE_READ:
  2158. filep->access.fp = fopen(path, "r");
  2159. break;
  2160. case MG_FOPEN_MODE_WRITE:
  2161. filep->access.fp = fopen(path, "w");
  2162. break;
  2163. case MG_FOPEN_MODE_APPEND:
  2164. filep->access.fp = fopen(path, "a");
  2165. break;
  2166. }
  2167. #endif
  2168. if (!found) {
  2169. /* File did not exist before fopen was called.
  2170. * Maybe it has been created now. Get stat info
  2171. * like creation time now. */
  2172. found = mg_stat(conn, path, &(filep->stat));
  2173. (void)found;
  2174. }
  2175. /* file is on disk */
  2176. return (filep->access.fp != NULL);
  2177. } else {
  2178. /* is_file_in_memory returned true */
  2179. if (open_file_in_memory(conn, path, filep, mode)) {
  2180. /* file is in memory */
  2181. return (filep->access.membuf != NULL);
  2182. }
  2183. }
  2184. /* Open failed */
  2185. return 0;
  2186. }
  2187. /* return 0 on success, just like fclose */
  2188. static int
  2189. mg_fclose(struct mg_file_access *fileacc)
  2190. {
  2191. int ret = -1;
  2192. if (fileacc != NULL) {
  2193. if (fileacc->fp != NULL) {
  2194. ret = fclose(fileacc->fp);
  2195. } else if (fileacc->membuf != NULL) {
  2196. ret = 0;
  2197. }
  2198. /* reset all members of fileacc */
  2199. memset(fileacc, 0, sizeof(*fileacc));
  2200. }
  2201. return ret;
  2202. }
  2203. static void
  2204. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2205. {
  2206. for (; *src != '\0' && n > 1; n--) {
  2207. *dst++ = *src++;
  2208. }
  2209. *dst = '\0';
  2210. }
  2211. static int
  2212. lowercase(const char *s)
  2213. {
  2214. return tolower(*(const unsigned char *)s);
  2215. }
  2216. int
  2217. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2218. {
  2219. int diff = 0;
  2220. if (len > 0) {
  2221. do {
  2222. diff = lowercase(s1++) - lowercase(s2++);
  2223. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2224. }
  2225. return diff;
  2226. }
  2227. int
  2228. mg_strcasecmp(const char *s1, const char *s2)
  2229. {
  2230. int diff;
  2231. do {
  2232. diff = lowercase(s1++) - lowercase(s2++);
  2233. } while (diff == 0 && s1[-1] != '\0');
  2234. return diff;
  2235. }
  2236. static char *
  2237. mg_strndup(const char *ptr, size_t len)
  2238. {
  2239. char *p;
  2240. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2241. mg_strlcpy(p, ptr, len + 1);
  2242. }
  2243. return p;
  2244. }
  2245. static char *
  2246. mg_strdup(const char *str)
  2247. {
  2248. return mg_strndup(str, strlen(str));
  2249. }
  2250. static const char *
  2251. mg_strcasestr(const char *big_str, const char *small_str)
  2252. {
  2253. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2254. if (big_len >= small_len) {
  2255. for (i = 0; i <= (big_len - small_len); i++) {
  2256. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2257. return big_str + i;
  2258. }
  2259. }
  2260. }
  2261. return NULL;
  2262. }
  2263. /* Return null terminated string of given maximum length.
  2264. * Report errors if length is exceeded. */
  2265. static void
  2266. mg_vsnprintf(const struct mg_connection *conn,
  2267. int *truncated,
  2268. char *buf,
  2269. size_t buflen,
  2270. const char *fmt,
  2271. va_list ap)
  2272. {
  2273. int n, ok;
  2274. if (buflen == 0) {
  2275. return;
  2276. }
  2277. #ifdef __clang__
  2278. #pragma clang diagnostic push
  2279. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2280. /* Using fmt as a non-literal is intended here, since it is mostly called
  2281. * indirectly by mg_snprintf */
  2282. #endif
  2283. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2284. ok = (n >= 0) && ((size_t)n < buflen);
  2285. #ifdef __clang__
  2286. #pragma clang diagnostic pop
  2287. #endif
  2288. if (ok) {
  2289. if (truncated) {
  2290. *truncated = 0;
  2291. }
  2292. } else {
  2293. if (truncated) {
  2294. *truncated = 1;
  2295. }
  2296. mg_cry(conn,
  2297. "truncating vsnprintf buffer: [%.*s]",
  2298. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2299. buf);
  2300. n = (int)buflen - 1;
  2301. }
  2302. buf[n] = '\0';
  2303. }
  2304. static void
  2305. mg_snprintf(const struct mg_connection *conn,
  2306. int *truncated,
  2307. char *buf,
  2308. size_t buflen,
  2309. const char *fmt,
  2310. ...)
  2311. {
  2312. va_list ap;
  2313. va_start(ap, fmt);
  2314. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2315. va_end(ap);
  2316. }
  2317. static int
  2318. get_option_index(const char *name)
  2319. {
  2320. int i;
  2321. for (i = 0; config_options[i].name != NULL; i++) {
  2322. if (strcmp(config_options[i].name, name) == 0) {
  2323. return i;
  2324. }
  2325. }
  2326. return -1;
  2327. }
  2328. const char *
  2329. mg_get_option(const struct mg_context *ctx, const char *name)
  2330. {
  2331. int i;
  2332. if ((i = get_option_index(name)) == -1) {
  2333. return NULL;
  2334. } else if (!ctx || ctx->config[i] == NULL) {
  2335. return "";
  2336. } else {
  2337. return ctx->config[i];
  2338. }
  2339. }
  2340. struct mg_context *
  2341. mg_get_context(const struct mg_connection *conn)
  2342. {
  2343. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2344. }
  2345. void *
  2346. mg_get_user_data(const struct mg_context *ctx)
  2347. {
  2348. return (ctx == NULL) ? NULL : ctx->user_data;
  2349. }
  2350. void
  2351. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2352. {
  2353. if (conn != NULL) {
  2354. conn->request_info.conn_data = data;
  2355. }
  2356. }
  2357. void *
  2358. mg_get_user_connection_data(const struct mg_connection *conn)
  2359. {
  2360. if (conn != NULL) {
  2361. return conn->request_info.conn_data;
  2362. }
  2363. return NULL;
  2364. }
  2365. #if defined(MG_LEGACY_INTERFACE)
  2366. /* Deprecated: Use mg_get_server_ports instead. */
  2367. size_t
  2368. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2369. {
  2370. size_t i;
  2371. if (!ctx) {
  2372. return 0;
  2373. }
  2374. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2375. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2376. ports[i] =
  2377. #if defined(USE_IPV6)
  2378. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2379. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2380. :
  2381. #endif
  2382. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2383. }
  2384. return i;
  2385. }
  2386. #endif
  2387. int
  2388. mg_get_server_ports(const struct mg_context *ctx,
  2389. int size,
  2390. struct mg_server_ports *ports)
  2391. {
  2392. int i, cnt = 0;
  2393. if (size <= 0) {
  2394. return -1;
  2395. }
  2396. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2397. if (!ctx) {
  2398. return -1;
  2399. }
  2400. if (!ctx->listening_sockets) {
  2401. return -1;
  2402. }
  2403. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2404. ports[cnt].port =
  2405. #if defined(USE_IPV6)
  2406. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2407. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2408. :
  2409. #endif
  2410. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2411. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2412. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2413. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2414. /* IPv4 */
  2415. ports[cnt].protocol = 1;
  2416. cnt++;
  2417. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2418. /* IPv6 */
  2419. ports[cnt].protocol = 3;
  2420. cnt++;
  2421. }
  2422. }
  2423. return cnt;
  2424. }
  2425. static void
  2426. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2427. {
  2428. buf[0] = '\0';
  2429. if (!usa) {
  2430. return;
  2431. }
  2432. if (usa->sa.sa_family == AF_INET) {
  2433. getnameinfo(&usa->sa,
  2434. sizeof(usa->sin),
  2435. buf,
  2436. (unsigned)len,
  2437. NULL,
  2438. 0,
  2439. NI_NUMERICHOST);
  2440. }
  2441. #if defined(USE_IPV6)
  2442. else if (usa->sa.sa_family == AF_INET6) {
  2443. getnameinfo(&usa->sa,
  2444. sizeof(usa->sin6),
  2445. buf,
  2446. (unsigned)len,
  2447. NULL,
  2448. 0,
  2449. NI_NUMERICHOST);
  2450. }
  2451. #endif
  2452. }
  2453. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2454. * included in all responses other than 100, 101, 5xx. */
  2455. static void
  2456. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2457. {
  2458. struct tm *tm;
  2459. tm = ((t != NULL) ? gmtime(t) : NULL);
  2460. if (tm != NULL) {
  2461. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2462. } else {
  2463. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2464. buf[buf_len - 1] = '\0';
  2465. }
  2466. }
  2467. /* difftime for struct timespec. Return value is in seconds. */
  2468. static double
  2469. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2470. {
  2471. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2472. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2473. }
  2474. /* Print error message to the opened error log stream. */
  2475. void
  2476. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2477. {
  2478. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2479. va_list ap;
  2480. struct mg_file fi;
  2481. time_t timestamp;
  2482. va_start(ap, fmt);
  2483. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2484. va_end(ap);
  2485. buf[sizeof(buf) - 1] = 0;
  2486. if (!conn) {
  2487. puts(buf);
  2488. return;
  2489. }
  2490. /* Do not lock when getting the callback value, here and below.
  2491. * I suppose this is fine, since function cannot disappear in the
  2492. * same way string option can. */
  2493. if ((conn->ctx->callbacks.log_message == NULL)
  2494. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2495. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2496. if (mg_fopen(conn,
  2497. conn->ctx->config[ERROR_LOG_FILE],
  2498. MG_FOPEN_MODE_APPEND,
  2499. &fi) == 0) {
  2500. fi.access.fp = NULL;
  2501. }
  2502. } else {
  2503. fi.access.fp = NULL;
  2504. }
  2505. if (fi.access.fp != NULL) {
  2506. flockfile(fi.access.fp);
  2507. timestamp = time(NULL);
  2508. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2509. fprintf(fi.access.fp,
  2510. "[%010lu] [error] [client %s] ",
  2511. (unsigned long)timestamp,
  2512. src_addr);
  2513. if (conn->request_info.request_method != NULL) {
  2514. fprintf(fi.access.fp,
  2515. "%s %s: ",
  2516. conn->request_info.request_method,
  2517. conn->request_info.request_uri);
  2518. }
  2519. fprintf(fi.access.fp, "%s", buf);
  2520. fputc('\n', fi.access.fp);
  2521. fflush(fi.access.fp);
  2522. funlockfile(fi.access.fp);
  2523. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2524. * mg_cry here anyway ;-) */
  2525. }
  2526. }
  2527. }
  2528. /* Return fake connection structure. Used for logging, if connection
  2529. * is not applicable at the moment of logging. */
  2530. static struct mg_connection *
  2531. fc(struct mg_context *ctx)
  2532. {
  2533. static struct mg_connection fake_connection;
  2534. fake_connection.ctx = ctx;
  2535. return &fake_connection;
  2536. }
  2537. const char *
  2538. mg_version(void)
  2539. {
  2540. return CIVETWEB_VERSION;
  2541. }
  2542. const struct mg_request_info *
  2543. mg_get_request_info(const struct mg_connection *conn)
  2544. {
  2545. if (!conn) {
  2546. return NULL;
  2547. }
  2548. return &conn->request_info;
  2549. }
  2550. int
  2551. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2552. {
  2553. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2554. return -1;
  2555. } else {
  2556. int truncated = 0;
  2557. const struct mg_request_info *ri = &conn->request_info;
  2558. #ifdef __clang__
  2559. #pragma clang diagnostic push
  2560. #pragma clang diagnostic ignored "-Wunreachable-code"
  2561. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2562. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2563. * unreachable, but splitting into four different #ifdef clauses here is more
  2564. * complicated.
  2565. */
  2566. #endif
  2567. const char *proto =
  2568. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2569. : (ri->is_ssl ? "https" : "http"));
  2570. #ifdef __clang__
  2571. #pragma clang diagnostic pop
  2572. #endif
  2573. if (ri->local_uri == NULL) {
  2574. return -1;
  2575. }
  2576. if ((ri->request_uri != NULL)
  2577. && strcmp(ri->local_uri, ri->request_uri)) {
  2578. mg_snprintf(conn,
  2579. &truncated,
  2580. buf,
  2581. buflen,
  2582. "%s://%s",
  2583. proto,
  2584. ri->request_uri);
  2585. if (truncated) {
  2586. return -1;
  2587. }
  2588. return 0;
  2589. } else {
  2590. #if defined(USE_IPV6)
  2591. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2592. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2593. : htons(conn->client.lsa.sin.sin_port);
  2594. #else
  2595. int port = htons(conn->client.lsa.sin.sin_port);
  2596. #endif
  2597. int def_port = ri->is_ssl ? 443 : 80;
  2598. int auth_domain_check_enabled =
  2599. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2600. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2601. "yes"));
  2602. const char *server_domain =
  2603. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2604. char portstr[16];
  2605. char server_ip[48];
  2606. if (port != def_port) {
  2607. sprintf(portstr, ":%u", (unsigned)port);
  2608. } else {
  2609. portstr[0] = 0;
  2610. }
  2611. if (!auth_domain_check_enabled || !server_domain) {
  2612. sockaddr_to_string(server_ip,
  2613. sizeof(server_ip),
  2614. &conn->client.lsa);
  2615. server_domain = server_ip;
  2616. }
  2617. mg_snprintf(conn,
  2618. &truncated,
  2619. buf,
  2620. buflen,
  2621. "%s://%s%s%s",
  2622. proto,
  2623. server_domain,
  2624. portstr,
  2625. ri->local_uri);
  2626. if (truncated) {
  2627. return -1;
  2628. }
  2629. return 0;
  2630. }
  2631. }
  2632. }
  2633. /* Skip the characters until one of the delimiters characters found.
  2634. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2635. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2636. * Delimiters can be quoted with quotechar. */
  2637. static char *
  2638. skip_quoted(char **buf,
  2639. const char *delimiters,
  2640. const char *whitespace,
  2641. char quotechar)
  2642. {
  2643. char *p, *begin_word, *end_word, *end_whitespace;
  2644. begin_word = *buf;
  2645. end_word = begin_word + strcspn(begin_word, delimiters);
  2646. /* Check for quotechar */
  2647. if (end_word > begin_word) {
  2648. p = end_word - 1;
  2649. while (*p == quotechar) {
  2650. /* While the delimiter is quoted, look for the next delimiter. */
  2651. /* This happens, e.g., in calls from parse_auth_header,
  2652. * if the user name contains a " character. */
  2653. /* If there is anything beyond end_word, copy it. */
  2654. if (*end_word != '\0') {
  2655. size_t end_off = strcspn(end_word + 1, delimiters);
  2656. memmove(p, end_word, end_off + 1);
  2657. p += end_off; /* p must correspond to end_word - 1 */
  2658. end_word += end_off + 1;
  2659. } else {
  2660. *p = '\0';
  2661. break;
  2662. }
  2663. }
  2664. for (p++; p < end_word; p++) {
  2665. *p = '\0';
  2666. }
  2667. }
  2668. if (*end_word == '\0') {
  2669. *buf = end_word;
  2670. } else {
  2671. #if defined(__GNUC__) || defined(__MINGW32__)
  2672. /* Disable spurious conversion warning for GCC */
  2673. #pragma GCC diagnostic push
  2674. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2675. #endif
  2676. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2677. #if defined(__GNUC__) || defined(__MINGW32__)
  2678. #pragma GCC diagnostic pop
  2679. #endif
  2680. for (p = end_word; p < end_whitespace; p++) {
  2681. *p = '\0';
  2682. }
  2683. *buf = end_whitespace;
  2684. }
  2685. return begin_word;
  2686. }
  2687. /* Simplified version of skip_quoted without quote char
  2688. * and whitespace == delimiters */
  2689. static char *
  2690. skip(char **buf, const char *delimiters)
  2691. {
  2692. return skip_quoted(buf, delimiters, delimiters, 0);
  2693. }
  2694. /* Return HTTP header value, or NULL if not found. */
  2695. static const char *
  2696. get_header(const struct mg_request_info *ri, const char *name)
  2697. {
  2698. int i;
  2699. if (ri) {
  2700. for (i = 0; i < ri->num_headers; i++) {
  2701. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2702. return ri->http_headers[i].value;
  2703. }
  2704. }
  2705. }
  2706. return NULL;
  2707. }
  2708. const char *
  2709. mg_get_header(const struct mg_connection *conn, const char *name)
  2710. {
  2711. if (!conn) {
  2712. return NULL;
  2713. }
  2714. return get_header(&conn->request_info, name);
  2715. }
  2716. /* A helper function for traversing a comma separated list of values.
  2717. * It returns a list pointer shifted to the next value, or NULL if the end
  2718. * of the list found.
  2719. * Value is stored in val vector. If value has form "x=y", then eq_val
  2720. * vector is initialized to point to the "y" part, and val vector length
  2721. * is adjusted to point only to "x". */
  2722. static const char *
  2723. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2724. {
  2725. int end;
  2726. reparse:
  2727. if (val == NULL || list == NULL || *list == '\0') {
  2728. /* End of the list */
  2729. list = NULL;
  2730. } else {
  2731. /* Skip over leading LWS */
  2732. while (*list == ' ' || *list == '\t')
  2733. list++;
  2734. val->ptr = list;
  2735. if ((list = strchr(val->ptr, ',')) != NULL) {
  2736. /* Comma found. Store length and shift the list ptr */
  2737. val->len = ((size_t)(list - val->ptr));
  2738. list++;
  2739. } else {
  2740. /* This value is the last one */
  2741. list = val->ptr + strlen(val->ptr);
  2742. val->len = ((size_t)(list - val->ptr));
  2743. }
  2744. /* Adjust length for trailing LWS */
  2745. end = (int)val->len - 1;
  2746. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2747. end--;
  2748. val->len = (size_t)(end + 1);
  2749. if (val->len == 0) {
  2750. /* Ignore any empty entries. */
  2751. goto reparse;
  2752. }
  2753. if (eq_val != NULL) {
  2754. /* Value has form "x=y", adjust pointers and lengths
  2755. * so that val points to "x", and eq_val points to "y". */
  2756. eq_val->len = 0;
  2757. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2758. if (eq_val->ptr != NULL) {
  2759. eq_val->ptr++; /* Skip over '=' character */
  2760. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2761. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2762. }
  2763. }
  2764. }
  2765. return list;
  2766. }
  2767. /* A helper function for checking if a comma separated list of values contains
  2768. * the given option (case insensitvely).
  2769. * 'header' can be NULL, in which case false is returned. */
  2770. static int
  2771. header_has_option(const char *header, const char *option)
  2772. {
  2773. struct vec opt_vec;
  2774. struct vec eq_vec;
  2775. assert(option != NULL);
  2776. assert(option[0] != '\0');
  2777. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2778. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2779. return 1;
  2780. }
  2781. return 0;
  2782. }
  2783. /* Perform case-insensitive match of string against pattern */
  2784. static int
  2785. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2786. {
  2787. const char *or_str;
  2788. size_t i;
  2789. int j, len, res;
  2790. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2791. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2792. return (res > 0) ? res : match_prefix(or_str + 1,
  2793. (size_t)((pattern + pattern_len)
  2794. - (or_str + 1)),
  2795. str);
  2796. }
  2797. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2798. if (pattern[i] == '?' && str[j] != '\0') {
  2799. continue;
  2800. } else if (pattern[i] == '$') {
  2801. return (str[j] == '\0') ? j : -1;
  2802. } else if (pattern[i] == '*') {
  2803. i++;
  2804. if (pattern[i] == '*') {
  2805. i++;
  2806. len = (int)strlen(str + j);
  2807. } else {
  2808. len = (int)strcspn(str + j, "/");
  2809. }
  2810. if (i == pattern_len) {
  2811. return j + len;
  2812. }
  2813. do {
  2814. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2815. } while (res == -1 && len-- > 0);
  2816. return (res == -1) ? -1 : j + res + len;
  2817. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2818. return -1;
  2819. }
  2820. }
  2821. return j;
  2822. }
  2823. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2824. * This function must tolerate situations when connection info is not
  2825. * set up, for example if request parsing failed. */
  2826. static int
  2827. should_keep_alive(const struct mg_connection *conn)
  2828. {
  2829. if (conn != NULL) {
  2830. const char *http_version = conn->request_info.http_version;
  2831. const char *header = mg_get_header(conn, "Connection");
  2832. if (conn->must_close || conn->status_code == 401
  2833. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2834. || (header != NULL && !header_has_option(header, "keep-alive"))
  2835. || (header == NULL && http_version
  2836. && 0 != strcmp(http_version, "1.1"))) {
  2837. return 0;
  2838. }
  2839. return 1;
  2840. }
  2841. return 0;
  2842. }
  2843. static int
  2844. should_decode_url(const struct mg_connection *conn)
  2845. {
  2846. if (!conn || !conn->ctx) {
  2847. return 0;
  2848. }
  2849. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2850. }
  2851. static const char *
  2852. suggest_connection_header(const struct mg_connection *conn)
  2853. {
  2854. return should_keep_alive(conn) ? "keep-alive" : "close";
  2855. }
  2856. static int
  2857. send_no_cache_header(struct mg_connection *conn)
  2858. {
  2859. /* Send all current and obsolete cache opt-out directives. */
  2860. return mg_printf(conn,
  2861. "Cache-Control: no-cache, no-store, "
  2862. "must-revalidate, private, max-age=0\r\n"
  2863. "Pragma: no-cache\r\n"
  2864. "Expires: 0\r\n");
  2865. }
  2866. static int
  2867. send_static_cache_header(struct mg_connection *conn)
  2868. {
  2869. #if !defined(NO_CACHING)
  2870. /* Read the server config to check how long a file may be cached.
  2871. * The configuration is in seconds. */
  2872. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2873. if (max_age <= 0) {
  2874. /* 0 means "do not cache". All values <0 are reserved
  2875. * and may be used differently in the future. */
  2876. /* If a file should not be cached, do not only send
  2877. * max-age=0, but also pragmas and Expires headers. */
  2878. return send_no_cache_header(conn);
  2879. }
  2880. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2881. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2882. /* See also https://www.mnot.net/cache_docs/ */
  2883. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2884. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2885. * year to 31622400 seconds. For the moment, we just send whatever has
  2886. * been configured, still the behavior for >1 year should be considered
  2887. * as undefined. */
  2888. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2889. #else /* NO_CACHING */
  2890. return send_no_cache_header(conn);
  2891. #endif /* !NO_CACHING */
  2892. }
  2893. static int
  2894. send_additional_header(struct mg_connection *conn)
  2895. {
  2896. int i = 0;
  2897. if (conn->ctx->config[STRICT_HTTPS_MAX_AGE]) {
  2898. int max_age = atoi(conn->ctx->config[STRICT_HTTPS_MAX_AGE]);
  2899. if (max_age >= 0) {
  2900. i += mg_printf(conn,
  2901. "Strict-Transport-Security: max-age=%u\r\n",
  2902. (unsigned)max_age);
  2903. }
  2904. }
  2905. return i;
  2906. }
  2907. static void handle_file_based_request(struct mg_connection *conn,
  2908. const char *path,
  2909. struct mg_file *filep);
  2910. const char *
  2911. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  2912. {
  2913. /* See IANA HTTP status code assignment:
  2914. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2915. */
  2916. switch (response_code) {
  2917. /* RFC2616 Section 10.1 - Informational 1xx */
  2918. case 100:
  2919. return "Continue"; /* RFC2616 Section 10.1.1 */
  2920. case 101:
  2921. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2922. case 102:
  2923. return "Processing"; /* RFC2518 Section 10.1 */
  2924. /* RFC2616 Section 10.2 - Successful 2xx */
  2925. case 200:
  2926. return "OK"; /* RFC2616 Section 10.2.1 */
  2927. case 201:
  2928. return "Created"; /* RFC2616 Section 10.2.2 */
  2929. case 202:
  2930. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2931. case 203:
  2932. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2933. case 204:
  2934. return "No Content"; /* RFC2616 Section 10.2.5 */
  2935. case 205:
  2936. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2937. case 206:
  2938. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2939. case 207:
  2940. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2941. case 208:
  2942. return "Already Reported"; /* RFC5842 Section 7.1 */
  2943. case 226:
  2944. return "IM used"; /* RFC3229 Section 10.4.1 */
  2945. /* RFC2616 Section 10.3 - Redirection 3xx */
  2946. case 300:
  2947. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2948. case 301:
  2949. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2950. case 302:
  2951. return "Found"; /* RFC2616 Section 10.3.3 */
  2952. case 303:
  2953. return "See Other"; /* RFC2616 Section 10.3.4 */
  2954. case 304:
  2955. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2956. case 305:
  2957. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2958. case 307:
  2959. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2960. case 308:
  2961. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2962. /* RFC2616 Section 10.4 - Client Error 4xx */
  2963. case 400:
  2964. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2965. case 401:
  2966. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2967. case 402:
  2968. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2969. case 403:
  2970. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2971. case 404:
  2972. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2973. case 405:
  2974. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2975. case 406:
  2976. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2977. case 407:
  2978. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2979. case 408:
  2980. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2981. case 409:
  2982. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2983. case 410:
  2984. return "Gone"; /* RFC2616 Section 10.4.11 */
  2985. case 411:
  2986. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2987. case 412:
  2988. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2989. case 413:
  2990. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2991. case 414:
  2992. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2993. case 415:
  2994. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2995. case 416:
  2996. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2997. case 417:
  2998. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2999. case 421:
  3000. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3001. case 422:
  3002. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3003. * Section 11.2 */
  3004. case 423:
  3005. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3006. case 424:
  3007. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3008. * Section 11.4 */
  3009. case 426:
  3010. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3011. case 428:
  3012. return "Precondition Required"; /* RFC 6585, Section 3 */
  3013. case 429:
  3014. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3015. case 431:
  3016. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3017. case 451:
  3018. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3019. * Section 3 */
  3020. /* RFC2616 Section 10.5 - Server Error 5xx */
  3021. case 500:
  3022. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3023. case 501:
  3024. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3025. case 502:
  3026. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3027. case 503:
  3028. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3029. case 504:
  3030. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3031. case 505:
  3032. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3033. case 506:
  3034. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3035. case 507:
  3036. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3037. * Section 11.5 */
  3038. case 508:
  3039. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3040. case 510:
  3041. return "Not Extended"; /* RFC 2774, Section 7 */
  3042. case 511:
  3043. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3044. /* Other status codes, not shown in the IANA HTTP status code assignment.
  3045. * E.g., "de facto" standards due to common use, ... */
  3046. case 418:
  3047. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3048. case 419:
  3049. return "Authentication Timeout"; /* common use */
  3050. case 420:
  3051. return "Enhance Your Calm"; /* common use */
  3052. case 440:
  3053. return "Login Timeout"; /* common use */
  3054. case 509:
  3055. return "Bandwidth Limit Exceeded"; /* common use */
  3056. default:
  3057. /* This error code is unknown. This should not happen. */
  3058. if (conn) {
  3059. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3060. }
  3061. /* Return at least a category according to RFC 2616 Section 10. */
  3062. if (response_code >= 100 && response_code < 200) {
  3063. /* Unknown informational status code */
  3064. return "Information";
  3065. }
  3066. if (response_code >= 200 && response_code < 300) {
  3067. /* Unknown success code */
  3068. return "Success";
  3069. }
  3070. if (response_code >= 300 && response_code < 400) {
  3071. /* Unknown redirection code */
  3072. return "Redirection";
  3073. }
  3074. if (response_code >= 400 && response_code < 500) {
  3075. /* Unknown request error code */
  3076. return "Client Error";
  3077. }
  3078. if (response_code >= 500 && response_code < 600) {
  3079. /* Unknown server error code */
  3080. return "Server Error";
  3081. }
  3082. /* Response code not even within reasonable range */
  3083. return "";
  3084. }
  3085. }
  3086. void
  3087. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3088. {
  3089. char buf[MG_BUF_LEN];
  3090. va_list ap;
  3091. int len, i, page_handler_found, scope, truncated, has_body;
  3092. char date[64];
  3093. time_t curtime = time(NULL);
  3094. const char *error_handler = NULL;
  3095. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3096. const char *error_page_file_ext, *tstr;
  3097. const char *status_text = mg_get_response_code_text(conn, status);
  3098. if (conn == NULL) {
  3099. return;
  3100. }
  3101. conn->status_code = status;
  3102. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  3103. || conn->ctx->callbacks.http_error(conn, status)) {
  3104. if (!conn->in_error_handler) {
  3105. /* Send user defined error pages, if defined */
  3106. error_handler = conn->ctx->config[ERROR_PAGES];
  3107. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3108. page_handler_found = 0;
  3109. if (error_handler != NULL) {
  3110. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3111. switch (scope) {
  3112. case 1: /* Handler for specific error, e.g. 404 error */
  3113. mg_snprintf(conn,
  3114. &truncated,
  3115. buf,
  3116. sizeof(buf) - 32,
  3117. "%serror%03u.",
  3118. error_handler,
  3119. status);
  3120. break;
  3121. case 2: /* Handler for error group, e.g., 5xx error handler
  3122. * for all server errors (500-599) */
  3123. mg_snprintf(conn,
  3124. &truncated,
  3125. buf,
  3126. sizeof(buf) - 32,
  3127. "%serror%01uxx.",
  3128. error_handler,
  3129. status / 100);
  3130. break;
  3131. default: /* Handler for all errors */
  3132. mg_snprintf(conn,
  3133. &truncated,
  3134. buf,
  3135. sizeof(buf) - 32,
  3136. "%serror.",
  3137. error_handler);
  3138. break;
  3139. }
  3140. /* String truncation in buf may only occur if error_handler
  3141. * is too long. This string is from the config, not from a
  3142. * client. */
  3143. (void)truncated;
  3144. len = (int)strlen(buf);
  3145. tstr = strchr(error_page_file_ext, '.');
  3146. while (tstr) {
  3147. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  3148. i++)
  3149. buf[len + i - 1] = tstr[i];
  3150. buf[len + i - 1] = 0;
  3151. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3152. page_handler_found = 1;
  3153. break;
  3154. }
  3155. tstr = strchr(tstr + i, '.');
  3156. }
  3157. }
  3158. }
  3159. if (page_handler_found) {
  3160. conn->in_error_handler = 1;
  3161. handle_file_based_request(conn, buf, &error_page_file);
  3162. conn->in_error_handler = 0;
  3163. return;
  3164. }
  3165. }
  3166. /* No custom error page. Send default error page. */
  3167. gmt_time_string(date, sizeof(date), &curtime);
  3168. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3169. has_body = (status > 199 && status != 204 && status != 304);
  3170. conn->must_close = 1;
  3171. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3172. send_no_cache_header(conn);
  3173. send_additional_header(conn);
  3174. if (has_body) {
  3175. mg_printf(conn,
  3176. "%s",
  3177. "Content-Type: text/plain; charset=utf-8\r\n");
  3178. }
  3179. mg_printf(conn,
  3180. "Date: %s\r\n"
  3181. "Connection: close\r\n\r\n",
  3182. date);
  3183. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3184. if (has_body) {
  3185. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3186. if (fmt != NULL) {
  3187. va_start(ap, fmt);
  3188. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3189. va_end(ap);
  3190. mg_write(conn, buf, strlen(buf));
  3191. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3192. }
  3193. } else {
  3194. /* No body allowed. Close the connection. */
  3195. DEBUG_TRACE("Error %i", status);
  3196. }
  3197. }
  3198. }
  3199. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3200. /* Create substitutes for POSIX functions in Win32. */
  3201. #if defined(__MINGW32__)
  3202. /* Show no warning in case system functions are not used. */
  3203. #pragma GCC diagnostic push
  3204. #pragma GCC diagnostic ignored "-Wunused-function"
  3205. #endif
  3206. static int
  3207. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3208. {
  3209. (void)unused;
  3210. *mutex = CreateMutex(NULL, FALSE, NULL);
  3211. return (*mutex == NULL) ? -1 : 0;
  3212. }
  3213. static int
  3214. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3215. {
  3216. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3217. }
  3218. static int
  3219. pthread_mutex_lock(pthread_mutex_t *mutex)
  3220. {
  3221. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3222. }
  3223. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3224. static int
  3225. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3226. {
  3227. switch (WaitForSingleObject(*mutex, 0)) {
  3228. case WAIT_OBJECT_0:
  3229. return 0;
  3230. case WAIT_TIMEOUT:
  3231. return -2; /* EBUSY */
  3232. }
  3233. return -1;
  3234. }
  3235. #endif
  3236. static int
  3237. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3238. {
  3239. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3240. }
  3241. static int
  3242. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3243. {
  3244. (void)unused;
  3245. InitializeCriticalSection(&cv->threadIdSec);
  3246. cv->waiting_thread = NULL;
  3247. return 0;
  3248. }
  3249. static int
  3250. pthread_cond_timedwait(pthread_cond_t *cv,
  3251. pthread_mutex_t *mutex,
  3252. const struct timespec *abstime)
  3253. {
  3254. struct mg_workerTLS **ptls,
  3255. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3256. int ok;
  3257. int64_t nsnow, nswaitabs, nswaitrel;
  3258. DWORD mswaitrel;
  3259. EnterCriticalSection(&cv->threadIdSec);
  3260. /* Add this thread to cv's waiting list */
  3261. ptls = &cv->waiting_thread;
  3262. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3263. ;
  3264. tls->next_waiting_thread = NULL;
  3265. *ptls = tls;
  3266. LeaveCriticalSection(&cv->threadIdSec);
  3267. if (abstime) {
  3268. nsnow = mg_get_current_time_ns();
  3269. nswaitabs =
  3270. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3271. nswaitrel = nswaitabs - nsnow;
  3272. if (nswaitrel < 0) {
  3273. nswaitrel = 0;
  3274. }
  3275. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3276. } else {
  3277. mswaitrel = INFINITE;
  3278. }
  3279. pthread_mutex_unlock(mutex);
  3280. ok = (WAIT_OBJECT_0
  3281. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3282. if (!ok) {
  3283. ok = 1;
  3284. EnterCriticalSection(&cv->threadIdSec);
  3285. ptls = &cv->waiting_thread;
  3286. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3287. if (*ptls == tls) {
  3288. *ptls = tls->next_waiting_thread;
  3289. ok = 0;
  3290. break;
  3291. }
  3292. }
  3293. LeaveCriticalSection(&cv->threadIdSec);
  3294. if (ok) {
  3295. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3296. }
  3297. }
  3298. /* This thread has been removed from cv's waiting list */
  3299. pthread_mutex_lock(mutex);
  3300. return ok ? 0 : -1;
  3301. }
  3302. static int
  3303. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3304. {
  3305. return pthread_cond_timedwait(cv, mutex, NULL);
  3306. }
  3307. static int
  3308. pthread_cond_signal(pthread_cond_t *cv)
  3309. {
  3310. HANDLE wkup = NULL;
  3311. BOOL ok = FALSE;
  3312. EnterCriticalSection(&cv->threadIdSec);
  3313. if (cv->waiting_thread) {
  3314. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3315. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3316. ok = SetEvent(wkup);
  3317. assert(ok);
  3318. }
  3319. LeaveCriticalSection(&cv->threadIdSec);
  3320. return ok ? 0 : 1;
  3321. }
  3322. static int
  3323. pthread_cond_broadcast(pthread_cond_t *cv)
  3324. {
  3325. EnterCriticalSection(&cv->threadIdSec);
  3326. while (cv->waiting_thread) {
  3327. pthread_cond_signal(cv);
  3328. }
  3329. LeaveCriticalSection(&cv->threadIdSec);
  3330. return 0;
  3331. }
  3332. static int
  3333. pthread_cond_destroy(pthread_cond_t *cv)
  3334. {
  3335. EnterCriticalSection(&cv->threadIdSec);
  3336. assert(cv->waiting_thread == NULL);
  3337. LeaveCriticalSection(&cv->threadIdSec);
  3338. DeleteCriticalSection(&cv->threadIdSec);
  3339. return 0;
  3340. }
  3341. #ifdef ALTERNATIVE_QUEUE
  3342. static void *
  3343. event_create(void)
  3344. {
  3345. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3346. }
  3347. static int
  3348. event_wait(void *eventhdl)
  3349. {
  3350. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3351. return (res == WAIT_OBJECT_0);
  3352. }
  3353. static int
  3354. event_signal(void *eventhdl)
  3355. {
  3356. return (int)SetEvent((HANDLE)eventhdl);
  3357. }
  3358. static void
  3359. event_destroy(void *eventhdl)
  3360. {
  3361. CloseHandle((HANDLE)eventhdl);
  3362. }
  3363. #endif
  3364. #if defined(__MINGW32__)
  3365. /* Enable unused function warning again */
  3366. #pragma GCC diagnostic pop
  3367. #endif
  3368. /* For Windows, change all slashes to backslashes in path names. */
  3369. static void
  3370. change_slashes_to_backslashes(char *path)
  3371. {
  3372. int i;
  3373. for (i = 0; path[i] != '\0'; i++) {
  3374. if (path[i] == '/') {
  3375. path[i] = '\\';
  3376. }
  3377. /* remove double backslash (check i > 0 to preserve UNC paths,
  3378. * like \\server\file.txt) */
  3379. if ((path[i] == '\\') && (i > 0)) {
  3380. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3381. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3382. }
  3383. }
  3384. }
  3385. }
  3386. static int
  3387. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3388. {
  3389. int diff;
  3390. do {
  3391. diff = tolower(*s1) - tolower(*s2);
  3392. s1++;
  3393. s2++;
  3394. } while (diff == 0 && s1[-1] != '\0');
  3395. return diff;
  3396. }
  3397. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3398. * wbuf and wbuf_len is a target buffer and its length. */
  3399. static void
  3400. path_to_unicode(const struct mg_connection *conn,
  3401. const char *path,
  3402. wchar_t *wbuf,
  3403. size_t wbuf_len)
  3404. {
  3405. char buf[PATH_MAX], buf2[PATH_MAX];
  3406. wchar_t wbuf2[MAX_PATH + 1];
  3407. DWORD long_len, err;
  3408. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3409. mg_strlcpy(buf, path, sizeof(buf));
  3410. change_slashes_to_backslashes(buf);
  3411. /* Convert to Unicode and back. If doubly-converted string does not
  3412. * match the original, something is fishy, reject. */
  3413. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3414. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3415. WideCharToMultiByte(
  3416. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3417. if (strcmp(buf, buf2) != 0) {
  3418. wbuf[0] = L'\0';
  3419. }
  3420. /* Windows file systems are not case sensitive, but you can still use
  3421. * uppercase and lowercase letters (on all modern file systems).
  3422. * The server can check if the URI uses the same upper/lowercase
  3423. * letters an the file system, effectively making Windows servers
  3424. * case sensitive (like Linux servers are). It is still not possible
  3425. * to use two files with the same name in different cases on Windows
  3426. * (like /a and /A) - this would be possible in Linux.
  3427. * As a default, Windows is not case sensitive, but the case sensitive
  3428. * file name check can be activated by an additional configuration. */
  3429. if (conn) {
  3430. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3431. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3432. /* Use case sensitive compare function */
  3433. fcompare = wcscmp;
  3434. }
  3435. }
  3436. (void)conn; /* conn is currently unused */
  3437. #if !defined(_WIN32_WCE)
  3438. /* Only accept a full file path, not a Windows short (8.3) path. */
  3439. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3440. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3441. if (long_len == 0) {
  3442. err = GetLastError();
  3443. if (err == ERROR_FILE_NOT_FOUND) {
  3444. /* File does not exist. This is not always a problem here. */
  3445. return;
  3446. }
  3447. }
  3448. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3449. /* Short name is used. */
  3450. wbuf[0] = L'\0';
  3451. }
  3452. #else
  3453. (void)long_len;
  3454. (void)wbuf2;
  3455. (void)err;
  3456. if (strchr(path, '~')) {
  3457. wbuf[0] = L'\0';
  3458. }
  3459. #endif
  3460. }
  3461. /* Windows happily opens files with some garbage at the end of file name.
  3462. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3463. * "a.cgi", despite one would expect an error back.
  3464. * This function returns non-0 if path ends with some garbage. */
  3465. static int
  3466. path_cannot_disclose_cgi(const char *path)
  3467. {
  3468. static const char *allowed_last_characters = "_-";
  3469. int last = path[strlen(path) - 1];
  3470. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3471. }
  3472. static int
  3473. mg_stat(const struct mg_connection *conn,
  3474. const char *path,
  3475. struct mg_file_stat *filep)
  3476. {
  3477. wchar_t wbuf[PATH_MAX];
  3478. WIN32_FILE_ATTRIBUTE_DATA info;
  3479. time_t creation_time;
  3480. if (!filep) {
  3481. return 0;
  3482. }
  3483. memset(filep, 0, sizeof(*filep));
  3484. if (conn && is_file_in_memory(conn, path)) {
  3485. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3486. * memset */
  3487. /* Quick fix (for 1.9.x): */
  3488. /* mg_stat must fill all fields, also for files in memory */
  3489. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3490. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3491. filep->size = tmp_file.stat.size;
  3492. filep->location = 2;
  3493. /* TODO: for 1.10: restructure how files in memory are handled */
  3494. /* The "file in memory" feature is a candidate for deletion.
  3495. * Please join the discussion at
  3496. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3497. */
  3498. filep->last_modified = time(NULL); /* TODO */
  3499. /* last_modified = now ... assumes the file may change during runtime,
  3500. * so every mg_fopen call may return different data */
  3501. /* last_modified = conn->ctx.start_time;
  3502. * May be used it the data does not change during runtime. This allows
  3503. * browser caching. Since we do not know, we have to assume the file
  3504. * in memory may change. */
  3505. return 1;
  3506. }
  3507. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3508. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3509. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3510. filep->last_modified =
  3511. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3512. info.ftLastWriteTime.dwHighDateTime);
  3513. /* On Windows, the file creation time can be higher than the
  3514. * modification time, e.g. when a file is copied.
  3515. * Since the Last-Modified timestamp is used for caching
  3516. * it should be based on the most recent timestamp. */
  3517. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3518. info.ftCreationTime.dwHighDateTime);
  3519. if (creation_time > filep->last_modified) {
  3520. filep->last_modified = creation_time;
  3521. }
  3522. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3523. /* If file name is fishy, reset the file structure and return
  3524. * error.
  3525. * Note it is important to reset, not just return the error, cause
  3526. * functions like is_file_opened() check the struct. */
  3527. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3528. memset(filep, 0, sizeof(*filep));
  3529. return 0;
  3530. }
  3531. return 1;
  3532. }
  3533. return 0;
  3534. }
  3535. static int
  3536. mg_remove(const struct mg_connection *conn, const char *path)
  3537. {
  3538. wchar_t wbuf[PATH_MAX];
  3539. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3540. return DeleteFileW(wbuf) ? 0 : -1;
  3541. }
  3542. static int
  3543. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3544. {
  3545. wchar_t wbuf[PATH_MAX];
  3546. (void)mode;
  3547. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3548. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3549. }
  3550. /* Create substitutes for POSIX functions in Win32. */
  3551. #if defined(__MINGW32__)
  3552. /* Show no warning in case system functions are not used. */
  3553. #pragma GCC diagnostic push
  3554. #pragma GCC diagnostic ignored "-Wunused-function"
  3555. #endif
  3556. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3557. static DIR *
  3558. mg_opendir(const struct mg_connection *conn, const char *name)
  3559. {
  3560. DIR *dir = NULL;
  3561. wchar_t wpath[PATH_MAX];
  3562. DWORD attrs;
  3563. if (name == NULL) {
  3564. SetLastError(ERROR_BAD_ARGUMENTS);
  3565. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3566. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3567. } else {
  3568. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3569. attrs = GetFileAttributesW(wpath);
  3570. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3571. == FILE_ATTRIBUTE_DIRECTORY)) {
  3572. (void)wcscat(wpath, L"\\*");
  3573. dir->handle = FindFirstFileW(wpath, &dir->info);
  3574. dir->result.d_name[0] = '\0';
  3575. } else {
  3576. mg_free(dir);
  3577. dir = NULL;
  3578. }
  3579. }
  3580. return dir;
  3581. }
  3582. static int
  3583. mg_closedir(DIR *dir)
  3584. {
  3585. int result = 0;
  3586. if (dir != NULL) {
  3587. if (dir->handle != INVALID_HANDLE_VALUE)
  3588. result = FindClose(dir->handle) ? 0 : -1;
  3589. mg_free(dir);
  3590. } else {
  3591. result = -1;
  3592. SetLastError(ERROR_BAD_ARGUMENTS);
  3593. }
  3594. return result;
  3595. }
  3596. static struct dirent *
  3597. mg_readdir(DIR *dir)
  3598. {
  3599. struct dirent *result = 0;
  3600. if (dir) {
  3601. if (dir->handle != INVALID_HANDLE_VALUE) {
  3602. result = &dir->result;
  3603. (void)WideCharToMultiByte(CP_UTF8,
  3604. 0,
  3605. dir->info.cFileName,
  3606. -1,
  3607. result->d_name,
  3608. sizeof(result->d_name),
  3609. NULL,
  3610. NULL);
  3611. if (!FindNextFileW(dir->handle, &dir->info)) {
  3612. (void)FindClose(dir->handle);
  3613. dir->handle = INVALID_HANDLE_VALUE;
  3614. }
  3615. } else {
  3616. SetLastError(ERROR_FILE_NOT_FOUND);
  3617. }
  3618. } else {
  3619. SetLastError(ERROR_BAD_ARGUMENTS);
  3620. }
  3621. return result;
  3622. }
  3623. #ifndef HAVE_POLL
  3624. static int
  3625. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3626. {
  3627. struct timeval tv;
  3628. fd_set set;
  3629. unsigned int i;
  3630. int result;
  3631. SOCKET maxfd = 0;
  3632. memset(&tv, 0, sizeof(tv));
  3633. tv.tv_sec = milliseconds / 1000;
  3634. tv.tv_usec = (milliseconds % 1000) * 1000;
  3635. FD_ZERO(&set);
  3636. for (i = 0; i < n; i++) {
  3637. FD_SET((SOCKET)pfd[i].fd, &set);
  3638. pfd[i].revents = 0;
  3639. if (pfd[i].fd > maxfd) {
  3640. maxfd = pfd[i].fd;
  3641. }
  3642. }
  3643. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3644. for (i = 0; i < n; i++) {
  3645. if (FD_ISSET(pfd[i].fd, &set)) {
  3646. pfd[i].revents = POLLIN;
  3647. }
  3648. }
  3649. }
  3650. /* We should subtract the time used in select from remaining
  3651. * "milliseconds", in particular if called from mg_poll with a
  3652. * timeout quantum.
  3653. * Unfortunately, the remaining time is not stored in "tv" in all
  3654. * implementations, so the result in "tv" must be considered undefined.
  3655. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3656. return result;
  3657. }
  3658. #endif /* HAVE_POLL */
  3659. #if defined(__MINGW32__)
  3660. /* Enable unused function warning again */
  3661. #pragma GCC diagnostic pop
  3662. #endif
  3663. static void
  3664. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3665. {
  3666. (void)conn; /* Unused. */
  3667. #if defined(_WIN32_WCE)
  3668. (void)sock;
  3669. #else
  3670. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3671. #endif
  3672. }
  3673. int
  3674. mg_start_thread(mg_thread_func_t f, void *p)
  3675. {
  3676. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3677. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3678. */
  3679. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3680. == ((uintptr_t)(-1L)))
  3681. ? -1
  3682. : 0);
  3683. #else
  3684. return (
  3685. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3686. ? -1
  3687. : 0);
  3688. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3689. }
  3690. /* Start a thread storing the thread context. */
  3691. static int
  3692. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3693. void *p,
  3694. pthread_t *threadidptr)
  3695. {
  3696. uintptr_t uip;
  3697. HANDLE threadhandle;
  3698. int result = -1;
  3699. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3700. threadhandle = (HANDLE)uip;
  3701. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3702. *threadidptr = threadhandle;
  3703. result = 0;
  3704. }
  3705. return result;
  3706. }
  3707. /* Wait for a thread to finish. */
  3708. static int
  3709. mg_join_thread(pthread_t threadid)
  3710. {
  3711. int result;
  3712. DWORD dwevent;
  3713. result = -1;
  3714. dwevent = WaitForSingleObject(threadid, INFINITE);
  3715. if (dwevent == WAIT_FAILED) {
  3716. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3717. } else {
  3718. if (dwevent == WAIT_OBJECT_0) {
  3719. CloseHandle(threadid);
  3720. result = 0;
  3721. }
  3722. }
  3723. return result;
  3724. }
  3725. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3726. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3727. /* Create substitutes for POSIX functions in Win32. */
  3728. #if defined(__MINGW32__)
  3729. /* Show no warning in case system functions are not used. */
  3730. #pragma GCC diagnostic push
  3731. #pragma GCC diagnostic ignored "-Wunused-function"
  3732. #endif
  3733. static HANDLE
  3734. dlopen(const char *dll_name, int flags)
  3735. {
  3736. wchar_t wbuf[PATH_MAX];
  3737. (void)flags;
  3738. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3739. return LoadLibraryW(wbuf);
  3740. }
  3741. static int
  3742. dlclose(void *handle)
  3743. {
  3744. int result;
  3745. if (FreeLibrary((HMODULE)handle) != 0) {
  3746. result = 0;
  3747. } else {
  3748. result = -1;
  3749. }
  3750. return result;
  3751. }
  3752. #if defined(__MINGW32__)
  3753. /* Enable unused function warning again */
  3754. #pragma GCC diagnostic pop
  3755. #endif
  3756. #endif
  3757. #if !defined(NO_CGI)
  3758. #define SIGKILL (0)
  3759. static int
  3760. kill(pid_t pid, int sig_num)
  3761. {
  3762. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3763. (void)CloseHandle((HANDLE)pid);
  3764. return 0;
  3765. }
  3766. static void
  3767. trim_trailing_whitespaces(char *s)
  3768. {
  3769. char *e = s + strlen(s) - 1;
  3770. while (e > s && isspace(*(unsigned char *)e)) {
  3771. *e-- = '\0';
  3772. }
  3773. }
  3774. static pid_t
  3775. spawn_process(struct mg_connection *conn,
  3776. const char *prog,
  3777. char *envblk,
  3778. char *envp[],
  3779. int fdin[2],
  3780. int fdout[2],
  3781. int fderr[2],
  3782. const char *dir)
  3783. {
  3784. HANDLE me;
  3785. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3786. cmdline[PATH_MAX], buf[PATH_MAX];
  3787. int truncated;
  3788. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3789. STARTUPINFOA si;
  3790. PROCESS_INFORMATION pi = {0};
  3791. (void)envp;
  3792. memset(&si, 0, sizeof(si));
  3793. si.cb = sizeof(si);
  3794. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3795. si.wShowWindow = SW_HIDE;
  3796. me = GetCurrentProcess();
  3797. DuplicateHandle(me,
  3798. (HANDLE)_get_osfhandle(fdin[0]),
  3799. me,
  3800. &si.hStdInput,
  3801. 0,
  3802. TRUE,
  3803. DUPLICATE_SAME_ACCESS);
  3804. DuplicateHandle(me,
  3805. (HANDLE)_get_osfhandle(fdout[1]),
  3806. me,
  3807. &si.hStdOutput,
  3808. 0,
  3809. TRUE,
  3810. DUPLICATE_SAME_ACCESS);
  3811. DuplicateHandle(me,
  3812. (HANDLE)_get_osfhandle(fderr[1]),
  3813. me,
  3814. &si.hStdError,
  3815. 0,
  3816. TRUE,
  3817. DUPLICATE_SAME_ACCESS);
  3818. /* Mark handles that should not be inherited. See
  3819. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3820. */
  3821. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3822. HANDLE_FLAG_INHERIT,
  3823. 0);
  3824. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3825. HANDLE_FLAG_INHERIT,
  3826. 0);
  3827. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3828. HANDLE_FLAG_INHERIT,
  3829. 0);
  3830. /* If CGI file is a script, try to read the interpreter line */
  3831. interp = conn->ctx->config[CGI_INTERPRETER];
  3832. if (interp == NULL) {
  3833. buf[0] = buf[1] = '\0';
  3834. /* Read the first line of the script into the buffer */
  3835. mg_snprintf(
  3836. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3837. if (truncated) {
  3838. pi.hProcess = (pid_t)-1;
  3839. goto spawn_cleanup;
  3840. }
  3841. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3842. p = (char *)file.access.membuf;
  3843. mg_fgets(buf, sizeof(buf), &file, &p);
  3844. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3845. buf[sizeof(buf) - 1] = '\0';
  3846. }
  3847. if (buf[0] == '#' && buf[1] == '!') {
  3848. trim_trailing_whitespaces(buf + 2);
  3849. } else {
  3850. buf[2] = '\0';
  3851. }
  3852. interp = buf + 2;
  3853. }
  3854. if (interp[0] != '\0') {
  3855. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3856. interp = full_interp;
  3857. }
  3858. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3859. if (interp[0] != '\0') {
  3860. mg_snprintf(conn,
  3861. &truncated,
  3862. cmdline,
  3863. sizeof(cmdline),
  3864. "\"%s\" \"%s\\%s\"",
  3865. interp,
  3866. full_dir,
  3867. prog);
  3868. } else {
  3869. mg_snprintf(conn,
  3870. &truncated,
  3871. cmdline,
  3872. sizeof(cmdline),
  3873. "\"%s\\%s\"",
  3874. full_dir,
  3875. prog);
  3876. }
  3877. if (truncated) {
  3878. pi.hProcess = (pid_t)-1;
  3879. goto spawn_cleanup;
  3880. }
  3881. DEBUG_TRACE("Running [%s]", cmdline);
  3882. if (CreateProcessA(NULL,
  3883. cmdline,
  3884. NULL,
  3885. NULL,
  3886. TRUE,
  3887. CREATE_NEW_PROCESS_GROUP,
  3888. envblk,
  3889. NULL,
  3890. &si,
  3891. &pi) == 0) {
  3892. mg_cry(
  3893. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3894. pi.hProcess = (pid_t)-1;
  3895. /* goto spawn_cleanup; */
  3896. }
  3897. spawn_cleanup:
  3898. (void)CloseHandle(si.hStdOutput);
  3899. (void)CloseHandle(si.hStdError);
  3900. (void)CloseHandle(si.hStdInput);
  3901. if (pi.hThread != NULL) {
  3902. (void)CloseHandle(pi.hThread);
  3903. }
  3904. return (pid_t)pi.hProcess;
  3905. }
  3906. #endif /* !NO_CGI */
  3907. static int
  3908. set_blocking_mode(SOCKET sock, int blocking)
  3909. {
  3910. unsigned long non_blocking = !blocking;
  3911. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3912. }
  3913. #else
  3914. static int
  3915. mg_stat(const struct mg_connection *conn,
  3916. const char *path,
  3917. struct mg_file_stat *filep)
  3918. {
  3919. struct stat st;
  3920. if (!filep) {
  3921. return 0;
  3922. }
  3923. memset(filep, 0, sizeof(*filep));
  3924. if (conn && is_file_in_memory(conn, path)) {
  3925. /* Quick fix (for 1.9.x): */
  3926. /* mg_stat must fill all fields, also for files in memory */
  3927. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3928. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3929. filep->size = tmp_file.stat.size;
  3930. filep->last_modified = time(NULL);
  3931. filep->location = 2;
  3932. /* TODO: for 1.10: restructure how files in memory are handled */
  3933. return 1;
  3934. }
  3935. if (0 == stat(path, &st)) {
  3936. filep->size = (uint64_t)(st.st_size);
  3937. filep->last_modified = st.st_mtime;
  3938. filep->is_directory = S_ISDIR(st.st_mode);
  3939. return 1;
  3940. }
  3941. return 0;
  3942. }
  3943. static void
  3944. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3945. {
  3946. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3947. if (conn) {
  3948. mg_cry(conn,
  3949. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3950. __func__,
  3951. strerror(ERRNO));
  3952. }
  3953. }
  3954. }
  3955. int
  3956. mg_start_thread(mg_thread_func_t func, void *param)
  3957. {
  3958. pthread_t thread_id;
  3959. pthread_attr_t attr;
  3960. int result;
  3961. (void)pthread_attr_init(&attr);
  3962. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3963. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3964. /* Compile-time option to control stack size,
  3965. * e.g. -DUSE_STACK_SIZE=16384 */
  3966. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3967. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3968. result = pthread_create(&thread_id, &attr, func, param);
  3969. pthread_attr_destroy(&attr);
  3970. return result;
  3971. }
  3972. /* Start a thread storing the thread context. */
  3973. static int
  3974. mg_start_thread_with_id(mg_thread_func_t func,
  3975. void *param,
  3976. pthread_t *threadidptr)
  3977. {
  3978. pthread_t thread_id;
  3979. pthread_attr_t attr;
  3980. int result;
  3981. (void)pthread_attr_init(&attr);
  3982. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3983. /* Compile-time option to control stack size,
  3984. * e.g. -DUSE_STACK_SIZE=16384 */
  3985. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3986. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3987. result = pthread_create(&thread_id, &attr, func, param);
  3988. pthread_attr_destroy(&attr);
  3989. if ((result == 0) && (threadidptr != NULL)) {
  3990. *threadidptr = thread_id;
  3991. }
  3992. return result;
  3993. }
  3994. /* Wait for a thread to finish. */
  3995. static int
  3996. mg_join_thread(pthread_t threadid)
  3997. {
  3998. int result;
  3999. result = pthread_join(threadid, NULL);
  4000. return result;
  4001. }
  4002. #ifndef NO_CGI
  4003. static pid_t
  4004. spawn_process(struct mg_connection *conn,
  4005. const char *prog,
  4006. char *envblk,
  4007. char *envp[],
  4008. int fdin[2],
  4009. int fdout[2],
  4010. int fderr[2],
  4011. const char *dir)
  4012. {
  4013. pid_t pid;
  4014. const char *interp;
  4015. (void)envblk;
  4016. if (conn == NULL) {
  4017. return 0;
  4018. }
  4019. if ((pid = fork()) == -1) {
  4020. /* Parent */
  4021. mg_send_http_error(conn,
  4022. 500,
  4023. "Error: Creating CGI process\nfork(): %s",
  4024. strerror(ERRNO));
  4025. } else if (pid == 0) {
  4026. /* Child */
  4027. if (chdir(dir) != 0) {
  4028. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4029. } else if (dup2(fdin[0], 0) == -1) {
  4030. mg_cry(conn,
  4031. "%s: dup2(%d, 0): %s",
  4032. __func__,
  4033. fdin[0],
  4034. strerror(ERRNO));
  4035. } else if (dup2(fdout[1], 1) == -1) {
  4036. mg_cry(conn,
  4037. "%s: dup2(%d, 1): %s",
  4038. __func__,
  4039. fdout[1],
  4040. strerror(ERRNO));
  4041. } else if (dup2(fderr[1], 2) == -1) {
  4042. mg_cry(conn,
  4043. "%s: dup2(%d, 2): %s",
  4044. __func__,
  4045. fderr[1],
  4046. strerror(ERRNO));
  4047. } else {
  4048. /* Keep stderr and stdout in two different pipes.
  4049. * Stdout will be sent back to the client,
  4050. * stderr should go into a server error log. */
  4051. (void)close(fdin[0]);
  4052. (void)close(fdout[1]);
  4053. (void)close(fderr[1]);
  4054. /* Close write end fdin and read end fdout and fderr */
  4055. (void)close(fdin[1]);
  4056. (void)close(fdout[0]);
  4057. (void)close(fderr[0]);
  4058. /* After exec, all signal handlers are restored to their default
  4059. * values, with one exception of SIGCHLD. According to
  4060. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4061. * leave unchanged after exec if it was set to be ignored. Restore
  4062. * it to default action. */
  4063. signal(SIGCHLD, SIG_DFL);
  4064. interp = conn->ctx->config[CGI_INTERPRETER];
  4065. if (interp == NULL) {
  4066. (void)execle(prog, prog, NULL, envp);
  4067. mg_cry(conn,
  4068. "%s: execle(%s): %s",
  4069. __func__,
  4070. prog,
  4071. strerror(ERRNO));
  4072. } else {
  4073. (void)execle(interp, interp, prog, NULL, envp);
  4074. mg_cry(conn,
  4075. "%s: execle(%s %s): %s",
  4076. __func__,
  4077. interp,
  4078. prog,
  4079. strerror(ERRNO));
  4080. }
  4081. }
  4082. exit(EXIT_FAILURE);
  4083. }
  4084. return pid;
  4085. }
  4086. #endif /* !NO_CGI */
  4087. static int
  4088. set_blocking_mode(SOCKET sock, int blocking)
  4089. {
  4090. int flags;
  4091. flags = fcntl(sock, F_GETFL, 0);
  4092. if (blocking) {
  4093. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  4094. } else {
  4095. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  4096. }
  4097. return 0;
  4098. }
  4099. #endif /* _WIN32 */
  4100. /* End of initial operating system specific define block. */
  4101. /* Get a random number (independent of C rand function) */
  4102. static uint64_t
  4103. get_random(void)
  4104. {
  4105. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4106. static uint64_t lcg = 0; /* Linear congruential generator */
  4107. uint64_t now = mg_get_current_time_ns();
  4108. if (lfsr == 0) {
  4109. /* lfsr will be only 0 if has not been initialized,
  4110. * so this code is called only once. */
  4111. lfsr = mg_get_current_time_ns();
  4112. lcg = mg_get_current_time_ns();
  4113. } else {
  4114. /* Get the next step of both random number generators. */
  4115. lfsr = (lfsr >> 1)
  4116. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4117. << 63);
  4118. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  4119. }
  4120. /* Combining two pseudo-random number generators and a high resolution part
  4121. * of the current server time will make it hard (impossible?) to guess the
  4122. * next number. */
  4123. return (lfsr ^ lcg ^ now);
  4124. }
  4125. static int
  4126. mg_poll(struct pollfd *pfd,
  4127. unsigned int n,
  4128. int milliseconds,
  4129. volatile int *stop_server)
  4130. {
  4131. int ms_now, result;
  4132. /* Call poll, but only for a maximum time of a few seconds.
  4133. * This will allow to stop the server after some seconds, instead
  4134. * of having to wait for a long socket timeout. */
  4135. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4136. do {
  4137. if (*stop_server) {
  4138. /* Shut down signal */
  4139. return -2;
  4140. }
  4141. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4142. ms_now = milliseconds;
  4143. }
  4144. result = poll(pfd, n, ms_now);
  4145. if (result != 0) {
  4146. /* Poll returned either success (1) or error (-1).
  4147. * Forward both to the caller. */
  4148. return result;
  4149. }
  4150. /* Poll returned timeout (0). */
  4151. if (milliseconds > 0) {
  4152. milliseconds -= ms_now;
  4153. }
  4154. } while (milliseconds != 0);
  4155. return result;
  4156. }
  4157. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4158. * descriptor. Return number of bytes written. */
  4159. static int
  4160. push(struct mg_context *ctx,
  4161. FILE *fp,
  4162. SOCKET sock,
  4163. SSL *ssl,
  4164. const char *buf,
  4165. int len,
  4166. double timeout)
  4167. {
  4168. uint64_t start = 0, now = 0, timeout_ns = 0;
  4169. int n, err;
  4170. #ifdef _WIN32
  4171. typedef int len_t;
  4172. #else
  4173. typedef size_t len_t;
  4174. #endif
  4175. if (timeout > 0) {
  4176. start = mg_get_current_time_ns();
  4177. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4178. }
  4179. if (ctx == NULL) {
  4180. return -1;
  4181. }
  4182. #ifdef NO_SSL
  4183. if (ssl) {
  4184. return -1;
  4185. }
  4186. #endif
  4187. do {
  4188. #ifndef NO_SSL
  4189. if (ssl != NULL) {
  4190. n = SSL_write(ssl, buf, len);
  4191. if (n <= 0) {
  4192. err = SSL_get_error(ssl, n);
  4193. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4194. err = ERRNO;
  4195. } else if ((err == SSL_ERROR_WANT_READ)
  4196. || (err == SSL_ERROR_WANT_WRITE)) {
  4197. n = 0;
  4198. } else {
  4199. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4200. return -1;
  4201. }
  4202. } else {
  4203. err = 0;
  4204. }
  4205. } else
  4206. #endif
  4207. if (fp != NULL) {
  4208. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4209. if (ferror(fp)) {
  4210. n = -1;
  4211. err = ERRNO;
  4212. } else {
  4213. err = 0;
  4214. }
  4215. } else {
  4216. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4217. err = (n < 0) ? ERRNO : 0;
  4218. #ifdef _WIN32
  4219. if (err == WSAEWOULDBLOCK) {
  4220. err = 0;
  4221. n = 0;
  4222. }
  4223. #else
  4224. if (err == EWOULDBLOCK) {
  4225. err = 0;
  4226. n = 0;
  4227. }
  4228. #endif
  4229. if (n < 0) {
  4230. /* shutdown of the socket at client side */
  4231. return -1;
  4232. }
  4233. }
  4234. if (ctx->stop_flag) {
  4235. return -1;
  4236. }
  4237. if ((n > 0) || (n == 0 && len == 0)) {
  4238. /* some data has been read, or no data was requested */
  4239. return n;
  4240. }
  4241. if (n < 0) {
  4242. /* socket error - check errno */
  4243. DEBUG_TRACE("send() failed, error %d", err);
  4244. /* TODO (mid): error handling depending on the error code.
  4245. * These codes are different between Windows and Linux.
  4246. * Currently there is no problem with failing send calls,
  4247. * if there is a reproducible situation, it should be
  4248. * investigated in detail.
  4249. */
  4250. return -1;
  4251. }
  4252. /* Only in case n=0 (timeout), repeat calling the write function */
  4253. if (timeout >= 0) {
  4254. now = mg_get_current_time_ns();
  4255. }
  4256. } while ((timeout <= 0) || ((now - start) <= timeout_ns));
  4257. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4258. used */
  4259. return -1;
  4260. }
  4261. static int64_t
  4262. push_all(struct mg_context *ctx,
  4263. FILE *fp,
  4264. SOCKET sock,
  4265. SSL *ssl,
  4266. const char *buf,
  4267. int64_t len)
  4268. {
  4269. double timeout = -1.0;
  4270. int64_t n, nwritten = 0;
  4271. if (ctx == NULL) {
  4272. return -1;
  4273. }
  4274. if (ctx->config[REQUEST_TIMEOUT]) {
  4275. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4276. }
  4277. while (len > 0 && ctx->stop_flag == 0) {
  4278. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4279. if (n < 0) {
  4280. if (nwritten == 0) {
  4281. nwritten = n; /* Propagate the error */
  4282. }
  4283. break;
  4284. } else if (n == 0) {
  4285. break; /* No more data to write */
  4286. } else {
  4287. nwritten += n;
  4288. len -= n;
  4289. }
  4290. }
  4291. return nwritten;
  4292. }
  4293. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4294. * Return value:
  4295. * >=0 .. number of bytes successfully read
  4296. * -1 .. timeout
  4297. * -2 .. error
  4298. */
  4299. static int
  4300. pull_inner(FILE *fp,
  4301. struct mg_connection *conn,
  4302. char *buf,
  4303. int len,
  4304. double timeout)
  4305. {
  4306. int nread, err = 0;
  4307. #ifdef _WIN32
  4308. typedef int len_t;
  4309. #else
  4310. typedef size_t len_t;
  4311. #endif
  4312. #ifndef NO_SSL
  4313. int ssl_pending;
  4314. #endif
  4315. /* We need an additional wait loop around this, because in some cases
  4316. * with TLSwe may get data from the socket but not from SSL_read.
  4317. * In this case we need to repeat at least once.
  4318. */
  4319. if (fp != NULL) {
  4320. #if !defined(_WIN32_WCE)
  4321. /* Use read() instead of fread(), because if we're reading from the
  4322. * CGI pipe, fread() may block until IO buffer is filled up. We
  4323. * cannot afford to block and must pass all read bytes immediately
  4324. * to the client. */
  4325. nread = (int)read(fileno(fp), buf, (size_t)len);
  4326. #else
  4327. /* WinCE does not support CGI pipes */
  4328. nread = (int)fread(buf, 1, (size_t)len, fp);
  4329. #endif
  4330. err = (nread < 0) ? ERRNO : 0;
  4331. #ifndef NO_SSL
  4332. } else if ((conn->ssl != NULL)
  4333. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4334. /* We already know there is no more data buffered in conn->buf
  4335. * but there is more available in the SSL layer. So don't poll
  4336. * conn->client.sock yet. */
  4337. if (ssl_pending > len) {
  4338. ssl_pending = len;
  4339. }
  4340. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4341. if (nread <= 0) {
  4342. err = SSL_get_error(conn->ssl, nread);
  4343. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4344. err = ERRNO;
  4345. } else if ((err == SSL_ERROR_WANT_READ)
  4346. || (err == SSL_ERROR_WANT_WRITE)) {
  4347. nread = 0;
  4348. } else {
  4349. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4350. return -1;
  4351. }
  4352. } else {
  4353. err = 0;
  4354. }
  4355. } else if (conn->ssl != NULL) {
  4356. struct pollfd pfd[1];
  4357. int pollres;
  4358. pfd[0].fd = conn->client.sock;
  4359. pfd[0].events = POLLIN;
  4360. pollres =
  4361. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4362. if (conn->ctx->stop_flag) {
  4363. return -2;
  4364. }
  4365. if (pollres > 0) {
  4366. nread = SSL_read(conn->ssl, buf, len);
  4367. if (nread <= 0) {
  4368. err = SSL_get_error(conn->ssl, nread);
  4369. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4370. err = ERRNO;
  4371. } else if ((err == SSL_ERROR_WANT_READ)
  4372. || (err == SSL_ERROR_WANT_WRITE)) {
  4373. nread = 0;
  4374. } else {
  4375. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4376. return -2;
  4377. }
  4378. } else {
  4379. err = 0;
  4380. }
  4381. } else if (pollres < 0) {
  4382. /* Error */
  4383. return -2;
  4384. } else {
  4385. /* pollres = 0 means timeout */
  4386. nread = 0;
  4387. }
  4388. #endif
  4389. } else {
  4390. struct pollfd pfd[1];
  4391. int pollres;
  4392. pfd[0].fd = conn->client.sock;
  4393. pfd[0].events = POLLIN;
  4394. pollres =
  4395. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4396. if (conn->ctx->stop_flag) {
  4397. return -2;
  4398. }
  4399. if (pollres > 0) {
  4400. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4401. err = (nread < 0) ? ERRNO : 0;
  4402. if (nread <= 0) {
  4403. /* shutdown of the socket at client side */
  4404. return -2;
  4405. }
  4406. } else if (pollres < 0) {
  4407. /* error callint poll */
  4408. return -2;
  4409. } else {
  4410. /* pollres = 0 means timeout */
  4411. nread = 0;
  4412. }
  4413. }
  4414. if (conn->ctx->stop_flag) {
  4415. return -2;
  4416. }
  4417. if ((nread > 0) || (nread == 0 && len == 0)) {
  4418. /* some data has been read, or no data was requested */
  4419. return nread;
  4420. }
  4421. if (nread < 0) {
  4422. /* socket error - check errno */
  4423. #ifdef _WIN32
  4424. if (err == WSAEWOULDBLOCK) {
  4425. /* TODO (low): check if this is still required */
  4426. /* standard case if called from close_socket_gracefully */
  4427. return -2;
  4428. } else if (err == WSAETIMEDOUT) {
  4429. /* TODO (low): check if this is still required */
  4430. /* timeout is handled by the while loop */
  4431. return 0;
  4432. } else if (err == WSAECONNABORTED) {
  4433. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4434. return -2;
  4435. } else {
  4436. DEBUG_TRACE("recv() failed, error %d", err);
  4437. return -2;
  4438. }
  4439. #else
  4440. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4441. * if the timeout is reached and if the socket was set to non-
  4442. * blocking in close_socket_gracefully, so we can not distinguish
  4443. * here. We have to wait for the timeout in both cases for now.
  4444. */
  4445. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4446. /* TODO (low): check if this is still required */
  4447. /* EAGAIN/EWOULDBLOCK:
  4448. * standard case if called from close_socket_gracefully
  4449. * => should return -1 */
  4450. /* or timeout occured
  4451. * => the code must stay in the while loop */
  4452. /* EINTR can be generated on a socket with a timeout set even
  4453. * when SA_RESTART is effective for all relevant signals
  4454. * (see signal(7)).
  4455. * => stay in the while loop */
  4456. } else {
  4457. DEBUG_TRACE("recv() failed, error %d", err);
  4458. return -2;
  4459. }
  4460. #endif
  4461. }
  4462. /* Timeout occured, but no data available. */
  4463. return -1;
  4464. }
  4465. static int
  4466. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4467. {
  4468. int n, nread = 0;
  4469. double timeout = -1.0;
  4470. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4471. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4472. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4473. }
  4474. if (timeout >= 0.0) {
  4475. start_time = mg_get_current_time_ns();
  4476. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4477. }
  4478. while (len > 0 && conn->ctx->stop_flag == 0) {
  4479. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4480. if (n == -2) {
  4481. if (nread == 0) {
  4482. nread = -1; /* Propagate the error */
  4483. }
  4484. break;
  4485. } else if (n == -1) {
  4486. /* timeout */
  4487. if (timeout >= 0.0) {
  4488. now = mg_get_current_time_ns();
  4489. if ((now - start_time) <= timeout_ns) {
  4490. continue;
  4491. }
  4492. }
  4493. break;
  4494. } else if (n == 0) {
  4495. break; /* No more data to read */
  4496. } else {
  4497. conn->consumed_content += n;
  4498. nread += n;
  4499. len -= n;
  4500. }
  4501. }
  4502. return nread;
  4503. }
  4504. static void
  4505. discard_unread_request_data(struct mg_connection *conn)
  4506. {
  4507. char buf[MG_BUF_LEN];
  4508. size_t to_read;
  4509. int nread;
  4510. if (conn == NULL) {
  4511. return;
  4512. }
  4513. to_read = sizeof(buf);
  4514. if (conn->is_chunked) {
  4515. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4516. * completely */
  4517. while (conn->is_chunked == 1) {
  4518. nread = mg_read(conn, buf, to_read);
  4519. if (nread <= 0) {
  4520. break;
  4521. }
  4522. }
  4523. } else {
  4524. /* Not chunked: content length is known */
  4525. while (conn->consumed_content < conn->content_len) {
  4526. if (to_read
  4527. > (size_t)(conn->content_len - conn->consumed_content)) {
  4528. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4529. }
  4530. nread = mg_read(conn, buf, to_read);
  4531. if (nread <= 0) {
  4532. break;
  4533. }
  4534. }
  4535. }
  4536. }
  4537. static int
  4538. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4539. {
  4540. int64_t n, buffered_len, nread;
  4541. int64_t len64 =
  4542. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4543. * int, we may not read more
  4544. * bytes */
  4545. const char *body;
  4546. if (conn == NULL) {
  4547. return 0;
  4548. }
  4549. /* If Content-Length is not set for a PUT or POST request, read until
  4550. * socket is closed */
  4551. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4552. conn->content_len = INT64_MAX;
  4553. conn->must_close = 1;
  4554. }
  4555. nread = 0;
  4556. if (conn->consumed_content < conn->content_len) {
  4557. /* Adjust number of bytes to read. */
  4558. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4559. if (left_to_read < len64) {
  4560. /* Do not read more than the total content length of the request.
  4561. */
  4562. len64 = left_to_read;
  4563. }
  4564. /* Return buffered data */
  4565. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4566. - conn->consumed_content;
  4567. if (buffered_len > 0) {
  4568. if (len64 < buffered_len) {
  4569. buffered_len = len64;
  4570. }
  4571. body = conn->buf + conn->request_len + conn->consumed_content;
  4572. memcpy(buf, body, (size_t)buffered_len);
  4573. len64 -= buffered_len;
  4574. conn->consumed_content += buffered_len;
  4575. nread += buffered_len;
  4576. buf = (char *)buf + buffered_len;
  4577. }
  4578. /* We have returned all buffered data. Read new data from the remote
  4579. * socket.
  4580. */
  4581. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4582. nread += n;
  4583. } else {
  4584. nread = ((nread > 0) ? nread : n);
  4585. }
  4586. }
  4587. return (int)nread;
  4588. }
  4589. static char
  4590. mg_getc(struct mg_connection *conn)
  4591. {
  4592. char c;
  4593. if (conn == NULL) {
  4594. return 0;
  4595. }
  4596. conn->content_len++;
  4597. if (mg_read_inner(conn, &c, 1) <= 0) {
  4598. return (char)0;
  4599. }
  4600. return c;
  4601. }
  4602. int
  4603. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4604. {
  4605. if (len > INT_MAX) {
  4606. len = INT_MAX;
  4607. }
  4608. if (conn == NULL) {
  4609. return 0;
  4610. }
  4611. if (conn->is_chunked) {
  4612. size_t all_read = 0;
  4613. while (len > 0) {
  4614. if (conn->is_chunked == 2) {
  4615. /* No more data left to read */
  4616. return 0;
  4617. }
  4618. if (conn->chunk_remainder) {
  4619. /* copy from the remainder of the last received chunk */
  4620. long read_ret;
  4621. size_t read_now =
  4622. ((conn->chunk_remainder > len) ? (len)
  4623. : (conn->chunk_remainder));
  4624. conn->content_len += (int)read_now;
  4625. read_ret =
  4626. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4627. if (read_ret < 1) {
  4628. /* read error */
  4629. return -1;
  4630. }
  4631. all_read += (size_t)read_ret;
  4632. conn->chunk_remainder -= (size_t)read_ret;
  4633. len -= (size_t)read_ret;
  4634. if (conn->chunk_remainder == 0) {
  4635. /* Add data bytes in the current chunk have been read,
  4636. * so we are expecting \r\n now. */
  4637. char x1 = mg_getc(conn);
  4638. char x2 = mg_getc(conn);
  4639. if ((x1 != '\r') || (x2 != '\n')) {
  4640. /* Protocol violation */
  4641. return -1;
  4642. }
  4643. }
  4644. } else {
  4645. /* fetch a new chunk */
  4646. int i = 0;
  4647. char lenbuf[64];
  4648. char *end = 0;
  4649. unsigned long chunkSize = 0;
  4650. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4651. lenbuf[i] = mg_getc(conn);
  4652. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4653. continue;
  4654. }
  4655. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4656. lenbuf[i + 1] = 0;
  4657. chunkSize = strtoul(lenbuf, &end, 16);
  4658. if (chunkSize == 0) {
  4659. /* regular end of content */
  4660. conn->is_chunked = 2;
  4661. }
  4662. break;
  4663. }
  4664. if (!isxdigit(lenbuf[i])) {
  4665. /* illegal character for chunk length */
  4666. return -1;
  4667. }
  4668. }
  4669. if ((end == NULL) || (*end != '\r')) {
  4670. /* chunksize not set correctly */
  4671. return -1;
  4672. }
  4673. if (chunkSize == 0) {
  4674. break;
  4675. }
  4676. conn->chunk_remainder = chunkSize;
  4677. }
  4678. }
  4679. return (int)all_read;
  4680. }
  4681. return mg_read_inner(conn, buf, len);
  4682. }
  4683. int
  4684. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4685. {
  4686. time_t now;
  4687. int64_t n, total, allowed;
  4688. if (conn == NULL) {
  4689. return 0;
  4690. }
  4691. if (conn->throttle > 0) {
  4692. if ((now = time(NULL)) != conn->last_throttle_time) {
  4693. conn->last_throttle_time = now;
  4694. conn->last_throttle_bytes = 0;
  4695. }
  4696. allowed = conn->throttle - conn->last_throttle_bytes;
  4697. if (allowed > (int64_t)len) {
  4698. allowed = (int64_t)len;
  4699. }
  4700. if ((total = push_all(conn->ctx,
  4701. NULL,
  4702. conn->client.sock,
  4703. conn->ssl,
  4704. (const char *)buf,
  4705. (int64_t)allowed)) == allowed) {
  4706. buf = (const char *)buf + total;
  4707. conn->last_throttle_bytes += total;
  4708. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4709. allowed = (conn->throttle > ((int64_t)len - total))
  4710. ? (int64_t)len - total
  4711. : conn->throttle;
  4712. if ((n = push_all(conn->ctx,
  4713. NULL,
  4714. conn->client.sock,
  4715. conn->ssl,
  4716. (const char *)buf,
  4717. (int64_t)allowed)) != allowed) {
  4718. break;
  4719. }
  4720. sleep(1);
  4721. conn->last_throttle_bytes = allowed;
  4722. conn->last_throttle_time = time(NULL);
  4723. buf = (const char *)buf + n;
  4724. total += n;
  4725. }
  4726. }
  4727. } else {
  4728. total = push_all(conn->ctx,
  4729. NULL,
  4730. conn->client.sock,
  4731. conn->ssl,
  4732. (const char *)buf,
  4733. (int64_t)len);
  4734. }
  4735. return (int)total;
  4736. }
  4737. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  4738. int
  4739. mg_send_chunk(struct mg_connection *conn,
  4740. const char *chunk,
  4741. unsigned int chunk_len)
  4742. {
  4743. char lenbuf[16];
  4744. size_t lenbuf_len;
  4745. int ret;
  4746. int t;
  4747. /* First store the length information in a text buffer. */
  4748. sprintf(lenbuf, "%x\r\n", chunk_len);
  4749. lenbuf_len = strlen(lenbuf);
  4750. /* Then send length information, chunk and terminating \r\n. */
  4751. ret = mg_write(conn, lenbuf, lenbuf_len);
  4752. if (ret != (int)lenbuf_len) {
  4753. return -1;
  4754. }
  4755. t = ret;
  4756. ret = mg_write(conn, chunk, chunk_len);
  4757. if (ret != (int)chunk_len) {
  4758. return -1;
  4759. }
  4760. t += ret;
  4761. ret = mg_write(conn, "\r\n", 2);
  4762. if (ret != 2) {
  4763. return -1;
  4764. }
  4765. t += ret;
  4766. return t;
  4767. }
  4768. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4769. static int
  4770. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4771. {
  4772. va_list ap_copy;
  4773. size_t size = MG_BUF_LEN / 4;
  4774. int len = -1;
  4775. *buf = NULL;
  4776. while (len < 0) {
  4777. if (*buf) {
  4778. mg_free(*buf);
  4779. }
  4780. size *= 4;
  4781. *buf = (char *)mg_malloc(size);
  4782. if (!*buf) {
  4783. break;
  4784. }
  4785. va_copy(ap_copy, ap);
  4786. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4787. va_end(ap_copy);
  4788. (*buf)[size - 1] = 0;
  4789. }
  4790. return len;
  4791. }
  4792. /* Print message to buffer. If buffer is large enough to hold the message,
  4793. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4794. * and return allocated buffer. */
  4795. static int
  4796. alloc_vprintf(char **out_buf,
  4797. char *prealloc_buf,
  4798. size_t prealloc_size,
  4799. const char *fmt,
  4800. va_list ap)
  4801. {
  4802. va_list ap_copy;
  4803. int len;
  4804. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4805. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4806. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4807. * Therefore, we make two passes: on first pass, get required message
  4808. * length.
  4809. * On second pass, actually print the message. */
  4810. va_copy(ap_copy, ap);
  4811. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4812. va_end(ap_copy);
  4813. if (len < 0) {
  4814. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4815. * Switch to alternative code path that uses incremental allocations.
  4816. */
  4817. va_copy(ap_copy, ap);
  4818. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4819. va_end(ap_copy);
  4820. } else if ((size_t)(len) >= prealloc_size) {
  4821. /* The pre-allocated buffer not large enough. */
  4822. /* Allocate a new buffer. */
  4823. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4824. if (!*out_buf) {
  4825. /* Allocation failed. Return -1 as "out of memory" error. */
  4826. return -1;
  4827. }
  4828. /* Buffer allocation successful. Store the string there. */
  4829. va_copy(ap_copy, ap);
  4830. IGNORE_UNUSED_RESULT(
  4831. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4832. va_end(ap_copy);
  4833. } else {
  4834. /* The pre-allocated buffer is large enough.
  4835. * Use it to store the string and return the address. */
  4836. va_copy(ap_copy, ap);
  4837. IGNORE_UNUSED_RESULT(
  4838. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4839. va_end(ap_copy);
  4840. *out_buf = prealloc_buf;
  4841. }
  4842. return len;
  4843. }
  4844. static int
  4845. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4846. {
  4847. char mem[MG_BUF_LEN];
  4848. char *buf = NULL;
  4849. int len;
  4850. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4851. len = mg_write(conn, buf, (size_t)len);
  4852. }
  4853. if (buf != mem && buf != NULL) {
  4854. mg_free(buf);
  4855. }
  4856. return len;
  4857. }
  4858. int
  4859. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4860. {
  4861. va_list ap;
  4862. int result;
  4863. va_start(ap, fmt);
  4864. result = mg_vprintf(conn, fmt, ap);
  4865. va_end(ap);
  4866. return result;
  4867. }
  4868. int
  4869. mg_url_decode(const char *src,
  4870. int src_len,
  4871. char *dst,
  4872. int dst_len,
  4873. int is_form_url_encoded)
  4874. {
  4875. int i, j, a, b;
  4876. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4877. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4878. if (i < src_len - 2 && src[i] == '%'
  4879. && isxdigit(*(const unsigned char *)(src + i + 1))
  4880. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4881. a = tolower(*(const unsigned char *)(src + i + 1));
  4882. b = tolower(*(const unsigned char *)(src + i + 2));
  4883. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4884. i += 2;
  4885. } else if (is_form_url_encoded && src[i] == '+') {
  4886. dst[j] = ' ';
  4887. } else {
  4888. dst[j] = src[i];
  4889. }
  4890. }
  4891. dst[j] = '\0'; /* Null-terminate the destination */
  4892. return (i >= src_len) ? j : -1;
  4893. }
  4894. int
  4895. mg_get_var(const char *data,
  4896. size_t data_len,
  4897. const char *name,
  4898. char *dst,
  4899. size_t dst_len)
  4900. {
  4901. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4902. }
  4903. int
  4904. mg_get_var2(const char *data,
  4905. size_t data_len,
  4906. const char *name,
  4907. char *dst,
  4908. size_t dst_len,
  4909. size_t occurrence)
  4910. {
  4911. const char *p, *e, *s;
  4912. size_t name_len;
  4913. int len;
  4914. if (dst == NULL || dst_len == 0) {
  4915. len = -2;
  4916. } else if (data == NULL || name == NULL || data_len == 0) {
  4917. len = -1;
  4918. dst[0] = '\0';
  4919. } else {
  4920. name_len = strlen(name);
  4921. e = data + data_len;
  4922. len = -1;
  4923. dst[0] = '\0';
  4924. /* data is "var1=val1&var2=val2...". Find variable first */
  4925. for (p = data; p + name_len < e; p++) {
  4926. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4927. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4928. /* Point p to variable value */
  4929. p += name_len + 1;
  4930. /* Point s to the end of the value */
  4931. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4932. if (s == NULL) {
  4933. s = e;
  4934. }
  4935. /* assert(s >= p); */
  4936. if (s < p) {
  4937. return -3;
  4938. }
  4939. /* Decode variable into destination buffer */
  4940. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4941. /* Redirect error code from -1 to -2 (destination buffer too
  4942. * small). */
  4943. if (len == -1) {
  4944. len = -2;
  4945. }
  4946. break;
  4947. }
  4948. }
  4949. }
  4950. return len;
  4951. }
  4952. /* HCP24: some changes to compare hole var_name */
  4953. int
  4954. mg_get_cookie(const char *cookie_header,
  4955. const char *var_name,
  4956. char *dst,
  4957. size_t dst_size)
  4958. {
  4959. const char *s, *p, *end;
  4960. int name_len, len = -1;
  4961. if (dst == NULL || dst_size == 0) {
  4962. return -2;
  4963. }
  4964. dst[0] = '\0';
  4965. if (var_name == NULL || (s = cookie_header) == NULL) {
  4966. return -1;
  4967. }
  4968. name_len = (int)strlen(var_name);
  4969. end = s + strlen(s);
  4970. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4971. if (s[name_len] == '=') {
  4972. /* HCP24: now check is it a substring or a full cookie name */
  4973. if ((s == cookie_header) || (s[-1] == ' ')) {
  4974. s += name_len + 1;
  4975. if ((p = strchr(s, ' ')) == NULL) {
  4976. p = end;
  4977. }
  4978. if (p[-1] == ';') {
  4979. p--;
  4980. }
  4981. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4982. s++;
  4983. p--;
  4984. }
  4985. if ((size_t)(p - s) < dst_size) {
  4986. len = (int)(p - s);
  4987. mg_strlcpy(dst, s, (size_t)len + 1);
  4988. } else {
  4989. len = -3;
  4990. }
  4991. break;
  4992. }
  4993. }
  4994. }
  4995. return len;
  4996. }
  4997. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4998. static void
  4999. base64_encode(const unsigned char *src, int src_len, char *dst)
  5000. {
  5001. static const char *b64 =
  5002. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5003. int i, j, a, b, c;
  5004. for (i = j = 0; i < src_len; i += 3) {
  5005. a = src[i];
  5006. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5007. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5008. dst[j++] = b64[a >> 2];
  5009. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5010. if (i + 1 < src_len) {
  5011. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5012. }
  5013. if (i + 2 < src_len) {
  5014. dst[j++] = b64[c & 63];
  5015. }
  5016. }
  5017. while (j % 4 != 0) {
  5018. dst[j++] = '=';
  5019. }
  5020. dst[j++] = '\0';
  5021. }
  5022. #endif
  5023. #if defined(USE_LUA)
  5024. static unsigned char
  5025. b64reverse(char letter)
  5026. {
  5027. if (letter >= 'A' && letter <= 'Z') {
  5028. return letter - 'A';
  5029. }
  5030. if (letter >= 'a' && letter <= 'z') {
  5031. return letter - 'a' + 26;
  5032. }
  5033. if (letter >= '0' && letter <= '9') {
  5034. return letter - '0' + 52;
  5035. }
  5036. if (letter == '+') {
  5037. return 62;
  5038. }
  5039. if (letter == '/') {
  5040. return 63;
  5041. }
  5042. if (letter == '=') {
  5043. return 255; /* normal end */
  5044. }
  5045. return 254; /* error */
  5046. }
  5047. static int
  5048. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5049. {
  5050. int i;
  5051. unsigned char a, b, c, d;
  5052. *dst_len = 0;
  5053. for (i = 0; i < src_len; i += 4) {
  5054. a = b64reverse(src[i]);
  5055. if (a >= 254) {
  5056. return i;
  5057. }
  5058. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5059. if (b >= 254) {
  5060. return i + 1;
  5061. }
  5062. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5063. if (c == 254) {
  5064. return i + 2;
  5065. }
  5066. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5067. if (d == 254) {
  5068. return i + 3;
  5069. }
  5070. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5071. if (c != 255) {
  5072. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5073. if (d != 255) {
  5074. dst[(*dst_len)++] = (c << 6) + d;
  5075. }
  5076. }
  5077. }
  5078. return -1;
  5079. }
  5080. #endif
  5081. static int
  5082. is_put_or_delete_method(const struct mg_connection *conn)
  5083. {
  5084. if (conn) {
  5085. const char *s = conn->request_info.request_method;
  5086. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5087. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5088. }
  5089. return 0;
  5090. }
  5091. #if !defined(NO_FILES)
  5092. static int
  5093. extention_matches_script(
  5094. struct mg_connection *conn, /* in: request (must be valid) */
  5095. const char *filename /* in: filename (must be valid) */
  5096. )
  5097. {
  5098. #if !defined(NO_CGI)
  5099. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5100. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5101. filename) > 0) {
  5102. return 1;
  5103. }
  5104. #endif
  5105. #if defined(USE_LUA)
  5106. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5107. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5108. filename) > 0) {
  5109. return 1;
  5110. }
  5111. #endif
  5112. #if defined(USE_DUKTAPE)
  5113. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5114. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5115. filename) > 0) {
  5116. return 1;
  5117. }
  5118. #endif
  5119. /* filename and conn could be unused, if all preocessor conditions
  5120. * are false (no script language supported). */
  5121. (void)filename;
  5122. (void)conn;
  5123. return 0;
  5124. }
  5125. /* For given directory path, substitute it to valid index file.
  5126. * Return 1 if index file has been found, 0 if not found.
  5127. * If the file is found, it's stats is returned in stp. */
  5128. static int
  5129. substitute_index_file(struct mg_connection *conn,
  5130. char *path,
  5131. size_t path_len,
  5132. struct mg_file_stat *filestat)
  5133. {
  5134. const char *list = conn->ctx->config[INDEX_FILES];
  5135. struct vec filename_vec;
  5136. size_t n = strlen(path);
  5137. int found = 0;
  5138. /* The 'path' given to us points to the directory. Remove all trailing
  5139. * directory separator characters from the end of the path, and
  5140. * then append single directory separator character. */
  5141. while (n > 0 && path[n - 1] == '/') {
  5142. n--;
  5143. }
  5144. path[n] = '/';
  5145. /* Traverse index files list. For each entry, append it to the given
  5146. * path and see if the file exists. If it exists, break the loop */
  5147. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5148. /* Ignore too long entries that may overflow path buffer */
  5149. if (filename_vec.len > path_len - (n + 2)) {
  5150. continue;
  5151. }
  5152. /* Prepare full path to the index file */
  5153. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5154. /* Does it exist? */
  5155. if (mg_stat(conn, path, filestat)) {
  5156. /* Yes it does, break the loop */
  5157. found = 1;
  5158. break;
  5159. }
  5160. }
  5161. /* If no index file exists, restore directory path */
  5162. if (!found) {
  5163. path[n] = '\0';
  5164. }
  5165. return found;
  5166. }
  5167. #endif
  5168. static void
  5169. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5170. char *filename, /* out: filename */
  5171. size_t filename_buf_len, /* in: size of filename buffer */
  5172. struct mg_file_stat *filestat, /* out: file status structure */
  5173. int *is_found, /* out: file found (directly) */
  5174. int *is_script_resource, /* out: handled by a script? */
  5175. int *is_websocket_request, /* out: websocket connetion? */
  5176. int *is_put_or_delete_request /* out: put/delete a file? */
  5177. )
  5178. {
  5179. #if !defined(NO_FILES)
  5180. const char *uri = conn->request_info.local_uri;
  5181. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5182. const char *rewrite;
  5183. struct vec a, b;
  5184. int match_len;
  5185. char gz_path[PATH_MAX];
  5186. char const *accept_encoding;
  5187. int truncated;
  5188. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5189. char *tmp_str;
  5190. size_t tmp_str_len, sep_pos;
  5191. #endif
  5192. #else
  5193. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5194. #endif
  5195. /* Step 1: Set all initially unknown outputs to zero */
  5196. memset(filestat, 0, sizeof(*filestat));
  5197. *filename = 0;
  5198. *is_found = 0;
  5199. *is_script_resource = 0;
  5200. /* Step 2: Check if the request attempts to modify the file system */
  5201. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5202. /* Step 3: Check if it is a websocket request, and modify the document
  5203. * root if required */
  5204. #if defined(USE_WEBSOCKET)
  5205. *is_websocket_request = is_websocket_protocol(conn);
  5206. #if !defined(NO_FILES)
  5207. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5208. root = conn->ctx->config[WEBSOCKET_ROOT];
  5209. }
  5210. #endif /* !NO_FILES */
  5211. #else /* USE_WEBSOCKET */
  5212. *is_websocket_request = 0;
  5213. #endif /* USE_WEBSOCKET */
  5214. #if !defined(NO_FILES)
  5215. /* Step 4: If there is no root directory, don't look for files. */
  5216. /* Note that root == NULL is a regular use case here. This occurs,
  5217. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5218. * config is not required. */
  5219. if (root == NULL) {
  5220. /* all file related outputs have already been set to 0, just return
  5221. */
  5222. return;
  5223. }
  5224. /* Step 5: Determine the local file path from the root path and the
  5225. * request uri. */
  5226. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5227. * part of the path one byte on the right. */
  5228. mg_snprintf(
  5229. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5230. if (truncated) {
  5231. goto interpret_cleanup;
  5232. }
  5233. /* Step 6: URI rewriting */
  5234. rewrite = conn->ctx->config[REWRITE];
  5235. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5236. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5237. mg_snprintf(conn,
  5238. &truncated,
  5239. filename,
  5240. filename_buf_len - 1,
  5241. "%.*s%s",
  5242. (int)b.len,
  5243. b.ptr,
  5244. uri + match_len);
  5245. break;
  5246. }
  5247. }
  5248. if (truncated) {
  5249. goto interpret_cleanup;
  5250. }
  5251. /* Step 7: Check if the file exists at the server */
  5252. /* Local file path and name, corresponding to requested URI
  5253. * is now stored in "filename" variable. */
  5254. if (mg_stat(conn, filename, filestat)) {
  5255. /* 7.1: File exists. */
  5256. *is_found = 1;
  5257. /* 7.2: Check if it is a script type. */
  5258. if (extention_matches_script(conn, filename)) {
  5259. /* The request addresses a CGI resource, Lua script or
  5260. * server-side javascript.
  5261. * The URI corresponds to the script itself (like
  5262. * /path/script.cgi), and there is no additional resource
  5263. * path (like /path/script.cgi/something).
  5264. * Requests that modify (replace or delete) a resource, like
  5265. * PUT and DELETE requests, should replace/delete the script
  5266. * file.
  5267. * Requests that read or write from/to a resource, like GET and
  5268. * POST requests, should call the script and return the
  5269. * generated response. */
  5270. *is_script_resource = (!*is_put_or_delete_request);
  5271. }
  5272. /* 7.3: If the request target is a directory, there could be
  5273. * a substitute file (index.html, index.cgi, ...). */
  5274. if (filestat->is_directory) {
  5275. /* Use a local copy here, since substitute_index_file will
  5276. * change the content of the file status */
  5277. struct mg_file_stat tmp_filestat;
  5278. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5279. if (substitute_index_file(
  5280. conn, filename, filename_buf_len, &tmp_filestat)) {
  5281. /* Substitute file found. Copy stat to the output, then
  5282. * check if the file is a script file */
  5283. *filestat = tmp_filestat;
  5284. if (extention_matches_script(conn, filename)) {
  5285. /* Substitute file is a script file */
  5286. *is_script_resource = 1;
  5287. } else {
  5288. /* Substitute file is a regular file */
  5289. *is_script_resource = 0;
  5290. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5291. }
  5292. }
  5293. /* If there is no substitute file, the server could return
  5294. * a directory listing in a later step */
  5295. }
  5296. return;
  5297. }
  5298. /* Step 8: Check for zipped files: */
  5299. /* If we can't find the actual file, look for the file
  5300. * with the same name but a .gz extension. If we find it,
  5301. * use that and set the gzipped flag in the file struct
  5302. * to indicate that the response need to have the content-
  5303. * encoding: gzip header.
  5304. * We can only do this if the browser declares support. */
  5305. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5306. if (strstr(accept_encoding, "gzip") != NULL) {
  5307. mg_snprintf(
  5308. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5309. if (truncated) {
  5310. goto interpret_cleanup;
  5311. }
  5312. if (mg_stat(conn, gz_path, filestat)) {
  5313. if (filestat) {
  5314. filestat->is_gzipped = 1;
  5315. *is_found = 1;
  5316. }
  5317. /* Currently gz files can not be scripts. */
  5318. return;
  5319. }
  5320. }
  5321. }
  5322. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5323. /* Step 9: Script resources may handle sub-resources */
  5324. /* Support PATH_INFO for CGI scripts. */
  5325. tmp_str_len = strlen(filename);
  5326. tmp_str = mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->ctx);
  5327. if (!tmp_str) {
  5328. /* Out of memory */
  5329. goto interpret_cleanup;
  5330. }
  5331. memcpy(tmp_str, filename, tmp_str_len + 1);
  5332. sep_pos = tmp_str_len;
  5333. while (sep_pos > 0) {
  5334. sep_pos--;
  5335. if (tmp_str[sep_pos] == '/') {
  5336. int is_script = 0, does_exist = 0;
  5337. tmp_str[sep_pos] = 0;
  5338. if (tmp_str[0]) {
  5339. is_script = extention_matches_script(conn, tmp_str);
  5340. does_exist = mg_stat(conn, tmp_str, filestat);
  5341. }
  5342. if (does_exist && is_script) {
  5343. filename[sep_pos] = 0;
  5344. memmove(filename + sep_pos + 2,
  5345. filename + sep_pos + 1,
  5346. strlen(filename + sep_pos + 1) + 1);
  5347. conn->path_info = filename + sep_pos + 1;
  5348. filename[sep_pos + 1] = '/';
  5349. *is_script_resource = 1;
  5350. *is_found = 1;
  5351. break;
  5352. }
  5353. if (substitute_index_file(
  5354. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5355. /* some intermediate directory has an index file */
  5356. if (extention_matches_script(conn, tmp_str)) {
  5357. /* this index file is a script */
  5358. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5359. mg_snprintf(conn,
  5360. &truncated,
  5361. filename,
  5362. filename_buf_len,
  5363. "%s//%s",
  5364. tmp_str,
  5365. tmp_str2);
  5366. mg_free(tmp_str2);
  5367. if (truncated) {
  5368. mg_free(tmp_str);
  5369. tmp_str = NULL;
  5370. goto interpret_cleanup;
  5371. }
  5372. sep_pos = strlen(tmp_str);
  5373. filename[sep_pos] = 0;
  5374. conn->path_info = filename + sep_pos + 1;
  5375. *is_script_resource = 1;
  5376. *is_found = 1;
  5377. break;
  5378. } else {
  5379. /* non-script files will not have sub-resources */
  5380. filename[sep_pos] = 0;
  5381. conn->path_info = 0;
  5382. *is_script_resource = 0;
  5383. *is_found = 0;
  5384. break;
  5385. }
  5386. }
  5387. tmp_str[sep_pos] = '/';
  5388. }
  5389. }
  5390. mg_free(tmp_str);
  5391. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5392. #endif /* !defined(NO_FILES) */
  5393. return;
  5394. #if !defined(NO_FILES)
  5395. /* Reset all outputs */
  5396. interpret_cleanup:
  5397. memset(filestat, 0, sizeof(*filestat));
  5398. *filename = 0;
  5399. *is_found = 0;
  5400. *is_script_resource = 0;
  5401. *is_websocket_request = 0;
  5402. *is_put_or_delete_request = 0;
  5403. #endif /* !defined(NO_FILES) */
  5404. }
  5405. /* Check whether full request is buffered. Return:
  5406. * -1 if request is malformed
  5407. * 0 if request is not yet fully buffered
  5408. * >0 actual request length, including last \r\n\r\n */
  5409. static int
  5410. get_request_len(const char *buf, int buflen)
  5411. {
  5412. const char *s, *e;
  5413. int len = 0;
  5414. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  5415. /* Control characters are not allowed but >=128 is. */
  5416. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  5417. && *(const unsigned char *)s < 128) {
  5418. len = -1;
  5419. break; /* [i_a] abort scan as soon as one malformed character is
  5420. * found; */
  5421. /* don't let subsequent \r\n\r\n win us over anyhow */
  5422. } else if (s[0] == '\n' && s[1] == '\n') {
  5423. len = (int)(s - buf) + 2;
  5424. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  5425. len = (int)(s - buf) + 3;
  5426. }
  5427. return len;
  5428. }
  5429. #if !defined(NO_CACHING)
  5430. /* Convert month to the month number. Return -1 on error, or month number */
  5431. static int
  5432. get_month_index(const char *s)
  5433. {
  5434. size_t i;
  5435. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5436. if (!strcmp(s, month_names[i])) {
  5437. return (int)i;
  5438. }
  5439. }
  5440. return -1;
  5441. }
  5442. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5443. static time_t
  5444. parse_date_string(const char *datetime)
  5445. {
  5446. char month_str[32] = {0};
  5447. int second, minute, hour, day, month, year;
  5448. time_t result = (time_t)0;
  5449. struct tm tm;
  5450. if ((sscanf(datetime,
  5451. "%d/%3s/%d %d:%d:%d",
  5452. &day,
  5453. month_str,
  5454. &year,
  5455. &hour,
  5456. &minute,
  5457. &second) == 6) || (sscanf(datetime,
  5458. "%d %3s %d %d:%d:%d",
  5459. &day,
  5460. month_str,
  5461. &year,
  5462. &hour,
  5463. &minute,
  5464. &second) == 6)
  5465. || (sscanf(datetime,
  5466. "%*3s, %d %3s %d %d:%d:%d",
  5467. &day,
  5468. month_str,
  5469. &year,
  5470. &hour,
  5471. &minute,
  5472. &second) == 6) || (sscanf(datetime,
  5473. "%d-%3s-%d %d:%d:%d",
  5474. &day,
  5475. month_str,
  5476. &year,
  5477. &hour,
  5478. &minute,
  5479. &second) == 6)) {
  5480. month = get_month_index(month_str);
  5481. if ((month >= 0) && (year >= 1970)) {
  5482. memset(&tm, 0, sizeof(tm));
  5483. tm.tm_year = year - 1900;
  5484. tm.tm_mon = month;
  5485. tm.tm_mday = day;
  5486. tm.tm_hour = hour;
  5487. tm.tm_min = minute;
  5488. tm.tm_sec = second;
  5489. result = timegm(&tm);
  5490. }
  5491. }
  5492. return result;
  5493. }
  5494. #endif /* !NO_CACHING */
  5495. /* Protect against directory disclosure attack by removing '..',
  5496. * excessive '/' and '\' characters */
  5497. static void
  5498. remove_double_dots_and_double_slashes(char *s)
  5499. {
  5500. char *p = s;
  5501. while ((s[0] == '.') && (s[1] == '.')) {
  5502. s++;
  5503. }
  5504. while (*s != '\0') {
  5505. *p++ = *s++;
  5506. if (s[-1] == '/' || s[-1] == '\\') {
  5507. /* Skip all following slashes, backslashes and double-dots */
  5508. while (s[0] != '\0') {
  5509. if (s[0] == '/' || s[0] == '\\') {
  5510. s++;
  5511. } else if (s[0] == '.' && s[1] == '.') {
  5512. s += 2;
  5513. } else {
  5514. break;
  5515. }
  5516. }
  5517. }
  5518. }
  5519. *p = '\0';
  5520. }
  5521. static const struct {
  5522. const char *extension;
  5523. size_t ext_len;
  5524. const char *mime_type;
  5525. } builtin_mime_types[] = {
  5526. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5527. * application types */
  5528. {".doc", 4, "application/msword"},
  5529. {".eps", 4, "application/postscript"},
  5530. {".exe", 4, "application/octet-stream"},
  5531. {".js", 3, "application/javascript"},
  5532. {".json", 5, "application/json"},
  5533. {".pdf", 4, "application/pdf"},
  5534. {".ps", 3, "application/postscript"},
  5535. {".rtf", 4, "application/rtf"},
  5536. {".xhtml", 6, "application/xhtml+xml"},
  5537. {".xsl", 4, "application/xml"},
  5538. {".xslt", 5, "application/xml"},
  5539. /* fonts */
  5540. {".ttf", 4, "application/font-sfnt"},
  5541. {".cff", 4, "application/font-sfnt"},
  5542. {".otf", 4, "application/font-sfnt"},
  5543. {".aat", 4, "application/font-sfnt"},
  5544. {".sil", 4, "application/font-sfnt"},
  5545. {".pfr", 4, "application/font-tdpfr"},
  5546. {".woff", 5, "application/font-woff"},
  5547. /* audio */
  5548. {".mp3", 4, "audio/mpeg"},
  5549. {".oga", 4, "audio/ogg"},
  5550. {".ogg", 4, "audio/ogg"},
  5551. /* image */
  5552. {".gif", 4, "image/gif"},
  5553. {".ief", 4, "image/ief"},
  5554. {".jpeg", 5, "image/jpeg"},
  5555. {".jpg", 4, "image/jpeg"},
  5556. {".jpm", 4, "image/jpm"},
  5557. {".jpx", 4, "image/jpx"},
  5558. {".png", 4, "image/png"},
  5559. {".svg", 4, "image/svg+xml"},
  5560. {".tif", 4, "image/tiff"},
  5561. {".tiff", 5, "image/tiff"},
  5562. /* model */
  5563. {".wrl", 4, "model/vrml"},
  5564. /* text */
  5565. {".css", 4, "text/css"},
  5566. {".csv", 4, "text/csv"},
  5567. {".htm", 4, "text/html"},
  5568. {".html", 5, "text/html"},
  5569. {".sgm", 4, "text/sgml"},
  5570. {".shtm", 5, "text/html"},
  5571. {".shtml", 6, "text/html"},
  5572. {".txt", 4, "text/plain"},
  5573. {".xml", 4, "text/xml"},
  5574. /* video */
  5575. {".mov", 4, "video/quicktime"},
  5576. {".mp4", 4, "video/mp4"},
  5577. {".mpeg", 5, "video/mpeg"},
  5578. {".mpg", 4, "video/mpeg"},
  5579. {".ogv", 4, "video/ogg"},
  5580. {".qt", 3, "video/quicktime"},
  5581. /* not registered types
  5582. * (http://reference.sitepoint.com/html/mime-types-full,
  5583. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5584. {".arj", 4, "application/x-arj-compressed"},
  5585. {".gz", 3, "application/x-gunzip"},
  5586. {".rar", 4, "application/x-arj-compressed"},
  5587. {".swf", 4, "application/x-shockwave-flash"},
  5588. {".tar", 4, "application/x-tar"},
  5589. {".tgz", 4, "application/x-tar-gz"},
  5590. {".torrent", 8, "application/x-bittorrent"},
  5591. {".ppt", 4, "application/x-mspowerpoint"},
  5592. {".xls", 4, "application/x-msexcel"},
  5593. {".zip", 4, "application/x-zip-compressed"},
  5594. {".aac",
  5595. 4,
  5596. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5597. {".aif", 4, "audio/x-aif"},
  5598. {".m3u", 4, "audio/x-mpegurl"},
  5599. {".mid", 4, "audio/x-midi"},
  5600. {".ra", 3, "audio/x-pn-realaudio"},
  5601. {".ram", 4, "audio/x-pn-realaudio"},
  5602. {".wav", 4, "audio/x-wav"},
  5603. {".bmp", 4, "image/bmp"},
  5604. {".ico", 4, "image/x-icon"},
  5605. {".pct", 4, "image/x-pct"},
  5606. {".pict", 5, "image/pict"},
  5607. {".rgb", 4, "image/x-rgb"},
  5608. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5609. {".asf", 4, "video/x-ms-asf"},
  5610. {".avi", 4, "video/x-msvideo"},
  5611. {".m4v", 4, "video/x-m4v"},
  5612. {NULL, 0, NULL}};
  5613. const char *
  5614. mg_get_builtin_mime_type(const char *path)
  5615. {
  5616. const char *ext;
  5617. size_t i, path_len;
  5618. path_len = strlen(path);
  5619. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5620. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5621. if (path_len > builtin_mime_types[i].ext_len
  5622. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5623. return builtin_mime_types[i].mime_type;
  5624. }
  5625. }
  5626. return "text/plain";
  5627. }
  5628. /* Look at the "path" extension and figure what mime type it has.
  5629. * Store mime type in the vector. */
  5630. static void
  5631. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5632. {
  5633. struct vec ext_vec, mime_vec;
  5634. const char *list, *ext;
  5635. size_t path_len;
  5636. path_len = strlen(path);
  5637. if (ctx == NULL || vec == NULL) {
  5638. return;
  5639. }
  5640. /* Scan user-defined mime types first, in case user wants to
  5641. * override default mime types. */
  5642. list = ctx->config[EXTRA_MIME_TYPES];
  5643. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5644. /* ext now points to the path suffix */
  5645. ext = path + path_len - ext_vec.len;
  5646. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5647. *vec = mime_vec;
  5648. return;
  5649. }
  5650. }
  5651. vec->ptr = mg_get_builtin_mime_type(path);
  5652. vec->len = strlen(vec->ptr);
  5653. }
  5654. /* Stringify binary data. Output buffer must be twice as big as input,
  5655. * because each byte takes 2 bytes in string representation */
  5656. static void
  5657. bin2str(char *to, const unsigned char *p, size_t len)
  5658. {
  5659. static const char *hex = "0123456789abcdef";
  5660. for (; len--; p++) {
  5661. *to++ = hex[p[0] >> 4];
  5662. *to++ = hex[p[0] & 0x0f];
  5663. }
  5664. *to = '\0';
  5665. }
  5666. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5667. char *
  5668. mg_md5(char buf[33], ...)
  5669. {
  5670. md5_byte_t hash[16];
  5671. const char *p;
  5672. va_list ap;
  5673. md5_state_t ctx;
  5674. md5_init(&ctx);
  5675. va_start(ap, buf);
  5676. while ((p = va_arg(ap, const char *)) != NULL) {
  5677. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5678. }
  5679. va_end(ap);
  5680. md5_finish(&ctx, hash);
  5681. bin2str(buf, hash, sizeof(hash));
  5682. return buf;
  5683. }
  5684. /* Check the user's password, return 1 if OK */
  5685. static int
  5686. check_password(const char *method,
  5687. const char *ha1,
  5688. const char *uri,
  5689. const char *nonce,
  5690. const char *nc,
  5691. const char *cnonce,
  5692. const char *qop,
  5693. const char *response)
  5694. {
  5695. char ha2[32 + 1], expected_response[32 + 1];
  5696. /* Some of the parameters may be NULL */
  5697. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5698. || qop == NULL
  5699. || response == NULL) {
  5700. return 0;
  5701. }
  5702. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5703. if (strlen(response) != 32) {
  5704. return 0;
  5705. }
  5706. mg_md5(ha2, method, ":", uri, NULL);
  5707. mg_md5(expected_response,
  5708. ha1,
  5709. ":",
  5710. nonce,
  5711. ":",
  5712. nc,
  5713. ":",
  5714. cnonce,
  5715. ":",
  5716. qop,
  5717. ":",
  5718. ha2,
  5719. NULL);
  5720. return mg_strcasecmp(response, expected_response) == 0;
  5721. }
  5722. /* Use the global passwords file, if specified by auth_gpass option,
  5723. * or search for .htpasswd in the requested directory. */
  5724. static void
  5725. open_auth_file(struct mg_connection *conn,
  5726. const char *path,
  5727. struct mg_file *filep)
  5728. {
  5729. if (conn != NULL && conn->ctx != NULL) {
  5730. char name[PATH_MAX];
  5731. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5732. int truncated;
  5733. if (gpass != NULL) {
  5734. /* Use global passwords file */
  5735. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5736. #ifdef DEBUG
  5737. /* Use mg_cry here, since gpass has been configured. */
  5738. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5739. #endif
  5740. }
  5741. /* Important: using local struct mg_file to test path for
  5742. * is_directory flag. If filep is used, mg_stat() makes it
  5743. * appear as if auth file was opened.
  5744. * TODO(mid): Check if this is still required after rewriting
  5745. * mg_stat */
  5746. } else if (mg_stat(conn, path, &filep->stat)
  5747. && filep->stat.is_directory) {
  5748. mg_snprintf(conn,
  5749. &truncated,
  5750. name,
  5751. sizeof(name),
  5752. "%s/%s",
  5753. path,
  5754. PASSWORDS_FILE_NAME);
  5755. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5756. #ifdef DEBUG
  5757. /* Don't use mg_cry here, but only a trace, since this is
  5758. * a typical case. It will occur for every directory
  5759. * without a password file. */
  5760. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5761. #endif
  5762. }
  5763. } else {
  5764. /* Try to find .htpasswd in requested directory. */
  5765. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5766. if (e[0] == '/') {
  5767. break;
  5768. }
  5769. }
  5770. mg_snprintf(conn,
  5771. &truncated,
  5772. name,
  5773. sizeof(name),
  5774. "%.*s/%s",
  5775. (int)(e - p),
  5776. p,
  5777. PASSWORDS_FILE_NAME);
  5778. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5779. #ifdef DEBUG
  5780. /* Don't use mg_cry here, but only a trace, since this is
  5781. * a typical case. It will occur for every directory
  5782. * without a password file. */
  5783. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5784. #endif
  5785. }
  5786. }
  5787. }
  5788. }
  5789. /* Parsed Authorization header */
  5790. struct ah {
  5791. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5792. };
  5793. /* Return 1 on success. Always initializes the ah structure. */
  5794. static int
  5795. parse_auth_header(struct mg_connection *conn,
  5796. char *buf,
  5797. size_t buf_size,
  5798. struct ah *ah)
  5799. {
  5800. char *name, *value, *s;
  5801. const char *auth_header;
  5802. uint64_t nonce;
  5803. if (!ah || !conn) {
  5804. return 0;
  5805. }
  5806. (void)memset(ah, 0, sizeof(*ah));
  5807. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5808. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5809. return 0;
  5810. }
  5811. /* Make modifiable copy of the auth header */
  5812. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5813. s = buf;
  5814. /* Parse authorization header */
  5815. for (;;) {
  5816. /* Gobble initial spaces */
  5817. while (isspace(*(unsigned char *)s)) {
  5818. s++;
  5819. }
  5820. name = skip_quoted(&s, "=", " ", 0);
  5821. /* Value is either quote-delimited, or ends at first comma or space. */
  5822. if (s[0] == '\"') {
  5823. s++;
  5824. value = skip_quoted(&s, "\"", " ", '\\');
  5825. if (s[0] == ',') {
  5826. s++;
  5827. }
  5828. } else {
  5829. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5830. * spaces */
  5831. }
  5832. if (*name == '\0') {
  5833. break;
  5834. }
  5835. if (!strcmp(name, "username")) {
  5836. ah->user = value;
  5837. } else if (!strcmp(name, "cnonce")) {
  5838. ah->cnonce = value;
  5839. } else if (!strcmp(name, "response")) {
  5840. ah->response = value;
  5841. } else if (!strcmp(name, "uri")) {
  5842. ah->uri = value;
  5843. } else if (!strcmp(name, "qop")) {
  5844. ah->qop = value;
  5845. } else if (!strcmp(name, "nc")) {
  5846. ah->nc = value;
  5847. } else if (!strcmp(name, "nonce")) {
  5848. ah->nonce = value;
  5849. }
  5850. }
  5851. #ifndef NO_NONCE_CHECK
  5852. /* Read the nonce from the response. */
  5853. if (ah->nonce == NULL) {
  5854. return 0;
  5855. }
  5856. s = NULL;
  5857. nonce = strtoull(ah->nonce, &s, 10);
  5858. if ((s == NULL) || (*s != 0)) {
  5859. return 0;
  5860. }
  5861. /* Convert the nonce from the client to a number. */
  5862. nonce ^= conn->ctx->auth_nonce_mask;
  5863. /* The converted number corresponds to the time the nounce has been
  5864. * created. This should not be earlier than the server start. */
  5865. /* Server side nonce check is valuable in all situations but one:
  5866. * if the server restarts frequently, but the client should not see
  5867. * that, so the server should accept nonces from previous starts. */
  5868. /* However, the reasonable default is to not accept a nonce from a
  5869. * previous start, so if anyone changed the access rights between
  5870. * two restarts, a new login is required. */
  5871. if (nonce < (uint64_t)conn->ctx->start_time) {
  5872. /* nonce is from a previous start of the server and no longer valid
  5873. * (replay attack?) */
  5874. return 0;
  5875. }
  5876. /* Check if the nonce is too high, so it has not (yet) been used by the
  5877. * server. */
  5878. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5879. return 0;
  5880. }
  5881. #else
  5882. (void)nonce;
  5883. #endif
  5884. /* CGI needs it as REMOTE_USER */
  5885. if (ah->user != NULL) {
  5886. conn->request_info.remote_user = mg_strdup(ah->user);
  5887. } else {
  5888. return 0;
  5889. }
  5890. return 1;
  5891. }
  5892. static const char *
  5893. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5894. {
  5895. const char *eof;
  5896. size_t len;
  5897. const char *memend;
  5898. if (!filep) {
  5899. return NULL;
  5900. }
  5901. if (filep->access.membuf != NULL && *p != NULL) {
  5902. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5903. /* Search for \n from p till the end of stream */
  5904. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5905. if (eof != NULL) {
  5906. eof += 1; /* Include \n */
  5907. } else {
  5908. eof = memend; /* Copy remaining data */
  5909. }
  5910. len =
  5911. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5912. memcpy(buf, *p, len);
  5913. buf[len] = '\0';
  5914. *p += len;
  5915. return len ? eof : NULL;
  5916. } else if (filep->access.fp != NULL) {
  5917. return fgets(buf, (int)size, filep->access.fp);
  5918. } else {
  5919. return NULL;
  5920. }
  5921. }
  5922. /* Define the initial recursion depth for procesesing htpasswd files that
  5923. * include other htpasswd
  5924. * (or even the same) files. It is not difficult to provide a file or files
  5925. * s.t. they force civetweb
  5926. * to infinitely recurse and then crash.
  5927. */
  5928. #define INITIAL_DEPTH 9
  5929. #if INITIAL_DEPTH <= 0
  5930. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5931. #endif
  5932. struct read_auth_file_struct {
  5933. struct mg_connection *conn;
  5934. struct ah ah;
  5935. char *domain;
  5936. char buf[256 + 256 + 40];
  5937. char *f_user;
  5938. char *f_domain;
  5939. char *f_ha1;
  5940. };
  5941. static int
  5942. read_auth_file(struct mg_file *filep,
  5943. struct read_auth_file_struct *workdata,
  5944. int depth)
  5945. {
  5946. char *p;
  5947. int is_authorized = 0;
  5948. struct mg_file fp;
  5949. size_t l;
  5950. if (!filep || !workdata || 0 == depth) {
  5951. return 0;
  5952. }
  5953. /* Loop over passwords file */
  5954. p = (char *)filep->access.membuf;
  5955. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5956. l = strlen(workdata->buf);
  5957. while (l > 0) {
  5958. if (isspace(workdata->buf[l - 1])
  5959. || iscntrl(workdata->buf[l - 1])) {
  5960. l--;
  5961. workdata->buf[l] = 0;
  5962. } else
  5963. break;
  5964. }
  5965. if (l < 1) {
  5966. continue;
  5967. }
  5968. workdata->f_user = workdata->buf;
  5969. if (workdata->f_user[0] == ':') {
  5970. /* user names may not contain a ':' and may not be empty,
  5971. * so lines starting with ':' may be used for a special purpose */
  5972. if (workdata->f_user[1] == '#') {
  5973. /* :# is a comment */
  5974. continue;
  5975. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5976. if (mg_fopen(workdata->conn,
  5977. workdata->f_user + 9,
  5978. MG_FOPEN_MODE_READ,
  5979. &fp)) {
  5980. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5981. (void)mg_fclose(
  5982. &fp.access); /* ignore error on read only file */
  5983. /* No need to continue processing files once we have a
  5984. * match, since nothing will reset it back
  5985. * to 0.
  5986. */
  5987. if (is_authorized) {
  5988. return is_authorized;
  5989. }
  5990. } else {
  5991. mg_cry(workdata->conn,
  5992. "%s: cannot open authorization file: %s",
  5993. __func__,
  5994. workdata->buf);
  5995. }
  5996. continue;
  5997. }
  5998. /* everything is invalid for the moment (might change in the
  5999. * future) */
  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 = strchr(workdata->f_user, ':');
  6007. if (workdata->f_domain == NULL) {
  6008. mg_cry(workdata->conn,
  6009. "%s: syntax error in authorization file: %s",
  6010. __func__,
  6011. workdata->buf);
  6012. continue;
  6013. }
  6014. *(workdata->f_domain) = 0;
  6015. (workdata->f_domain)++;
  6016. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6017. if (workdata->f_ha1 == NULL) {
  6018. mg_cry(workdata->conn,
  6019. "%s: syntax error in authorization file: %s",
  6020. __func__,
  6021. workdata->buf);
  6022. continue;
  6023. }
  6024. *(workdata->f_ha1) = 0;
  6025. (workdata->f_ha1)++;
  6026. if (!strcmp(workdata->ah.user, workdata->f_user)
  6027. && !strcmp(workdata->domain, workdata->f_domain)) {
  6028. return check_password(workdata->conn->request_info.request_method,
  6029. workdata->f_ha1,
  6030. workdata->ah.uri,
  6031. workdata->ah.nonce,
  6032. workdata->ah.nc,
  6033. workdata->ah.cnonce,
  6034. workdata->ah.qop,
  6035. workdata->ah.response);
  6036. }
  6037. }
  6038. return is_authorized;
  6039. }
  6040. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6041. static int
  6042. authorize(struct mg_connection *conn, struct mg_file *filep)
  6043. {
  6044. struct read_auth_file_struct workdata;
  6045. char buf[MG_BUF_LEN];
  6046. if (!conn || !conn->ctx) {
  6047. return 0;
  6048. }
  6049. memset(&workdata, 0, sizeof(workdata));
  6050. workdata.conn = conn;
  6051. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6052. return 0;
  6053. }
  6054. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6055. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6056. }
  6057. /* Return 1 if request is authorised, 0 otherwise. */
  6058. static int
  6059. check_authorization(struct mg_connection *conn, const char *path)
  6060. {
  6061. char fname[PATH_MAX];
  6062. struct vec uri_vec, filename_vec;
  6063. const char *list;
  6064. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6065. int authorized = 1, truncated;
  6066. if (!conn || !conn->ctx) {
  6067. return 0;
  6068. }
  6069. list = conn->ctx->config[PROTECT_URI];
  6070. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6071. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6072. mg_snprintf(conn,
  6073. &truncated,
  6074. fname,
  6075. sizeof(fname),
  6076. "%.*s",
  6077. (int)filename_vec.len,
  6078. filename_vec.ptr);
  6079. if (truncated
  6080. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6081. mg_cry(conn,
  6082. "%s: cannot open %s: %s",
  6083. __func__,
  6084. fname,
  6085. strerror(errno));
  6086. }
  6087. break;
  6088. }
  6089. }
  6090. if (!is_file_opened(&file.access)) {
  6091. open_auth_file(conn, path, &file);
  6092. }
  6093. if (is_file_opened(&file.access)) {
  6094. authorized = authorize(conn, &file);
  6095. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6096. }
  6097. return authorized;
  6098. }
  6099. static void
  6100. send_authorization_request(struct mg_connection *conn)
  6101. {
  6102. char date[64];
  6103. time_t curtime = time(NULL);
  6104. if (conn && conn->ctx) {
  6105. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6106. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6107. nonce += conn->ctx->nonce_count;
  6108. ++conn->ctx->nonce_count;
  6109. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6110. nonce ^= conn->ctx->auth_nonce_mask;
  6111. conn->status_code = 401;
  6112. conn->must_close = 1;
  6113. gmt_time_string(date, sizeof(date), &curtime);
  6114. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6115. send_no_cache_header(conn);
  6116. send_additional_header(conn);
  6117. mg_printf(conn,
  6118. "Date: %s\r\n"
  6119. "Connection: %s\r\n"
  6120. "Content-Length: 0\r\n"
  6121. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6122. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6123. date,
  6124. suggest_connection_header(conn),
  6125. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6126. nonce);
  6127. }
  6128. }
  6129. #if !defined(NO_FILES)
  6130. static int
  6131. is_authorized_for_put(struct mg_connection *conn)
  6132. {
  6133. if (conn) {
  6134. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6135. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6136. int ret = 0;
  6137. if (passfile != NULL
  6138. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6139. ret = authorize(conn, &file);
  6140. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6141. }
  6142. return ret;
  6143. }
  6144. return 0;
  6145. }
  6146. #endif
  6147. int
  6148. mg_modify_passwords_file(const char *fname,
  6149. const char *domain,
  6150. const char *user,
  6151. const char *pass)
  6152. {
  6153. int found, i;
  6154. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6155. FILE *fp, *fp2;
  6156. found = 0;
  6157. fp = fp2 = NULL;
  6158. /* Regard empty password as no password - remove user record. */
  6159. if (pass != NULL && pass[0] == '\0') {
  6160. pass = NULL;
  6161. }
  6162. /* Other arguments must not be empty */
  6163. if (fname == NULL || domain == NULL || user == NULL) {
  6164. return 0;
  6165. }
  6166. /* Using the given file format, user name and domain must not contain ':'
  6167. */
  6168. if (strchr(user, ':') != NULL) {
  6169. return 0;
  6170. }
  6171. if (strchr(domain, ':') != NULL) {
  6172. return 0;
  6173. }
  6174. /* Do not allow control characters like newline in user name and domain.
  6175. * Do not allow excessively long names either. */
  6176. for (i = 0; i < 255 && user[i] != 0; i++) {
  6177. if (iscntrl(user[i])) {
  6178. return 0;
  6179. }
  6180. }
  6181. if (user[i]) {
  6182. return 0;
  6183. }
  6184. for (i = 0; i < 255 && domain[i] != 0; i++) {
  6185. if (iscntrl(domain[i])) {
  6186. return 0;
  6187. }
  6188. }
  6189. if (domain[i]) {
  6190. return 0;
  6191. }
  6192. /* The maximum length of the path to the password file is limited */
  6193. if ((strlen(fname) + 4) >= PATH_MAX) {
  6194. return 0;
  6195. }
  6196. /* Create a temporary file name. Length has been checked before. */
  6197. strcpy(tmp, fname);
  6198. strcat(tmp, ".tmp");
  6199. /* Create the file if does not exist */
  6200. /* Use of fopen here is OK, since fname is only ASCII */
  6201. if ((fp = fopen(fname, "a+")) != NULL) {
  6202. (void)fclose(fp);
  6203. }
  6204. /* Open the given file and temporary file */
  6205. if ((fp = fopen(fname, "r")) == NULL) {
  6206. return 0;
  6207. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6208. fclose(fp);
  6209. return 0;
  6210. }
  6211. /* Copy the stuff to temporary file */
  6212. while (fgets(line, sizeof(line), fp) != NULL) {
  6213. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6214. continue;
  6215. }
  6216. u[255] = 0;
  6217. d[255] = 0;
  6218. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6219. found++;
  6220. if (pass != NULL) {
  6221. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6222. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6223. }
  6224. } else {
  6225. fprintf(fp2, "%s", line);
  6226. }
  6227. }
  6228. /* If new user, just add it */
  6229. if (!found && pass != NULL) {
  6230. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6231. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6232. }
  6233. /* Close files */
  6234. fclose(fp);
  6235. fclose(fp2);
  6236. /* Put the temp file in place of real file */
  6237. IGNORE_UNUSED_RESULT(remove(fname));
  6238. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6239. return 1;
  6240. }
  6241. static int
  6242. is_valid_port(unsigned long port)
  6243. {
  6244. return (port <= 0xffff);
  6245. }
  6246. static int
  6247. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6248. {
  6249. struct addrinfo hints, *res, *ressave;
  6250. int func_ret = 0;
  6251. int gai_ret;
  6252. memset(&hints, 0, sizeof(struct addrinfo));
  6253. hints.ai_family = af;
  6254. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6255. if (gai_ret != 0) {
  6256. /* gai_strerror could be used to convert gai_ret to a string */
  6257. /* POSIX return values: see
  6258. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6259. */
  6260. /* Windows return values: see
  6261. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6262. */
  6263. return 0;
  6264. }
  6265. ressave = res;
  6266. while (res) {
  6267. if (dstlen >= res->ai_addrlen) {
  6268. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6269. func_ret = 1;
  6270. }
  6271. res = res->ai_next;
  6272. }
  6273. freeaddrinfo(ressave);
  6274. return func_ret;
  6275. }
  6276. static int
  6277. connect_socket(struct mg_context *ctx /* may be NULL */,
  6278. const char *host,
  6279. int port,
  6280. int use_ssl,
  6281. char *ebuf,
  6282. size_t ebuf_len,
  6283. SOCKET *sock /* output: socket, must not be NULL */,
  6284. union usa *sa /* output: socket address, must not be NULL */
  6285. )
  6286. {
  6287. int ip_ver = 0;
  6288. *sock = INVALID_SOCKET;
  6289. memset(sa, 0, sizeof(*sa));
  6290. if (ebuf_len > 0) {
  6291. *ebuf = 0;
  6292. }
  6293. if (host == NULL) {
  6294. mg_snprintf(NULL,
  6295. NULL, /* No truncation check for ebuf */
  6296. ebuf,
  6297. ebuf_len,
  6298. "%s",
  6299. "NULL host");
  6300. return 0;
  6301. }
  6302. if (port <= 0 || !is_valid_port((unsigned)port)) {
  6303. mg_snprintf(NULL,
  6304. NULL, /* No truncation check for ebuf */
  6305. ebuf,
  6306. ebuf_len,
  6307. "%s",
  6308. "invalid port");
  6309. return 0;
  6310. }
  6311. #if !defined(NO_SSL)
  6312. #if !defined(NO_SSL_DL)
  6313. #ifdef OPENSSL_API_1_1
  6314. if (use_ssl && (TLS_client_method == NULL)) {
  6315. mg_snprintf(NULL,
  6316. NULL, /* No truncation check for ebuf */
  6317. ebuf,
  6318. ebuf_len,
  6319. "%s",
  6320. "SSL is not initialized");
  6321. return 0;
  6322. }
  6323. #else
  6324. if (use_ssl && (SSLv23_client_method == NULL)) {
  6325. mg_snprintf(NULL,
  6326. NULL, /* No truncation check for ebuf */
  6327. ebuf,
  6328. ebuf_len,
  6329. "%s",
  6330. "SSL is not initialized");
  6331. return 0;
  6332. }
  6333. #endif /* OPENSSL_API_1_1 */
  6334. #else
  6335. (void)use_ssl;
  6336. #endif /* NO_SSL_DL */
  6337. #else
  6338. (void)use_ssl;
  6339. #endif /* !defined(NO_SSL) */
  6340. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6341. sa->sin.sin_port = htons((uint16_t)port);
  6342. ip_ver = 4;
  6343. #ifdef USE_IPV6
  6344. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6345. sa->sin6.sin6_port = htons((uint16_t)port);
  6346. ip_ver = 6;
  6347. } else if (host[0] == '[') {
  6348. /* While getaddrinfo on Windows will work with [::1],
  6349. * getaddrinfo on Linux only works with ::1 (without []). */
  6350. size_t l = strlen(host + 1);
  6351. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6352. if (h) {
  6353. h[l - 1] = 0;
  6354. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6355. sa->sin6.sin6_port = htons((uint16_t)port);
  6356. ip_ver = 6;
  6357. }
  6358. mg_free(h);
  6359. }
  6360. #endif
  6361. }
  6362. if (ip_ver == 0) {
  6363. mg_snprintf(NULL,
  6364. NULL, /* No truncation check for ebuf */
  6365. ebuf,
  6366. ebuf_len,
  6367. "%s",
  6368. "host not found");
  6369. return 0;
  6370. }
  6371. if (ip_ver == 4) {
  6372. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6373. }
  6374. #ifdef USE_IPV6
  6375. else if (ip_ver == 6) {
  6376. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6377. }
  6378. #endif
  6379. if (*sock == INVALID_SOCKET) {
  6380. mg_snprintf(NULL,
  6381. NULL, /* No truncation check for ebuf */
  6382. ebuf,
  6383. ebuf_len,
  6384. "socket(): %s",
  6385. strerror(ERRNO));
  6386. return 0;
  6387. }
  6388. set_close_on_exec(*sock, fc(ctx));
  6389. if ((ip_ver == 4)
  6390. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6391. == 0)) {
  6392. /* connected with IPv4 */
  6393. set_blocking_mode(*sock, 0);
  6394. return 1;
  6395. }
  6396. #ifdef USE_IPV6
  6397. if ((ip_ver == 6)
  6398. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6399. == 0)) {
  6400. /* connected with IPv6 */
  6401. set_blocking_mode(*sock, 0);
  6402. return 1;
  6403. }
  6404. #endif
  6405. /* Not connected */
  6406. mg_snprintf(NULL,
  6407. NULL, /* No truncation check for ebuf */
  6408. ebuf,
  6409. ebuf_len,
  6410. "connect(%s:%d): %s",
  6411. host,
  6412. port,
  6413. strerror(ERRNO));
  6414. closesocket(*sock);
  6415. *sock = INVALID_SOCKET;
  6416. return 0;
  6417. }
  6418. int
  6419. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6420. {
  6421. static const char *dont_escape = "._-$,;~()";
  6422. static const char *hex = "0123456789abcdef";
  6423. char *pos = dst;
  6424. const char *end = dst + dst_len - 1;
  6425. for (; *src != '\0' && pos < end; src++, pos++) {
  6426. if (isalnum(*(const unsigned char *)src)
  6427. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  6428. *pos = *src;
  6429. } else if (pos + 2 < end) {
  6430. pos[0] = '%';
  6431. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6432. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6433. pos += 2;
  6434. } else {
  6435. break;
  6436. }
  6437. }
  6438. *pos = '\0';
  6439. return (*src == '\0') ? (int)(pos - dst) : -1;
  6440. }
  6441. static void
  6442. print_dir_entry(struct de *de)
  6443. {
  6444. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6445. struct tm *tm;
  6446. if (de->file.is_directory) {
  6447. mg_snprintf(de->conn,
  6448. NULL, /* Buffer is big enough */
  6449. size,
  6450. sizeof(size),
  6451. "%s",
  6452. "[DIRECTORY]");
  6453. } else {
  6454. /* We use (signed) cast below because MSVC 6 compiler cannot
  6455. * convert unsigned __int64 to double. Sigh. */
  6456. if (de->file.size < 1024) {
  6457. mg_snprintf(de->conn,
  6458. NULL, /* Buffer is big enough */
  6459. size,
  6460. sizeof(size),
  6461. "%d",
  6462. (int)de->file.size);
  6463. } else if (de->file.size < 0x100000) {
  6464. mg_snprintf(de->conn,
  6465. NULL, /* Buffer is big enough */
  6466. size,
  6467. sizeof(size),
  6468. "%.1fk",
  6469. (double)de->file.size / 1024.0);
  6470. } else if (de->file.size < 0x40000000) {
  6471. mg_snprintf(de->conn,
  6472. NULL, /* Buffer is big enough */
  6473. size,
  6474. sizeof(size),
  6475. "%.1fM",
  6476. (double)de->file.size / 1048576);
  6477. } else {
  6478. mg_snprintf(de->conn,
  6479. NULL, /* Buffer is big enough */
  6480. size,
  6481. sizeof(size),
  6482. "%.1fG",
  6483. (double)de->file.size / 1073741824);
  6484. }
  6485. }
  6486. /* Note: mg_snprintf will not cause a buffer overflow above.
  6487. * So, string truncation checks are not required here. */
  6488. tm = localtime(&de->file.last_modified);
  6489. if (tm != NULL) {
  6490. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6491. } else {
  6492. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6493. mod[sizeof(mod) - 1] = '\0';
  6494. }
  6495. mg_url_encode(de->file_name, href, sizeof(href));
  6496. de->conn->num_bytes_sent +=
  6497. mg_printf(de->conn,
  6498. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6499. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6500. de->conn->request_info.local_uri,
  6501. href,
  6502. de->file.is_directory ? "/" : "",
  6503. de->file_name,
  6504. de->file.is_directory ? "/" : "",
  6505. mod,
  6506. size);
  6507. }
  6508. /* This function is called from send_directory() and used for
  6509. * sorting directory entries by size, or name, or modification time.
  6510. * On windows, __cdecl specification is needed in case if project is built
  6511. * with __stdcall convention. qsort always requires __cdels callback. */
  6512. static int WINCDECL
  6513. compare_dir_entries(const void *p1, const void *p2)
  6514. {
  6515. if (p1 && p2) {
  6516. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6517. const char *query_string = a->conn->request_info.query_string;
  6518. int cmp_result = 0;
  6519. if (query_string == NULL) {
  6520. query_string = "na";
  6521. }
  6522. if (a->file.is_directory && !b->file.is_directory) {
  6523. return -1; /* Always put directories on top */
  6524. } else if (!a->file.is_directory && b->file.is_directory) {
  6525. return 1; /* Always put directories on top */
  6526. } else if (*query_string == 'n') {
  6527. cmp_result = strcmp(a->file_name, b->file_name);
  6528. } else if (*query_string == 's') {
  6529. cmp_result = (a->file.size == b->file.size)
  6530. ? 0
  6531. : ((a->file.size > b->file.size) ? 1 : -1);
  6532. } else if (*query_string == 'd') {
  6533. cmp_result =
  6534. (a->file.last_modified == b->file.last_modified)
  6535. ? 0
  6536. : ((a->file.last_modified > b->file.last_modified) ? 1
  6537. : -1);
  6538. }
  6539. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6540. }
  6541. return 0;
  6542. }
  6543. static int
  6544. must_hide_file(struct mg_connection *conn, const char *path)
  6545. {
  6546. if (conn && conn->ctx) {
  6547. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6548. const char *pattern = conn->ctx->config[HIDE_FILES];
  6549. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6550. || (pattern != NULL
  6551. && match_prefix(pattern, strlen(pattern), path) > 0);
  6552. }
  6553. return 0;
  6554. }
  6555. static int
  6556. scan_directory(struct mg_connection *conn,
  6557. const char *dir,
  6558. void *data,
  6559. void (*cb)(struct de *, void *))
  6560. {
  6561. char path[PATH_MAX];
  6562. struct dirent *dp;
  6563. DIR *dirp;
  6564. struct de de;
  6565. int truncated;
  6566. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6567. return 0;
  6568. } else {
  6569. de.conn = conn;
  6570. while ((dp = mg_readdir(dirp)) != NULL) {
  6571. /* Do not show current dir and hidden files */
  6572. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6573. || must_hide_file(conn, dp->d_name)) {
  6574. continue;
  6575. }
  6576. mg_snprintf(
  6577. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6578. /* If we don't memset stat structure to zero, mtime will have
  6579. * garbage and strftime() will segfault later on in
  6580. * print_dir_entry(). memset is required only if mg_stat()
  6581. * fails. For more details, see
  6582. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6583. memset(&de.file, 0, sizeof(de.file));
  6584. if (truncated) {
  6585. /* If the path is not complete, skip processing. */
  6586. continue;
  6587. }
  6588. if (!mg_stat(conn, path, &de.file)) {
  6589. mg_cry(conn,
  6590. "%s: mg_stat(%s) failed: %s",
  6591. __func__,
  6592. path,
  6593. strerror(ERRNO));
  6594. }
  6595. de.file_name = dp->d_name;
  6596. cb(&de, data);
  6597. }
  6598. (void)mg_closedir(dirp);
  6599. }
  6600. return 1;
  6601. }
  6602. #if !defined(NO_FILES)
  6603. static int
  6604. remove_directory(struct mg_connection *conn, const char *dir)
  6605. {
  6606. char path[PATH_MAX];
  6607. struct dirent *dp;
  6608. DIR *dirp;
  6609. struct de de;
  6610. int truncated;
  6611. int ok = 1;
  6612. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6613. return 0;
  6614. } else {
  6615. de.conn = conn;
  6616. while ((dp = mg_readdir(dirp)) != NULL) {
  6617. /* Do not show current dir (but show hidden files as they will
  6618. * also be removed) */
  6619. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6620. continue;
  6621. }
  6622. mg_snprintf(
  6623. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6624. /* If we don't memset stat structure to zero, mtime will have
  6625. * garbage and strftime() will segfault later on in
  6626. * print_dir_entry(). memset is required only if mg_stat()
  6627. * fails. For more details, see
  6628. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6629. memset(&de.file, 0, sizeof(de.file));
  6630. if (truncated) {
  6631. /* Do not delete anything shorter */
  6632. ok = 0;
  6633. continue;
  6634. }
  6635. if (!mg_stat(conn, path, &de.file)) {
  6636. mg_cry(conn,
  6637. "%s: mg_stat(%s) failed: %s",
  6638. __func__,
  6639. path,
  6640. strerror(ERRNO));
  6641. ok = 0;
  6642. }
  6643. if (de.file.is_directory) {
  6644. if (remove_directory(conn, path) == 0) {
  6645. ok = 0;
  6646. }
  6647. } else {
  6648. /* This will fail file is the file is in memory */
  6649. if (mg_remove(conn, path) == 0) {
  6650. ok = 0;
  6651. }
  6652. }
  6653. }
  6654. (void)mg_closedir(dirp);
  6655. IGNORE_UNUSED_RESULT(rmdir(dir));
  6656. }
  6657. return ok;
  6658. }
  6659. #endif
  6660. struct dir_scan_data {
  6661. struct de *entries;
  6662. unsigned int num_entries;
  6663. unsigned int arr_size;
  6664. };
  6665. /* Behaves like realloc(), but frees original pointer on failure */
  6666. static void *
  6667. realloc2(void *ptr, size_t size)
  6668. {
  6669. void *new_ptr = mg_realloc(ptr, size);
  6670. if (new_ptr == NULL) {
  6671. mg_free(ptr);
  6672. }
  6673. return new_ptr;
  6674. }
  6675. static void
  6676. dir_scan_callback(struct de *de, void *data)
  6677. {
  6678. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6679. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6680. dsd->arr_size *= 2;
  6681. dsd->entries =
  6682. (struct de *)realloc2(dsd->entries,
  6683. dsd->arr_size * sizeof(dsd->entries[0]));
  6684. }
  6685. if (dsd->entries == NULL) {
  6686. /* TODO(lsm, low): propagate an error to the caller */
  6687. dsd->num_entries = 0;
  6688. } else {
  6689. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6690. dsd->entries[dsd->num_entries].file = de->file;
  6691. dsd->entries[dsd->num_entries].conn = de->conn;
  6692. dsd->num_entries++;
  6693. }
  6694. }
  6695. static void
  6696. handle_directory_request(struct mg_connection *conn, const char *dir)
  6697. {
  6698. unsigned int i;
  6699. int sort_direction;
  6700. struct dir_scan_data data = {NULL, 0, 128};
  6701. char date[64];
  6702. time_t curtime = time(NULL);
  6703. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6704. mg_send_http_error(conn,
  6705. 500,
  6706. "Error: Cannot open directory\nopendir(%s): %s",
  6707. dir,
  6708. strerror(ERRNO));
  6709. return;
  6710. }
  6711. gmt_time_string(date, sizeof(date), &curtime);
  6712. if (!conn) {
  6713. return;
  6714. }
  6715. sort_direction = ((conn->request_info.query_string != NULL)
  6716. && (conn->request_info.query_string[1] == 'd'))
  6717. ? 'a'
  6718. : 'd';
  6719. conn->must_close = 1;
  6720. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6721. send_static_cache_header(conn);
  6722. send_additional_header(conn);
  6723. mg_printf(conn,
  6724. "Date: %s\r\n"
  6725. "Connection: close\r\n"
  6726. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6727. date);
  6728. conn->num_bytes_sent +=
  6729. mg_printf(conn,
  6730. "<html><head><title>Index of %s</title>"
  6731. "<style>th {text-align: left;}</style></head>"
  6732. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6733. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6734. "<th><a href=\"?d%c\">Modified</a></th>"
  6735. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6736. "<tr><td colspan=\"3\"><hr></td></tr>",
  6737. conn->request_info.local_uri,
  6738. conn->request_info.local_uri,
  6739. sort_direction,
  6740. sort_direction,
  6741. sort_direction);
  6742. /* Print first entry - link to a parent directory */
  6743. conn->num_bytes_sent +=
  6744. mg_printf(conn,
  6745. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6746. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6747. conn->request_info.local_uri,
  6748. "..",
  6749. "Parent directory",
  6750. "-",
  6751. "-");
  6752. /* Sort and print directory entries */
  6753. if (data.entries != NULL) {
  6754. qsort(data.entries,
  6755. (size_t)data.num_entries,
  6756. sizeof(data.entries[0]),
  6757. compare_dir_entries);
  6758. for (i = 0; i < data.num_entries; i++) {
  6759. print_dir_entry(&data.entries[i]);
  6760. mg_free(data.entries[i].file_name);
  6761. }
  6762. mg_free(data.entries);
  6763. }
  6764. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6765. conn->status_code = 200;
  6766. }
  6767. /* Send len bytes from the opened file to the client. */
  6768. static void
  6769. send_file_data(struct mg_connection *conn,
  6770. struct mg_file *filep,
  6771. int64_t offset,
  6772. int64_t len)
  6773. {
  6774. char buf[MG_BUF_LEN];
  6775. int to_read, num_read, num_written;
  6776. int64_t size;
  6777. if (!filep || !conn) {
  6778. return;
  6779. }
  6780. /* Sanity check the offset */
  6781. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6782. : (int64_t)(filep->stat.size);
  6783. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6784. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6785. /* file stored in memory */
  6786. if (len > size - offset) {
  6787. len = size - offset;
  6788. }
  6789. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6790. } else if (len > 0 && filep->access.fp != NULL) {
  6791. /* file stored on disk */
  6792. #if defined(__linux__)
  6793. /* sendfile is only available for Linux */
  6794. if ((conn->ssl == 0) && (conn->throttle == 0)
  6795. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6796. "yes"))) {
  6797. off_t sf_offs = (off_t)offset;
  6798. ssize_t sf_sent;
  6799. int sf_file = fileno(filep->access.fp);
  6800. int loop_cnt = 0;
  6801. do {
  6802. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6803. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6804. size_t sf_tosend =
  6805. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6806. sf_sent =
  6807. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6808. if (sf_sent > 0) {
  6809. conn->num_bytes_sent += sf_sent;
  6810. len -= sf_sent;
  6811. offset += sf_sent;
  6812. } else if (loop_cnt == 0) {
  6813. /* This file can not be sent using sendfile.
  6814. * This might be the case for pseudo-files in the
  6815. * /sys/ and /proc/ file system.
  6816. * Use the regular user mode copy code instead. */
  6817. break;
  6818. } else if (sf_sent == 0) {
  6819. /* No error, but 0 bytes sent. May be EOF? */
  6820. return;
  6821. }
  6822. loop_cnt++;
  6823. } while ((len > 0) && (sf_sent >= 0));
  6824. if (sf_sent > 0) {
  6825. return; /* OK */
  6826. }
  6827. /* sf_sent<0 means error, thus fall back to the classic way */
  6828. /* This is always the case, if sf_file is not a "normal" file,
  6829. * e.g., for sending data from the output of a CGI process. */
  6830. offset = (int64_t)sf_offs;
  6831. }
  6832. #endif
  6833. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6834. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6835. mg_send_http_error(
  6836. conn,
  6837. 500,
  6838. "%s",
  6839. "Error: Unable to access file at requested position.");
  6840. } else {
  6841. while (len > 0) {
  6842. /* Calculate how much to read from the file in the buffer */
  6843. to_read = sizeof(buf);
  6844. if ((int64_t)to_read > len) {
  6845. to_read = (int)len;
  6846. }
  6847. /* Read from file, exit the loop on error */
  6848. if ((num_read =
  6849. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6850. <= 0) {
  6851. break;
  6852. }
  6853. /* Send read bytes to the client, exit the loop on error */
  6854. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6855. != num_read) {
  6856. break;
  6857. }
  6858. /* Both read and were successful, adjust counters */
  6859. conn->num_bytes_sent += num_written;
  6860. len -= num_written;
  6861. }
  6862. }
  6863. }
  6864. }
  6865. static int
  6866. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6867. {
  6868. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6869. }
  6870. static void
  6871. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6872. {
  6873. if (filestat != NULL && buf != NULL) {
  6874. mg_snprintf(NULL,
  6875. NULL, /* All calls to construct_etag use 64 byte buffer */
  6876. buf,
  6877. buf_len,
  6878. "\"%lx.%" INT64_FMT "\"",
  6879. (unsigned long)filestat->last_modified,
  6880. filestat->size);
  6881. }
  6882. }
  6883. static void
  6884. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6885. {
  6886. if (filep != NULL && filep->fp != NULL) {
  6887. #ifdef _WIN32
  6888. (void)conn; /* Unused. */
  6889. #else
  6890. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6891. mg_cry(conn,
  6892. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6893. __func__,
  6894. strerror(ERRNO));
  6895. }
  6896. #endif
  6897. }
  6898. }
  6899. static void
  6900. handle_static_file_request(struct mg_connection *conn,
  6901. const char *path,
  6902. struct mg_file *filep,
  6903. const char *mime_type,
  6904. const char *additional_headers)
  6905. {
  6906. char date[64], lm[64], etag[64];
  6907. char range[128]; /* large enough, so there will be no overflow */
  6908. const char *msg = "OK", *hdr;
  6909. time_t curtime = time(NULL);
  6910. int64_t cl, r1, r2;
  6911. struct vec mime_vec;
  6912. int n, truncated;
  6913. char gz_path[PATH_MAX];
  6914. const char *encoding = "";
  6915. const char *cors1, *cors2, *cors3;
  6916. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6917. return;
  6918. }
  6919. if (mime_type == NULL) {
  6920. get_mime_type(conn->ctx, path, &mime_vec);
  6921. } else {
  6922. mime_vec.ptr = mime_type;
  6923. mime_vec.len = strlen(mime_type);
  6924. }
  6925. if (filep->stat.size > INT64_MAX) {
  6926. mg_send_http_error(conn,
  6927. 500,
  6928. "Error: File size is too large to send\n%" INT64_FMT,
  6929. filep->stat.size);
  6930. }
  6931. cl = (int64_t)filep->stat.size;
  6932. conn->status_code = 200;
  6933. range[0] = '\0';
  6934. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6935. * it's important to rewrite the filename after resolving
  6936. * the mime type from it, to preserve the actual file's type */
  6937. if (filep->stat.is_gzipped) {
  6938. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6939. if (truncated) {
  6940. mg_send_http_error(conn,
  6941. 500,
  6942. "Error: Path of zipped file too long (%s)",
  6943. path);
  6944. return;
  6945. }
  6946. path = gz_path;
  6947. encoding = "Content-Encoding: gzip\r\n";
  6948. }
  6949. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6950. mg_send_http_error(conn,
  6951. 500,
  6952. "Error: Cannot open file\nfopen(%s): %s",
  6953. path,
  6954. strerror(ERRNO));
  6955. return;
  6956. }
  6957. fclose_on_exec(&filep->access, conn);
  6958. /* If Range: header specified, act accordingly */
  6959. r1 = r2 = 0;
  6960. hdr = mg_get_header(conn, "Range");
  6961. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6962. && r2 >= 0) {
  6963. /* actually, range requests don't play well with a pre-gzipped
  6964. * file (since the range is specified in the uncompressed space) */
  6965. if (filep->stat.is_gzipped) {
  6966. mg_send_http_error(
  6967. conn,
  6968. 416, /* 416 = Range Not Satisfiable */
  6969. "%s",
  6970. "Error: Range requests in gzipped files are not supported");
  6971. (void)mg_fclose(
  6972. &filep->access); /* ignore error on read only file */
  6973. return;
  6974. }
  6975. conn->status_code = 206;
  6976. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6977. mg_snprintf(conn,
  6978. NULL, /* range buffer is big enough */
  6979. range,
  6980. sizeof(range),
  6981. "Content-Range: bytes "
  6982. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6983. r1,
  6984. r1 + cl - 1,
  6985. filep->stat.size);
  6986. msg = "Partial Content";
  6987. }
  6988. hdr = mg_get_header(conn, "Origin");
  6989. if (hdr) {
  6990. /* Cross-origin resource sharing (CORS), see
  6991. * http://www.html5rocks.com/en/tutorials/cors/,
  6992. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6993. * preflight is not supported for files. */
  6994. cors1 = "Access-Control-Allow-Origin: ";
  6995. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6996. cors3 = "\r\n";
  6997. } else {
  6998. cors1 = cors2 = cors3 = "";
  6999. }
  7000. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  7001. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7002. gmt_time_string(date, sizeof(date), &curtime);
  7003. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7004. construct_etag(etag, sizeof(etag), &filep->stat);
  7005. (void)mg_printf(conn,
  7006. "HTTP/1.1 %d %s\r\n"
  7007. "%s%s%s"
  7008. "Date: %s\r\n",
  7009. conn->status_code,
  7010. msg,
  7011. cors1,
  7012. cors2,
  7013. cors3,
  7014. date);
  7015. send_static_cache_header(conn);
  7016. send_additional_header(conn);
  7017. (void)mg_printf(conn,
  7018. "Last-Modified: %s\r\n"
  7019. "Etag: %s\r\n"
  7020. "Content-Type: %.*s\r\n"
  7021. "Content-Length: %" INT64_FMT "\r\n"
  7022. "Connection: %s\r\n"
  7023. "Accept-Ranges: bytes\r\n"
  7024. "%s%s",
  7025. lm,
  7026. etag,
  7027. (int)mime_vec.len,
  7028. mime_vec.ptr,
  7029. cl,
  7030. suggest_connection_header(conn),
  7031. range,
  7032. encoding);
  7033. /* The previous code must not add any header starting with X- to make
  7034. * sure no one of the additional_headers is included twice */
  7035. if (additional_headers != NULL) {
  7036. (void)mg_printf(conn,
  7037. "%.*s\r\n\r\n",
  7038. (int)strlen(additional_headers),
  7039. additional_headers);
  7040. } else {
  7041. (void)mg_printf(conn, "\r\n");
  7042. }
  7043. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7044. send_file_data(conn, filep, r1, cl);
  7045. }
  7046. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7047. }
  7048. #if !defined(NO_CACHING)
  7049. static void
  7050. handle_not_modified_static_file_request(struct mg_connection *conn,
  7051. struct mg_file *filep)
  7052. {
  7053. char date[64], lm[64], etag[64];
  7054. time_t curtime = time(NULL);
  7055. if (conn == NULL || filep == NULL) {
  7056. return;
  7057. }
  7058. conn->status_code = 304;
  7059. gmt_time_string(date, sizeof(date), &curtime);
  7060. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7061. construct_etag(etag, sizeof(etag), &filep->stat);
  7062. (void)mg_printf(conn,
  7063. "HTTP/1.1 %d %s\r\n"
  7064. "Date: %s\r\n",
  7065. conn->status_code,
  7066. mg_get_response_code_text(conn, conn->status_code),
  7067. date);
  7068. send_static_cache_header(conn);
  7069. send_additional_header(conn);
  7070. (void)mg_printf(conn,
  7071. "Last-Modified: %s\r\n"
  7072. "Etag: %s\r\n"
  7073. "Connection: %s\r\n"
  7074. "\r\n",
  7075. lm,
  7076. etag,
  7077. suggest_connection_header(conn));
  7078. }
  7079. #endif
  7080. void
  7081. mg_send_file(struct mg_connection *conn, const char *path)
  7082. {
  7083. mg_send_mime_file(conn, path, NULL);
  7084. }
  7085. void
  7086. mg_send_mime_file(struct mg_connection *conn,
  7087. const char *path,
  7088. const char *mime_type)
  7089. {
  7090. mg_send_mime_file2(conn, path, mime_type, NULL);
  7091. }
  7092. void
  7093. mg_send_mime_file2(struct mg_connection *conn,
  7094. const char *path,
  7095. const char *mime_type,
  7096. const char *additional_headers)
  7097. {
  7098. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7099. if (mg_stat(conn, path, &file.stat)) {
  7100. if (file.stat.is_directory) {
  7101. if (!conn) {
  7102. return;
  7103. }
  7104. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7105. "yes")) {
  7106. handle_directory_request(conn, path);
  7107. } else {
  7108. mg_send_http_error(conn,
  7109. 403,
  7110. "%s",
  7111. "Error: Directory listing denied");
  7112. }
  7113. } else {
  7114. handle_static_file_request(
  7115. conn, path, &file, mime_type, additional_headers);
  7116. }
  7117. } else {
  7118. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7119. }
  7120. }
  7121. /* For a given PUT path, create all intermediate subdirectories.
  7122. * Return 0 if the path itself is a directory.
  7123. * Return 1 if the path leads to a file.
  7124. * Return -1 for if the path is too long.
  7125. * Return -2 if path can not be created.
  7126. */
  7127. static int
  7128. put_dir(struct mg_connection *conn, const char *path)
  7129. {
  7130. char buf[PATH_MAX];
  7131. const char *s, *p;
  7132. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7133. size_t len;
  7134. int res = 1;
  7135. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7136. len = (size_t)(p - path);
  7137. if (len >= sizeof(buf)) {
  7138. /* path too long */
  7139. res = -1;
  7140. break;
  7141. }
  7142. memcpy(buf, path, len);
  7143. buf[len] = '\0';
  7144. /* Try to create intermediate directory */
  7145. DEBUG_TRACE("mkdir(%s)", buf);
  7146. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7147. /* path does not exixt and can not be created */
  7148. res = -2;
  7149. break;
  7150. }
  7151. /* Is path itself a directory? */
  7152. if (p[1] == '\0') {
  7153. res = 0;
  7154. }
  7155. }
  7156. return res;
  7157. }
  7158. static void
  7159. remove_bad_file(const struct mg_connection *conn, const char *path)
  7160. {
  7161. int r = mg_remove(conn, path);
  7162. if (r != 0) {
  7163. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7164. }
  7165. }
  7166. long long
  7167. mg_store_body(struct mg_connection *conn, const char *path)
  7168. {
  7169. char buf[MG_BUF_LEN];
  7170. long long len = 0;
  7171. int ret, n;
  7172. struct mg_file fi;
  7173. if (conn->consumed_content != 0) {
  7174. mg_cry(conn, "%s: Contents already consumed", __func__);
  7175. return -11;
  7176. }
  7177. ret = put_dir(conn, path);
  7178. if (ret < 0) {
  7179. /* -1 for path too long,
  7180. * -2 for path can not be created. */
  7181. return ret;
  7182. }
  7183. if (ret != 1) {
  7184. /* Return 0 means, path itself is a directory. */
  7185. return 0;
  7186. }
  7187. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7188. return -12;
  7189. }
  7190. ret = mg_read(conn, buf, sizeof(buf));
  7191. while (ret > 0) {
  7192. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7193. if (n != ret) {
  7194. (void)mg_fclose(
  7195. &fi.access); /* File is bad and will be removed anyway. */
  7196. remove_bad_file(conn, path);
  7197. return -13;
  7198. }
  7199. len += ret;
  7200. ret = mg_read(conn, buf, sizeof(buf));
  7201. }
  7202. /* File is open for writing. If fclose fails, there was probably an
  7203. * error flushing the buffer to disk, so the file on disk might be
  7204. * broken. Delete it and return an error to the caller. */
  7205. if (mg_fclose(&fi.access) != 0) {
  7206. remove_bad_file(conn, path);
  7207. return -14;
  7208. }
  7209. return len;
  7210. }
  7211. /* Parse HTTP headers from the given buffer, advance buf pointer
  7212. * to the point where parsing stopped.
  7213. * All parameters must be valid pointers (not NULL).
  7214. * Return <0 on error. */
  7215. static int
  7216. parse_http_headers(char **buf, struct mg_request_info *ri)
  7217. {
  7218. int i;
  7219. ri->num_headers = 0;
  7220. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  7221. char *dp = *buf;
  7222. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7223. dp++;
  7224. }
  7225. if (dp == *buf) {
  7226. /* End of headers reached. */
  7227. break;
  7228. }
  7229. if (*dp != ':') {
  7230. /* This is not a valid field. */
  7231. return -1;
  7232. }
  7233. /* End of header key (*dp == ':') */
  7234. /* Truncate here and set the key name */
  7235. *dp = 0;
  7236. ri->http_headers[i].name = *buf;
  7237. do {
  7238. dp++;
  7239. } while (*dp == ' ');
  7240. /* The rest of the line is the value */
  7241. ri->http_headers[i].value = dp;
  7242. *buf = dp + strcspn(dp, "\r\n");
  7243. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7244. *buf = NULL;
  7245. }
  7246. ri->num_headers = i + 1;
  7247. if (*buf) {
  7248. (*buf)[0] = 0;
  7249. (*buf)[1] = 0;
  7250. *buf += 2;
  7251. } else {
  7252. *buf = dp;
  7253. break;
  7254. }
  7255. if ((*buf)[0] == '\r') {
  7256. /* This is the end of the header */
  7257. break;
  7258. }
  7259. }
  7260. return ri->num_headers;
  7261. }
  7262. static int
  7263. is_valid_http_method(const char *method)
  7264. {
  7265. /* Check if the method is known to the server. The list of all known
  7266. * HTTP methods can be found here at
  7267. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7268. */
  7269. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7270. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7271. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7272. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7273. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7274. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7275. /* TRACE method (RFC 2616) is not supported for security reasons */
  7276. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7277. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7278. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7279. /* Unsupported WEBDAV Methods: */
  7280. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7281. /* + 11 methods from RFC 3253 */
  7282. /* ORDERPATCH (RFC 3648) */
  7283. /* ACL (RFC 3744) */
  7284. /* SEARCH (RFC 5323) */
  7285. /* + MicroSoft extensions
  7286. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7287. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7288. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7289. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7290. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7291. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7292. * to be useful for REST in case a "GET request with body" is
  7293. * required. */
  7294. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7295. ;
  7296. }
  7297. /* Parse HTTP request, fill in mg_request_info structure.
  7298. * This function modifies the buffer by NUL-terminating
  7299. * HTTP request components, header names and header values.
  7300. * Parameters:
  7301. * buf (in/out): pointer to the HTTP header to parse and split
  7302. * len (in): length of HTTP header buffer
  7303. * re (out): parsed header as mg_request_info
  7304. * buf and ri must be valid pointers (not NULL), len>0.
  7305. * Returns <0 on error. */
  7306. static int
  7307. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  7308. {
  7309. int is_request, request_length;
  7310. char *start_line;
  7311. request_length = get_request_len(buf, len);
  7312. if (request_length > 0) {
  7313. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7314. * remote_port */
  7315. ri->remote_user = ri->request_method = ri->request_uri =
  7316. ri->http_version = NULL;
  7317. ri->num_headers = 0;
  7318. buf[request_length - 1] = '\0';
  7319. /* RFC says that all initial whitespaces should be ingored */
  7320. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  7321. buf++;
  7322. }
  7323. start_line = skip(&buf, "\r\n");
  7324. ri->request_method = skip(&start_line, " ");
  7325. ri->request_uri = skip(&start_line, " ");
  7326. ri->http_version = start_line;
  7327. /* HTTP message could be either HTTP request:
  7328. * "GET / HTTP/1.0 ..."
  7329. * or a HTTP response:
  7330. * "HTTP/1.0 200 OK ..."
  7331. * otherwise it is invalid.
  7332. */
  7333. is_request = is_valid_http_method(ri->request_method);
  7334. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  7335. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  7336. /* Not a valid request or response: invalid */
  7337. return -1;
  7338. }
  7339. if (is_request) {
  7340. ri->http_version += 5;
  7341. }
  7342. if (parse_http_headers(&buf, ri) < 0) {
  7343. /* Error while parsing headers */
  7344. return -1;
  7345. }
  7346. }
  7347. return request_length;
  7348. }
  7349. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7350. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7351. * buffer (which marks the end of HTTP request). Buffer buf may already
  7352. * have some data. The length of the data is stored in nread.
  7353. * Upon every read operation, increase nread by the number of bytes read. */
  7354. static int
  7355. read_request(FILE *fp,
  7356. struct mg_connection *conn,
  7357. char *buf,
  7358. int bufsiz,
  7359. int *nread)
  7360. {
  7361. int request_len, n = 0;
  7362. struct timespec last_action_time;
  7363. double request_timeout;
  7364. if (!conn) {
  7365. return 0;
  7366. }
  7367. memset(&last_action_time, 0, sizeof(last_action_time));
  7368. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7369. /* value of request_timeout is in seconds, config in milliseconds */
  7370. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7371. } else {
  7372. request_timeout = -1.0;
  7373. }
  7374. if (conn->handled_requests > 0) {
  7375. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7376. request_timeout =
  7377. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7378. }
  7379. }
  7380. request_len = get_request_len(buf, *nread);
  7381. /* first time reading from this connection */
  7382. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7383. while (request_len == 0) {
  7384. /* Full request not yet received */
  7385. if (conn->ctx->stop_flag != 0) {
  7386. /* Server is to be stopped. */
  7387. return -1;
  7388. }
  7389. if (*nread >= bufsiz) {
  7390. /* Request too long */
  7391. return -2;
  7392. }
  7393. n = pull_inner(
  7394. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7395. if (n == -2) {
  7396. /* Receive error */
  7397. return -1;
  7398. }
  7399. if (n > 0) {
  7400. *nread += n;
  7401. request_len = get_request_len(buf, *nread);
  7402. } else {
  7403. request_len = 0;
  7404. }
  7405. if ((request_len == 0) && (request_timeout >= 0)) {
  7406. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7407. > request_timeout) {
  7408. /* Timeout */
  7409. return -1;
  7410. }
  7411. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7412. }
  7413. }
  7414. return request_len;
  7415. }
  7416. #if !defined(NO_CACHING)
  7417. /* Return True if we should reply 304 Not Modified. */
  7418. static int
  7419. is_not_modified(const struct mg_connection *conn,
  7420. const struct mg_file_stat *filestat)
  7421. {
  7422. char etag[64];
  7423. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7424. const char *inm = mg_get_header(conn, "If-None-Match");
  7425. construct_etag(etag, sizeof(etag), filestat);
  7426. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7427. || ((ims != NULL)
  7428. && (filestat->last_modified <= parse_date_string(ims)));
  7429. }
  7430. #endif /* !NO_CACHING */
  7431. #if !defined(NO_CGI) || !defined(NO_FILES)
  7432. static int
  7433. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7434. {
  7435. const char *expect, *body;
  7436. char buf[MG_BUF_LEN];
  7437. int to_read, nread, success = 0;
  7438. int64_t buffered_len;
  7439. double timeout = -1.0;
  7440. if (!conn) {
  7441. return 0;
  7442. }
  7443. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7444. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7445. }
  7446. expect = mg_get_header(conn, "Expect");
  7447. /* assert(fp != NULL); */
  7448. if (!fp) {
  7449. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  7450. return 0;
  7451. }
  7452. if (conn->content_len == -1 && !conn->is_chunked) {
  7453. /* Content length is not specified by the client. */
  7454. mg_send_http_error(conn,
  7455. 411,
  7456. "%s",
  7457. "Error: Client did not specify content length");
  7458. } else if ((expect != NULL)
  7459. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7460. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7461. mg_send_http_error(conn,
  7462. 417,
  7463. "Error: Can not fulfill expectation %s",
  7464. expect);
  7465. } else {
  7466. if (expect != NULL) {
  7467. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7468. conn->status_code = 100;
  7469. } else {
  7470. conn->status_code = 200;
  7471. }
  7472. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7473. - conn->consumed_content;
  7474. /* assert(buffered_len >= 0); */
  7475. /* assert(conn->consumed_content == 0); */
  7476. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7477. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7478. return 0;
  7479. }
  7480. if (buffered_len > 0) {
  7481. if ((int64_t)buffered_len > conn->content_len) {
  7482. buffered_len = (int)conn->content_len;
  7483. }
  7484. body = conn->buf + conn->request_len + conn->consumed_content;
  7485. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7486. conn->consumed_content += buffered_len;
  7487. }
  7488. nread = 0;
  7489. while (conn->consumed_content < conn->content_len) {
  7490. to_read = sizeof(buf);
  7491. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7492. to_read = (int)(conn->content_len - conn->consumed_content);
  7493. }
  7494. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7495. if (nread == -2) {
  7496. /* error */
  7497. break;
  7498. }
  7499. if (nread > 0) {
  7500. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7501. break;
  7502. }
  7503. }
  7504. conn->consumed_content += nread;
  7505. }
  7506. if (conn->consumed_content == conn->content_len) {
  7507. success = (nread >= 0);
  7508. }
  7509. /* Each error code path in this function must send an error */
  7510. if (!success) {
  7511. /* NOTE: Maybe some data has already been sent. */
  7512. /* TODO (low): If some data has been sent, a correct error
  7513. * reply can no longer be sent, so just close the connection */
  7514. mg_send_http_error(conn, 500, "%s", "");
  7515. }
  7516. }
  7517. return success;
  7518. }
  7519. #endif
  7520. #if !defined(NO_CGI)
  7521. /* This structure helps to create an environment for the spawned CGI program.
  7522. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7523. * last element must be NULL.
  7524. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7525. * strings must reside in a contiguous buffer. The end of the buffer is
  7526. * marked by two '\0' characters.
  7527. * We satisfy both worlds: we create an envp array (which is vars), all
  7528. * entries are actually pointers inside buf. */
  7529. struct cgi_environment {
  7530. struct mg_connection *conn;
  7531. /* Data block */
  7532. char *buf; /* Environment buffer */
  7533. size_t buflen; /* Space available in buf */
  7534. size_t bufused; /* Space taken in buf */
  7535. /* Index block */
  7536. char **var; /* char **envp */
  7537. size_t varlen; /* Number of variables available in var */
  7538. size_t varused; /* Number of variables stored in var */
  7539. };
  7540. static void addenv(struct cgi_environment *env,
  7541. PRINTF_FORMAT_STRING(const char *fmt),
  7542. ...) PRINTF_ARGS(2, 3);
  7543. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7544. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7545. static void
  7546. addenv(struct cgi_environment *env, const char *fmt, ...)
  7547. {
  7548. size_t n, space;
  7549. int truncated = 0;
  7550. char *added;
  7551. va_list ap;
  7552. /* Calculate how much space is left in the buffer */
  7553. space = (env->buflen - env->bufused);
  7554. /* Calculate an estimate for the required space */
  7555. n = strlen(fmt) + 2 + 128;
  7556. do {
  7557. if (space <= n) {
  7558. /* Allocate new buffer */
  7559. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7560. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  7561. if (!added) {
  7562. /* Out of memory */
  7563. mg_cry(env->conn,
  7564. "%s: Cannot allocate memory for CGI variable [%s]",
  7565. __func__,
  7566. fmt);
  7567. return;
  7568. }
  7569. env->buf = added;
  7570. env->buflen = n;
  7571. space = (env->buflen - env->bufused);
  7572. }
  7573. /* Make a pointer to the free space int the buffer */
  7574. added = env->buf + env->bufused;
  7575. /* Copy VARIABLE=VALUE\0 string into the free space */
  7576. va_start(ap, fmt);
  7577. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7578. va_end(ap);
  7579. /* Do not add truncated strings to the environment */
  7580. if (truncated) {
  7581. /* Reallocate the buffer */
  7582. space = 0;
  7583. n = 1;
  7584. }
  7585. } while (truncated);
  7586. /* Calculate number of bytes added to the environment */
  7587. n = strlen(added) + 1;
  7588. env->bufused += n;
  7589. /* Now update the variable index */
  7590. space = (env->varlen - env->varused);
  7591. if (space < 2) {
  7592. mg_cry(env->conn,
  7593. "%s: Cannot register CGI variable [%s]",
  7594. __func__,
  7595. fmt);
  7596. return;
  7597. }
  7598. /* Append a pointer to the added string into the envp array */
  7599. env->var[env->varused] = added;
  7600. env->varused++;
  7601. }
  7602. static void
  7603. prepare_cgi_environment(struct mg_connection *conn,
  7604. const char *prog,
  7605. struct cgi_environment *env)
  7606. {
  7607. const char *s;
  7608. struct vec var_vec;
  7609. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7610. int i, truncated, uri_len;
  7611. if (conn == NULL || prog == NULL || env == NULL) {
  7612. return;
  7613. }
  7614. env->conn = conn;
  7615. env->buflen = CGI_ENVIRONMENT_SIZE;
  7616. env->bufused = 0;
  7617. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  7618. env->varlen = MAX_CGI_ENVIR_VARS;
  7619. env->varused = 0;
  7620. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  7621. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7622. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7623. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7624. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7625. /* Prepare the environment block */
  7626. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7627. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7628. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7629. #if defined(USE_IPV6)
  7630. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7631. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7632. } else
  7633. #endif
  7634. {
  7635. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7636. }
  7637. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7638. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7639. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7640. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7641. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7642. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7643. /* SCRIPT_NAME */
  7644. uri_len = (int)strlen(conn->request_info.local_uri);
  7645. if (conn->path_info == NULL) {
  7646. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7647. /* URI: /path_to_script/script.cgi */
  7648. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7649. } else {
  7650. /* URI: /path_to_script/ ... using index.cgi */
  7651. const char *index_file = strrchr(prog, '/');
  7652. if (index_file) {
  7653. addenv(env,
  7654. "SCRIPT_NAME=%s%s",
  7655. conn->request_info.local_uri,
  7656. index_file + 1);
  7657. }
  7658. }
  7659. } else {
  7660. /* URI: /path_to_script/script.cgi/path_info */
  7661. addenv(env,
  7662. "SCRIPT_NAME=%.*s",
  7663. uri_len - (int)strlen(conn->path_info),
  7664. conn->request_info.local_uri);
  7665. }
  7666. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7667. if (conn->path_info == NULL) {
  7668. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7669. } else {
  7670. addenv(env,
  7671. "PATH_TRANSLATED=%s%s",
  7672. conn->ctx->config[DOCUMENT_ROOT],
  7673. conn->path_info);
  7674. }
  7675. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7676. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7677. addenv(env, "CONTENT_TYPE=%s", s);
  7678. }
  7679. if (conn->request_info.query_string != NULL) {
  7680. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7681. }
  7682. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7683. addenv(env, "CONTENT_LENGTH=%s", s);
  7684. }
  7685. if ((s = getenv("PATH")) != NULL) {
  7686. addenv(env, "PATH=%s", s);
  7687. }
  7688. if (conn->path_info != NULL) {
  7689. addenv(env, "PATH_INFO=%s", conn->path_info);
  7690. }
  7691. if (conn->status_code > 0) {
  7692. /* CGI error handler should show the status code */
  7693. addenv(env, "STATUS=%d", conn->status_code);
  7694. }
  7695. #if defined(_WIN32)
  7696. if ((s = getenv("COMSPEC")) != NULL) {
  7697. addenv(env, "COMSPEC=%s", s);
  7698. }
  7699. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7700. addenv(env, "SYSTEMROOT=%s", s);
  7701. }
  7702. if ((s = getenv("SystemDrive")) != NULL) {
  7703. addenv(env, "SystemDrive=%s", s);
  7704. }
  7705. if ((s = getenv("ProgramFiles")) != NULL) {
  7706. addenv(env, "ProgramFiles=%s", s);
  7707. }
  7708. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7709. addenv(env, "ProgramFiles(x86)=%s", s);
  7710. }
  7711. #else
  7712. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7713. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7714. }
  7715. #endif /* _WIN32 */
  7716. if ((s = getenv("PERLLIB")) != NULL) {
  7717. addenv(env, "PERLLIB=%s", s);
  7718. }
  7719. if (conn->request_info.remote_user != NULL) {
  7720. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7721. addenv(env, "%s", "AUTH_TYPE=Digest");
  7722. }
  7723. /* Add all headers as HTTP_* variables */
  7724. for (i = 0; i < conn->request_info.num_headers; i++) {
  7725. (void)mg_snprintf(conn,
  7726. &truncated,
  7727. http_var_name,
  7728. sizeof(http_var_name),
  7729. "HTTP_%s",
  7730. conn->request_info.http_headers[i].name);
  7731. if (truncated) {
  7732. mg_cry(conn,
  7733. "%s: HTTP header variable too long [%s]",
  7734. __func__,
  7735. conn->request_info.http_headers[i].name);
  7736. continue;
  7737. }
  7738. /* Convert variable name into uppercase, and change - to _ */
  7739. for (p = http_var_name; *p != '\0'; p++) {
  7740. if (*p == '-') {
  7741. *p = '_';
  7742. }
  7743. *p = (char)toupper(*(unsigned char *)p);
  7744. }
  7745. addenv(env,
  7746. "%s=%s",
  7747. http_var_name,
  7748. conn->request_info.http_headers[i].value);
  7749. }
  7750. /* Add user-specified variables */
  7751. s = conn->ctx->config[CGI_ENVIRONMENT];
  7752. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7753. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7754. }
  7755. env->var[env->varused] = NULL;
  7756. env->buf[env->bufused] = '\0';
  7757. }
  7758. static void
  7759. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7760. {
  7761. char *buf;
  7762. size_t buflen;
  7763. int headers_len, data_len, i, truncated;
  7764. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7765. const char *status, *status_text, *connection_state;
  7766. char *pbuf, dir[PATH_MAX], *p;
  7767. struct mg_request_info ri;
  7768. struct cgi_environment blk;
  7769. FILE *in = NULL, *out = NULL, *err = NULL;
  7770. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7771. pid_t pid = (pid_t)-1;
  7772. if (conn == NULL) {
  7773. return;
  7774. }
  7775. buf = NULL;
  7776. buflen = 16384;
  7777. prepare_cgi_environment(conn, prog, &blk);
  7778. /* CGI must be executed in its own directory. 'dir' must point to the
  7779. * directory containing executable program, 'p' must point to the
  7780. * executable program name relative to 'dir'. */
  7781. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7782. if (truncated) {
  7783. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7784. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7785. goto done;
  7786. }
  7787. if ((p = strrchr(dir, '/')) != NULL) {
  7788. *p++ = '\0';
  7789. } else {
  7790. dir[0] = '.', dir[1] = '\0';
  7791. p = (char *)prog;
  7792. }
  7793. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7794. status = strerror(ERRNO);
  7795. mg_cry(conn,
  7796. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7797. prog,
  7798. status);
  7799. mg_send_http_error(conn,
  7800. 500,
  7801. "Error: Cannot create CGI pipe: %s",
  7802. status);
  7803. goto done;
  7804. }
  7805. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7806. if (pid == (pid_t)-1) {
  7807. status = strerror(ERRNO);
  7808. mg_cry(conn,
  7809. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7810. prog,
  7811. status);
  7812. mg_send_http_error(conn,
  7813. 500,
  7814. "Error: Cannot spawn CGI process [%s]: %s",
  7815. prog,
  7816. status);
  7817. goto done;
  7818. }
  7819. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7820. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7821. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7822. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7823. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7824. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7825. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7826. /* Parent closes only one side of the pipes.
  7827. * If we don't mark them as closed, close() attempt before
  7828. * return from this function throws an exception on Windows.
  7829. * Windows does not like when closed descriptor is closed again. */
  7830. (void)close(fdin[0]);
  7831. (void)close(fdout[1]);
  7832. (void)close(fderr[1]);
  7833. fdin[0] = fdout[1] = fderr[1] = -1;
  7834. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7835. status = strerror(ERRNO);
  7836. mg_cry(conn,
  7837. "Error: CGI program \"%s\": Can not open stdin: %s",
  7838. prog,
  7839. status);
  7840. mg_send_http_error(conn,
  7841. 500,
  7842. "Error: CGI can not open fdin\nfopen: %s",
  7843. status);
  7844. goto done;
  7845. }
  7846. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7847. status = strerror(ERRNO);
  7848. mg_cry(conn,
  7849. "Error: CGI program \"%s\": Can not open stdout: %s",
  7850. prog,
  7851. status);
  7852. mg_send_http_error(conn,
  7853. 500,
  7854. "Error: CGI can not open fdout\nfopen: %s",
  7855. status);
  7856. goto done;
  7857. }
  7858. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7859. status = strerror(ERRNO);
  7860. mg_cry(conn,
  7861. "Error: CGI program \"%s\": Can not open stderr: %s",
  7862. prog,
  7863. status);
  7864. mg_send_http_error(conn,
  7865. 500,
  7866. "Error: CGI can not open fdout\nfopen: %s",
  7867. status);
  7868. goto done;
  7869. }
  7870. setbuf(in, NULL);
  7871. setbuf(out, NULL);
  7872. setbuf(err, NULL);
  7873. fout.access.fp = out;
  7874. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7875. /* This is a POST/PUT request, or another request with body data. */
  7876. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7877. /* Error sending the body data */
  7878. mg_cry(conn,
  7879. "Error: CGI program \"%s\": Forward body data failed",
  7880. prog);
  7881. goto done;
  7882. }
  7883. }
  7884. /* Close so child gets an EOF. */
  7885. fclose(in);
  7886. in = NULL;
  7887. fdin[1] = -1;
  7888. /* Now read CGI reply into a buffer. We need to set correct
  7889. * status code, thus we need to see all HTTP headers first.
  7890. * Do not send anything back to client, until we buffer in all
  7891. * HTTP headers. */
  7892. data_len = 0;
  7893. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  7894. if (buf == NULL) {
  7895. mg_send_http_error(conn,
  7896. 500,
  7897. "Error: Not enough memory for CGI buffer (%u bytes)",
  7898. (unsigned int)buflen);
  7899. mg_cry(conn,
  7900. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7901. "bytes)",
  7902. prog,
  7903. (unsigned int)buflen);
  7904. goto done;
  7905. }
  7906. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7907. if (headers_len <= 0) {
  7908. /* Could not parse the CGI response. Check if some error message on
  7909. * stderr. */
  7910. i = pull_all(err, conn, buf, (int)buflen);
  7911. if (i > 0) {
  7912. mg_cry(conn,
  7913. "Error: CGI program \"%s\" sent error "
  7914. "message: [%.*s]",
  7915. prog,
  7916. i,
  7917. buf);
  7918. mg_send_http_error(conn,
  7919. 500,
  7920. "Error: CGI program \"%s\" sent error "
  7921. "message: [%.*s]",
  7922. prog,
  7923. i,
  7924. buf);
  7925. } else {
  7926. mg_cry(conn,
  7927. "Error: CGI program sent malformed or too big "
  7928. "(>%u bytes) HTTP headers: [%.*s]",
  7929. (unsigned)buflen,
  7930. data_len,
  7931. buf);
  7932. mg_send_http_error(conn,
  7933. 500,
  7934. "Error: CGI program sent malformed or too big "
  7935. "(>%u bytes) HTTP headers: [%.*s]",
  7936. (unsigned)buflen,
  7937. data_len,
  7938. buf);
  7939. }
  7940. goto done;
  7941. }
  7942. pbuf = buf;
  7943. buf[headers_len - 1] = '\0';
  7944. parse_http_headers(&pbuf, &ri);
  7945. /* Make up and send the status line */
  7946. status_text = "OK";
  7947. if ((status = get_header(&ri, "Status")) != NULL) {
  7948. conn->status_code = atoi(status);
  7949. status_text = status;
  7950. while (isdigit(*(const unsigned char *)status_text)
  7951. || *status_text == ' ') {
  7952. status_text++;
  7953. }
  7954. } else if (get_header(&ri, "Location") != NULL) {
  7955. conn->status_code = 302;
  7956. } else {
  7957. conn->status_code = 200;
  7958. }
  7959. connection_state = get_header(&ri, "Connection");
  7960. if (!header_has_option(connection_state, "keep-alive")) {
  7961. conn->must_close = 1;
  7962. }
  7963. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7964. /* Send headers */
  7965. for (i = 0; i < ri.num_headers; i++) {
  7966. mg_printf(conn,
  7967. "%s: %s\r\n",
  7968. ri.http_headers[i].name,
  7969. ri.http_headers[i].value);
  7970. }
  7971. mg_write(conn, "\r\n", 2);
  7972. /* Send chunk of data that may have been read after the headers */
  7973. conn->num_bytes_sent +=
  7974. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7975. /* Read the rest of CGI output and send to the client */
  7976. send_file_data(conn, &fout, 0, INT64_MAX);
  7977. done:
  7978. mg_free(blk.var);
  7979. mg_free(blk.buf);
  7980. if (pid != (pid_t)-1) {
  7981. kill(pid, SIGKILL);
  7982. #if !defined(_WIN32)
  7983. {
  7984. int st;
  7985. while (waitpid(pid, &st, 0) != -1)
  7986. ; /* clean zombies */
  7987. }
  7988. #endif
  7989. }
  7990. if (fdin[0] != -1) {
  7991. close(fdin[0]);
  7992. }
  7993. if (fdout[1] != -1) {
  7994. close(fdout[1]);
  7995. }
  7996. if (in != NULL) {
  7997. fclose(in);
  7998. } else if (fdin[1] != -1) {
  7999. close(fdin[1]);
  8000. }
  8001. if (out != NULL) {
  8002. fclose(out);
  8003. } else if (fdout[0] != -1) {
  8004. close(fdout[0]);
  8005. }
  8006. if (err != NULL) {
  8007. fclose(err);
  8008. } else if (fderr[0] != -1) {
  8009. close(fderr[0]);
  8010. }
  8011. if (buf != NULL) {
  8012. mg_free(buf);
  8013. }
  8014. }
  8015. #endif /* !NO_CGI */
  8016. #if !defined(NO_FILES)
  8017. static void
  8018. mkcol(struct mg_connection *conn, const char *path)
  8019. {
  8020. int rc, body_len;
  8021. struct de de;
  8022. char date[64];
  8023. time_t curtime = time(NULL);
  8024. if (conn == NULL) {
  8025. return;
  8026. }
  8027. /* TODO (mid): Check the mg_send_http_error situations in this function */
  8028. memset(&de.file, 0, sizeof(de.file));
  8029. if (!mg_stat(conn, path, &de.file)) {
  8030. mg_cry(conn,
  8031. "%s: mg_stat(%s) failed: %s",
  8032. __func__,
  8033. path,
  8034. strerror(ERRNO));
  8035. }
  8036. if (de.file.last_modified) {
  8037. /* TODO (mid): This check does not seem to make any sense ! */
  8038. /* TODO (mid): Add a webdav unit test first, before changing
  8039. * anything here. */
  8040. mg_send_http_error(
  8041. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8042. return;
  8043. }
  8044. body_len = conn->data_len - conn->request_len;
  8045. if (body_len > 0) {
  8046. mg_send_http_error(
  8047. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8048. return;
  8049. }
  8050. rc = mg_mkdir(conn, path, 0755);
  8051. if (rc == 0) {
  8052. conn->status_code = 201;
  8053. gmt_time_string(date, sizeof(date), &curtime);
  8054. mg_printf(conn,
  8055. "HTTP/1.1 %d Created\r\n"
  8056. "Date: %s\r\n",
  8057. conn->status_code,
  8058. date);
  8059. send_static_cache_header(conn);
  8060. send_additional_header(conn);
  8061. mg_printf(conn,
  8062. "Content-Length: 0\r\n"
  8063. "Connection: %s\r\n\r\n",
  8064. suggest_connection_header(conn));
  8065. } else if (rc == -1) {
  8066. if (errno == EEXIST) {
  8067. mg_send_http_error(
  8068. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8069. } else if (errno == EACCES) {
  8070. mg_send_http_error(
  8071. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8072. } else if (errno == ENOENT) {
  8073. mg_send_http_error(
  8074. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8075. } else {
  8076. mg_send_http_error(
  8077. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8078. }
  8079. }
  8080. }
  8081. static void
  8082. put_file(struct mg_connection *conn, const char *path)
  8083. {
  8084. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8085. const char *range;
  8086. int64_t r1, r2;
  8087. int rc;
  8088. char date[64];
  8089. time_t curtime = time(NULL);
  8090. if (conn == NULL) {
  8091. return;
  8092. }
  8093. if (mg_stat(conn, path, &file.stat)) {
  8094. /* File already exists */
  8095. conn->status_code = 200;
  8096. if (file.stat.is_directory) {
  8097. /* This is an already existing directory,
  8098. * so there is nothing to do for the server. */
  8099. rc = 0;
  8100. } else {
  8101. /* File exists and is not a directory. */
  8102. /* Can it be replaced? */
  8103. if (file.access.membuf != NULL) {
  8104. /* This is an "in-memory" file, that can not be replaced */
  8105. mg_send_http_error(
  8106. conn,
  8107. 405,
  8108. "Error: Put not possible\nReplacing %s is not supported",
  8109. path);
  8110. return;
  8111. }
  8112. /* Check if the server may write this file */
  8113. if (access(path, W_OK) == 0) {
  8114. /* Access granted */
  8115. conn->status_code = 200;
  8116. rc = 1;
  8117. } else {
  8118. mg_send_http_error(
  8119. conn,
  8120. 403,
  8121. "Error: Put not possible\nReplacing %s is not allowed",
  8122. path);
  8123. return;
  8124. }
  8125. }
  8126. } else {
  8127. /* File should be created */
  8128. conn->status_code = 201;
  8129. rc = put_dir(conn, path);
  8130. }
  8131. if (rc == 0) {
  8132. /* put_dir returns 0 if path is a directory */
  8133. gmt_time_string(date, sizeof(date), &curtime);
  8134. mg_printf(conn,
  8135. "HTTP/1.1 %d %s\r\n",
  8136. conn->status_code,
  8137. mg_get_response_code_text(NULL, conn->status_code));
  8138. send_no_cache_header(conn);
  8139. send_additional_header(conn);
  8140. mg_printf(conn,
  8141. "Date: %s\r\n"
  8142. "Content-Length: 0\r\n"
  8143. "Connection: %s\r\n\r\n",
  8144. date,
  8145. suggest_connection_header(conn));
  8146. /* Request to create a directory has been fulfilled successfully.
  8147. * No need to put a file. */
  8148. return;
  8149. }
  8150. if (rc == -1) {
  8151. /* put_dir returns -1 if the path is too long */
  8152. mg_send_http_error(conn,
  8153. 414,
  8154. "Error: Path too long\nput_dir(%s): %s",
  8155. path,
  8156. strerror(ERRNO));
  8157. return;
  8158. }
  8159. if (rc == -2) {
  8160. /* put_dir returns -2 if the directory can not be created */
  8161. mg_send_http_error(conn,
  8162. 500,
  8163. "Error: Can not create directory\nput_dir(%s): %s",
  8164. path,
  8165. strerror(ERRNO));
  8166. return;
  8167. }
  8168. /* A file should be created or overwritten. */
  8169. /* Currently CivetWeb does not nead read+write access. */
  8170. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8171. || file.access.fp == NULL) {
  8172. (void)mg_fclose(&file.access);
  8173. mg_send_http_error(conn,
  8174. 500,
  8175. "Error: Can not create file\nfopen(%s): %s",
  8176. path,
  8177. strerror(ERRNO));
  8178. return;
  8179. }
  8180. fclose_on_exec(&file.access, conn);
  8181. range = mg_get_header(conn, "Content-Range");
  8182. r1 = r2 = 0;
  8183. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  8184. conn->status_code = 206; /* Partial content */
  8185. fseeko(file.access.fp, r1, SEEK_SET);
  8186. }
  8187. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8188. /* forward_body_data failed.
  8189. * The error code has already been sent to the client,
  8190. * and conn->status_code is already set. */
  8191. (void)mg_fclose(&file.access);
  8192. return;
  8193. }
  8194. if (mg_fclose(&file.access) != 0) {
  8195. /* fclose failed. This might have different reasons, but a likely
  8196. * one is "no space on disk", http 507. */
  8197. conn->status_code = 507;
  8198. }
  8199. gmt_time_string(date, sizeof(date), &curtime);
  8200. mg_printf(conn,
  8201. "HTTP/1.1 %d %s\r\n",
  8202. conn->status_code,
  8203. mg_get_response_code_text(NULL, conn->status_code));
  8204. send_no_cache_header(conn);
  8205. send_additional_header(conn);
  8206. mg_printf(conn,
  8207. "Date: %s\r\n"
  8208. "Content-Length: 0\r\n"
  8209. "Connection: %s\r\n\r\n",
  8210. date,
  8211. suggest_connection_header(conn));
  8212. }
  8213. static void
  8214. delete_file(struct mg_connection *conn, const char *path)
  8215. {
  8216. struct de de;
  8217. memset(&de.file, 0, sizeof(de.file));
  8218. if (!mg_stat(conn, path, &de.file)) {
  8219. /* mg_stat returns 0 if the file does not exist */
  8220. mg_send_http_error(conn,
  8221. 404,
  8222. "Error: Cannot delete file\nFile %s not found",
  8223. path);
  8224. return;
  8225. }
  8226. #if 0 /* Ignore if a file in memory is inside a folder */
  8227. if (de.access.membuf != NULL) {
  8228. /* the file is cached in memory */
  8229. mg_send_http_error(
  8230. conn,
  8231. 405,
  8232. "Error: Delete not possible\nDeleting %s is not supported",
  8233. path);
  8234. return;
  8235. }
  8236. #endif
  8237. if (de.file.is_directory) {
  8238. if (remove_directory(conn, path)) {
  8239. /* Delete is successful: Return 204 without content. */
  8240. mg_send_http_error(conn, 204, "%s", "");
  8241. } else {
  8242. /* Delete is not successful: Return 500 (Server error). */
  8243. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8244. }
  8245. return;
  8246. }
  8247. /* This is an existing file (not a directory).
  8248. * Check if write permission is granted. */
  8249. if (access(path, W_OK) != 0) {
  8250. /* File is read only */
  8251. mg_send_http_error(
  8252. conn,
  8253. 403,
  8254. "Error: Delete not possible\nDeleting %s is not allowed",
  8255. path);
  8256. return;
  8257. }
  8258. /* Try to delete it. */
  8259. if (mg_remove(conn, path) == 0) {
  8260. /* Delete was successful: Return 204 without content. */
  8261. mg_send_http_error(conn, 204, "%s", "");
  8262. } else {
  8263. /* Delete not successful (file locked). */
  8264. mg_send_http_error(conn,
  8265. 423,
  8266. "Error: Cannot delete file\nremove(%s): %s",
  8267. path,
  8268. strerror(ERRNO));
  8269. }
  8270. }
  8271. #endif /* !NO_FILES */
  8272. static void
  8273. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8274. static void
  8275. do_ssi_include(struct mg_connection *conn,
  8276. const char *ssi,
  8277. char *tag,
  8278. int include_level)
  8279. {
  8280. char file_name[MG_BUF_LEN], path[512], *p;
  8281. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8282. size_t len;
  8283. int truncated = 0;
  8284. if (conn == NULL) {
  8285. return;
  8286. }
  8287. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8288. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8289. * always < MG_BUF_LEN. */
  8290. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8291. /* File name is relative to the webserver root */
  8292. file_name[511] = 0;
  8293. (void)mg_snprintf(conn,
  8294. &truncated,
  8295. path,
  8296. sizeof(path),
  8297. "%s/%s",
  8298. conn->ctx->config[DOCUMENT_ROOT],
  8299. file_name);
  8300. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8301. /* File name is relative to the webserver working directory
  8302. * or it is absolute system path */
  8303. file_name[511] = 0;
  8304. (void)
  8305. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8306. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  8307. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  8308. /* File name is relative to the currect document */
  8309. file_name[511] = 0;
  8310. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8311. if (!truncated) {
  8312. if ((p = strrchr(path, '/')) != NULL) {
  8313. p[1] = '\0';
  8314. }
  8315. len = strlen(path);
  8316. (void)mg_snprintf(conn,
  8317. &truncated,
  8318. path + len,
  8319. sizeof(path) - len,
  8320. "%s",
  8321. file_name);
  8322. }
  8323. } else {
  8324. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8325. return;
  8326. }
  8327. if (truncated) {
  8328. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8329. return;
  8330. }
  8331. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8332. mg_cry(conn,
  8333. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8334. tag,
  8335. path,
  8336. strerror(ERRNO));
  8337. } else {
  8338. fclose_on_exec(&file.access, conn);
  8339. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8340. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8341. path) > 0) {
  8342. send_ssi_file(conn, path, &file, include_level + 1);
  8343. } else {
  8344. send_file_data(conn, &file, 0, INT64_MAX);
  8345. }
  8346. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8347. }
  8348. }
  8349. #if !defined(NO_POPEN)
  8350. static void
  8351. do_ssi_exec(struct mg_connection *conn, char *tag)
  8352. {
  8353. char cmd[1024] = "";
  8354. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8355. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8356. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8357. } else {
  8358. cmd[1023] = 0;
  8359. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8360. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8361. } else {
  8362. send_file_data(conn, &file, 0, INT64_MAX);
  8363. pclose(file.access.fp);
  8364. }
  8365. }
  8366. }
  8367. #endif /* !NO_POPEN */
  8368. static int
  8369. mg_fgetc(struct mg_file *filep, int offset)
  8370. {
  8371. if (filep == NULL) {
  8372. return EOF;
  8373. }
  8374. if (filep->access.membuf != NULL && offset >= 0
  8375. && ((unsigned int)(offset)) < filep->stat.size) {
  8376. return ((const unsigned char *)filep->access.membuf)[offset];
  8377. } else if (filep->access.fp != NULL) {
  8378. return fgetc(filep->access.fp);
  8379. } else {
  8380. return EOF;
  8381. }
  8382. }
  8383. static void
  8384. send_ssi_file(struct mg_connection *conn,
  8385. const char *path,
  8386. struct mg_file *filep,
  8387. int include_level)
  8388. {
  8389. char buf[MG_BUF_LEN];
  8390. int ch, offset, len, in_ssi_tag;
  8391. if (include_level > 10) {
  8392. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8393. return;
  8394. }
  8395. in_ssi_tag = len = offset = 0;
  8396. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  8397. if (in_ssi_tag && ch == '>') {
  8398. in_ssi_tag = 0;
  8399. buf[len++] = (char)ch;
  8400. buf[len] = '\0';
  8401. /* assert(len <= (int) sizeof(buf)); */
  8402. if (len > (int)sizeof(buf)) {
  8403. break;
  8404. }
  8405. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  8406. /* Not an SSI tag, pass it */
  8407. (void)mg_write(conn, buf, (size_t)len);
  8408. } else {
  8409. if (!memcmp(buf + 5, "include", 7)) {
  8410. do_ssi_include(conn, path, buf + 12, include_level);
  8411. #if !defined(NO_POPEN)
  8412. } else if (!memcmp(buf + 5, "exec", 4)) {
  8413. do_ssi_exec(conn, buf + 9);
  8414. #endif /* !NO_POPEN */
  8415. } else {
  8416. mg_cry(conn,
  8417. "%s: unknown SSI "
  8418. "command: \"%s\"",
  8419. path,
  8420. buf);
  8421. }
  8422. }
  8423. len = 0;
  8424. } else if (in_ssi_tag) {
  8425. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8426. /* Not an SSI tag */
  8427. in_ssi_tag = 0;
  8428. } else if (len == (int)sizeof(buf) - 2) {
  8429. mg_cry(conn, "%s: SSI tag is too large", path);
  8430. len = 0;
  8431. }
  8432. buf[len++] = (char)(ch & 0xff);
  8433. } else if (ch == '<') {
  8434. in_ssi_tag = 1;
  8435. if (len > 0) {
  8436. mg_write(conn, buf, (size_t)len);
  8437. }
  8438. len = 0;
  8439. buf[len++] = (char)(ch & 0xff);
  8440. } else {
  8441. buf[len++] = (char)(ch & 0xff);
  8442. if (len == (int)sizeof(buf)) {
  8443. mg_write(conn, buf, (size_t)len);
  8444. len = 0;
  8445. }
  8446. }
  8447. }
  8448. /* Send the rest of buffered data */
  8449. if (len > 0) {
  8450. mg_write(conn, buf, (size_t)len);
  8451. }
  8452. }
  8453. static void
  8454. handle_ssi_file_request(struct mg_connection *conn,
  8455. const char *path,
  8456. struct mg_file *filep)
  8457. {
  8458. char date[64];
  8459. time_t curtime = time(NULL);
  8460. const char *cors1, *cors2, *cors3;
  8461. if (conn == NULL || path == NULL || filep == NULL) {
  8462. return;
  8463. }
  8464. if (mg_get_header(conn, "Origin")) {
  8465. /* Cross-origin resource sharing (CORS). */
  8466. cors1 = "Access-Control-Allow-Origin: ";
  8467. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8468. cors3 = "\r\n";
  8469. } else {
  8470. cors1 = cors2 = cors3 = "";
  8471. }
  8472. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8473. /* File exists (precondition for calling this function),
  8474. * but can not be opened by the server. */
  8475. mg_send_http_error(conn,
  8476. 500,
  8477. "Error: Cannot read file\nfopen(%s): %s",
  8478. path,
  8479. strerror(ERRNO));
  8480. } else {
  8481. conn->must_close = 1;
  8482. gmt_time_string(date, sizeof(date), &curtime);
  8483. fclose_on_exec(&filep->access, conn);
  8484. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8485. send_no_cache_header(conn);
  8486. send_additional_header(conn);
  8487. mg_printf(conn,
  8488. "%s%s%s"
  8489. "Date: %s\r\n"
  8490. "Content-Type: text/html\r\n"
  8491. "Connection: %s\r\n\r\n",
  8492. cors1,
  8493. cors2,
  8494. cors3,
  8495. date,
  8496. suggest_connection_header(conn));
  8497. send_ssi_file(conn, path, filep, 0);
  8498. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8499. }
  8500. }
  8501. #if !defined(NO_FILES)
  8502. static void
  8503. send_options(struct mg_connection *conn)
  8504. {
  8505. char date[64];
  8506. time_t curtime = time(NULL);
  8507. if (!conn) {
  8508. return;
  8509. }
  8510. conn->status_code = 200;
  8511. conn->must_close = 1;
  8512. gmt_time_string(date, sizeof(date), &curtime);
  8513. /* We do not set a "Cache-Control" header here, but leave the default.
  8514. * Since browsers do not send an OPTIONS request, we can not test the
  8515. * effect anyway. */
  8516. mg_printf(conn,
  8517. "HTTP/1.1 200 OK\r\n"
  8518. "Date: %s\r\n"
  8519. "Connection: %s\r\n"
  8520. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8521. "PROPFIND, MKCOL\r\n"
  8522. "DAV: 1\r\n",
  8523. date,
  8524. suggest_connection_header(conn));
  8525. send_additional_header(conn);
  8526. mg_printf(conn, "\r\n");
  8527. }
  8528. /* Writes PROPFIND properties for a collection element */
  8529. static void
  8530. print_props(struct mg_connection *conn,
  8531. const char *uri,
  8532. struct mg_file_stat *filep)
  8533. {
  8534. char mtime[64];
  8535. if (conn == NULL || uri == NULL || filep == NULL) {
  8536. return;
  8537. }
  8538. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8539. conn->num_bytes_sent +=
  8540. mg_printf(conn,
  8541. "<d:response>"
  8542. "<d:href>%s</d:href>"
  8543. "<d:propstat>"
  8544. "<d:prop>"
  8545. "<d:resourcetype>%s</d:resourcetype>"
  8546. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8547. "<d:getlastmodified>%s</d:getlastmodified>"
  8548. "</d:prop>"
  8549. "<d:status>HTTP/1.1 200 OK</d:status>"
  8550. "</d:propstat>"
  8551. "</d:response>\n",
  8552. uri,
  8553. filep->is_directory ? "<d:collection/>" : "",
  8554. filep->size,
  8555. mtime);
  8556. }
  8557. static void
  8558. print_dav_dir_entry(struct de *de, void *data)
  8559. {
  8560. char href[PATH_MAX];
  8561. char href_encoded[PATH_MAX * 3 /* worst case */];
  8562. int truncated;
  8563. struct mg_connection *conn = (struct mg_connection *)data;
  8564. if (!de || !conn) {
  8565. return;
  8566. }
  8567. mg_snprintf(conn,
  8568. &truncated,
  8569. href,
  8570. sizeof(href),
  8571. "%s%s",
  8572. conn->request_info.local_uri,
  8573. de->file_name);
  8574. if (!truncated) {
  8575. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8576. print_props(conn, href_encoded, &de->file);
  8577. }
  8578. }
  8579. static void
  8580. handle_propfind(struct mg_connection *conn,
  8581. const char *path,
  8582. struct mg_file_stat *filep)
  8583. {
  8584. const char *depth = mg_get_header(conn, "Depth");
  8585. char date[64];
  8586. time_t curtime = time(NULL);
  8587. gmt_time_string(date, sizeof(date), &curtime);
  8588. if (!conn || !path || !filep || !conn->ctx) {
  8589. return;
  8590. }
  8591. conn->must_close = 1;
  8592. conn->status_code = 207;
  8593. mg_printf(conn,
  8594. "HTTP/1.1 207 Multi-Status\r\n"
  8595. "Date: %s\r\n",
  8596. date);
  8597. send_static_cache_header(conn);
  8598. send_additional_header(conn);
  8599. mg_printf(conn,
  8600. "Connection: %s\r\n"
  8601. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8602. suggest_connection_header(conn));
  8603. conn->num_bytes_sent +=
  8604. mg_printf(conn,
  8605. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8606. "<d:multistatus xmlns:d='DAV:'>\n");
  8607. /* Print properties for the requested resource itself */
  8608. print_props(conn, conn->request_info.local_uri, filep);
  8609. /* If it is a directory, print directory entries too if Depth is not 0 */
  8610. if (filep && filep->is_directory
  8611. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8612. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8613. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8614. }
  8615. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8616. }
  8617. #endif
  8618. void
  8619. mg_lock_connection(struct mg_connection *conn)
  8620. {
  8621. if (conn) {
  8622. (void)pthread_mutex_lock(&conn->mutex);
  8623. }
  8624. }
  8625. void
  8626. mg_unlock_connection(struct mg_connection *conn)
  8627. {
  8628. if (conn) {
  8629. (void)pthread_mutex_unlock(&conn->mutex);
  8630. }
  8631. }
  8632. void
  8633. mg_lock_context(struct mg_context *ctx)
  8634. {
  8635. if (ctx) {
  8636. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8637. }
  8638. }
  8639. void
  8640. mg_unlock_context(struct mg_context *ctx)
  8641. {
  8642. if (ctx) {
  8643. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8644. }
  8645. }
  8646. #if defined(USE_TIMERS)
  8647. #define TIMER_API static
  8648. #include "timer.inl"
  8649. #endif /* USE_TIMERS */
  8650. #ifdef USE_LUA
  8651. #include "mod_lua.inl"
  8652. #endif /* USE_LUA */
  8653. #ifdef USE_DUKTAPE
  8654. #include "mod_duktape.inl"
  8655. #endif /* USE_DUKTAPE */
  8656. #if defined(USE_WEBSOCKET)
  8657. #if !defined(NO_SSL_DL)
  8658. #define SHA_API static
  8659. #include "sha1.inl"
  8660. #endif
  8661. static int
  8662. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8663. {
  8664. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8665. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8666. SHA_CTX sha_ctx;
  8667. int truncated;
  8668. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8669. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8670. if (truncated) {
  8671. conn->must_close = 1;
  8672. return 0;
  8673. }
  8674. SHA1_Init(&sha_ctx);
  8675. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8676. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8677. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8678. mg_printf(conn,
  8679. "HTTP/1.1 101 Switching Protocols\r\n"
  8680. "Upgrade: websocket\r\n"
  8681. "Connection: Upgrade\r\n"
  8682. "Sec-WebSocket-Accept: %s\r\n",
  8683. b64_sha);
  8684. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8685. mg_printf(conn,
  8686. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8687. conn->request_info.acceptedWebSocketSubprotocol);
  8688. } else {
  8689. mg_printf(conn, "%s", "\r\n");
  8690. }
  8691. return 1;
  8692. }
  8693. static void
  8694. read_websocket(struct mg_connection *conn,
  8695. mg_websocket_data_handler ws_data_handler,
  8696. void *callback_data)
  8697. {
  8698. /* Pointer to the beginning of the portion of the incoming websocket
  8699. * message queue.
  8700. * The original websocket upgrade request is never removed, so the queue
  8701. * begins after it. */
  8702. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8703. int n, error, exit_by_callback;
  8704. /* body_len is the length of the entire queue in bytes
  8705. * len is the length of the current message
  8706. * data_len is the length of the current message's data payload
  8707. * header_len is the length of the current message's header */
  8708. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8709. /* "The masking key is a 32-bit value chosen at random by the client."
  8710. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8711. */
  8712. unsigned char mask[4];
  8713. /* data points to the place where the message is stored when passed to
  8714. * the
  8715. * websocket_data callback. This is either mem on the stack, or a
  8716. * dynamically allocated buffer if it is too large. */
  8717. unsigned char mem[4096];
  8718. unsigned char *data = mem;
  8719. unsigned char mop; /* mask flag and opcode */
  8720. double timeout = -1.0;
  8721. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8722. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8723. }
  8724. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8725. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8726. }
  8727. mg_set_thread_name("wsock");
  8728. /* Loop continuously, reading messages from the socket, invoking the
  8729. * callback, and waiting repeatedly until an error occurs. */
  8730. while (!conn->ctx->stop_flag) {
  8731. header_len = 0;
  8732. assert(conn->data_len >= conn->request_len);
  8733. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8734. len = buf[1] & 127;
  8735. mask_len = (buf[1] & 128) ? 4 : 0;
  8736. if ((len < 126) && (body_len >= mask_len)) {
  8737. /* inline 7-bit length field */
  8738. data_len = len;
  8739. header_len = 2 + mask_len;
  8740. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8741. /* 16-bit length field */
  8742. header_len = 4 + mask_len;
  8743. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8744. } else if (body_len >= (10 + mask_len)) {
  8745. /* 64-bit length field */
  8746. uint32_t l1, l2;
  8747. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  8748. memcpy(&l2, &buf[6], 4);
  8749. header_len = 10 + mask_len;
  8750. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  8751. }
  8752. }
  8753. if (header_len > 0 && body_len >= header_len) {
  8754. /* Allocate space to hold websocket payload */
  8755. data = mem;
  8756. if (data_len > sizeof(mem)) {
  8757. data = (unsigned char *)mg_malloc_ctx(data_len, conn->ctx);
  8758. if (data == NULL) {
  8759. /* Allocation failed, exit the loop and then close the
  8760. * connection */
  8761. mg_cry(conn, "websocket out of memory; closing connection");
  8762. break;
  8763. }
  8764. }
  8765. /* Copy the mask before we shift the queue and destroy it */
  8766. if (mask_len > 0) {
  8767. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8768. } else {
  8769. memset(mask, 0, sizeof(mask));
  8770. }
  8771. /* Read frame payload from the first message in the queue into
  8772. * data and advance the queue by moving the memory in place. */
  8773. assert(body_len >= header_len);
  8774. if (data_len + header_len > body_len) {
  8775. mop = buf[0]; /* current mask and opcode */
  8776. /* Overflow case */
  8777. len = body_len - header_len;
  8778. memcpy(data, buf + header_len, len);
  8779. error = 0;
  8780. while (len < data_len) {
  8781. n = pull_inner(NULL,
  8782. conn,
  8783. (char *)(data + len),
  8784. (int)(data_len - len),
  8785. timeout);
  8786. if (n <= -2) {
  8787. error = 1;
  8788. break;
  8789. } else if (n > 0) {
  8790. len += (size_t)n;
  8791. } else {
  8792. /* Timeout: should retry */
  8793. /* TODO: retry condition */
  8794. }
  8795. }
  8796. if (error) {
  8797. mg_cry(conn, "Websocket pull failed; closing connection");
  8798. break;
  8799. }
  8800. conn->data_len = conn->request_len;
  8801. } else {
  8802. mop = buf[0]; /* current mask and opcode, overwritten by
  8803. * memmove() */
  8804. /* Length of the message being read at the front of the
  8805. * queue */
  8806. len = data_len + header_len;
  8807. /* Copy the data payload into the data pointer for the
  8808. * callback */
  8809. memcpy(data, buf + header_len, data_len);
  8810. /* Move the queue forward len bytes */
  8811. memmove(buf, buf + len, body_len - len);
  8812. /* Mark the queue as advanced */
  8813. conn->data_len -= (int)len;
  8814. }
  8815. /* Apply mask if necessary */
  8816. if (mask_len > 0) {
  8817. for (i = 0; i < data_len; ++i) {
  8818. data[i] ^= mask[i & 3];
  8819. }
  8820. }
  8821. /* Exit the loop if callback signals to exit (server side),
  8822. * or "connection close" opcode received (client side). */
  8823. exit_by_callback = 0;
  8824. if ((ws_data_handler != NULL)
  8825. && !ws_data_handler(
  8826. conn, mop, (char *)data, data_len, callback_data)) {
  8827. exit_by_callback = 1;
  8828. }
  8829. if (data != mem) {
  8830. mg_free(data);
  8831. }
  8832. if (exit_by_callback
  8833. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8834. /* Opcode == 8, connection close */
  8835. break;
  8836. }
  8837. /* Not breaking the loop, process next websocket frame. */
  8838. } else {
  8839. /* Read from the socket into the next available location in the
  8840. * message queue. */
  8841. n = pull_inner(NULL,
  8842. conn,
  8843. conn->buf + conn->data_len,
  8844. conn->buf_size - conn->data_len,
  8845. timeout);
  8846. if (n <= -2) {
  8847. /* Error, no bytes read */
  8848. break;
  8849. }
  8850. if (n > 0) {
  8851. conn->data_len += n;
  8852. } else {
  8853. /* Timeout: should retry */
  8854. /* TODO: get timeout def */
  8855. }
  8856. }
  8857. }
  8858. mg_set_thread_name("worker");
  8859. }
  8860. static int
  8861. mg_websocket_write_exec(struct mg_connection *conn,
  8862. int opcode,
  8863. const char *data,
  8864. size_t dataLen,
  8865. uint32_t masking_key)
  8866. {
  8867. unsigned char header[14];
  8868. size_t headerLen = 1;
  8869. int retval = -1;
  8870. #if defined(__GNUC__) || defined(__MINGW32__)
  8871. /* Disable spurious conversion warning for GCC */
  8872. #pragma GCC diagnostic push
  8873. #pragma GCC diagnostic ignored "-Wconversion"
  8874. #endif
  8875. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8876. #if defined(__GNUC__) || defined(__MINGW32__)
  8877. #pragma GCC diagnostic pop
  8878. #endif
  8879. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8880. if (dataLen < 126) {
  8881. /* inline 7-bit length field */
  8882. header[1] = (unsigned char)dataLen;
  8883. headerLen = 2;
  8884. } else if (dataLen <= 0xFFFF) {
  8885. /* 16-bit length field */
  8886. uint16_t len = htons((uint16_t)dataLen);
  8887. header[1] = 126;
  8888. memcpy(header + 2, &len, 2);
  8889. headerLen = 4;
  8890. } else {
  8891. /* 64-bit length field */
  8892. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8893. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8894. header[1] = 127;
  8895. memcpy(header + 2, &len1, 4);
  8896. memcpy(header + 6, &len2, 4);
  8897. headerLen = 10;
  8898. }
  8899. if (masking_key) {
  8900. /* add mask */
  8901. header[1] |= 0x80;
  8902. memcpy(header + headerLen, &masking_key, 4);
  8903. headerLen += 4;
  8904. }
  8905. /* Note that POSIX/Winsock's send() is threadsafe
  8906. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8907. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8908. * push(), although that is only a problem if the packet is large or
  8909. * outgoing buffer is full). */
  8910. /* TODO: Check if this lock should be moved to user land.
  8911. * Currently the server sets this lock for websockets, but
  8912. * not for any other connection. It must be set for every
  8913. * conn read/written by more than one thread, no matter if
  8914. * it is a websocket or regular connection. */
  8915. (void)mg_lock_connection(conn);
  8916. retval = mg_write(conn, header, headerLen);
  8917. if (dataLen > 0) {
  8918. retval = mg_write(conn, data, dataLen);
  8919. }
  8920. /* TODO: Remove this unlock as well, when lock is moved. */
  8921. mg_unlock_connection(conn);
  8922. return retval;
  8923. }
  8924. int
  8925. mg_websocket_write(struct mg_connection *conn,
  8926. int opcode,
  8927. const char *data,
  8928. size_t dataLen)
  8929. {
  8930. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8931. }
  8932. static void
  8933. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8934. {
  8935. size_t i = 0;
  8936. i = 0;
  8937. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8938. /* Convert in 32 bit words, if data is 4 byte aligned */
  8939. while (i < (in_len - 3)) {
  8940. *(uint32_t *)(void *)(out + i) =
  8941. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8942. i += 4;
  8943. }
  8944. }
  8945. if (i != in_len) {
  8946. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8947. while (i < in_len) {
  8948. *(uint8_t *)(void *)(out + i) =
  8949. *(uint8_t *)(void *)(in + i)
  8950. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8951. i++;
  8952. }
  8953. }
  8954. }
  8955. int
  8956. mg_websocket_client_write(struct mg_connection *conn,
  8957. int opcode,
  8958. const char *data,
  8959. size_t dataLen)
  8960. {
  8961. int retval = -1;
  8962. char *masked_data =
  8963. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  8964. uint32_t masking_key = (uint32_t)get_random();
  8965. if (masked_data == NULL) {
  8966. /* Return -1 in an error case */
  8967. mg_cry(conn,
  8968. "Cannot allocate buffer for masked websocket response: "
  8969. "Out of memory");
  8970. return -1;
  8971. }
  8972. mask_data(data, dataLen, masking_key, masked_data);
  8973. retval = mg_websocket_write_exec(
  8974. conn, opcode, masked_data, dataLen, masking_key);
  8975. mg_free(masked_data);
  8976. return retval;
  8977. }
  8978. static void
  8979. handle_websocket_request(struct mg_connection *conn,
  8980. const char *path,
  8981. int is_callback_resource,
  8982. struct mg_websocket_subprotocols *subprotocols,
  8983. mg_websocket_connect_handler ws_connect_handler,
  8984. mg_websocket_ready_handler ws_ready_handler,
  8985. mg_websocket_data_handler ws_data_handler,
  8986. mg_websocket_close_handler ws_close_handler,
  8987. void *cbData)
  8988. {
  8989. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8990. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8991. int lua_websock = 0;
  8992. #if !defined(USE_LUA)
  8993. (void)path;
  8994. #endif
  8995. /* Step 1: Check websocket protocol version. */
  8996. /* Step 1.1: Check Sec-WebSocket-Key. */
  8997. if (!websock_key) {
  8998. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8999. * requires a Sec-WebSocket-Key header.
  9000. */
  9001. /* It could be the hixie draft version
  9002. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  9003. */
  9004. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  9005. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  9006. char key3[8];
  9007. if ((key1 != NULL) && (key2 != NULL)) {
  9008. /* This version uses 8 byte body data in a GET request */
  9009. conn->content_len = 8;
  9010. if (8 == mg_read(conn, key3, 8)) {
  9011. /* This is the hixie version */
  9012. mg_send_http_error(conn,
  9013. 426,
  9014. "%s",
  9015. "Protocol upgrade to RFC 6455 required");
  9016. return;
  9017. }
  9018. }
  9019. /* This is an unknown version */
  9020. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  9021. return;
  9022. }
  9023. /* Step 1.2: Check websocket protocol version. */
  9024. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  9025. if (version == NULL || strcmp(version, "13") != 0) {
  9026. /* Reject wrong versions */
  9027. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  9028. return;
  9029. }
  9030. /* Step 1.3: Could check for "Host", but we do not really nead this
  9031. * value for anything, so just ignore it. */
  9032. /* Step 2: If a callback is responsible, call it. */
  9033. if (is_callback_resource) {
  9034. /* Step 2.1 check and select subprotocol */
  9035. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  9036. if (protocol && subprotocols) {
  9037. int idx;
  9038. unsigned long len;
  9039. const char *sep, *curSubProtocol,
  9040. *acceptedWebSocketSubprotocol = NULL;
  9041. /* look for matching subprotocol */
  9042. do {
  9043. sep = strchr(protocol, ',');
  9044. curSubProtocol = protocol;
  9045. len = sep ? (unsigned long)(sep - protocol)
  9046. : (unsigned long)strlen(protocol);
  9047. while (sep && isspace(*++sep)) {
  9048. ; /* ignore leading whitespaces */
  9049. }
  9050. protocol = sep;
  9051. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  9052. if ((strlen(subprotocols->subprotocols[idx]) == len)
  9053. && (strncmp(curSubProtocol,
  9054. subprotocols->subprotocols[idx],
  9055. len) == 0)) {
  9056. acceptedWebSocketSubprotocol =
  9057. subprotocols->subprotocols[idx];
  9058. break;
  9059. }
  9060. }
  9061. } while (sep && !acceptedWebSocketSubprotocol);
  9062. conn->request_info.acceptedWebSocketSubprotocol =
  9063. acceptedWebSocketSubprotocol;
  9064. } else if (protocol) {
  9065. /* keep legacy behavior */
  9066. /* The protocol is a comma seperated list of names. */
  9067. /* The server must only return one value from this list. */
  9068. /* First check if it is a list or just a single value. */
  9069. const char *sep = strrchr(protocol, ',');
  9070. if (sep == NULL) {
  9071. /* Just a single protocol -> accept it. */
  9072. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  9073. } else {
  9074. /* Multiple protocols -> accept the last one. */
  9075. /* This is just a quick fix if the client offers multiple
  9076. * protocols. The handler should have a list of accepted
  9077. * protocols on his own
  9078. * and use it to select one protocol among those the client has
  9079. * offered.
  9080. */
  9081. while (isspace(*++sep)) {
  9082. ; /* ignore leading whitespaces */
  9083. }
  9084. conn->request_info.acceptedWebSocketSubprotocol = sep;
  9085. }
  9086. }
  9087. if (ws_connect_handler != NULL
  9088. && ws_connect_handler(conn, cbData) != 0) {
  9089. /* C callback has returned non-zero, do not proceed with
  9090. * handshake.
  9091. */
  9092. /* Note that C callbacks are no longer called when Lua is
  9093. * responsible, so C can no longer filter callbacks for Lua. */
  9094. return;
  9095. }
  9096. }
  9097. #if defined(USE_LUA)
  9098. /* Step 3: No callback. Check if Lua is responsible. */
  9099. else {
  9100. /* Step 3.1: Check if Lua is responsible. */
  9101. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  9102. lua_websock =
  9103. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  9104. strlen(
  9105. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  9106. path);
  9107. }
  9108. if (lua_websock) {
  9109. /* Step 3.2: Lua is responsible: call it. */
  9110. conn->lua_websocket_state = lua_websocket_new(path, conn);
  9111. if (!conn->lua_websocket_state) {
  9112. /* Lua rejected the new client */
  9113. return;
  9114. }
  9115. }
  9116. }
  9117. #endif
  9118. /* Step 4: Check if there is a responsible websocket handler. */
  9119. if (!is_callback_resource && !lua_websock) {
  9120. /* There is no callback, and Lua is not responsible either. */
  9121. /* Reply with a 404 Not Found. We are still at a standard
  9122. * HTTP request here, before the websocket handshake, so
  9123. * we can still send standard HTTP error replies. */
  9124. mg_send_http_error(conn, 404, "%s", "Not found");
  9125. return;
  9126. }
  9127. /* Step 5: The websocket connection has been accepted */
  9128. if (!send_websocket_handshake(conn, websock_key)) {
  9129. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  9130. return;
  9131. }
  9132. /* Step 6: Call the ready handler */
  9133. if (is_callback_resource) {
  9134. if (ws_ready_handler != NULL) {
  9135. ws_ready_handler(conn, cbData);
  9136. }
  9137. #if defined(USE_LUA)
  9138. } else if (lua_websock) {
  9139. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9140. /* the ready handler returned false */
  9141. return;
  9142. }
  9143. #endif
  9144. }
  9145. /* Step 7: Enter the read loop */
  9146. if (is_callback_resource) {
  9147. read_websocket(conn, ws_data_handler, cbData);
  9148. #if defined(USE_LUA)
  9149. } else if (lua_websock) {
  9150. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9151. #endif
  9152. }
  9153. /* Step 8: Call the close handler */
  9154. if (ws_close_handler) {
  9155. ws_close_handler(conn, cbData);
  9156. }
  9157. }
  9158. static int
  9159. is_websocket_protocol(const struct mg_connection *conn)
  9160. {
  9161. const char *upgrade, *connection;
  9162. /* A websocket protocoll has the following HTTP headers:
  9163. *
  9164. * Connection: Upgrade
  9165. * Upgrade: Websocket
  9166. */
  9167. upgrade = mg_get_header(conn, "Upgrade");
  9168. if (upgrade == NULL) {
  9169. return 0; /* fail early, don't waste time checking other header
  9170. * fields
  9171. */
  9172. }
  9173. if (!mg_strcasestr(upgrade, "websocket")) {
  9174. return 0;
  9175. }
  9176. connection = mg_get_header(conn, "Connection");
  9177. if (connection == NULL) {
  9178. return 0;
  9179. }
  9180. if (!mg_strcasestr(connection, "upgrade")) {
  9181. return 0;
  9182. }
  9183. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9184. * "Sec-WebSocket-Version" are also required.
  9185. * Don't check them here, since even an unsupported websocket protocol
  9186. * request still IS a websocket request (in contrast to a standard HTTP
  9187. * request). It will fail later in handle_websocket_request.
  9188. */
  9189. return 1;
  9190. }
  9191. #endif /* !USE_WEBSOCKET */
  9192. static int
  9193. isbyte(int n)
  9194. {
  9195. return n >= 0 && n <= 255;
  9196. }
  9197. static int
  9198. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9199. {
  9200. int n, a, b, c, d, slash = 32, len = 0;
  9201. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  9202. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  9203. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  9204. && slash < 33) {
  9205. len = n;
  9206. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9207. | (uint32_t)d;
  9208. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9209. }
  9210. return len;
  9211. }
  9212. static int
  9213. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9214. {
  9215. int throttle = 0;
  9216. struct vec vec, val;
  9217. uint32_t net, mask;
  9218. char mult;
  9219. double v;
  9220. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9221. mult = ',';
  9222. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9223. || (v < 0) || ((lowercase(&mult) != 'k')
  9224. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9225. continue;
  9226. }
  9227. v *= (lowercase(&mult) == 'k')
  9228. ? 1024
  9229. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9230. if (vec.len == 1 && vec.ptr[0] == '*') {
  9231. throttle = (int)v;
  9232. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9233. if ((remote_ip & mask) == net) {
  9234. throttle = (int)v;
  9235. }
  9236. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9237. throttle = (int)v;
  9238. }
  9239. }
  9240. return throttle;
  9241. }
  9242. static uint32_t
  9243. get_remote_ip(const struct mg_connection *conn)
  9244. {
  9245. if (!conn) {
  9246. return 0;
  9247. }
  9248. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9249. }
  9250. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9251. #include "handle_form.inl"
  9252. #if defined(MG_LEGACY_INTERFACE)
  9253. /* Implement the deprecated mg_upload function by calling the new
  9254. * mg_handle_form_request function. While mg_upload could only handle
  9255. * HTML forms sent as POST request in multipart/form-data format
  9256. * containing only file input elements, mg_handle_form_request can
  9257. * handle all form input elements and all standard request methods. */
  9258. struct mg_upload_user_data {
  9259. struct mg_connection *conn;
  9260. const char *destination_dir;
  9261. int num_uploaded_files;
  9262. };
  9263. /* Helper function for deprecated mg_upload. */
  9264. static int
  9265. mg_upload_field_found(const char *key,
  9266. const char *filename,
  9267. char *path,
  9268. size_t pathlen,
  9269. void *user_data)
  9270. {
  9271. int truncated = 0;
  9272. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9273. (void)key;
  9274. if (!filename) {
  9275. mg_cry(fud->conn, "%s: No filename set", __func__);
  9276. return FORM_FIELD_STORAGE_ABORT;
  9277. }
  9278. mg_snprintf(fud->conn,
  9279. &truncated,
  9280. path,
  9281. pathlen - 1,
  9282. "%s/%s",
  9283. fud->destination_dir,
  9284. filename);
  9285. if (!truncated) {
  9286. mg_cry(fud->conn, "%s: File path too long", __func__);
  9287. return FORM_FIELD_STORAGE_ABORT;
  9288. }
  9289. return FORM_FIELD_STORAGE_STORE;
  9290. }
  9291. /* Helper function for deprecated mg_upload. */
  9292. static int
  9293. mg_upload_field_get(const char *key,
  9294. const char *value,
  9295. size_t value_size,
  9296. void *user_data)
  9297. {
  9298. /* Function should never be called */
  9299. (void)key;
  9300. (void)value;
  9301. (void)value_size;
  9302. (void)user_data;
  9303. return 0;
  9304. }
  9305. /* Helper function for deprecated mg_upload. */
  9306. static int
  9307. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9308. {
  9309. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9310. (void)file_size;
  9311. fud->num_uploaded_files++;
  9312. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9313. return 0;
  9314. }
  9315. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9316. int
  9317. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9318. {
  9319. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9320. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9321. mg_upload_field_get,
  9322. mg_upload_field_stored,
  9323. 0};
  9324. int ret;
  9325. fdh.user_data = (void *)&fud;
  9326. ret = mg_handle_form_request(conn, &fdh);
  9327. if (ret < 0) {
  9328. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9329. }
  9330. return fud.num_uploaded_files;
  9331. }
  9332. #endif
  9333. static int
  9334. get_first_ssl_listener_index(const struct mg_context *ctx)
  9335. {
  9336. unsigned int i;
  9337. int idx = -1;
  9338. if (ctx) {
  9339. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  9340. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9341. }
  9342. }
  9343. return idx;
  9344. }
  9345. static void
  9346. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9347. {
  9348. char host[1025];
  9349. const char *host_header;
  9350. size_t hostlen;
  9351. host_header = mg_get_header(conn, "Host");
  9352. hostlen = sizeof(host);
  9353. if (host_header != NULL) {
  9354. char *pos;
  9355. mg_strlcpy(host, host_header, hostlen);
  9356. host[hostlen - 1] = '\0';
  9357. pos = strchr(host, ':');
  9358. if (pos != NULL) {
  9359. *pos = '\0';
  9360. }
  9361. } else {
  9362. /* Cannot get host from the Host: header.
  9363. * Fallback to our IP address. */
  9364. if (conn) {
  9365. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9366. }
  9367. }
  9368. /* Send host, port, uri and (if it exists) ?query_string */
  9369. if (conn) {
  9370. mg_printf(conn,
  9371. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9372. host,
  9373. #if defined(USE_IPV6)
  9374. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9375. == AF_INET6)
  9376. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9377. .lsa.sin6.sin6_port)
  9378. :
  9379. #endif
  9380. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9381. .lsa.sin.sin_port),
  9382. conn->request_info.local_uri,
  9383. (conn->request_info.query_string == NULL) ? "" : "?",
  9384. (conn->request_info.query_string == NULL)
  9385. ? ""
  9386. : conn->request_info.query_string);
  9387. }
  9388. }
  9389. static void
  9390. mg_set_handler_type(struct mg_context *ctx,
  9391. const char *uri,
  9392. int handler_type,
  9393. int is_delete_request,
  9394. mg_request_handler handler,
  9395. struct mg_websocket_subprotocols *subprotocols,
  9396. mg_websocket_connect_handler connect_handler,
  9397. mg_websocket_ready_handler ready_handler,
  9398. mg_websocket_data_handler data_handler,
  9399. mg_websocket_close_handler close_handler,
  9400. mg_authorization_handler auth_handler,
  9401. void *cbdata)
  9402. {
  9403. struct mg_handler_info *tmp_rh, **lastref;
  9404. size_t urilen = strlen(uri);
  9405. if (handler_type == WEBSOCKET_HANDLER) {
  9406. /* assert(handler == NULL); */
  9407. /* assert(is_delete_request || connect_handler!=NULL ||
  9408. * ready_handler!=NULL || data_handler!=NULL ||
  9409. * close_handler!=NULL);
  9410. */
  9411. /* assert(auth_handler == NULL); */
  9412. if (handler != NULL) {
  9413. return;
  9414. }
  9415. if (!is_delete_request && connect_handler == NULL
  9416. && ready_handler == NULL
  9417. && data_handler == NULL
  9418. && close_handler == NULL) {
  9419. return;
  9420. }
  9421. if (auth_handler != NULL) {
  9422. return;
  9423. }
  9424. } else if (handler_type == REQUEST_HANDLER) {
  9425. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9426. * data_handler==NULL && close_handler==NULL); */
  9427. /* assert(is_delete_request || (handler!=NULL));
  9428. */
  9429. /* assert(auth_handler == NULL); */
  9430. if (connect_handler != NULL || ready_handler != NULL
  9431. || data_handler != NULL
  9432. || close_handler != NULL) {
  9433. return;
  9434. }
  9435. if (!is_delete_request && (handler == NULL)) {
  9436. return;
  9437. }
  9438. if (auth_handler != NULL) {
  9439. return;
  9440. }
  9441. } else { /* AUTH_HANDLER */
  9442. /* assert(handler == NULL); */
  9443. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9444. * data_handler==NULL && close_handler==NULL); */
  9445. /* assert(auth_handler != NULL); */
  9446. if (handler != NULL) {
  9447. return;
  9448. }
  9449. if (connect_handler != NULL || ready_handler != NULL
  9450. || data_handler != NULL
  9451. || close_handler != NULL) {
  9452. return;
  9453. }
  9454. if (!is_delete_request && (auth_handler == NULL)) {
  9455. return;
  9456. }
  9457. }
  9458. if (!ctx) {
  9459. return;
  9460. }
  9461. mg_lock_context(ctx);
  9462. /* first try to find an existing handler */
  9463. lastref = &(ctx->handlers);
  9464. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9465. if (tmp_rh->handler_type == handler_type) {
  9466. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9467. if (!is_delete_request) {
  9468. /* update existing handler */
  9469. if (handler_type == REQUEST_HANDLER) {
  9470. tmp_rh->handler = handler;
  9471. } else if (handler_type == WEBSOCKET_HANDLER) {
  9472. tmp_rh->subprotocols = subprotocols;
  9473. tmp_rh->connect_handler = connect_handler;
  9474. tmp_rh->ready_handler = ready_handler;
  9475. tmp_rh->data_handler = data_handler;
  9476. tmp_rh->close_handler = close_handler;
  9477. } else { /* AUTH_HANDLER */
  9478. tmp_rh->auth_handler = auth_handler;
  9479. }
  9480. tmp_rh->cbdata = cbdata;
  9481. } else {
  9482. /* remove existing handler */
  9483. *lastref = tmp_rh->next;
  9484. mg_free(tmp_rh->uri);
  9485. mg_free(tmp_rh);
  9486. }
  9487. mg_unlock_context(ctx);
  9488. return;
  9489. }
  9490. }
  9491. lastref = &(tmp_rh->next);
  9492. }
  9493. if (is_delete_request) {
  9494. /* no handler to set, this was a remove request to a non-existing
  9495. * handler */
  9496. mg_unlock_context(ctx);
  9497. return;
  9498. }
  9499. tmp_rh =
  9500. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  9501. 1,
  9502. ctx);
  9503. if (tmp_rh == NULL) {
  9504. mg_unlock_context(ctx);
  9505. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9506. return;
  9507. }
  9508. tmp_rh->uri = mg_strdup(uri);
  9509. if (!tmp_rh->uri) {
  9510. mg_unlock_context(ctx);
  9511. mg_free(tmp_rh);
  9512. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9513. return;
  9514. }
  9515. tmp_rh->uri_len = urilen;
  9516. if (handler_type == REQUEST_HANDLER) {
  9517. tmp_rh->handler = handler;
  9518. } else if (handler_type == WEBSOCKET_HANDLER) {
  9519. tmp_rh->subprotocols = subprotocols;
  9520. tmp_rh->connect_handler = connect_handler;
  9521. tmp_rh->ready_handler = ready_handler;
  9522. tmp_rh->data_handler = data_handler;
  9523. tmp_rh->close_handler = close_handler;
  9524. } else { /* AUTH_HANDLER */
  9525. tmp_rh->auth_handler = auth_handler;
  9526. }
  9527. tmp_rh->cbdata = cbdata;
  9528. tmp_rh->handler_type = handler_type;
  9529. tmp_rh->next = NULL;
  9530. *lastref = tmp_rh;
  9531. mg_unlock_context(ctx);
  9532. }
  9533. void
  9534. mg_set_request_handler(struct mg_context *ctx,
  9535. const char *uri,
  9536. mg_request_handler handler,
  9537. void *cbdata)
  9538. {
  9539. mg_set_handler_type(ctx,
  9540. uri,
  9541. REQUEST_HANDLER,
  9542. handler == NULL,
  9543. handler,
  9544. NULL,
  9545. NULL,
  9546. NULL,
  9547. NULL,
  9548. NULL,
  9549. NULL,
  9550. cbdata);
  9551. }
  9552. void
  9553. mg_set_websocket_handler(struct mg_context *ctx,
  9554. const char *uri,
  9555. mg_websocket_connect_handler connect_handler,
  9556. mg_websocket_ready_handler ready_handler,
  9557. mg_websocket_data_handler data_handler,
  9558. mg_websocket_close_handler close_handler,
  9559. void *cbdata)
  9560. {
  9561. mg_set_websocket_handler_with_subprotocols(ctx,
  9562. uri,
  9563. NULL,
  9564. connect_handler,
  9565. ready_handler,
  9566. data_handler,
  9567. close_handler,
  9568. cbdata);
  9569. }
  9570. void
  9571. mg_set_websocket_handler_with_subprotocols(
  9572. struct mg_context *ctx,
  9573. const char *uri,
  9574. struct mg_websocket_subprotocols *subprotocols,
  9575. mg_websocket_connect_handler connect_handler,
  9576. mg_websocket_ready_handler ready_handler,
  9577. mg_websocket_data_handler data_handler,
  9578. mg_websocket_close_handler close_handler,
  9579. void *cbdata)
  9580. {
  9581. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9582. && (data_handler == NULL)
  9583. && (close_handler == NULL);
  9584. mg_set_handler_type(ctx,
  9585. uri,
  9586. WEBSOCKET_HANDLER,
  9587. is_delete_request,
  9588. NULL,
  9589. subprotocols,
  9590. connect_handler,
  9591. ready_handler,
  9592. data_handler,
  9593. close_handler,
  9594. NULL,
  9595. cbdata);
  9596. }
  9597. void
  9598. mg_set_auth_handler(struct mg_context *ctx,
  9599. const char *uri,
  9600. mg_request_handler handler,
  9601. void *cbdata)
  9602. {
  9603. mg_set_handler_type(ctx,
  9604. uri,
  9605. AUTH_HANDLER,
  9606. handler == NULL,
  9607. NULL,
  9608. NULL,
  9609. NULL,
  9610. NULL,
  9611. NULL,
  9612. NULL,
  9613. handler,
  9614. cbdata);
  9615. }
  9616. static int
  9617. get_request_handler(struct mg_connection *conn,
  9618. int handler_type,
  9619. mg_request_handler *handler,
  9620. struct mg_websocket_subprotocols **subprotocols,
  9621. mg_websocket_connect_handler *connect_handler,
  9622. mg_websocket_ready_handler *ready_handler,
  9623. mg_websocket_data_handler *data_handler,
  9624. mg_websocket_close_handler *close_handler,
  9625. mg_authorization_handler *auth_handler,
  9626. void **cbdata)
  9627. {
  9628. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9629. if (request_info) {
  9630. const char *uri = request_info->local_uri;
  9631. size_t urilen = strlen(uri);
  9632. struct mg_handler_info *tmp_rh;
  9633. if (!conn || !conn->ctx) {
  9634. return 0;
  9635. }
  9636. mg_lock_context(conn->ctx);
  9637. /* first try for an exact match */
  9638. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9639. tmp_rh = tmp_rh->next) {
  9640. if (tmp_rh->handler_type == handler_type) {
  9641. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9642. if (handler_type == WEBSOCKET_HANDLER) {
  9643. *subprotocols = tmp_rh->subprotocols;
  9644. *connect_handler = tmp_rh->connect_handler;
  9645. *ready_handler = tmp_rh->ready_handler;
  9646. *data_handler = tmp_rh->data_handler;
  9647. *close_handler = tmp_rh->close_handler;
  9648. } else if (handler_type == REQUEST_HANDLER) {
  9649. *handler = tmp_rh->handler;
  9650. } else { /* AUTH_HANDLER */
  9651. *auth_handler = tmp_rh->auth_handler;
  9652. }
  9653. *cbdata = tmp_rh->cbdata;
  9654. mg_unlock_context(conn->ctx);
  9655. return 1;
  9656. }
  9657. }
  9658. }
  9659. /* next try for a partial match, we will accept uri/something */
  9660. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9661. tmp_rh = tmp_rh->next) {
  9662. if (tmp_rh->handler_type == handler_type) {
  9663. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9664. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9665. if (handler_type == WEBSOCKET_HANDLER) {
  9666. *subprotocols = tmp_rh->subprotocols;
  9667. *connect_handler = tmp_rh->connect_handler;
  9668. *ready_handler = tmp_rh->ready_handler;
  9669. *data_handler = tmp_rh->data_handler;
  9670. *close_handler = tmp_rh->close_handler;
  9671. } else if (handler_type == REQUEST_HANDLER) {
  9672. *handler = tmp_rh->handler;
  9673. } else { /* AUTH_HANDLER */
  9674. *auth_handler = tmp_rh->auth_handler;
  9675. }
  9676. *cbdata = tmp_rh->cbdata;
  9677. mg_unlock_context(conn->ctx);
  9678. return 1;
  9679. }
  9680. }
  9681. }
  9682. /* finally try for pattern match */
  9683. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9684. tmp_rh = tmp_rh->next) {
  9685. if (tmp_rh->handler_type == handler_type) {
  9686. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9687. if (handler_type == WEBSOCKET_HANDLER) {
  9688. *subprotocols = tmp_rh->subprotocols;
  9689. *connect_handler = tmp_rh->connect_handler;
  9690. *ready_handler = tmp_rh->ready_handler;
  9691. *data_handler = tmp_rh->data_handler;
  9692. *close_handler = tmp_rh->close_handler;
  9693. } else if (handler_type == REQUEST_HANDLER) {
  9694. *handler = tmp_rh->handler;
  9695. } else { /* AUTH_HANDLER */
  9696. *auth_handler = tmp_rh->auth_handler;
  9697. }
  9698. *cbdata = tmp_rh->cbdata;
  9699. mg_unlock_context(conn->ctx);
  9700. return 1;
  9701. }
  9702. }
  9703. }
  9704. mg_unlock_context(conn->ctx);
  9705. }
  9706. return 0; /* none found */
  9707. }
  9708. /* Check if the script file is in a path, allowed for script files.
  9709. * This can be used if uploading files is possible not only for the server
  9710. * admin, and the upload mechanism does not check the file extension.
  9711. */
  9712. static int
  9713. is_in_script_path(const struct mg_connection *conn, const char *path)
  9714. {
  9715. /* TODO (Feature): Add config value for allowed script path.
  9716. * Default: All allowed. */
  9717. (void)conn;
  9718. (void)path;
  9719. return 1;
  9720. }
  9721. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9722. static int
  9723. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9724. void *cbdata)
  9725. {
  9726. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9727. if (pcallbacks->websocket_connect) {
  9728. return pcallbacks->websocket_connect(conn);
  9729. }
  9730. /* No handler set - assume "OK" */
  9731. return 0;
  9732. }
  9733. static void
  9734. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9735. {
  9736. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9737. if (pcallbacks->websocket_ready) {
  9738. pcallbacks->websocket_ready(conn);
  9739. }
  9740. }
  9741. static int
  9742. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9743. int bits,
  9744. char *data,
  9745. size_t len,
  9746. void *cbdata)
  9747. {
  9748. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9749. if (pcallbacks->websocket_data) {
  9750. return pcallbacks->websocket_data(conn, bits, data, len);
  9751. }
  9752. /* No handler set - assume "OK" */
  9753. return 1;
  9754. }
  9755. #endif
  9756. /* This is the heart of the Civetweb's logic.
  9757. * This function is called when the request is read, parsed and validated,
  9758. * and Civetweb must decide what action to take: serve a file, or
  9759. * a directory, or call embedded function, etcetera. */
  9760. static void
  9761. handle_request(struct mg_connection *conn)
  9762. {
  9763. struct mg_request_info *ri = &conn->request_info;
  9764. char path[PATH_MAX];
  9765. int uri_len, ssl_index;
  9766. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9767. is_put_or_delete_request = 0, is_callback_resource = 0;
  9768. int i;
  9769. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9770. mg_request_handler callback_handler = NULL;
  9771. struct mg_websocket_subprotocols *subprotocols;
  9772. mg_websocket_connect_handler ws_connect_handler = NULL;
  9773. mg_websocket_ready_handler ws_ready_handler = NULL;
  9774. mg_websocket_data_handler ws_data_handler = NULL;
  9775. mg_websocket_close_handler ws_close_handler = NULL;
  9776. void *callback_data = NULL;
  9777. mg_authorization_handler auth_handler = NULL;
  9778. void *auth_callback_data = NULL;
  9779. #if !defined(NO_FILES)
  9780. time_t curtime = time(NULL);
  9781. char date[64];
  9782. #endif
  9783. path[0] = 0;
  9784. /* 1. get the request url */
  9785. /* 1.1. split into url and query string */
  9786. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9787. != NULL) {
  9788. *((char *)conn->request_info.query_string++) = '\0';
  9789. }
  9790. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9791. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9792. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9793. if (ssl_index >= 0) {
  9794. redirect_to_https_port(conn, ssl_index);
  9795. } else {
  9796. /* A http to https forward port has been specified,
  9797. * but no https port to forward to. */
  9798. mg_send_http_error(conn,
  9799. 503,
  9800. "%s",
  9801. "Error: SSL forward not configured properly");
  9802. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9803. }
  9804. return;
  9805. }
  9806. uri_len = (int)strlen(ri->local_uri);
  9807. /* 1.3. decode url (if config says so) */
  9808. if (should_decode_url(conn)) {
  9809. mg_url_decode(
  9810. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9811. }
  9812. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9813. * not possible */
  9814. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9815. /* step 1. completed, the url is known now */
  9816. uri_len = (int)strlen(ri->local_uri);
  9817. DEBUG_TRACE("URL: %s", ri->local_uri);
  9818. /* 3. if this ip has limited speed, set it for this connection */
  9819. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9820. get_remote_ip(conn),
  9821. ri->local_uri);
  9822. /* 4. call a "handle everything" callback, if registered */
  9823. if (conn->ctx->callbacks.begin_request != NULL) {
  9824. /* Note that since V1.7 the "begin_request" function is called
  9825. * before an authorization check. If an authorization check is
  9826. * required, use a request_handler instead. */
  9827. i = conn->ctx->callbacks.begin_request(conn);
  9828. if (i > 0) {
  9829. /* callback already processed the request. Store the
  9830. return value as a status code for the access log. */
  9831. conn->status_code = i;
  9832. discard_unread_request_data(conn);
  9833. return;
  9834. } else if (i == 0) {
  9835. /* civetweb should process the request */
  9836. } else {
  9837. /* unspecified - may change with the next version */
  9838. return;
  9839. }
  9840. }
  9841. /* request not yet handled by a handler or redirect, so the request
  9842. * is processed here */
  9843. /* 5. interpret the url to find out how the request must be handled
  9844. */
  9845. /* 5.1. first test, if the request targets the regular http(s)://
  9846. * protocol namespace or the websocket ws(s):// protocol namespace.
  9847. */
  9848. is_websocket_request = is_websocket_protocol(conn);
  9849. /* 5.2. check if the request will be handled by a callback */
  9850. if (get_request_handler(conn,
  9851. is_websocket_request ? WEBSOCKET_HANDLER
  9852. : REQUEST_HANDLER,
  9853. &callback_handler,
  9854. &subprotocols,
  9855. &ws_connect_handler,
  9856. &ws_ready_handler,
  9857. &ws_data_handler,
  9858. &ws_close_handler,
  9859. NULL,
  9860. &callback_data)) {
  9861. /* 5.2.1. A callback will handle this request. All requests
  9862. * handled
  9863. * by a callback have to be considered as requests to a script
  9864. * resource. */
  9865. is_callback_resource = 1;
  9866. is_script_resource = 1;
  9867. is_put_or_delete_request = is_put_or_delete_method(conn);
  9868. } else {
  9869. no_callback_resource:
  9870. /* 5.2.2. No callback is responsible for this request. The URI
  9871. * addresses a file based resource (static content or Lua/cgi
  9872. * scripts in the file system). */
  9873. is_callback_resource = 0;
  9874. interpret_uri(conn,
  9875. path,
  9876. sizeof(path),
  9877. &file.stat,
  9878. &is_found,
  9879. &is_script_resource,
  9880. &is_websocket_request,
  9881. &is_put_or_delete_request);
  9882. }
  9883. /* 6. authorization check */
  9884. /* 6.1. a custom authorization handler is installed */
  9885. if (get_request_handler(conn,
  9886. AUTH_HANDLER,
  9887. NULL,
  9888. NULL,
  9889. NULL,
  9890. NULL,
  9891. NULL,
  9892. NULL,
  9893. &auth_handler,
  9894. &auth_callback_data)) {
  9895. if (!auth_handler(conn, auth_callback_data)) {
  9896. return;
  9897. }
  9898. } else if (is_put_or_delete_request && !is_script_resource
  9899. && !is_callback_resource) {
  9900. /* 6.2. this request is a PUT/DELETE to a real file */
  9901. /* 6.2.1. thus, the server must have real files */
  9902. #if defined(NO_FILES)
  9903. if (1) {
  9904. #else
  9905. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9906. #endif
  9907. /* This server does not have any real files, thus the
  9908. * PUT/DELETE methods are not valid. */
  9909. mg_send_http_error(conn,
  9910. 405,
  9911. "%s method not allowed",
  9912. conn->request_info.request_method);
  9913. return;
  9914. }
  9915. #if !defined(NO_FILES)
  9916. /* 6.2.2. Check if put authorization for static files is
  9917. * available.
  9918. */
  9919. if (!is_authorized_for_put(conn)) {
  9920. send_authorization_request(conn);
  9921. return;
  9922. }
  9923. #endif
  9924. } else {
  9925. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9926. * or it is a PUT or DELETE request to a resource that does not
  9927. * correspond to a file. Check authorization. */
  9928. if (!check_authorization(conn, path)) {
  9929. send_authorization_request(conn);
  9930. return;
  9931. }
  9932. }
  9933. /* request is authorized or does not need authorization */
  9934. /* 7. check if there are request handlers for this uri */
  9935. if (is_callback_resource) {
  9936. if (!is_websocket_request) {
  9937. i = callback_handler(conn, callback_data);
  9938. if (i > 0) {
  9939. /* Do nothing, callback has served the request. Store
  9940. * then return value as status code for the log and discard
  9941. * all data from the client not used by the callback. */
  9942. conn->status_code = i;
  9943. discard_unread_request_data(conn);
  9944. } else {
  9945. /* The handler did NOT handle the request. */
  9946. /* Some proper reactions would be:
  9947. * a) close the connections without sending anything
  9948. * b) send a 404 not found
  9949. * c) try if there is a file matching the URI
  9950. * It would be possible to do a, b or c in the callback
  9951. * implementation, and return 1 - we cannot do anything
  9952. * here, that is not possible in the callback.
  9953. *
  9954. * TODO: What would be the best reaction here?
  9955. * (Note: The reaction may change, if there is a better idea.)
  9956. */
  9957. /* For the moment, use option c: We look for a proper file,
  9958. * but since a file request is not always a script resource,
  9959. * the authorization check might be different. */
  9960. interpret_uri(conn,
  9961. path,
  9962. sizeof(path),
  9963. &file.stat,
  9964. &is_found,
  9965. &is_script_resource,
  9966. &is_websocket_request,
  9967. &is_put_or_delete_request);
  9968. callback_handler = NULL;
  9969. /* Here we are at a dead end:
  9970. * According to URI matching, a callback should be
  9971. * responsible for handling the request,
  9972. * we called it, but the callback declared itself
  9973. * not responsible.
  9974. * We use a goto here, to get out of this dead end,
  9975. * and continue with the default handling.
  9976. * A goto here is simpler and better to understand
  9977. * than some curious loop. */
  9978. goto no_callback_resource;
  9979. }
  9980. } else {
  9981. #if defined(USE_WEBSOCKET)
  9982. handle_websocket_request(conn,
  9983. path,
  9984. is_callback_resource,
  9985. subprotocols,
  9986. ws_connect_handler,
  9987. ws_ready_handler,
  9988. ws_data_handler,
  9989. ws_close_handler,
  9990. callback_data);
  9991. #endif
  9992. }
  9993. return;
  9994. }
  9995. /* 8. handle websocket requests */
  9996. #if defined(USE_WEBSOCKET)
  9997. if (is_websocket_request) {
  9998. if (is_script_resource) {
  9999. if (is_in_script_path(conn, path)) {
  10000. /* Websocket Lua script */
  10001. handle_websocket_request(conn,
  10002. path,
  10003. 0 /* Lua Script */,
  10004. NULL,
  10005. NULL,
  10006. NULL,
  10007. NULL,
  10008. NULL,
  10009. &conn->ctx->callbacks);
  10010. } else {
  10011. /* Script was in an illegal path */
  10012. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10013. }
  10014. } else {
  10015. #if defined(MG_LEGACY_INTERFACE)
  10016. handle_websocket_request(
  10017. conn,
  10018. path,
  10019. !is_script_resource /* could be deprecated global callback */,
  10020. NULL,
  10021. deprecated_websocket_connect_wrapper,
  10022. deprecated_websocket_ready_wrapper,
  10023. deprecated_websocket_data_wrapper,
  10024. NULL,
  10025. &conn->ctx->callbacks);
  10026. #else
  10027. mg_send_http_error(conn, 404, "%s", "Not found");
  10028. #endif
  10029. }
  10030. return;
  10031. } else
  10032. #endif
  10033. #if defined(NO_FILES)
  10034. /* 9a. In case the server uses only callbacks, this uri is
  10035. * unknown.
  10036. * Then, all request handling ends here. */
  10037. mg_send_http_error(conn, 404, "%s", "Not Found");
  10038. #else
  10039. /* 9b. This request is either for a static file or resource handled
  10040. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  10041. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10042. mg_send_http_error(conn, 404, "%s", "Not Found");
  10043. return;
  10044. }
  10045. /* 10. Request is handled by a script */
  10046. if (is_script_resource) {
  10047. handle_file_based_request(conn, path, &file);
  10048. return;
  10049. }
  10050. /* 11. Handle put/delete/mkcol requests */
  10051. if (is_put_or_delete_request) {
  10052. /* 11.1. PUT method */
  10053. if (!strcmp(ri->request_method, "PUT")) {
  10054. put_file(conn, path);
  10055. return;
  10056. }
  10057. /* 11.2. DELETE method */
  10058. if (!strcmp(ri->request_method, "DELETE")) {
  10059. delete_file(conn, path);
  10060. return;
  10061. }
  10062. /* 11.3. MKCOL method */
  10063. if (!strcmp(ri->request_method, "MKCOL")) {
  10064. mkcol(conn, path);
  10065. return;
  10066. }
  10067. /* 11.4. PATCH method
  10068. * This method is not supported for static resources,
  10069. * only for scripts (Lua, CGI) and callbacks. */
  10070. mg_send_http_error(conn,
  10071. 405,
  10072. "%s method not allowed",
  10073. conn->request_info.request_method);
  10074. return;
  10075. }
  10076. /* 11. File does not exist, or it was configured that it should be
  10077. * hidden */
  10078. if (!is_found || (must_hide_file(conn, path))) {
  10079. mg_send_http_error(conn, 404, "%s", "Not found");
  10080. return;
  10081. }
  10082. /* 12. Directory uris should end with a slash */
  10083. if (file.stat.is_directory && (uri_len > 0)
  10084. && (ri->local_uri[uri_len - 1] != '/')) {
  10085. gmt_time_string(date, sizeof(date), &curtime);
  10086. mg_printf(conn,
  10087. "HTTP/1.1 301 Moved Permanently\r\n"
  10088. "Location: %s/\r\n"
  10089. "Date: %s\r\n"
  10090. /* "Cache-Control: private\r\n" (= default) */
  10091. "Content-Length: 0\r\n"
  10092. "Connection: %s\r\n",
  10093. ri->request_uri,
  10094. date,
  10095. suggest_connection_header(conn));
  10096. send_additional_header(conn);
  10097. mg_printf(conn, "\r\n");
  10098. return;
  10099. }
  10100. /* 13. Handle other methods than GET/HEAD */
  10101. /* 13.1. Handle PROPFIND */
  10102. if (!strcmp(ri->request_method, "PROPFIND")) {
  10103. handle_propfind(conn, path, &file.stat);
  10104. return;
  10105. }
  10106. /* 13.2. Handle OPTIONS for files */
  10107. if (!strcmp(ri->request_method, "OPTIONS")) {
  10108. /* This standard handler is only used for real files.
  10109. * Scripts should support the OPTIONS method themselves, to allow a
  10110. * maximum flexibility.
  10111. * Lua and CGI scripts may fully support CORS this way (including
  10112. * preflights). */
  10113. send_options(conn);
  10114. return;
  10115. }
  10116. /* 13.3. everything but GET and HEAD (e.g. POST) */
  10117. if (0 != strcmp(ri->request_method, "GET")
  10118. && 0 != strcmp(ri->request_method, "HEAD")) {
  10119. mg_send_http_error(conn,
  10120. 405,
  10121. "%s method not allowed",
  10122. conn->request_info.request_method);
  10123. return;
  10124. }
  10125. /* 14. directories */
  10126. if (file.stat.is_directory) {
  10127. /* Substitute files have already been handled above. */
  10128. /* Here we can either generate and send a directory listing,
  10129. * or send an "access denied" error. */
  10130. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  10131. "yes")) {
  10132. handle_directory_request(conn, path);
  10133. } else {
  10134. mg_send_http_error(conn,
  10135. 403,
  10136. "%s",
  10137. "Error: Directory listing denied");
  10138. }
  10139. return;
  10140. }
  10141. handle_file_based_request(conn, path, &file);
  10142. #endif /* !defined(NO_FILES) */
  10143. #if 0
  10144. /* Perform redirect and auth checks before calling begin_request()
  10145. * handler.
  10146. * Otherwise, begin_request() would need to perform auth checks and
  10147. * redirects. */
  10148. #endif
  10149. }
  10150. static void
  10151. handle_file_based_request(struct mg_connection *conn,
  10152. const char *path,
  10153. struct mg_file *file)
  10154. {
  10155. if (!conn || !conn->ctx) {
  10156. return;
  10157. }
  10158. if (0) {
  10159. #ifdef USE_LUA
  10160. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10161. strlen(
  10162. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10163. path) > 0) {
  10164. if (is_in_script_path(conn, path)) {
  10165. /* Lua server page: an SSI like page containing mostly plain html
  10166. * code
  10167. * plus some tags with server generated contents. */
  10168. handle_lsp_request(conn, path, file, NULL);
  10169. } else {
  10170. /* Script was in an illegal path */
  10171. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10172. }
  10173. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10174. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10175. path) > 0) {
  10176. if (is_in_script_path(conn, path)) {
  10177. /* Lua in-server module script: a CGI like script used to generate
  10178. * the
  10179. * entire reply. */
  10180. mg_exec_lua_script(conn, path, NULL);
  10181. } else {
  10182. /* Script was in an illegal path */
  10183. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10184. }
  10185. #endif
  10186. #if defined(USE_DUKTAPE)
  10187. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10188. strlen(
  10189. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10190. path) > 0) {
  10191. if (is_in_script_path(conn, path)) {
  10192. /* Call duktape to generate the page */
  10193. mg_exec_duktape_script(conn, path);
  10194. } else {
  10195. /* Script was in an illegal path */
  10196. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10197. }
  10198. #endif
  10199. #if !defined(NO_CGI)
  10200. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10201. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10202. path) > 0) {
  10203. if (is_in_script_path(conn, path)) {
  10204. /* CGI scripts may support all HTTP methods */
  10205. handle_cgi_request(conn, path);
  10206. } else {
  10207. /* Script was in an illegal path */
  10208. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10209. }
  10210. #endif /* !NO_CGI */
  10211. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10212. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10213. path) > 0) {
  10214. if (is_in_script_path(conn, path)) {
  10215. handle_ssi_file_request(conn, path, file);
  10216. } else {
  10217. /* Script was in an illegal path */
  10218. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10219. }
  10220. #if !defined(NO_CACHING)
  10221. } else if ((!conn->in_error_handler)
  10222. && is_not_modified(conn, &file->stat)) {
  10223. /* Send 304 "Not Modified" - this must not send any body data */
  10224. handle_not_modified_static_file_request(conn, file);
  10225. #endif /* !NO_CACHING */
  10226. } else {
  10227. handle_static_file_request(conn, path, file, NULL, NULL);
  10228. }
  10229. }
  10230. static void
  10231. close_all_listening_sockets(struct mg_context *ctx)
  10232. {
  10233. unsigned int i;
  10234. if (!ctx) {
  10235. return;
  10236. }
  10237. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10238. closesocket(ctx->listening_sockets[i].sock);
  10239. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10240. }
  10241. mg_free(ctx->listening_sockets);
  10242. ctx->listening_sockets = NULL;
  10243. mg_free(ctx->listening_socket_fds);
  10244. ctx->listening_socket_fds = NULL;
  10245. }
  10246. /* Valid listening port specification is: [ip_address:]port[s]
  10247. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10248. * Examples for IPv6: [::]:80, [::1]:80,
  10249. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10250. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10251. * In order to bind to both, IPv4 and IPv6, you can either add
  10252. * both ports using 8080,[::]:8080, or the short form +8080.
  10253. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10254. * one only accepting IPv4 the other only IPv6. +8080 creates
  10255. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10256. * environment, they might work differently, or might not work
  10257. * at all - it must be tested what options work best in the
  10258. * relevant network environment.
  10259. */
  10260. static int
  10261. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10262. {
  10263. unsigned int a, b, c, d, port;
  10264. int ch, len;
  10265. #if defined(USE_IPV6)
  10266. char buf[100] = {0};
  10267. #endif
  10268. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10269. * Also, all-zeroes in the socket address means binding to all addresses
  10270. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10271. memset(so, 0, sizeof(*so));
  10272. so->lsa.sin.sin_family = AF_INET;
  10273. *ip_version = 0;
  10274. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10275. == 5) {
  10276. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10277. so->lsa.sin.sin_addr.s_addr =
  10278. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10279. so->lsa.sin.sin_port = htons((uint16_t)port);
  10280. *ip_version = 4;
  10281. #if defined(USE_IPV6)
  10282. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10283. && mg_inet_pton(
  10284. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10285. /* IPv6 address, examples: see above */
  10286. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10287. */
  10288. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10289. *ip_version = 6;
  10290. #endif
  10291. } else if ((vec->ptr[0] == '+')
  10292. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10293. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10294. /* Add 1 to len for the + character we skipped before */
  10295. len++;
  10296. #if defined(USE_IPV6)
  10297. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10298. so->lsa.sin6.sin6_family = AF_INET6;
  10299. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10300. *ip_version = 4 + 6;
  10301. #else
  10302. /* Bind to IPv4 only, since IPv6 is not built in. */
  10303. so->lsa.sin.sin_port = htons((uint16_t)port);
  10304. *ip_version = 4;
  10305. #endif
  10306. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10307. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10308. so->lsa.sin.sin_port = htons((uint16_t)port);
  10309. *ip_version = 4;
  10310. } else {
  10311. /* Parsing failure. Make port invalid. */
  10312. port = 0;
  10313. len = 0;
  10314. }
  10315. /* sscanf and the option splitting code ensure the following condition
  10316. */
  10317. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  10318. *ip_version = 0;
  10319. return 0;
  10320. }
  10321. ch = vec->ptr[len]; /* Next character after the port number */
  10322. so->is_ssl = (ch == 's');
  10323. so->ssl_redir = (ch == 'r');
  10324. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  10325. if (is_valid_port(port)
  10326. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  10327. return 1;
  10328. }
  10329. /* Reset ip_version to 0 of there is an error */
  10330. *ip_version = 0;
  10331. return 0;
  10332. }
  10333. static int
  10334. set_ports_option(struct mg_context *ctx)
  10335. {
  10336. const char *list;
  10337. int on = 1;
  10338. #if defined(USE_IPV6)
  10339. int off = 0;
  10340. #endif
  10341. struct vec vec;
  10342. struct socket so, *ptr;
  10343. struct pollfd *pfd;
  10344. union usa usa;
  10345. socklen_t len;
  10346. int ip_version;
  10347. int portsTotal = 0;
  10348. int portsOk = 0;
  10349. if (!ctx) {
  10350. return 0;
  10351. }
  10352. memset(&so, 0, sizeof(so));
  10353. memset(&usa, 0, sizeof(usa));
  10354. len = sizeof(usa);
  10355. list = ctx->config[LISTENING_PORTS];
  10356. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10357. portsTotal++;
  10358. if (!parse_port_string(&vec, &so, &ip_version)) {
  10359. mg_cry(fc(ctx),
  10360. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  10361. (int)vec.len,
  10362. vec.ptr,
  10363. portsTotal,
  10364. "[IP_ADDRESS:]PORT[s|r]");
  10365. continue;
  10366. }
  10367. #if !defined(NO_SSL)
  10368. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10369. mg_cry(fc(ctx),
  10370. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10371. "option set?",
  10372. portsTotal);
  10373. continue;
  10374. }
  10375. #endif
  10376. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10377. == INVALID_SOCKET) {
  10378. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10379. continue;
  10380. }
  10381. #ifdef _WIN32
  10382. /* Windows SO_REUSEADDR lets many procs binds to a
  10383. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10384. * if someone already has the socket -- DTL */
  10385. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10386. * Windows might need a few seconds before
  10387. * the same port can be used again in the
  10388. * same process, so a short Sleep may be
  10389. * required between mg_stop and mg_start.
  10390. */
  10391. if (setsockopt(so.sock,
  10392. SOL_SOCKET,
  10393. SO_EXCLUSIVEADDRUSE,
  10394. (SOCK_OPT_TYPE)&on,
  10395. sizeof(on)) != 0) {
  10396. /* Set reuse option, but don't abort on errors. */
  10397. mg_cry(fc(ctx),
  10398. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10399. portsTotal);
  10400. }
  10401. #else
  10402. if (setsockopt(so.sock,
  10403. SOL_SOCKET,
  10404. SO_REUSEADDR,
  10405. (SOCK_OPT_TYPE)&on,
  10406. sizeof(on)) != 0) {
  10407. /* Set reuse option, but don't abort on errors. */
  10408. mg_cry(fc(ctx),
  10409. "cannot set socket option SO_REUSEADDR (entry %i)",
  10410. portsTotal);
  10411. }
  10412. #endif
  10413. if (ip_version > 4) {
  10414. #if defined(USE_IPV6)
  10415. if (ip_version == 6) {
  10416. if (so.lsa.sa.sa_family == AF_INET6
  10417. && setsockopt(so.sock,
  10418. IPPROTO_IPV6,
  10419. IPV6_V6ONLY,
  10420. (void *)&off,
  10421. sizeof(off)) != 0) {
  10422. /* Set IPv6 only option, but don't abort on errors. */
  10423. mg_cry(fc(ctx),
  10424. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10425. portsTotal);
  10426. }
  10427. }
  10428. #else
  10429. mg_cry(fc(ctx), "IPv6 not available");
  10430. closesocket(so.sock);
  10431. so.sock = INVALID_SOCKET;
  10432. continue;
  10433. #endif
  10434. }
  10435. if (so.lsa.sa.sa_family == AF_INET) {
  10436. len = sizeof(so.lsa.sin);
  10437. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10438. mg_cry(fc(ctx),
  10439. "cannot bind to %.*s: %d (%s)",
  10440. (int)vec.len,
  10441. vec.ptr,
  10442. (int)ERRNO,
  10443. strerror(errno));
  10444. closesocket(so.sock);
  10445. so.sock = INVALID_SOCKET;
  10446. continue;
  10447. }
  10448. }
  10449. #if defined(USE_IPV6)
  10450. else if (so.lsa.sa.sa_family == AF_INET6) {
  10451. len = sizeof(so.lsa.sin6);
  10452. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10453. mg_cry(fc(ctx),
  10454. "cannot bind to IPv6 %.*s: %d (%s)",
  10455. (int)vec.len,
  10456. vec.ptr,
  10457. (int)ERRNO,
  10458. strerror(errno));
  10459. closesocket(so.sock);
  10460. so.sock = INVALID_SOCKET;
  10461. continue;
  10462. }
  10463. }
  10464. #endif
  10465. else {
  10466. mg_cry(fc(ctx),
  10467. "cannot bind: address family not supported (entry %i)",
  10468. portsTotal);
  10469. continue;
  10470. }
  10471. if (listen(so.sock, SOMAXCONN) != 0) {
  10472. mg_cry(fc(ctx),
  10473. "cannot listen to %.*s: %d (%s)",
  10474. (int)vec.len,
  10475. vec.ptr,
  10476. (int)ERRNO,
  10477. strerror(errno));
  10478. closesocket(so.sock);
  10479. so.sock = INVALID_SOCKET;
  10480. continue;
  10481. }
  10482. if (getsockname(so.sock, &(usa.sa), &len) != 0
  10483. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  10484. int err = (int)ERRNO;
  10485. mg_cry(fc(ctx),
  10486. "call to getsockname failed %.*s: %d (%s)",
  10487. (int)vec.len,
  10488. vec.ptr,
  10489. err,
  10490. strerror(errno));
  10491. closesocket(so.sock);
  10492. so.sock = INVALID_SOCKET;
  10493. continue;
  10494. }
  10495. /* Update lsa port in case of random free ports */
  10496. #if defined(USE_IPV6)
  10497. if (so.lsa.sa.sa_family == AF_INET6) {
  10498. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10499. } else
  10500. #endif
  10501. {
  10502. so.lsa.sin.sin_port = usa.sin.sin_port;
  10503. }
  10504. if ((ptr = (struct socket *)
  10505. mg_realloc_ctx(ctx->listening_sockets,
  10506. (ctx->num_listening_sockets + 1)
  10507. * sizeof(ctx->listening_sockets[0]),
  10508. ctx)) == NULL) {
  10509. mg_cry(fc(ctx), "%s", "Out of memory");
  10510. closesocket(so.sock);
  10511. so.sock = INVALID_SOCKET;
  10512. continue;
  10513. }
  10514. if ((pfd = (struct pollfd *)
  10515. mg_realloc_ctx(ctx->listening_socket_fds,
  10516. (ctx->num_listening_sockets + 1)
  10517. * sizeof(ctx->listening_socket_fds[0]),
  10518. ctx)) == NULL) {
  10519. mg_cry(fc(ctx), "%s", "Out of memory");
  10520. closesocket(so.sock);
  10521. so.sock = INVALID_SOCKET;
  10522. mg_free(ptr);
  10523. continue;
  10524. }
  10525. set_close_on_exec(so.sock, fc(ctx));
  10526. ctx->listening_sockets = ptr;
  10527. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10528. ctx->listening_socket_fds = pfd;
  10529. ctx->num_listening_sockets++;
  10530. portsOk++;
  10531. }
  10532. if (portsOk != portsTotal) {
  10533. close_all_listening_sockets(ctx);
  10534. portsOk = 0;
  10535. }
  10536. return portsOk;
  10537. }
  10538. static const char *
  10539. header_val(const struct mg_connection *conn, const char *header)
  10540. {
  10541. const char *header_value;
  10542. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10543. return "-";
  10544. } else {
  10545. return header_value;
  10546. }
  10547. }
  10548. static void
  10549. log_access(const struct mg_connection *conn)
  10550. {
  10551. const struct mg_request_info *ri;
  10552. struct mg_file fi;
  10553. char date[64], src_addr[IP_ADDR_STR_LEN];
  10554. struct tm *tm;
  10555. const char *referer;
  10556. const char *user_agent;
  10557. char buf[4096];
  10558. if (!conn || !conn->ctx) {
  10559. return;
  10560. }
  10561. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10562. if (mg_fopen(conn,
  10563. conn->ctx->config[ACCESS_LOG_FILE],
  10564. MG_FOPEN_MODE_APPEND,
  10565. &fi) == 0) {
  10566. fi.access.fp = NULL;
  10567. }
  10568. } else {
  10569. fi.access.fp = NULL;
  10570. }
  10571. /* Log is written to a file and/or a callback. If both are not set,
  10572. * executing the rest of the function is pointless. */
  10573. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10574. return;
  10575. }
  10576. tm = localtime(&conn->conn_birth_time);
  10577. if (tm != NULL) {
  10578. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10579. } else {
  10580. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10581. date[sizeof(date) - 1] = '\0';
  10582. }
  10583. ri = &conn->request_info;
  10584. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10585. referer = header_val(conn, "Referer");
  10586. user_agent = header_val(conn, "User-Agent");
  10587. mg_snprintf(conn,
  10588. NULL, /* Ignore truncation in access log */
  10589. buf,
  10590. sizeof(buf),
  10591. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10592. src_addr,
  10593. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10594. date,
  10595. ri->request_method ? ri->request_method : "-",
  10596. ri->request_uri ? ri->request_uri : "-",
  10597. ri->query_string ? "?" : "",
  10598. ri->query_string ? ri->query_string : "",
  10599. ri->http_version,
  10600. conn->status_code,
  10601. conn->num_bytes_sent,
  10602. referer,
  10603. user_agent);
  10604. if (conn->ctx->callbacks.log_access) {
  10605. conn->ctx->callbacks.log_access(conn, buf);
  10606. }
  10607. if (fi.access.fp) {
  10608. int ok = 1;
  10609. flockfile(fi.access.fp);
  10610. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10611. ok = 0;
  10612. }
  10613. if (fflush(fi.access.fp) != 0) {
  10614. ok = 0;
  10615. }
  10616. funlockfile(fi.access.fp);
  10617. if (mg_fclose(&fi.access) != 0) {
  10618. ok = 0;
  10619. }
  10620. if (!ok) {
  10621. mg_cry(conn,
  10622. "Error writing log file %s",
  10623. conn->ctx->config[ACCESS_LOG_FILE]);
  10624. }
  10625. }
  10626. }
  10627. /* Verify given socket address against the ACL.
  10628. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10629. */
  10630. static int
  10631. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10632. {
  10633. int allowed, flag;
  10634. uint32_t net, mask;
  10635. struct vec vec;
  10636. if (ctx) {
  10637. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10638. /* If any ACL is set, deny by default */
  10639. allowed = (list == NULL) ? '+' : '-';
  10640. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10641. flag = vec.ptr[0];
  10642. if ((flag != '+' && flag != '-')
  10643. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10644. mg_cry(fc(ctx),
  10645. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10646. __func__);
  10647. return -1;
  10648. }
  10649. if (net == (remote_ip & mask)) {
  10650. allowed = flag;
  10651. }
  10652. }
  10653. return allowed == '+';
  10654. }
  10655. return -1;
  10656. }
  10657. #if !defined(_WIN32)
  10658. static int
  10659. set_uid_option(struct mg_context *ctx)
  10660. {
  10661. struct passwd *pw;
  10662. if (ctx) {
  10663. const char *uid = ctx->config[RUN_AS_USER];
  10664. int success = 0;
  10665. if (uid == NULL) {
  10666. success = 1;
  10667. } else {
  10668. if ((pw = getpwnam(uid)) == NULL) {
  10669. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10670. } else if (setgid(pw->pw_gid) == -1) {
  10671. mg_cry(fc(ctx),
  10672. "%s: setgid(%s): %s",
  10673. __func__,
  10674. uid,
  10675. strerror(errno));
  10676. } else if (setgroups(0, NULL)) {
  10677. mg_cry(fc(ctx),
  10678. "%s: setgroups(): %s",
  10679. __func__,
  10680. strerror(errno));
  10681. } else if (setuid(pw->pw_uid) == -1) {
  10682. mg_cry(fc(ctx),
  10683. "%s: setuid(%s): %s",
  10684. __func__,
  10685. uid,
  10686. strerror(errno));
  10687. } else {
  10688. success = 1;
  10689. }
  10690. }
  10691. return success;
  10692. }
  10693. return 0;
  10694. }
  10695. #endif /* !_WIN32 */
  10696. static void
  10697. tls_dtor(void *key)
  10698. {
  10699. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10700. /* key == pthread_getspecific(sTlsKey); */
  10701. if (tls) {
  10702. if (tls->is_master == 2) {
  10703. tls->is_master = -3; /* Mark memory as dead */
  10704. mg_free(tls);
  10705. }
  10706. }
  10707. pthread_setspecific(sTlsKey, NULL);
  10708. }
  10709. #if !defined(NO_SSL)
  10710. static int
  10711. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  10712. static const char *ssl_error(void);
  10713. static int
  10714. refresh_trust(struct mg_connection *conn)
  10715. {
  10716. static int reload_lock = 0;
  10717. static long int data_check = 0;
  10718. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10719. struct stat cert_buf;
  10720. long int t;
  10721. const char *pem;
  10722. const char *chain;
  10723. int should_verify_peer;
  10724. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10725. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10726. * refresh_trust still can not work. */
  10727. return 0;
  10728. }
  10729. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  10730. if (chain == NULL) {
  10731. chain = pem;
  10732. }
  10733. if ((chain != NULL) && (*chain == 0)) {
  10734. chain = NULL;
  10735. }
  10736. t = data_check;
  10737. if (stat(pem, &cert_buf) != -1) {
  10738. t = (long int)cert_buf.st_mtime;
  10739. }
  10740. if (data_check != t) {
  10741. data_check = t;
  10742. should_verify_peer = 0;
  10743. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  10744. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10745. == 0) {
  10746. should_verify_peer = 1;
  10747. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  10748. "optional") == 0) {
  10749. should_verify_peer = 1;
  10750. }
  10751. }
  10752. if (should_verify_peer) {
  10753. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10754. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10755. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10756. ca_file,
  10757. ca_path) != 1) {
  10758. mg_cry(fc(conn->ctx),
  10759. "SSL_CTX_load_verify_locations error: %s "
  10760. "ssl_verify_peer requires setting "
  10761. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10762. "present in "
  10763. "the .conf file?",
  10764. ssl_error());
  10765. return 0;
  10766. }
  10767. }
  10768. if (1 == mg_atomic_inc(p_reload_lock)) {
  10769. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  10770. return 0;
  10771. }
  10772. *p_reload_lock = 0;
  10773. }
  10774. }
  10775. /* lock while cert is reloading */
  10776. while (*p_reload_lock) {
  10777. sleep(1);
  10778. }
  10779. return 1;
  10780. }
  10781. #ifdef OPENSSL_API_1_1
  10782. #else
  10783. static pthread_mutex_t *ssl_mutexes;
  10784. #endif /* OPENSSL_API_1_1 */
  10785. static int
  10786. sslize(struct mg_connection *conn,
  10787. SSL_CTX *s,
  10788. int (*func)(SSL *),
  10789. volatile int *stop_server)
  10790. {
  10791. int ret, err;
  10792. int short_trust;
  10793. unsigned i;
  10794. if (!conn) {
  10795. return 0;
  10796. }
  10797. short_trust =
  10798. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10799. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10800. if (short_trust) {
  10801. int trust_ret = refresh_trust(conn);
  10802. if (!trust_ret) {
  10803. return trust_ret;
  10804. }
  10805. }
  10806. conn->ssl = SSL_new(s);
  10807. if (conn->ssl == NULL) {
  10808. return 0;
  10809. }
  10810. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10811. if (ret != 1) {
  10812. err = SSL_get_error(conn->ssl, ret);
  10813. (void)err; /* TODO: set some error message */
  10814. SSL_free(conn->ssl);
  10815. conn->ssl = NULL;
  10816. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10817. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10818. #ifndef OPENSSL_API_1_1
  10819. ERR_remove_state(0);
  10820. #endif
  10821. return 0;
  10822. }
  10823. /* SSL functions may fail and require to be called again:
  10824. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10825. * Here "func" could be SSL_connect or SSL_accept. */
  10826. for (i = 16; i <= 1024; i *= 2) {
  10827. ret = func(conn->ssl);
  10828. if (ret != 1) {
  10829. err = SSL_get_error(conn->ssl, ret);
  10830. if ((err == SSL_ERROR_WANT_CONNECT)
  10831. || (err == SSL_ERROR_WANT_ACCEPT)
  10832. || (err == SSL_ERROR_WANT_READ)
  10833. || (err == SSL_ERROR_WANT_WRITE)) {
  10834. /* Need to retry the function call "later".
  10835. * See https://linux.die.net/man/3/ssl_get_error
  10836. * This is typical for non-blocking sockets. */
  10837. if (*stop_server) {
  10838. /* Don't wait if the server is going to be stopped. */
  10839. break;
  10840. }
  10841. mg_sleep(i);
  10842. } else if (err == SSL_ERROR_SYSCALL) {
  10843. /* This is an IO error. Look at errno. */
  10844. err = errno;
  10845. /* TODO: set some error message */
  10846. (void)err;
  10847. break;
  10848. } else {
  10849. /* This is an SSL specific error */
  10850. /* TODO: set some error message */
  10851. break;
  10852. }
  10853. } else {
  10854. /* success */
  10855. break;
  10856. }
  10857. }
  10858. if (ret != 1) {
  10859. SSL_free(conn->ssl);
  10860. conn->ssl = NULL;
  10861. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10862. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10863. #ifndef OPENSSL_API_1_1
  10864. ERR_remove_state(0);
  10865. #endif
  10866. return 0;
  10867. }
  10868. return 1;
  10869. }
  10870. /* Return OpenSSL error message (from CRYPTO lib) */
  10871. static const char *
  10872. ssl_error(void)
  10873. {
  10874. unsigned long err;
  10875. err = ERR_get_error();
  10876. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10877. }
  10878. static int
  10879. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10880. {
  10881. int i;
  10882. const char hexdigit[] = "0123456789abcdef";
  10883. if (memlen <= 0 || buflen <= 0) {
  10884. return 0;
  10885. }
  10886. if (buflen < (3 * memlen)) {
  10887. return 0;
  10888. }
  10889. for (i = 0; i < memlen; i++) {
  10890. if (i > 0) {
  10891. buf[3 * i - 1] = ' ';
  10892. }
  10893. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10894. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10895. }
  10896. buf[3 * memlen - 1] = 0;
  10897. return 1;
  10898. }
  10899. static void
  10900. ssl_get_client_cert_info(struct mg_connection *conn)
  10901. {
  10902. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10903. if (cert) {
  10904. char str_subject[1024];
  10905. char str_issuer[1024];
  10906. char str_finger[1024];
  10907. unsigned char buf[256];
  10908. char *str_serial = NULL;
  10909. unsigned int ulen;
  10910. int ilen;
  10911. unsigned char *tmp_buf;
  10912. unsigned char *tmp_p;
  10913. /* Handle to algorithm used for fingerprint */
  10914. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10915. /* Get Subject and issuer */
  10916. X509_NAME *subj = X509_get_subject_name(cert);
  10917. X509_NAME *iss = X509_get_issuer_name(cert);
  10918. /* Get serial number */
  10919. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10920. /* Translate serial number to a hex string */
  10921. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10922. str_serial = BN_bn2hex(serial_bn);
  10923. BN_free(serial_bn);
  10924. /* Translate subject and issuer to a string */
  10925. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10926. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10927. /* Calculate SHA1 fingerprint and store as a hex string */
  10928. ulen = 0;
  10929. /* ASN1_digest is deprecated. Do the calculation manually,
  10930. * using EVP_Digest. */
  10931. ilen = i2d_X509((void *)cert, NULL);
  10932. tmp_buf =
  10933. (ilen > 0)
  10934. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  10935. : NULL;
  10936. if (tmp_buf) {
  10937. tmp_p = tmp_buf;
  10938. (void)i2d_X509((void *)cert, &tmp_p);
  10939. if (!EVP_Digest(
  10940. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  10941. ulen = 0;
  10942. }
  10943. mg_free(tmp_buf);
  10944. }
  10945. if (!hexdump2string(
  10946. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10947. *str_finger = 0;
  10948. }
  10949. conn->request_info.client_cert =
  10950. (struct client_cert *)mg_malloc_ctx(sizeof(struct client_cert),
  10951. conn->ctx);
  10952. if (conn->request_info.client_cert) {
  10953. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10954. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10955. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10956. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10957. } else {
  10958. /* TODO: write some OOM message */
  10959. }
  10960. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10961. * see https://linux.die.net/man/3/bn_bn2hex */
  10962. OPENSSL_free(str_serial);
  10963. /* Free certificate memory */
  10964. X509_free(cert);
  10965. }
  10966. }
  10967. #ifdef OPENSSL_API_1_1
  10968. #else
  10969. static void
  10970. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10971. {
  10972. (void)line;
  10973. (void)file;
  10974. if (mode & 1) {
  10975. /* 1 is CRYPTO_LOCK */
  10976. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10977. } else {
  10978. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10979. }
  10980. }
  10981. #endif /* OPENSSL_API_1_1 */
  10982. #if !defined(NO_SSL_DL)
  10983. static void *
  10984. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  10985. {
  10986. union {
  10987. void *p;
  10988. void (*fp)(void);
  10989. } u;
  10990. void *dll_handle;
  10991. struct ssl_func *fp;
  10992. int ok;
  10993. int truncated = 0;
  10994. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10995. mg_snprintf(NULL,
  10996. NULL, /* No truncation check for ebuf */
  10997. ebuf,
  10998. ebuf_len,
  10999. "%s: cannot load %s",
  11000. __func__,
  11001. dll_name);
  11002. return NULL;
  11003. }
  11004. ok = 1;
  11005. for (fp = sw; fp->name != NULL; fp++) {
  11006. #ifdef _WIN32
  11007. /* GetProcAddress() returns pointer to function */
  11008. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  11009. #else
  11010. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  11011. * pointers to function pointers. We need to use a union to make a
  11012. * cast. */
  11013. u.p = dlsym(dll_handle, fp->name);
  11014. #endif /* _WIN32 */
  11015. if (u.fp == NULL) {
  11016. if (ok) {
  11017. mg_snprintf(NULL,
  11018. &truncated,
  11019. ebuf,
  11020. ebuf_len,
  11021. "%s: %s: cannot find %s",
  11022. __func__,
  11023. dll_name,
  11024. fp->name);
  11025. ok = 0;
  11026. } else {
  11027. size_t cur_len = strlen(ebuf);
  11028. if (!truncated) {
  11029. mg_snprintf(NULL,
  11030. &truncated,
  11031. ebuf + cur_len,
  11032. ebuf_len - cur_len - 3,
  11033. ", %s",
  11034. fp->name);
  11035. if (truncated) {
  11036. /* If truncated, add "..." */
  11037. strcat(ebuf, "...");
  11038. }
  11039. }
  11040. }
  11041. /* Debug:
  11042. * printf("Missing function: %s\n", fp->name); */
  11043. } else {
  11044. fp->ptr = u.fp;
  11045. }
  11046. }
  11047. if (!ok) {
  11048. (void)dlclose(dll_handle);
  11049. return NULL;
  11050. }
  11051. return dll_handle;
  11052. }
  11053. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  11054. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  11055. #endif /* NO_SSL_DL */
  11056. #if defined(SSL_ALREADY_INITIALIZED)
  11057. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  11058. #else
  11059. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  11060. #endif
  11061. static int
  11062. initialize_ssl(char *ebuf, size_t ebuf_len)
  11063. {
  11064. #ifdef OPENSSL_API_1_1
  11065. if (ebuf_len > 0) {
  11066. ebuf[0] = 0;
  11067. }
  11068. #if !defined(NO_SSL_DL)
  11069. if (!cryptolib_dll_handle) {
  11070. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11071. if (!cryptolib_dll_handle) {
  11072. return 0;
  11073. }
  11074. }
  11075. #endif /* NO_SSL_DL */
  11076. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11077. return 1;
  11078. }
  11079. #else /* not OPENSSL_API_1_1 */
  11080. int i;
  11081. size_t size;
  11082. if (ebuf_len > 0) {
  11083. ebuf[0] = 0;
  11084. }
  11085. #if !defined(NO_SSL_DL)
  11086. if (!cryptolib_dll_handle) {
  11087. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11088. if (!cryptolib_dll_handle) {
  11089. return 0;
  11090. }
  11091. }
  11092. #endif /* NO_SSL_DL */
  11093. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11094. return 1;
  11095. }
  11096. /* Initialize locking callbacks, needed for thread safety.
  11097. * http://www.openssl.org/support/faq.html#PROG1
  11098. */
  11099. i = CRYPTO_num_locks();
  11100. if (i < 0) {
  11101. i = 0;
  11102. }
  11103. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  11104. if (size == 0) {
  11105. ssl_mutexes = NULL;
  11106. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  11107. mg_snprintf(NULL,
  11108. NULL, /* No truncation check for ebuf */
  11109. ebuf,
  11110. ebuf_len,
  11111. "%s: cannot allocate mutexes: %s",
  11112. __func__,
  11113. ssl_error());
  11114. return 0;
  11115. }
  11116. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11117. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  11118. }
  11119. CRYPTO_set_locking_callback(&ssl_locking_callback);
  11120. CRYPTO_set_id_callback(&mg_current_thread_id);
  11121. #endif /* OPENSSL_API_1_1 */
  11122. return 1;
  11123. }
  11124. static int
  11125. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  11126. {
  11127. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  11128. mg_cry(fc(ctx),
  11129. "%s: cannot open certificate file %s: %s",
  11130. __func__,
  11131. pem,
  11132. ssl_error());
  11133. return 0;
  11134. }
  11135. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  11136. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  11137. mg_cry(fc(ctx),
  11138. "%s: cannot open private key file %s: %s",
  11139. __func__,
  11140. pem,
  11141. ssl_error());
  11142. return 0;
  11143. }
  11144. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  11145. mg_cry(fc(ctx),
  11146. "%s: certificate and private key do not match: %s",
  11147. __func__,
  11148. pem);
  11149. return 0;
  11150. }
  11151. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11152. * chain files that contain private keys and certificates in
  11153. * SSL_CTX_use_certificate_chain_file.
  11154. * The CivetWeb-Server used pem-Files that contained both information.
  11155. * In order to make wolfSSL work, it is split in two files.
  11156. * One file that contains key and certificate used by the server and
  11157. * an optional chain file for the ssl stack.
  11158. */
  11159. if (chain) {
  11160. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11161. mg_cry(fc(ctx),
  11162. "%s: cannot use certificate chain file %s: %s",
  11163. __func__,
  11164. pem,
  11165. ssl_error());
  11166. return 0;
  11167. }
  11168. }
  11169. return 1;
  11170. }
  11171. #ifdef OPENSSL_API_1_1
  11172. static unsigned long
  11173. ssl_get_protocol(int version_id)
  11174. {
  11175. long unsigned ret = SSL_OP_ALL;
  11176. if (version_id > 0)
  11177. ret |= SSL_OP_NO_SSLv2;
  11178. if (version_id > 1)
  11179. ret |= SSL_OP_NO_SSLv3;
  11180. if (version_id > 2)
  11181. ret |= SSL_OP_NO_TLSv1;
  11182. if (version_id > 3)
  11183. ret |= SSL_OP_NO_TLSv1_1;
  11184. return ret;
  11185. }
  11186. #else
  11187. static long
  11188. ssl_get_protocol(int version_id)
  11189. {
  11190. long ret = SSL_OP_ALL;
  11191. if (version_id > 0)
  11192. ret |= SSL_OP_NO_SSLv2;
  11193. if (version_id > 1)
  11194. ret |= SSL_OP_NO_SSLv3;
  11195. if (version_id > 2)
  11196. ret |= SSL_OP_NO_TLSv1;
  11197. if (version_id > 3)
  11198. ret |= SSL_OP_NO_TLSv1_1;
  11199. return ret;
  11200. }
  11201. #endif /* OPENSSL_API_1_1 */
  11202. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11203. static int
  11204. set_ssl_option(struct mg_context *ctx)
  11205. {
  11206. const char *pem;
  11207. const char *chain;
  11208. int callback_ret;
  11209. int should_verify_peer;
  11210. int peer_certificate_optional;
  11211. const char *ca_path;
  11212. const char *ca_file;
  11213. int use_default_verify_paths;
  11214. int verify_depth;
  11215. time_t now_rt = time(NULL);
  11216. struct timespec now_mt;
  11217. md5_byte_t ssl_context_id[16];
  11218. md5_state_t md5state;
  11219. int protocol_ver;
  11220. char ebuf[128];
  11221. /* If PEM file is not specified and the init_ssl callback
  11222. * is not specified, skip SSL initialization. */
  11223. if (!ctx) {
  11224. return 0;
  11225. }
  11226. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11227. && ctx->callbacks.init_ssl == NULL) {
  11228. return 1;
  11229. }
  11230. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11231. if (chain == NULL) {
  11232. chain = pem;
  11233. }
  11234. if ((chain != NULL) && (*chain == 0)) {
  11235. chain = NULL;
  11236. }
  11237. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11238. mg_cry(fc(ctx), "%s", ebuf);
  11239. return 0;
  11240. }
  11241. #if !defined(NO_SSL_DL)
  11242. if (!ssllib_dll_handle) {
  11243. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11244. if (!ssllib_dll_handle) {
  11245. mg_cry(fc(ctx), "%s", ebuf);
  11246. return 0;
  11247. }
  11248. }
  11249. #endif /* NO_SSL_DL */
  11250. #ifdef OPENSSL_API_1_1
  11251. /* Initialize SSL library */
  11252. OPENSSL_init_ssl(0, NULL);
  11253. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11254. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11255. NULL);
  11256. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11257. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11258. return 0;
  11259. }
  11260. #else
  11261. /* Initialize SSL library */
  11262. SSL_library_init();
  11263. SSL_load_error_strings();
  11264. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11265. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11266. return 0;
  11267. }
  11268. #endif /* OPENSSL_API_1_1 */
  11269. SSL_CTX_clear_options(ctx->ssl_ctx,
  11270. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11271. | SSL_OP_NO_TLSv1_1);
  11272. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11273. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11274. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11275. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11276. #if !defined(NO_SSL_DL)
  11277. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11278. #endif /* NO_SSL_DL */
  11279. /* If a callback has been specified, call it. */
  11280. callback_ret =
  11281. (ctx->callbacks.init_ssl == NULL)
  11282. ? 0
  11283. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11284. /* If callback returns 0, civetweb sets up the SSL certificate.
  11285. * If it returns 1, civetweb assumes the calback already did this.
  11286. * If it returns -1, initializing ssl fails. */
  11287. if (callback_ret < 0) {
  11288. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11289. return 0;
  11290. }
  11291. if (callback_ret > 0) {
  11292. if (pem != NULL) {
  11293. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11294. }
  11295. return 1;
  11296. }
  11297. /* Use some UID as session context ID. */
  11298. md5_init(&md5state);
  11299. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  11300. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  11301. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  11302. md5_append(&md5state,
  11303. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  11304. strlen(ctx->config[LISTENING_PORTS]));
  11305. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  11306. md5_finish(&md5state, ssl_context_id);
  11307. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  11308. (const unsigned char *)&ssl_context_id,
  11309. sizeof(ssl_context_id));
  11310. if (pem != NULL) {
  11311. if (!ssl_use_pem_file(ctx, pem, chain)) {
  11312. return 0;
  11313. }
  11314. }
  11315. /* Should we support client certificates? */
  11316. /* Default is "no". */
  11317. should_verify_peer = 0;
  11318. peer_certificate_optional = 0;
  11319. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11320. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  11321. /* Yes, they are mandatory */
  11322. should_verify_peer = 1;
  11323. peer_certificate_optional = 0;
  11324. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  11325. == 0) {
  11326. /* Yes, they are optional */
  11327. should_verify_peer = 1;
  11328. peer_certificate_optional = 1;
  11329. }
  11330. }
  11331. use_default_verify_paths =
  11332. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  11333. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  11334. if (should_verify_peer) {
  11335. ca_path = ctx->config[SSL_CA_PATH];
  11336. ca_file = ctx->config[SSL_CA_FILE];
  11337. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  11338. != 1) {
  11339. mg_cry(fc(ctx),
  11340. "SSL_CTX_load_verify_locations error: %s "
  11341. "ssl_verify_peer requires setting "
  11342. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11343. "present in "
  11344. "the .conf file?",
  11345. ssl_error());
  11346. return 0;
  11347. }
  11348. if (peer_certificate_optional) {
  11349. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  11350. } else {
  11351. SSL_CTX_set_verify(ctx->ssl_ctx,
  11352. SSL_VERIFY_PEER
  11353. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11354. NULL);
  11355. }
  11356. if (use_default_verify_paths
  11357. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  11358. mg_cry(fc(ctx),
  11359. "SSL_CTX_set_default_verify_paths error: %s",
  11360. ssl_error());
  11361. return 0;
  11362. }
  11363. if (ctx->config[SSL_VERIFY_DEPTH]) {
  11364. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  11365. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  11366. }
  11367. }
  11368. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  11369. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  11370. != 1) {
  11371. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  11372. }
  11373. }
  11374. return 1;
  11375. }
  11376. static void
  11377. uninitialize_ssl(void)
  11378. {
  11379. #ifdef OPENSSL_API_1_1
  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. CONF_modules_unload(1);
  11386. #else
  11387. int i;
  11388. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11389. /* Shutdown according to
  11390. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11391. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11392. */
  11393. CRYPTO_set_locking_callback(NULL);
  11394. CRYPTO_set_id_callback(NULL);
  11395. ENGINE_cleanup();
  11396. CONF_modules_unload(1);
  11397. ERR_free_strings();
  11398. EVP_cleanup();
  11399. CRYPTO_cleanup_all_ex_data();
  11400. ERR_remove_state(0);
  11401. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11402. pthread_mutex_destroy(&ssl_mutexes[i]);
  11403. }
  11404. mg_free(ssl_mutexes);
  11405. ssl_mutexes = NULL;
  11406. #endif /* OPENSSL_API_1_1 */
  11407. }
  11408. }
  11409. #endif /* !NO_SSL */
  11410. static int
  11411. set_gpass_option(struct mg_context *ctx)
  11412. {
  11413. if (ctx) {
  11414. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11415. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  11416. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  11417. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  11418. return 0;
  11419. }
  11420. return 1;
  11421. }
  11422. return 0;
  11423. }
  11424. static int
  11425. set_acl_option(struct mg_context *ctx)
  11426. {
  11427. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  11428. }
  11429. static void
  11430. reset_per_request_attributes(struct mg_connection *conn)
  11431. {
  11432. if (!conn) {
  11433. return;
  11434. }
  11435. conn->path_info = NULL;
  11436. conn->num_bytes_sent = conn->consumed_content = 0;
  11437. conn->status_code = -1;
  11438. conn->is_chunked = 0;
  11439. conn->must_close = conn->request_len = conn->throttle = 0;
  11440. conn->request_info.content_length = -1;
  11441. conn->request_info.remote_user = NULL;
  11442. conn->request_info.request_method = NULL;
  11443. conn->request_info.request_uri = NULL;
  11444. conn->request_info.local_uri = NULL;
  11445. #if defined(MG_LEGACY_INTERFACE)
  11446. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  11447. * local_uri and request_uri */
  11448. #endif
  11449. conn->request_info.http_version = NULL;
  11450. conn->request_info.num_headers = 0;
  11451. conn->data_len = 0;
  11452. conn->chunk_remainder = 0;
  11453. }
  11454. #if 0
  11455. /* Note: set_sock_timeout is not required for non-blocking sockets.
  11456. * Leave this function here (commented out) for reference until
  11457. * CivetWeb 1.9 is tested, and the tests confirme this function is
  11458. * no longer required.
  11459. */
  11460. static int
  11461. set_sock_timeout(SOCKET sock, int milliseconds)
  11462. {
  11463. int r0 = 0, r1, r2;
  11464. #ifdef _WIN32
  11465. /* Windows specific */
  11466. DWORD tv = (DWORD)milliseconds;
  11467. #else
  11468. /* Linux, ... (not Windows) */
  11469. struct timeval tv;
  11470. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  11471. * max. time waiting for the acknowledged of TCP data before the connection
  11472. * will be forcefully closed and ETIMEDOUT is returned to the application.
  11473. * If this option is not set, the default timeout of 20-30 minutes is used.
  11474. */
  11475. /* #define TCP_USER_TIMEOUT (18) */
  11476. #if defined(TCP_USER_TIMEOUT)
  11477. unsigned int uto = (unsigned int)milliseconds;
  11478. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  11479. #endif
  11480. memset(&tv, 0, sizeof(tv));
  11481. tv.tv_sec = milliseconds / 1000;
  11482. tv.tv_usec = (milliseconds * 1000) % 1000000;
  11483. #endif /* _WIN32 */
  11484. r1 = setsockopt(
  11485. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11486. r2 = setsockopt(
  11487. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11488. return r0 || r1 || r2;
  11489. }
  11490. #endif
  11491. static int
  11492. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11493. {
  11494. if (setsockopt(sock,
  11495. IPPROTO_TCP,
  11496. TCP_NODELAY,
  11497. (SOCK_OPT_TYPE)&nodelay_on,
  11498. sizeof(nodelay_on)) != 0) {
  11499. /* Error */
  11500. return 1;
  11501. }
  11502. /* OK */
  11503. return 0;
  11504. }
  11505. static void
  11506. close_socket_gracefully(struct mg_connection *conn)
  11507. {
  11508. #if defined(_WIN32)
  11509. char buf[MG_BUF_LEN];
  11510. int n;
  11511. #endif
  11512. struct linger linger;
  11513. int error_code = 0;
  11514. int linger_timeout = -2;
  11515. socklen_t opt_len = sizeof(error_code);
  11516. if (!conn) {
  11517. return;
  11518. }
  11519. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  11520. * "Note that enabling a nonzero timeout on a nonblocking socket
  11521. * is not recommended.", so set it to blocking now */
  11522. set_blocking_mode(conn->client.sock, 1);
  11523. /* Send FIN to the client */
  11524. shutdown(conn->client.sock, SHUTDOWN_WR);
  11525. #if defined(_WIN32)
  11526. /* Read and discard pending incoming data. If we do not do that and
  11527. * close
  11528. * the socket, the data in the send buffer may be discarded. This
  11529. * behaviour is seen on Windows, when client keeps sending data
  11530. * when server decides to close the connection; then when client
  11531. * does recv() it gets no data back. */
  11532. do {
  11533. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  11534. } while (n > 0);
  11535. #endif
  11536. if (conn->ctx->config[LINGER_TIMEOUT]) {
  11537. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  11538. }
  11539. /* Set linger option according to configuration */
  11540. if (linger_timeout >= 0) {
  11541. /* Set linger option to avoid socket hanging out after close. This
  11542. * prevent ephemeral port exhaust problem under high QPS. */
  11543. linger.l_onoff = 1;
  11544. #if defined(_MSC_VER)
  11545. #pragma warning(push)
  11546. #pragma warning(disable : 4244)
  11547. #endif
  11548. linger.l_linger = (linger_timeout + 999) / 1000;
  11549. #if defined(_MSC_VER)
  11550. #pragma warning(pop)
  11551. #endif
  11552. } else {
  11553. linger.l_onoff = 0;
  11554. linger.l_linger = 0;
  11555. }
  11556. if (linger_timeout < -1) {
  11557. /* Default: don't configure any linger */
  11558. } else if (getsockopt(conn->client.sock,
  11559. SOL_SOCKET,
  11560. SO_ERROR,
  11561. (char *)&error_code,
  11562. &opt_len) != 0) {
  11563. /* Cannot determine if socket is already closed. This should
  11564. * not occur and never did in a test. Log an error message
  11565. * and continue. */
  11566. mg_cry(conn,
  11567. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  11568. __func__,
  11569. strerror(ERRNO));
  11570. } else if (error_code == ECONNRESET) {
  11571. /* Socket already closed by client/peer, close socket without linger */
  11572. } else {
  11573. /* Set linger timeout */
  11574. if (setsockopt(conn->client.sock,
  11575. SOL_SOCKET,
  11576. SO_LINGER,
  11577. (char *)&linger,
  11578. sizeof(linger)) != 0) {
  11579. mg_cry(conn,
  11580. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  11581. __func__,
  11582. linger.l_onoff,
  11583. linger.l_linger,
  11584. strerror(ERRNO));
  11585. }
  11586. }
  11587. /* Now we know that our FIN is ACK-ed, safe to close */
  11588. closesocket(conn->client.sock);
  11589. conn->client.sock = INVALID_SOCKET;
  11590. }
  11591. static void
  11592. close_connection(struct mg_connection *conn)
  11593. {
  11594. if (!conn || !conn->ctx) {
  11595. return;
  11596. }
  11597. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11598. if (conn->lua_websocket_state) {
  11599. lua_websocket_close(conn, conn->lua_websocket_state);
  11600. conn->lua_websocket_state = NULL;
  11601. }
  11602. #endif
  11603. /* call the connection_close callback if assigned */
  11604. if ((conn->ctx->callbacks.connection_close != NULL)
  11605. && (conn->ctx->context_type == 1)) {
  11606. conn->ctx->callbacks.connection_close(conn);
  11607. }
  11608. mg_lock_connection(conn);
  11609. conn->must_close = 1;
  11610. #ifndef NO_SSL
  11611. if (conn->ssl != NULL) {
  11612. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11613. */
  11614. SSL_shutdown(conn->ssl);
  11615. SSL_free(conn->ssl);
  11616. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11617. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11618. #ifndef OPENSSL_API_1_1
  11619. ERR_remove_state(0);
  11620. #endif
  11621. conn->ssl = NULL;
  11622. }
  11623. #endif
  11624. if (conn->client.sock != INVALID_SOCKET) {
  11625. close_socket_gracefully(conn);
  11626. conn->client.sock = INVALID_SOCKET;
  11627. }
  11628. mg_unlock_connection(conn);
  11629. }
  11630. void
  11631. mg_close_connection(struct mg_connection *conn)
  11632. {
  11633. struct mg_context *client_ctx = NULL;
  11634. if (conn == NULL) {
  11635. return;
  11636. }
  11637. #if defined(USE_WEBSOCKET)
  11638. if (conn->ctx->context_type == 2) {
  11639. unsigned int i;
  11640. /* ws/wss client */
  11641. client_ctx = conn->ctx;
  11642. /* client context: loops must end */
  11643. conn->ctx->stop_flag = 1;
  11644. /* We need to get the client thread out of the select/recv call here. */
  11645. /* Since we use a sleep quantum of some seconds to check for recv
  11646. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11647. /* join worker thread */
  11648. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11649. if (client_ctx->worker_threadids[i] != 0) {
  11650. mg_join_thread(client_ctx->worker_threadids[i]);
  11651. }
  11652. }
  11653. }
  11654. #else
  11655. (void)client_ctx;
  11656. #endif
  11657. close_connection(conn);
  11658. #ifndef NO_SSL
  11659. if (conn->client_ssl_ctx != NULL) {
  11660. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11661. }
  11662. #endif
  11663. if (client_ctx != NULL) {
  11664. /* free context */
  11665. mg_free(client_ctx->worker_threadids);
  11666. mg_free(client_ctx);
  11667. (void)pthread_mutex_destroy(&conn->mutex);
  11668. mg_free(conn);
  11669. } else if (conn->ctx->context_type == 0) { // Client
  11670. mg_free(conn);
  11671. }
  11672. }
  11673. static struct mg_context common_client_context;
  11674. static struct mg_connection *
  11675. mg_connect_client_impl(const struct mg_client_options *client_options,
  11676. int use_ssl,
  11677. char *ebuf,
  11678. size_t ebuf_len)
  11679. {
  11680. struct mg_connection *conn = NULL;
  11681. SOCKET sock;
  11682. union usa sa;
  11683. if (!connect_socket(&common_client_context,
  11684. client_options->host,
  11685. client_options->port,
  11686. use_ssl,
  11687. ebuf,
  11688. ebuf_len,
  11689. &sock,
  11690. &sa)) {
  11691. return NULL;
  11692. }
  11693. if ((conn = (struct mg_connection *)mg_calloc_ctx(
  11694. 1, sizeof(*conn) + MAX_REQUEST_SIZE, &common_client_context))
  11695. == NULL) {
  11696. mg_snprintf(NULL,
  11697. NULL, /* No truncation check for ebuf */
  11698. ebuf,
  11699. ebuf_len,
  11700. "calloc(): %s",
  11701. strerror(ERRNO));
  11702. closesocket(sock);
  11703. return NULL;
  11704. }
  11705. #ifndef NO_SSL
  11706. #ifdef OPENSSL_API_1_1
  11707. if (use_ssl
  11708. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  11709. mg_snprintf(NULL,
  11710. NULL, /* No truncation check for ebuf */
  11711. ebuf,
  11712. ebuf_len,
  11713. "SSL_CTX_new error");
  11714. closesocket(sock);
  11715. mg_free(conn);
  11716. return NULL;
  11717. }
  11718. #else
  11719. if (use_ssl
  11720. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11721. == NULL) {
  11722. mg_snprintf(NULL,
  11723. NULL, /* No truncation check for ebuf */
  11724. ebuf,
  11725. ebuf_len,
  11726. "SSL_CTX_new error");
  11727. closesocket(sock);
  11728. mg_free(conn);
  11729. return NULL;
  11730. }
  11731. #endif /* OPENSSL_API_1_1 */
  11732. #endif /* NO_SSL */
  11733. #ifdef USE_IPV6
  11734. socklen_t len = (sa.sa.sa_family == AF_INET)
  11735. ? sizeof(conn->client.rsa.sin)
  11736. : sizeof(conn->client.rsa.sin6);
  11737. struct sockaddr *psa = (sa.sa.sa_family == AF_INET)
  11738. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11739. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11740. #else
  11741. socklen_t len = sizeof(conn->client.rsa.sin);
  11742. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11743. #endif
  11744. conn->buf_size = MAX_REQUEST_SIZE;
  11745. conn->buf = (char *)(conn + 1);
  11746. conn->ctx = &common_client_context;
  11747. conn->client.sock = sock;
  11748. conn->client.lsa = sa;
  11749. if (getsockname(sock, psa, &len) != 0) {
  11750. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  11751. }
  11752. conn->client.is_ssl = use_ssl ? 1 : 0;
  11753. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11754. #ifndef NO_SSL
  11755. if (use_ssl) {
  11756. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  11757. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11758. * SSL_CTX_set_verify call is needed to switch off server
  11759. * certificate checking, which is off by default in OpenSSL and
  11760. * on in yaSSL. */
  11761. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11762. * SSL_VERIFY_PEER, verify_ssl_server); */
  11763. if (client_options->client_cert) {
  11764. if (!ssl_use_pem_file(&common_client_context,
  11765. client_options->client_cert,
  11766. NULL)) {
  11767. mg_snprintf(NULL,
  11768. NULL, /* No truncation check for ebuf */
  11769. ebuf,
  11770. ebuf_len,
  11771. "Can not use SSL client certificate");
  11772. SSL_CTX_free(conn->client_ssl_ctx);
  11773. closesocket(sock);
  11774. mg_free(conn);
  11775. return NULL;
  11776. }
  11777. }
  11778. if (client_options->server_cert) {
  11779. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11780. client_options->server_cert,
  11781. NULL);
  11782. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11783. } else {
  11784. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11785. }
  11786. if (!sslize(conn,
  11787. conn->client_ssl_ctx,
  11788. SSL_connect,
  11789. &(conn->ctx->stop_flag))) {
  11790. mg_snprintf(NULL,
  11791. NULL, /* No truncation check for ebuf */
  11792. ebuf,
  11793. ebuf_len,
  11794. "SSL connection error");
  11795. SSL_CTX_free(conn->client_ssl_ctx);
  11796. closesocket(sock);
  11797. mg_free(conn);
  11798. return NULL;
  11799. }
  11800. }
  11801. #endif
  11802. set_blocking_mode(sock, 0);
  11803. return conn;
  11804. }
  11805. CIVETWEB_API struct mg_connection *
  11806. mg_connect_client_secure(const struct mg_client_options *client_options,
  11807. char *error_buffer,
  11808. size_t error_buffer_size)
  11809. {
  11810. return mg_connect_client_impl(client_options,
  11811. 1,
  11812. error_buffer,
  11813. error_buffer_size);
  11814. }
  11815. struct mg_connection *
  11816. mg_connect_client(const char *host,
  11817. int port,
  11818. int use_ssl,
  11819. char *error_buffer,
  11820. size_t error_buffer_size)
  11821. {
  11822. struct mg_client_options opts;
  11823. memset(&opts, 0, sizeof(opts));
  11824. opts.host = host;
  11825. opts.port = port;
  11826. return mg_connect_client_impl(&opts,
  11827. use_ssl,
  11828. error_buffer,
  11829. error_buffer_size);
  11830. }
  11831. static const struct {
  11832. const char *proto;
  11833. size_t proto_len;
  11834. unsigned default_port;
  11835. } abs_uri_protocols[] = {{"http://", 7, 80},
  11836. {"https://", 8, 443},
  11837. {"ws://", 5, 80},
  11838. {"wss://", 6, 443},
  11839. {NULL, 0, 0}};
  11840. /* Check if the uri is valid.
  11841. * return 0 for invalid uri,
  11842. * return 1 for *,
  11843. * return 2 for relative uri,
  11844. * return 3 for absolute uri without port,
  11845. * return 4 for absolute uri with port */
  11846. static int
  11847. get_uri_type(const char *uri)
  11848. {
  11849. int i;
  11850. const char *hostend, *portbegin;
  11851. char *portend;
  11852. unsigned long port;
  11853. /* According to the HTTP standard
  11854. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11855. * URI can be an asterisk (*) or should start with slash (relative uri),
  11856. * or it should start with the protocol (absolute uri). */
  11857. if (uri[0] == '*' && uri[1] == '\0') {
  11858. /* asterisk */
  11859. return 1;
  11860. }
  11861. /* Valid URIs according to RFC 3986
  11862. * (https://www.ietf.org/rfc/rfc3986.txt)
  11863. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11864. * and unreserved characters A-Z a-z 0-9 and -._~
  11865. * and % encoded symbols.
  11866. */
  11867. for (i = 0; uri[i] != 0; i++) {
  11868. if (uri[i] < 33) {
  11869. /* control characters and spaces are invalid */
  11870. return 0;
  11871. }
  11872. if (uri[i] > 126) {
  11873. /* non-ascii characters must be % encoded */
  11874. return 0;
  11875. } else {
  11876. switch (uri[i]) {
  11877. case '"': /* 34 */
  11878. case '<': /* 60 */
  11879. case '>': /* 62 */
  11880. case '\\': /* 92 */
  11881. case '^': /* 94 */
  11882. case '`': /* 96 */
  11883. case '{': /* 123 */
  11884. case '|': /* 124 */
  11885. case '}': /* 125 */
  11886. return 0;
  11887. default:
  11888. /* character is ok */
  11889. break;
  11890. }
  11891. }
  11892. }
  11893. /* A relative uri starts with a / character */
  11894. if (uri[0] == '/') {
  11895. /* relative uri */
  11896. return 2;
  11897. }
  11898. /* It could be an absolute uri: */
  11899. /* This function only checks if the uri is valid, not if it is
  11900. * addressing the current server. So civetweb can also be used
  11901. * as a proxy server. */
  11902. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11903. if (mg_strncasecmp(uri,
  11904. abs_uri_protocols[i].proto,
  11905. abs_uri_protocols[i].proto_len) == 0) {
  11906. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11907. if (!hostend) {
  11908. return 0;
  11909. }
  11910. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11911. if (!portbegin) {
  11912. return 3;
  11913. }
  11914. port = strtoul(portbegin + 1, &portend, 10);
  11915. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11916. return 0;
  11917. }
  11918. return 4;
  11919. }
  11920. }
  11921. return 0;
  11922. }
  11923. /* Return NULL or the relative uri at the current server */
  11924. static const char *
  11925. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11926. {
  11927. const char *server_domain;
  11928. size_t server_domain_len;
  11929. size_t request_domain_len = 0;
  11930. unsigned long port = 0;
  11931. int i, auth_domain_check_enabled;
  11932. const char *hostbegin = NULL;
  11933. const char *hostend = NULL;
  11934. const char *portbegin;
  11935. char *portend;
  11936. auth_domain_check_enabled =
  11937. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  11938. if (!auth_domain_check_enabled) {
  11939. return 0;
  11940. }
  11941. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11942. if (!server_domain) {
  11943. return 0;
  11944. }
  11945. server_domain_len = strlen(server_domain);
  11946. if (!server_domain_len) {
  11947. return 0;
  11948. }
  11949. /* DNS is case insensitive, so use case insensitive string compare here
  11950. */
  11951. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11952. if (mg_strncasecmp(uri,
  11953. abs_uri_protocols[i].proto,
  11954. abs_uri_protocols[i].proto_len) == 0) {
  11955. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11956. hostend = strchr(hostbegin, '/');
  11957. if (!hostend) {
  11958. return 0;
  11959. }
  11960. portbegin = strchr(hostbegin, ':');
  11961. if ((!portbegin) || (portbegin > hostend)) {
  11962. port = abs_uri_protocols[i].default_port;
  11963. request_domain_len = (size_t)(hostend - hostbegin);
  11964. } else {
  11965. port = strtoul(portbegin + 1, &portend, 10);
  11966. if ((portend != hostend) || (port <= 0)
  11967. || !is_valid_port(port)) {
  11968. return 0;
  11969. }
  11970. request_domain_len = (size_t)(portbegin - hostbegin);
  11971. }
  11972. /* protocol found, port set */
  11973. break;
  11974. }
  11975. }
  11976. if (!port) {
  11977. /* port remains 0 if the protocol is not found */
  11978. return 0;
  11979. }
  11980. /* Check if the request is directed to a different server. */
  11981. /* First check if the port is the same (IPv4 and IPv6). */
  11982. #if defined(USE_IPV6)
  11983. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11984. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11985. /* Request is directed to a different port */
  11986. return 0;
  11987. }
  11988. } else
  11989. #endif
  11990. {
  11991. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11992. /* Request is directed to a different port */
  11993. return 0;
  11994. }
  11995. }
  11996. /* Finally check if the server corresponds to the authentication
  11997. * domain of the server (the server domain).
  11998. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11999. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  12000. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  12001. * or http://mydomain.com.fake/path/file.ext).
  12002. */
  12003. if (auth_domain_check_enabled) {
  12004. if ((request_domain_len == server_domain_len)
  12005. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  12006. /* Request is directed to this server - full name match. */
  12007. } else {
  12008. if (request_domain_len < (server_domain_len + 2)) {
  12009. /* Request is directed to another server: The server name is
  12010. * longer
  12011. * than
  12012. * the request name. Drop this case here to avoid overflows in
  12013. * the
  12014. * following checks. */
  12015. return 0;
  12016. }
  12017. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  12018. /* Request is directed to another server: It could be a
  12019. * substring
  12020. * like notmyserver.com */
  12021. return 0;
  12022. }
  12023. if (0 != memcmp(server_domain,
  12024. hostbegin + request_domain_len - server_domain_len,
  12025. server_domain_len)) {
  12026. /* Request is directed to another server:
  12027. * The server name is different. */
  12028. return 0;
  12029. }
  12030. }
  12031. }
  12032. return hostend;
  12033. }
  12034. static int
  12035. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12036. {
  12037. const char *cl;
  12038. if (ebuf_len > 0) {
  12039. ebuf[0] = '\0';
  12040. }
  12041. *err = 0;
  12042. reset_per_request_attributes(conn);
  12043. if (!conn) {
  12044. mg_snprintf(conn,
  12045. NULL, /* No truncation check for ebuf */
  12046. ebuf,
  12047. ebuf_len,
  12048. "%s",
  12049. "Internal error");
  12050. *err = 500;
  12051. return 0;
  12052. }
  12053. /* Set the time the request was received. This value should be used for
  12054. * timeouts. */
  12055. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  12056. conn->request_len =
  12057. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  12058. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  12059. */
  12060. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  12061. mg_snprintf(conn,
  12062. NULL, /* No truncation check for ebuf */
  12063. ebuf,
  12064. ebuf_len,
  12065. "%s",
  12066. "Invalid request size");
  12067. *err = 500;
  12068. return 0;
  12069. }
  12070. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  12071. mg_snprintf(conn,
  12072. NULL, /* No truncation check for ebuf */
  12073. ebuf,
  12074. ebuf_len,
  12075. "%s",
  12076. "Request Too Large");
  12077. *err = 413;
  12078. return 0;
  12079. } else if (conn->request_len <= 0) {
  12080. if (conn->data_len > 0) {
  12081. mg_snprintf(conn,
  12082. NULL, /* No truncation check for ebuf */
  12083. ebuf,
  12084. ebuf_len,
  12085. "%s",
  12086. "Client sent malformed request");
  12087. *err = 400;
  12088. } else {
  12089. /* Server did not recv anything -> just close the connection */
  12090. conn->must_close = 1;
  12091. mg_snprintf(conn,
  12092. NULL, /* No truncation check for ebuf */
  12093. ebuf,
  12094. ebuf_len,
  12095. "%s",
  12096. "Client did not send a request");
  12097. *err = 0;
  12098. }
  12099. return 0;
  12100. } else if (parse_http_message(conn->buf,
  12101. conn->buf_size,
  12102. &conn->request_info) <= 0) {
  12103. mg_snprintf(conn,
  12104. NULL, /* No truncation check for ebuf */
  12105. ebuf,
  12106. ebuf_len,
  12107. "%s",
  12108. "Bad Request");
  12109. *err = 400;
  12110. return 0;
  12111. } else {
  12112. /* Message is a valid request or response */
  12113. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  12114. /* Request/response has content length set */
  12115. char *endptr = NULL;
  12116. conn->content_len = strtoll(cl, &endptr, 10);
  12117. if (endptr == cl) {
  12118. mg_snprintf(conn,
  12119. NULL, /* No truncation check for ebuf */
  12120. ebuf,
  12121. ebuf_len,
  12122. "%s",
  12123. "Bad Request");
  12124. *err = 411;
  12125. return 0;
  12126. }
  12127. /* Publish the content length back to the request info. */
  12128. conn->request_info.content_length = conn->content_len;
  12129. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  12130. != NULL
  12131. && !mg_strcasecmp(cl, "chunked")) {
  12132. conn->is_chunked = 1;
  12133. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  12134. || !mg_strcasecmp(conn->request_info.request_method,
  12135. "PUT")) {
  12136. /* POST or PUT request without content length set */
  12137. conn->content_len = -1;
  12138. } else if (!mg_strncasecmp(conn->request_info.request_method,
  12139. "HTTP/",
  12140. 5)) {
  12141. /* Response without content length set */
  12142. conn->content_len = -1;
  12143. } else {
  12144. /* Other request */
  12145. conn->content_len = 0;
  12146. }
  12147. }
  12148. return 1;
  12149. }
  12150. int
  12151. mg_get_response(struct mg_connection *conn,
  12152. char *ebuf,
  12153. size_t ebuf_len,
  12154. int timeout)
  12155. {
  12156. if (conn) {
  12157. /* Implementation of API function for HTTP clients */
  12158. int err, ret;
  12159. struct mg_context *octx = conn->ctx;
  12160. struct mg_context rctx = *(conn->ctx);
  12161. char txt[32]; /* will not overflow */
  12162. if (timeout >= 0) {
  12163. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  12164. rctx.config[REQUEST_TIMEOUT] = txt;
  12165. /* Not required for non-blocking sockets.
  12166. set_sock_timeout(conn->client.sock, timeout);
  12167. */
  12168. } else {
  12169. rctx.config[REQUEST_TIMEOUT] = NULL;
  12170. }
  12171. conn->ctx = &rctx;
  12172. ret = getreq(conn, ebuf, ebuf_len, &err);
  12173. conn->ctx = octx;
  12174. #if defined(MG_LEGACY_INTERFACE)
  12175. /* TODO: 1) uri is deprecated;
  12176. * 2) here, ri.uri is the http response code */
  12177. conn->request_info.uri = conn->request_info.request_uri;
  12178. #endif
  12179. conn->request_info.local_uri = conn->request_info.request_uri;
  12180. /* TODO (mid): Define proper return values - maybe return length?
  12181. * For the first test use <0 for error and >0 for OK */
  12182. return (ret == 0) ? -1 : +1;
  12183. }
  12184. return -1;
  12185. }
  12186. struct mg_connection *
  12187. mg_download(const char *host,
  12188. int port,
  12189. int use_ssl,
  12190. char *ebuf,
  12191. size_t ebuf_len,
  12192. const char *fmt,
  12193. ...)
  12194. {
  12195. struct mg_connection *conn;
  12196. va_list ap;
  12197. int i;
  12198. int reqerr;
  12199. va_start(ap, fmt);
  12200. ebuf[0] = '\0';
  12201. /* open a connection */
  12202. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  12203. if (conn != NULL) {
  12204. i = mg_vprintf(conn, fmt, ap);
  12205. if (i <= 0) {
  12206. mg_snprintf(conn,
  12207. NULL, /* No truncation check for ebuf */
  12208. ebuf,
  12209. ebuf_len,
  12210. "%s",
  12211. "Error sending request");
  12212. } else {
  12213. getreq(conn, ebuf, ebuf_len, &reqerr);
  12214. #if defined(MG_LEGACY_INTERFACE)
  12215. /* TODO: 1) uri is deprecated;
  12216. * 2) here, ri.uri is the http response code */
  12217. conn->request_info.uri = conn->request_info.request_uri;
  12218. #endif
  12219. conn->request_info.local_uri = conn->request_info.request_uri;
  12220. }
  12221. }
  12222. /* if an error occured, close the connection */
  12223. if (ebuf[0] != '\0' && conn != NULL) {
  12224. mg_close_connection(conn);
  12225. conn = NULL;
  12226. }
  12227. va_end(ap);
  12228. return conn;
  12229. }
  12230. struct websocket_client_thread_data {
  12231. struct mg_connection *conn;
  12232. mg_websocket_data_handler data_handler;
  12233. mg_websocket_close_handler close_handler;
  12234. void *callback_data;
  12235. };
  12236. #if defined(USE_WEBSOCKET)
  12237. #ifdef _WIN32
  12238. static unsigned __stdcall websocket_client_thread(void *data)
  12239. #else
  12240. static void *
  12241. websocket_client_thread(void *data)
  12242. #endif
  12243. {
  12244. struct websocket_client_thread_data *cdata =
  12245. (struct websocket_client_thread_data *)data;
  12246. mg_set_thread_name("ws-clnt");
  12247. if (cdata->conn->ctx) {
  12248. if (cdata->conn->ctx->callbacks.init_thread) {
  12249. /* 3 indicates a websocket client thread */
  12250. /* TODO: check if conn->ctx can be set */
  12251. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  12252. }
  12253. }
  12254. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  12255. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  12256. if (cdata->close_handler != NULL) {
  12257. cdata->close_handler(cdata->conn, cdata->callback_data);
  12258. }
  12259. /* The websocket_client context has only this thread. If it runs out,
  12260. set the stop_flag to 2 (= "stopped"). */
  12261. cdata->conn->ctx->stop_flag = 2;
  12262. mg_free((void *)cdata);
  12263. #ifdef _WIN32
  12264. return 0;
  12265. #else
  12266. return NULL;
  12267. #endif
  12268. }
  12269. #endif
  12270. struct mg_connection *
  12271. mg_connect_websocket_client(const char *host,
  12272. int port,
  12273. int use_ssl,
  12274. char *error_buffer,
  12275. size_t error_buffer_size,
  12276. const char *path,
  12277. const char *origin,
  12278. mg_websocket_data_handler data_func,
  12279. mg_websocket_close_handler close_func,
  12280. void *user_data)
  12281. {
  12282. struct mg_connection *conn = NULL;
  12283. #if defined(USE_WEBSOCKET)
  12284. struct mg_context *newctx = NULL;
  12285. struct websocket_client_thread_data *thread_data;
  12286. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  12287. static const char *handshake_req;
  12288. if (origin != NULL) {
  12289. handshake_req = "GET %s HTTP/1.1\r\n"
  12290. "Host: %s\r\n"
  12291. "Upgrade: websocket\r\n"
  12292. "Connection: Upgrade\r\n"
  12293. "Sec-WebSocket-Key: %s\r\n"
  12294. "Sec-WebSocket-Version: 13\r\n"
  12295. "Origin: %s\r\n"
  12296. "\r\n";
  12297. } else {
  12298. handshake_req = "GET %s HTTP/1.1\r\n"
  12299. "Host: %s\r\n"
  12300. "Upgrade: websocket\r\n"
  12301. "Connection: Upgrade\r\n"
  12302. "Sec-WebSocket-Key: %s\r\n"
  12303. "Sec-WebSocket-Version: 13\r\n"
  12304. "\r\n";
  12305. }
  12306. /* Establish the client connection and request upgrade */
  12307. conn = mg_download(host,
  12308. port,
  12309. use_ssl,
  12310. error_buffer,
  12311. error_buffer_size,
  12312. handshake_req,
  12313. path,
  12314. host,
  12315. magic,
  12316. origin);
  12317. /* Connection object will be null if something goes wrong */
  12318. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  12319. if (!*error_buffer) {
  12320. /* if there is a connection, but it did not return 101,
  12321. * error_buffer is not yet set */
  12322. mg_snprintf(conn,
  12323. NULL, /* No truncation check for ebuf */
  12324. error_buffer,
  12325. error_buffer_size,
  12326. "Unexpected server reply");
  12327. }
  12328. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  12329. if (conn != NULL) {
  12330. mg_free(conn);
  12331. conn = NULL;
  12332. }
  12333. return conn;
  12334. }
  12335. /* For client connections, mg_context is fake. Since we need to set a
  12336. * callback function, we need to create a copy and modify it. */
  12337. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  12338. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  12339. newctx->user_data = user_data;
  12340. newctx->context_type = 2; /* ws/wss client context type */
  12341. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  12342. newctx->worker_threadids =
  12343. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  12344. sizeof(pthread_t),
  12345. newctx);
  12346. conn->ctx = newctx;
  12347. thread_data = (struct websocket_client_thread_data *)
  12348. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  12349. thread_data->conn = conn;
  12350. thread_data->data_handler = data_func;
  12351. thread_data->close_handler = close_func;
  12352. thread_data->callback_data = user_data;
  12353. /* Start a thread to read the websocket client connection
  12354. * This thread will automatically stop when mg_disconnect is
  12355. * called on the client connection */
  12356. if (mg_start_thread_with_id(websocket_client_thread,
  12357. (void *)thread_data,
  12358. newctx->worker_threadids) != 0) {
  12359. mg_free((void *)thread_data);
  12360. mg_free((void *)newctx->worker_threadids);
  12361. mg_free((void *)newctx);
  12362. mg_free((void *)conn);
  12363. conn = NULL;
  12364. DEBUG_TRACE("%s",
  12365. "Websocket client connect thread could not be started\r\n");
  12366. }
  12367. #else
  12368. /* Appease "unused parameter" warnings */
  12369. (void)host;
  12370. (void)port;
  12371. (void)use_ssl;
  12372. (void)error_buffer;
  12373. (void)error_buffer_size;
  12374. (void)path;
  12375. (void)origin;
  12376. (void)user_data;
  12377. (void)data_func;
  12378. (void)close_func;
  12379. #endif
  12380. return conn;
  12381. }
  12382. static void
  12383. process_new_connection(struct mg_connection *conn)
  12384. {
  12385. if (conn && conn->ctx) {
  12386. struct mg_request_info *ri = &conn->request_info;
  12387. int keep_alive_enabled, keep_alive, discard_len;
  12388. char ebuf[100];
  12389. const char *hostend;
  12390. int reqerr, uri_type;
  12391. #if defined(USE_SERVER_STATS)
  12392. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  12393. mg_atomic_add(&(conn->ctx->total_connections), 1);
  12394. if (mcon > (conn->ctx->max_connections)) {
  12395. /* could use atomic compare exchange, but this
  12396. * seems overkill for statistics data */
  12397. conn->ctx->max_connections = mcon;
  12398. }
  12399. #endif
  12400. keep_alive_enabled =
  12401. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  12402. /* Important: on new connection, reset the receiving buffer. Credit
  12403. * goes to crule42. */
  12404. conn->data_len = 0;
  12405. conn->handled_requests = 0;
  12406. do {
  12407. DEBUG_TRACE("calling getreq (%i times for this connection)",
  12408. conn->handled_requests + 1);
  12409. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  12410. /* The request sent by the client could not be understood by
  12411. * the server, or it was incomplete or a timeout. Send an
  12412. * error message and close the connection. */
  12413. if (reqerr > 0) {
  12414. /*assert(ebuf[0] != '\0');*/
  12415. mg_send_http_error(conn, reqerr, "%s", ebuf);
  12416. }
  12417. } else if (strcmp(ri->http_version, "1.0")
  12418. && strcmp(ri->http_version, "1.1")) {
  12419. mg_snprintf(conn,
  12420. NULL, /* No truncation check for ebuf */
  12421. ebuf,
  12422. sizeof(ebuf),
  12423. "Bad HTTP version: [%s]",
  12424. ri->http_version);
  12425. mg_send_http_error(conn, 505, "%s", ebuf);
  12426. }
  12427. if (ebuf[0] == '\0') {
  12428. uri_type = get_uri_type(conn->request_info.request_uri);
  12429. switch (uri_type) {
  12430. case 1:
  12431. /* Asterisk */
  12432. conn->request_info.local_uri = NULL;
  12433. break;
  12434. case 2:
  12435. /* relative uri */
  12436. conn->request_info.local_uri =
  12437. conn->request_info.request_uri;
  12438. break;
  12439. case 3:
  12440. case 4:
  12441. /* absolute uri (with/without port) */
  12442. hostend = get_rel_url_at_current_server(
  12443. conn->request_info.request_uri, conn);
  12444. if (hostend) {
  12445. conn->request_info.local_uri = hostend;
  12446. } else {
  12447. conn->request_info.local_uri = NULL;
  12448. }
  12449. break;
  12450. default:
  12451. mg_snprintf(conn,
  12452. NULL, /* No truncation check for ebuf */
  12453. ebuf,
  12454. sizeof(ebuf),
  12455. "Invalid URI");
  12456. mg_send_http_error(conn, 400, "%s", ebuf);
  12457. conn->request_info.local_uri = NULL;
  12458. break;
  12459. }
  12460. #if defined(MG_LEGACY_INTERFACE)
  12461. /* TODO: cleanup uri, local_uri and request_uri */
  12462. conn->request_info.uri = conn->request_info.local_uri;
  12463. #endif
  12464. }
  12465. DEBUG_TRACE("http: %s, error: %s",
  12466. (ri->http_version ? ri->http_version : "none"),
  12467. (ebuf[0] ? ebuf : "none"));
  12468. if (ebuf[0] == '\0') {
  12469. if (conn->request_info.local_uri) {
  12470. /* handle request to local server */
  12471. handle_request(conn);
  12472. DEBUG_TRACE("%s", "handle_request done");
  12473. if (conn->ctx->callbacks.end_request != NULL) {
  12474. conn->ctx->callbacks.end_request(conn,
  12475. conn->status_code);
  12476. DEBUG_TRACE("%s", "end_request callback done");
  12477. }
  12478. log_access(conn);
  12479. } else {
  12480. /* TODO: handle non-local request (PROXY) */
  12481. conn->must_close = 1;
  12482. }
  12483. } else {
  12484. conn->must_close = 1;
  12485. }
  12486. if (ri->remote_user != NULL) {
  12487. mg_free((void *)ri->remote_user);
  12488. /* Important! When having connections with and without auth
  12489. * would cause double free and then crash */
  12490. ri->remote_user = NULL;
  12491. }
  12492. /* NOTE(lsm): order is important here. should_keep_alive() call
  12493. * is
  12494. * using parsed request, which will be invalid after memmove's
  12495. * below.
  12496. * Therefore, memorize should_keep_alive() result now for later
  12497. * use
  12498. * in loop exit condition. */
  12499. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  12500. && (conn->content_len >= 0) && should_keep_alive(conn);
  12501. /* Discard all buffered data for this request */
  12502. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  12503. && ((conn->request_len + conn->content_len)
  12504. < (int64_t)conn->data_len))
  12505. ? (int)(conn->request_len + conn->content_len)
  12506. : conn->data_len;
  12507. /*assert(discard_len >= 0);*/
  12508. if (discard_len < 0) {
  12509. DEBUG_TRACE("internal error: discard_len = %li",
  12510. (long int)discard_len);
  12511. break;
  12512. }
  12513. conn->data_len -= discard_len;
  12514. if (conn->data_len > 0) {
  12515. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  12516. memmove(conn->buf,
  12517. conn->buf + discard_len,
  12518. (size_t)conn->data_len);
  12519. }
  12520. /* assert(conn->data_len >= 0); */
  12521. /* assert(conn->data_len <= conn->buf_size); */
  12522. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  12523. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  12524. (long int)conn->data_len,
  12525. (long int)conn->buf_size);
  12526. break;
  12527. }
  12528. conn->handled_requests++;
  12529. } while (keep_alive);
  12530. #if defined(USE_SERVER_STATS)
  12531. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  12532. mg_atomic_dec(&(conn->ctx->active_connections));
  12533. #endif
  12534. }
  12535. }
  12536. #if defined(ALTERNATIVE_QUEUE)
  12537. static void
  12538. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12539. {
  12540. unsigned int i;
  12541. for (;;) {
  12542. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12543. /* find a free worker slot and signal it */
  12544. if (ctx->client_socks[i].in_use == 0) {
  12545. ctx->client_socks[i] = *sp;
  12546. ctx->client_socks[i].in_use = 1;
  12547. event_signal(ctx->client_wait_events[i]);
  12548. return;
  12549. }
  12550. }
  12551. /* queue is full */
  12552. mg_sleep(1);
  12553. }
  12554. }
  12555. static int
  12556. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12557. {
  12558. DEBUG_TRACE("%s", "going idle");
  12559. ctx->client_socks[thread_index].in_use = 0;
  12560. event_wait(ctx->client_wait_events[thread_index]);
  12561. *sp = ctx->client_socks[thread_index];
  12562. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12563. return !ctx->stop_flag;
  12564. }
  12565. #else /* ALTERNATIVE_QUEUE */
  12566. /* Worker threads take accepted socket from the queue */
  12567. static int
  12568. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12569. {
  12570. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12571. (void)thread_index;
  12572. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12573. DEBUG_TRACE("%s", "going idle");
  12574. /* If the queue is empty, wait. We're idle at this point. */
  12575. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  12576. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  12577. }
  12578. /* If we're stopping, sq_head may be equal to sq_tail. */
  12579. if (ctx->sq_head > ctx->sq_tail) {
  12580. /* Copy socket from the queue and increment tail */
  12581. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  12582. ctx->sq_tail++;
  12583. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12584. /* Wrap pointers if needed */
  12585. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  12586. ctx->sq_tail -= QUEUE_SIZE(ctx);
  12587. ctx->sq_head -= QUEUE_SIZE(ctx);
  12588. }
  12589. }
  12590. (void)pthread_cond_signal(&ctx->sq_empty);
  12591. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12592. return !ctx->stop_flag;
  12593. #undef QUEUE_SIZE
  12594. }
  12595. /* Master thread adds accepted socket to a queue */
  12596. static void
  12597. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12598. {
  12599. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12600. if (!ctx) {
  12601. return;
  12602. }
  12603. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12604. /* If the queue is full, wait */
  12605. while (ctx->stop_flag == 0
  12606. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  12607. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  12608. }
  12609. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  12610. /* Copy socket to the queue and increment head */
  12611. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  12612. ctx->sq_head++;
  12613. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12614. }
  12615. (void)pthread_cond_signal(&ctx->sq_full);
  12616. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12617. #undef QUEUE_SIZE
  12618. }
  12619. #endif /* ALTERNATIVE_QUEUE */
  12620. struct worker_thread_args {
  12621. struct mg_context *ctx;
  12622. int index;
  12623. };
  12624. static void *
  12625. worker_thread_run(struct worker_thread_args *thread_args)
  12626. {
  12627. struct mg_context *ctx = thread_args->ctx;
  12628. struct mg_connection *conn;
  12629. struct mg_workerTLS tls;
  12630. #if defined(MG_LEGACY_INTERFACE)
  12631. uint32_t addr;
  12632. #endif
  12633. mg_set_thread_name("worker");
  12634. tls.is_master = 0;
  12635. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12636. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12637. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12638. #endif
  12639. /* Initialize thread local storage before calling any callback */
  12640. pthread_setspecific(sTlsKey, &tls);
  12641. if (ctx->callbacks.init_thread) {
  12642. /* call init_thread for a worker thread (type 1) */
  12643. ctx->callbacks.init_thread(ctx, 1);
  12644. }
  12645. /* Connection structure has been pre-allocated */
  12646. if (((int)thread_args->index < 0)
  12647. || ((unsigned)thread_args->index
  12648. >= (unsigned)ctx->cfg_worker_threads)) {
  12649. mg_cry(fc(ctx),
  12650. "Internal error: Invalid worker index %i",
  12651. (int)thread_args->index);
  12652. return NULL;
  12653. }
  12654. conn = ctx->worker_connections + thread_args->index;
  12655. /* Request buffers are not pre-allocated. They are private to the
  12656. * request and do not contain any state information that might be
  12657. * of interest to anyone observing a server status. */
  12658. conn->buf = (char *)mg_malloc_ctx(MAX_REQUEST_SIZE, conn->ctx);
  12659. if (conn->buf == NULL) {
  12660. mg_cry(fc(ctx),
  12661. "Out of memory: Cannot allocate buffer for worker %i",
  12662. (int)thread_args->index);
  12663. return NULL;
  12664. }
  12665. conn->buf_size = MAX_REQUEST_SIZE;
  12666. conn->ctx = ctx;
  12667. conn->thread_index = thread_args->index;
  12668. conn->request_info.user_data = ctx->user_data;
  12669. /* Allocate a mutex for this connection to allow communication both
  12670. * within the request handler and from elsewhere in the application
  12671. */
  12672. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12673. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12674. * signal sq_empty condvar to wake up the master waiting in
  12675. * produce_socket() */
  12676. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12677. conn->conn_birth_time = time(NULL);
  12678. /* Fill in IP, port info early so even if SSL setup below fails,
  12679. * error handler would have the corresponding info.
  12680. * Thanks to Johannes Winkelmann for the patch.
  12681. */
  12682. #if defined(USE_IPV6)
  12683. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12684. conn->request_info.remote_port =
  12685. ntohs(conn->client.rsa.sin6.sin6_port);
  12686. } else
  12687. #endif
  12688. {
  12689. conn->request_info.remote_port =
  12690. ntohs(conn->client.rsa.sin.sin_port);
  12691. }
  12692. sockaddr_to_string(conn->request_info.remote_addr,
  12693. sizeof(conn->request_info.remote_addr),
  12694. &conn->client.rsa);
  12695. DEBUG_TRACE("Start processing connection from %s",
  12696. conn->request_info.remote_addr);
  12697. #if defined(MG_LEGACY_INTERFACE)
  12698. /* This legacy interface only works for the IPv4 case */
  12699. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12700. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12701. #endif
  12702. conn->request_info.is_ssl = conn->client.is_ssl;
  12703. if (conn->client.is_ssl) {
  12704. #ifndef NO_SSL
  12705. /* HTTPS connection */
  12706. if (sslize(conn,
  12707. conn->ctx->ssl_ctx,
  12708. SSL_accept,
  12709. &(conn->ctx->stop_flag))) {
  12710. /* Get SSL client certificate information (if set) */
  12711. ssl_get_client_cert_info(conn);
  12712. /* process HTTPS connection */
  12713. process_new_connection(conn);
  12714. /* Free client certificate info */
  12715. if (conn->request_info.client_cert) {
  12716. mg_free((void *)(conn->request_info.client_cert->subject));
  12717. mg_free((void *)(conn->request_info.client_cert->issuer));
  12718. mg_free((void *)(conn->request_info.client_cert->serial));
  12719. mg_free((void *)(conn->request_info.client_cert->finger));
  12720. conn->request_info.client_cert->subject = 0;
  12721. conn->request_info.client_cert->issuer = 0;
  12722. conn->request_info.client_cert->serial = 0;
  12723. conn->request_info.client_cert->finger = 0;
  12724. mg_free(conn->request_info.client_cert);
  12725. conn->request_info.client_cert = 0;
  12726. }
  12727. }
  12728. #endif
  12729. } else {
  12730. /* process HTTP connection */
  12731. process_new_connection(conn);
  12732. }
  12733. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12734. conn->request_info.remote_addr,
  12735. difftime(time(NULL), conn->conn_birth_time));
  12736. close_connection(conn);
  12737. DEBUG_TRACE("%s", "Connection closed");
  12738. }
  12739. pthread_setspecific(sTlsKey, NULL);
  12740. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12741. CloseHandle(tls.pthread_cond_helper_mutex);
  12742. #endif
  12743. pthread_mutex_destroy(&conn->mutex);
  12744. /* Free the request buffer. */
  12745. conn->buf_size = 0;
  12746. mg_free(conn->buf);
  12747. conn->buf = NULL;
  12748. DEBUG_TRACE("%s", "exiting");
  12749. return NULL;
  12750. }
  12751. /* Threads have different return types on Windows and Unix. */
  12752. #ifdef _WIN32
  12753. static unsigned __stdcall worker_thread(void *thread_func_param)
  12754. {
  12755. struct worker_thread_args *pwta =
  12756. (struct worker_thread_args *)thread_func_param;
  12757. worker_thread_run(pwta);
  12758. mg_free(thread_func_param);
  12759. return 0;
  12760. }
  12761. #else
  12762. static void *
  12763. worker_thread(void *thread_func_param)
  12764. {
  12765. struct worker_thread_args *pwta =
  12766. (struct worker_thread_args *)thread_func_param;
  12767. worker_thread_run(pwta);
  12768. mg_free(thread_func_param);
  12769. return NULL;
  12770. }
  12771. #endif /* _WIN32 */
  12772. static void
  12773. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12774. {
  12775. struct socket so;
  12776. char src_addr[IP_ADDR_STR_LEN];
  12777. socklen_t len = sizeof(so.rsa);
  12778. int on = 1;
  12779. if (!listener) {
  12780. return;
  12781. }
  12782. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12783. == INVALID_SOCKET) {
  12784. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12785. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12786. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12787. closesocket(so.sock);
  12788. so.sock = INVALID_SOCKET;
  12789. } else {
  12790. /* Put so socket structure into the queue */
  12791. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12792. set_close_on_exec(so.sock, fc(ctx));
  12793. so.is_ssl = listener->is_ssl;
  12794. so.ssl_redir = listener->ssl_redir;
  12795. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12796. mg_cry(fc(ctx),
  12797. "%s: getsockname() failed: %s",
  12798. __func__,
  12799. strerror(ERRNO));
  12800. }
  12801. /* Set TCP keep-alive. This is needed because if HTTP-level
  12802. * keep-alive
  12803. * is enabled, and client resets the connection, server won't get
  12804. * TCP FIN or RST and will keep the connection open forever. With
  12805. * TCP keep-alive, next keep-alive handshake will figure out that
  12806. * the client is down and will close the server end.
  12807. * Thanks to Igor Klopov who suggested the patch. */
  12808. if (setsockopt(so.sock,
  12809. SOL_SOCKET,
  12810. SO_KEEPALIVE,
  12811. (SOCK_OPT_TYPE)&on,
  12812. sizeof(on)) != 0) {
  12813. mg_cry(fc(ctx),
  12814. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12815. __func__,
  12816. strerror(ERRNO));
  12817. }
  12818. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12819. * to effectively fill up the underlying IP packet payload and
  12820. * reduce the overhead of sending lots of small buffers. However
  12821. * this hurts the server's throughput (ie. operations per second)
  12822. * when HTTP 1.1 persistent connections are used and the responses
  12823. * are relatively small (eg. less than 1400 bytes).
  12824. */
  12825. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12826. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12827. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12828. mg_cry(fc(ctx),
  12829. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12830. __func__,
  12831. strerror(ERRNO));
  12832. }
  12833. }
  12834. /* We are using non-blocking sockets. Thus, the
  12835. * set_sock_timeout(so.sock, timeout);
  12836. * call is no longer required. */
  12837. set_blocking_mode(so.sock, 0);
  12838. produce_socket(ctx, &so);
  12839. }
  12840. }
  12841. static void
  12842. master_thread_run(void *thread_func_param)
  12843. {
  12844. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12845. struct mg_workerTLS tls;
  12846. struct pollfd *pfd;
  12847. unsigned int i;
  12848. unsigned int workerthreadcount;
  12849. if (!ctx) {
  12850. return;
  12851. }
  12852. mg_set_thread_name("master");
  12853. /* Increase priority of the master thread */
  12854. #if defined(_WIN32)
  12855. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12856. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12857. int min_prio = sched_get_priority_min(SCHED_RR);
  12858. int max_prio = sched_get_priority_max(SCHED_RR);
  12859. if ((min_prio >= 0) && (max_prio >= 0)
  12860. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12861. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12862. struct sched_param sched_param = {0};
  12863. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12864. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12865. }
  12866. #endif
  12867. /* Initialize thread local storage */
  12868. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12869. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12870. #endif
  12871. tls.is_master = 1;
  12872. pthread_setspecific(sTlsKey, &tls);
  12873. if (ctx->callbacks.init_thread) {
  12874. /* Callback for the master thread (type 0) */
  12875. ctx->callbacks.init_thread(ctx, 0);
  12876. }
  12877. /* Server starts *now* */
  12878. ctx->start_time = time(NULL);
  12879. /* Start the server */
  12880. pfd = ctx->listening_socket_fds;
  12881. while (ctx->stop_flag == 0) {
  12882. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12883. pfd[i].fd = ctx->listening_sockets[i].sock;
  12884. pfd[i].events = POLLIN;
  12885. }
  12886. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12887. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12888. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12889. * successful poll, and POLLIN is defined as
  12890. * (POLLRDNORM | POLLRDBAND)
  12891. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12892. * pfd[i].revents == POLLIN. */
  12893. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12894. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12895. }
  12896. }
  12897. }
  12898. }
  12899. /* Here stop_flag is 1 - Initiate shutdown. */
  12900. DEBUG_TRACE("%s", "stopping workers");
  12901. /* Stop signal received: somebody called mg_stop. Quit. */
  12902. close_all_listening_sockets(ctx);
  12903. /* Wakeup workers that are waiting for connections to handle. */
  12904. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12905. #if defined(ALTERNATIVE_QUEUE)
  12906. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12907. event_signal(ctx->client_wait_events[i]);
  12908. /* Since we know all sockets, we can shutdown the connections. */
  12909. if (ctx->client_socks[i].in_use) {
  12910. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12911. }
  12912. }
  12913. #else
  12914. pthread_cond_broadcast(&ctx->sq_full);
  12915. #endif
  12916. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12917. /* Join all worker threads to avoid leaking threads. */
  12918. workerthreadcount = ctx->cfg_worker_threads;
  12919. for (i = 0; i < workerthreadcount; i++) {
  12920. if (ctx->worker_threadids[i] != 0) {
  12921. mg_join_thread(ctx->worker_threadids[i]);
  12922. }
  12923. }
  12924. #if defined(USE_LUA)
  12925. /* Free Lua state of lua background task */
  12926. if (ctx->lua_background_state) {
  12927. lua_close((lua_State *)ctx->lua_background_state);
  12928. ctx->lua_background_state = 0;
  12929. }
  12930. #endif
  12931. #if !defined(NO_SSL)
  12932. if (ctx->ssl_ctx != NULL) {
  12933. uninitialize_ssl();
  12934. }
  12935. #endif
  12936. DEBUG_TRACE("%s", "exiting");
  12937. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12938. CloseHandle(tls.pthread_cond_helper_mutex);
  12939. #endif
  12940. pthread_setspecific(sTlsKey, NULL);
  12941. /* Signal mg_stop() that we're done.
  12942. * WARNING: This must be the very last thing this
  12943. * thread does, as ctx becomes invalid after this line. */
  12944. ctx->stop_flag = 2;
  12945. }
  12946. /* Threads have different return types on Windows and Unix. */
  12947. #ifdef _WIN32
  12948. static unsigned __stdcall master_thread(void *thread_func_param)
  12949. {
  12950. master_thread_run(thread_func_param);
  12951. return 0;
  12952. }
  12953. #else
  12954. static void *
  12955. master_thread(void *thread_func_param)
  12956. {
  12957. master_thread_run(thread_func_param);
  12958. return NULL;
  12959. }
  12960. #endif /* _WIN32 */
  12961. static void
  12962. free_context(struct mg_context *ctx)
  12963. {
  12964. int i;
  12965. struct mg_handler_info *tmp_rh;
  12966. if (ctx == NULL) {
  12967. return;
  12968. }
  12969. if (ctx->callbacks.exit_context) {
  12970. ctx->callbacks.exit_context(ctx);
  12971. }
  12972. /* All threads exited, no sync is needed. Destroy thread mutex and
  12973. * condvars
  12974. */
  12975. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12976. #if defined(ALTERNATIVE_QUEUE)
  12977. mg_free(ctx->client_socks);
  12978. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12979. event_destroy(ctx->client_wait_events[i]);
  12980. }
  12981. mg_free(ctx->client_wait_events);
  12982. #else
  12983. (void)pthread_cond_destroy(&ctx->sq_empty);
  12984. (void)pthread_cond_destroy(&ctx->sq_full);
  12985. #endif
  12986. /* Destroy other context global data structures mutex */
  12987. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12988. #if defined(USE_TIMERS)
  12989. timers_exit(ctx);
  12990. #endif
  12991. /* Deallocate config parameters */
  12992. for (i = 0; i < NUM_OPTIONS; i++) {
  12993. if (ctx->config[i] != NULL) {
  12994. #if defined(_MSC_VER)
  12995. #pragma warning(suppress : 6001)
  12996. #endif
  12997. mg_free(ctx->config[i]);
  12998. }
  12999. }
  13000. /* Deallocate request handlers */
  13001. while (ctx->handlers) {
  13002. tmp_rh = ctx->handlers;
  13003. ctx->handlers = tmp_rh->next;
  13004. mg_free(tmp_rh->uri);
  13005. mg_free(tmp_rh);
  13006. }
  13007. #ifndef NO_SSL
  13008. /* Deallocate SSL context */
  13009. if (ctx->ssl_ctx != NULL) {
  13010. SSL_CTX_free(ctx->ssl_ctx);
  13011. }
  13012. #endif /* !NO_SSL */
  13013. /* Deallocate worker thread ID array */
  13014. if (ctx->worker_threadids != NULL) {
  13015. mg_free(ctx->worker_threadids);
  13016. }
  13017. /* Deallocate worker thread ID array */
  13018. if (ctx->worker_connections != NULL) {
  13019. mg_free(ctx->worker_connections);
  13020. }
  13021. /* Deallocate the tls variable */
  13022. if (mg_atomic_dec(&sTlsInit) == 0) {
  13023. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13024. DeleteCriticalSection(&global_log_file_lock);
  13025. #endif /* _WIN32 && !__SYMBIAN32__ */
  13026. #if !defined(_WIN32)
  13027. pthread_mutexattr_destroy(&pthread_mutex_attr);
  13028. #endif
  13029. pthread_key_delete(sTlsKey);
  13030. #if defined(USE_LUA)
  13031. lua_exit_optional_libraries();
  13032. #endif
  13033. }
  13034. /* deallocate system name string */
  13035. mg_free(ctx->systemName);
  13036. /* Deallocate context itself */
  13037. mg_free(ctx);
  13038. }
  13039. void
  13040. mg_stop(struct mg_context *ctx)
  13041. {
  13042. pthread_t mt;
  13043. if (!ctx) {
  13044. return;
  13045. }
  13046. /* We don't use a lock here. Calling mg_stop with the same ctx from
  13047. * two threads is not allowed. */
  13048. mt = ctx->masterthreadid;
  13049. if (mt == 0) {
  13050. return;
  13051. }
  13052. ctx->masterthreadid = 0;
  13053. /* Set stop flag, so all threads know they have to exit. */
  13054. ctx->stop_flag = 1;
  13055. /* Wait until everything has stopped. */
  13056. while (ctx->stop_flag != 2) {
  13057. (void)mg_sleep(10);
  13058. }
  13059. mg_join_thread(mt);
  13060. free_context(ctx);
  13061. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13062. (void)WSACleanup();
  13063. #endif /* _WIN32 && !__SYMBIAN32__ */
  13064. }
  13065. static void
  13066. get_system_name(char **sysName)
  13067. {
  13068. #if defined(_WIN32)
  13069. #if !defined(__SYMBIAN32__)
  13070. #if defined(_WIN32_WCE)
  13071. *sysName = mg_strdup("WinCE");
  13072. #else
  13073. char name[128];
  13074. DWORD dwVersion = 0;
  13075. DWORD dwMajorVersion = 0;
  13076. DWORD dwMinorVersion = 0;
  13077. DWORD dwBuild = 0;
  13078. BOOL wowRet, isWoW = FALSE;
  13079. #ifdef _MSC_VER
  13080. #pragma warning(push)
  13081. /* GetVersion was declared deprecated */
  13082. #pragma warning(disable : 4996)
  13083. #endif
  13084. dwVersion = GetVersion();
  13085. #ifdef _MSC_VER
  13086. #pragma warning(pop)
  13087. #endif
  13088. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13089. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13090. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  13091. (void)dwBuild;
  13092. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  13093. sprintf(name,
  13094. "Windows %u.%u%s",
  13095. (unsigned)dwMajorVersion,
  13096. (unsigned)dwMinorVersion,
  13097. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  13098. *sysName = mg_strdup(name);
  13099. #endif
  13100. #else
  13101. *sysName = mg_strdup("Symbian");
  13102. #endif
  13103. #else
  13104. struct utsname name;
  13105. memset(&name, 0, sizeof(name));
  13106. uname(&name);
  13107. *sysName = mg_strdup(name.sysname);
  13108. #endif
  13109. }
  13110. struct mg_context *
  13111. mg_start(const struct mg_callbacks *callbacks,
  13112. void *user_data,
  13113. const char **options)
  13114. {
  13115. struct mg_context *ctx;
  13116. const char *name, *value, *default_value;
  13117. int idx, ok, workerthreadcount;
  13118. unsigned int i;
  13119. void (*exit_callback)(const struct mg_context *ctx) = 0;
  13120. struct mg_workerTLS tls;
  13121. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13122. WSADATA data;
  13123. WSAStartup(MAKEWORD(2, 2), &data);
  13124. #endif /* _WIN32 && !__SYMBIAN32__ */
  13125. /* Allocate context and initialize reasonable general case defaults. */
  13126. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  13127. return NULL;
  13128. }
  13129. /* Random number generator will initialize at the first call */
  13130. ctx->auth_nonce_mask =
  13131. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  13132. if (mg_atomic_inc(&sTlsInit) == 1) {
  13133. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13134. InitializeCriticalSection(&global_log_file_lock);
  13135. #endif /* _WIN32 && !__SYMBIAN32__ */
  13136. #if !defined(_WIN32)
  13137. pthread_mutexattr_init(&pthread_mutex_attr);
  13138. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  13139. #endif
  13140. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  13141. /* Fatal error - abort start. However, this situation should
  13142. * never occur in practice. */
  13143. mg_atomic_dec(&sTlsInit);
  13144. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  13145. mg_free(ctx);
  13146. return NULL;
  13147. }
  13148. #if defined(USE_LUA)
  13149. lua_init_optional_libraries();
  13150. #endif
  13151. } else {
  13152. /* TODO (low): instead of sleeping, check if sTlsKey is already
  13153. * initialized. */
  13154. mg_sleep(1);
  13155. }
  13156. tls.is_master = -1;
  13157. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13158. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13159. tls.pthread_cond_helper_mutex = NULL;
  13160. #endif
  13161. pthread_setspecific(sTlsKey, &tls);
  13162. /* Dummy use this function - in some #ifdef combinations it's used,
  13163. * while it's not used in others, but GCC seems to stupid to understand
  13164. * #pragma GCC diagnostic ignored "-Wunused-function"
  13165. * in cases the function is unused, and it also complains on
  13166. * __attribute((unused))__ in cases it is used.
  13167. * So dummy use it, to have our peace. */
  13168. (void)mg_current_thread_id();
  13169. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  13170. #if !defined(ALTERNATIVE_QUEUE)
  13171. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  13172. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  13173. #endif
  13174. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  13175. if (!ok) {
  13176. /* Fatal error - abort start. However, this situation should never
  13177. * occur in practice. */
  13178. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  13179. mg_free(ctx);
  13180. pthread_setspecific(sTlsKey, NULL);
  13181. return NULL;
  13182. }
  13183. if (callbacks) {
  13184. ctx->callbacks = *callbacks;
  13185. exit_callback = callbacks->exit_context;
  13186. ctx->callbacks.exit_context = 0;
  13187. }
  13188. ctx->user_data = user_data;
  13189. ctx->handlers = NULL;
  13190. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13191. ctx->shared_lua_websockets = 0;
  13192. #endif
  13193. while (options && (name = *options++) != NULL) {
  13194. if ((idx = get_option_index(name)) == -1) {
  13195. mg_cry(fc(ctx), "Invalid option: %s", name);
  13196. free_context(ctx);
  13197. pthread_setspecific(sTlsKey, NULL);
  13198. return NULL;
  13199. } else if ((value = *options++) == NULL) {
  13200. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  13201. free_context(ctx);
  13202. pthread_setspecific(sTlsKey, NULL);
  13203. return NULL;
  13204. }
  13205. if (ctx->config[idx] != NULL) {
  13206. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  13207. mg_free(ctx->config[idx]);
  13208. }
  13209. ctx->config[idx] = mg_strdup(value);
  13210. DEBUG_TRACE("[%s] -> [%s]", name, value);
  13211. }
  13212. /* Set default value if needed */
  13213. for (i = 0; config_options[i].name != NULL; i++) {
  13214. default_value = config_options[i].default_value;
  13215. if (ctx->config[i] == NULL && default_value != NULL) {
  13216. ctx->config[i] = mg_strdup(default_value);
  13217. }
  13218. }
  13219. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  13220. if (workerthreadcount > MAX_WORKER_THREADS) {
  13221. mg_cry(fc(ctx), "Too many worker threads");
  13222. free_context(ctx);
  13223. pthread_setspecific(sTlsKey, NULL);
  13224. return NULL;
  13225. }
  13226. if (workerthreadcount <= 0) {
  13227. mg_cry(fc(ctx), "Invalid number of worker threads");
  13228. free_context(ctx);
  13229. pthread_setspecific(sTlsKey, NULL);
  13230. return NULL;
  13231. }
  13232. #if defined(NO_FILES)
  13233. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  13234. mg_cry(fc(ctx), "%s", "Document root must not be set");
  13235. free_context(ctx);
  13236. pthread_setspecific(sTlsKey, NULL);
  13237. return NULL;
  13238. }
  13239. #endif
  13240. get_system_name(&ctx->systemName);
  13241. #if defined(USE_LUA)
  13242. /* If a Lua background script has been configured, start it. */
  13243. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  13244. char ebuf[256];
  13245. void *state = (void *)mg_prepare_lua_context_script(
  13246. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  13247. if (!state) {
  13248. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  13249. free_context(ctx);
  13250. pthread_setspecific(sTlsKey, NULL);
  13251. return NULL;
  13252. }
  13253. ctx->lua_background_state = state;
  13254. } else {
  13255. ctx->lua_background_state = 0;
  13256. }
  13257. #endif
  13258. /* NOTE(lsm): order is important here. SSL certificates must
  13259. * be initialized before listening ports. UID must be set last. */
  13260. if (!set_gpass_option(ctx) ||
  13261. #if !defined(NO_SSL)
  13262. !set_ssl_option(ctx) ||
  13263. #endif
  13264. !set_ports_option(ctx) ||
  13265. #if !defined(_WIN32)
  13266. !set_uid_option(ctx) ||
  13267. #endif
  13268. !set_acl_option(ctx)) {
  13269. free_context(ctx);
  13270. pthread_setspecific(sTlsKey, NULL);
  13271. return NULL;
  13272. }
  13273. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  13274. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  13275. * won't kill the whole process. */
  13276. (void)signal(SIGPIPE, SIG_IGN);
  13277. #endif /* !_WIN32 && !__SYMBIAN32__ */
  13278. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  13279. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13280. sizeof(pthread_t),
  13281. ctx);
  13282. if (ctx->worker_threadids == NULL) {
  13283. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  13284. free_context(ctx);
  13285. pthread_setspecific(sTlsKey, NULL);
  13286. return NULL;
  13287. }
  13288. ctx->worker_connections =
  13289. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13290. sizeof(struct mg_connection),
  13291. ctx);
  13292. if (ctx->worker_connections == NULL) {
  13293. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  13294. free_context(ctx);
  13295. pthread_setspecific(sTlsKey, NULL);
  13296. return NULL;
  13297. }
  13298. #if defined(ALTERNATIVE_QUEUE)
  13299. ctx->client_wait_events = mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  13300. ctx->cfg_worker_threads,
  13301. ctx);
  13302. if (ctx->client_wait_events == NULL) {
  13303. mg_cry(fc(ctx), "Not enough memory for worker event array");
  13304. mg_free(ctx->worker_threadids);
  13305. free_context(ctx);
  13306. pthread_setspecific(sTlsKey, NULL);
  13307. return NULL;
  13308. }
  13309. ctx->client_socks = mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  13310. ctx->cfg_worker_threads,
  13311. ctx);
  13312. if (ctx->client_wait_events == NULL) {
  13313. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  13314. mg_free(ctx->client_socks);
  13315. mg_free(ctx->worker_threadids);
  13316. free_context(ctx);
  13317. pthread_setspecific(sTlsKey, NULL);
  13318. return NULL;
  13319. }
  13320. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13321. ctx->client_wait_events[i] = event_create();
  13322. if (ctx->client_wait_events[i] == 0) {
  13323. mg_cry(fc(ctx), "Error creating worker event %i", i);
  13324. while (i > 0) {
  13325. i--;
  13326. event_destroy(ctx->client_wait_events[i]);
  13327. }
  13328. mg_free(ctx->client_socks);
  13329. mg_free(ctx->worker_threadids);
  13330. free_context(ctx);
  13331. pthread_setspecific(sTlsKey, NULL);
  13332. return NULL;
  13333. }
  13334. }
  13335. #endif
  13336. #if defined(USE_TIMERS)
  13337. if (timers_init(ctx) != 0) {
  13338. mg_cry(fc(ctx), "Error creating timers");
  13339. free_context(ctx);
  13340. pthread_setspecific(sTlsKey, NULL);
  13341. return NULL;
  13342. }
  13343. #endif
  13344. /* Context has been created - init user libraries */
  13345. if (ctx->callbacks.init_context) {
  13346. ctx->callbacks.init_context(ctx);
  13347. }
  13348. ctx->callbacks.exit_context = exit_callback;
  13349. ctx->context_type = 1; /* server context */
  13350. /* Start master (listening) thread */
  13351. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  13352. /* Start worker threads */
  13353. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13354. struct worker_thread_args *wta = (struct worker_thread_args *)
  13355. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  13356. if (wta) {
  13357. wta->ctx = ctx;
  13358. wta->index = (int)i;
  13359. }
  13360. if ((wta == NULL)
  13361. || (mg_start_thread_with_id(worker_thread,
  13362. wta,
  13363. &ctx->worker_threadids[i]) != 0)) {
  13364. /* thread was not created */
  13365. if (wta != NULL) {
  13366. mg_free(wta);
  13367. }
  13368. if (i > 0) {
  13369. mg_cry(fc(ctx),
  13370. "Cannot start worker thread %i: error %ld",
  13371. i + 1,
  13372. (long)ERRNO);
  13373. } else {
  13374. mg_cry(fc(ctx),
  13375. "Cannot create threads: error %ld",
  13376. (long)ERRNO);
  13377. free_context(ctx);
  13378. pthread_setspecific(sTlsKey, NULL);
  13379. return NULL;
  13380. }
  13381. break;
  13382. }
  13383. }
  13384. pthread_setspecific(sTlsKey, NULL);
  13385. return ctx;
  13386. }
  13387. /* Feature check API function */
  13388. unsigned
  13389. mg_check_feature(unsigned feature)
  13390. {
  13391. static const unsigned feature_set = 0
  13392. /* Set bits for available features according to API documentation.
  13393. * This bit mask is created at compile time, according to the active
  13394. * preprocessor defines. It is a single const value at runtime. */
  13395. #if !defined(NO_FILES)
  13396. | 0x0001u
  13397. #endif
  13398. #if !defined(NO_SSL)
  13399. | 0x0002u
  13400. #endif
  13401. #if !defined(NO_CGI)
  13402. | 0x0004u
  13403. #endif
  13404. #if defined(USE_IPV6)
  13405. | 0x0008u
  13406. #endif
  13407. #if defined(USE_WEBSOCKET)
  13408. | 0x0010u
  13409. #endif
  13410. #if defined(USE_LUA)
  13411. | 0x0020u
  13412. #endif
  13413. #if defined(USE_DUKTAPE)
  13414. | 0x0040u
  13415. #endif
  13416. #if !defined(NO_CACHING)
  13417. | 0x0080u
  13418. #endif
  13419. #if defined(USE_SERVER_STATS)
  13420. | 0x0100u
  13421. #endif
  13422. /* Set some extra bits not defined in the API documentation.
  13423. * These bits may change without further notice. */
  13424. #if defined(MG_LEGACY_INTERFACE)
  13425. | 0x8000u
  13426. #endif
  13427. #if defined(MEMORY_DEBUGGING)
  13428. | 0x0100u
  13429. #endif
  13430. #if defined(USE_TIMERS)
  13431. | 0x0200u
  13432. #endif
  13433. #if !defined(NO_NONCE_CHECK)
  13434. | 0x0400u
  13435. #endif
  13436. #if !defined(NO_POPEN)
  13437. | 0x0800u
  13438. #endif
  13439. ;
  13440. return (feature & feature_set);
  13441. }
  13442. /* Get system information. It can be printed or stored by the caller.
  13443. * Return the size of available information. */
  13444. static int
  13445. mg_get_system_info_impl(char *buffer, int buflen)
  13446. {
  13447. char block[256];
  13448. int system_info_length = 0;
  13449. #if defined(_WIN32)
  13450. const char *eol = "\r\n";
  13451. #else
  13452. const char *eol = "\n";
  13453. #endif
  13454. if (buffer == NULL) {
  13455. /* Avoid some warning (although, if some dillweed supplies
  13456. * buffer==NULL combined with buflen>0, he deserves a crash).
  13457. */
  13458. buflen = 0;
  13459. }
  13460. /* Server version */
  13461. {
  13462. const char *version = mg_version();
  13463. mg_snprintf(NULL,
  13464. NULL,
  13465. block,
  13466. sizeof(block),
  13467. "Server Version: %s%s",
  13468. version,
  13469. eol);
  13470. system_info_length += (int)strlen(block);
  13471. if (system_info_length < buflen) {
  13472. strcat(buffer, block);
  13473. }
  13474. }
  13475. /* System info */
  13476. {
  13477. #if defined(_WIN32)
  13478. #if !defined(__SYMBIAN32__)
  13479. DWORD dwVersion = 0;
  13480. DWORD dwMajorVersion = 0;
  13481. DWORD dwMinorVersion = 0;
  13482. SYSTEM_INFO si;
  13483. GetSystemInfo(&si);
  13484. #ifdef _MSC_VER
  13485. #pragma warning(push)
  13486. /* GetVersion was declared deprecated */
  13487. #pragma warning(disable : 4996)
  13488. #endif
  13489. dwVersion = GetVersion();
  13490. #ifdef _MSC_VER
  13491. #pragma warning(pop)
  13492. #endif
  13493. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13494. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13495. mg_snprintf(NULL,
  13496. NULL,
  13497. block,
  13498. sizeof(block),
  13499. "Windows %u.%u%s",
  13500. (unsigned)dwMajorVersion,
  13501. (unsigned)dwMinorVersion,
  13502. eol);
  13503. system_info_length += (int)strlen(block);
  13504. if (system_info_length < buflen) {
  13505. strcat(buffer, block);
  13506. }
  13507. mg_snprintf(NULL,
  13508. NULL,
  13509. block,
  13510. sizeof(block),
  13511. "CPU: type %u, cores %u, mask %x%s",
  13512. (unsigned)si.wProcessorArchitecture,
  13513. (unsigned)si.dwNumberOfProcessors,
  13514. (unsigned)si.dwActiveProcessorMask,
  13515. eol);
  13516. system_info_length += (int)strlen(block);
  13517. if (system_info_length < buflen) {
  13518. strcat(buffer, block);
  13519. }
  13520. #else
  13521. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  13522. system_info_length += (int)strlen(block);
  13523. if (system_info_length < buflen) {
  13524. strcat(buffer, block);
  13525. }
  13526. #endif
  13527. #else
  13528. struct utsname name;
  13529. memset(&name, 0, sizeof(name));
  13530. uname(&name);
  13531. mg_snprintf(NULL,
  13532. NULL,
  13533. block,
  13534. sizeof(block),
  13535. "%s %s (%s) - %s%s",
  13536. name.sysname,
  13537. name.version,
  13538. name.release,
  13539. name.machine,
  13540. eol);
  13541. system_info_length += (int)strlen(block);
  13542. if (system_info_length < buflen) {
  13543. strcat(buffer, block);
  13544. }
  13545. #endif
  13546. }
  13547. /* Features */
  13548. {
  13549. mg_snprintf(NULL,
  13550. NULL,
  13551. block,
  13552. sizeof(block),
  13553. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  13554. mg_check_feature(0xFFFFFFFFu),
  13555. eol,
  13556. mg_check_feature(1) ? " Files" : "",
  13557. mg_check_feature(2) ? " HTTPS" : "",
  13558. mg_check_feature(4) ? " CGI" : "",
  13559. mg_check_feature(8) ? " IPv6" : "",
  13560. mg_check_feature(16) ? " WebSockets" : "",
  13561. mg_check_feature(32) ? " Lua" : "",
  13562. mg_check_feature(64) ? " JavaScript" : "",
  13563. mg_check_feature(128) ? " Cache" : "",
  13564. eol);
  13565. system_info_length += (int)strlen(block);
  13566. if (system_info_length < buflen) {
  13567. strcat(buffer, block);
  13568. }
  13569. #ifdef USE_LUA
  13570. mg_snprintf(NULL,
  13571. NULL,
  13572. block,
  13573. sizeof(block),
  13574. "Lua Version: %u (%s)%s",
  13575. (unsigned)LUA_VERSION_NUM,
  13576. LUA_RELEASE,
  13577. eol);
  13578. system_info_length += (int)strlen(block);
  13579. if (system_info_length < buflen) {
  13580. strcat(buffer, block);
  13581. }
  13582. #endif
  13583. #if defined(USE_DUKTAPE)
  13584. mg_snprintf(NULL,
  13585. NULL,
  13586. block,
  13587. sizeof(block),
  13588. "JavaScript: Duktape %u.%u.%u%s",
  13589. (unsigned)DUK_VERSION / 10000,
  13590. ((unsigned)DUK_VERSION / 100) % 100,
  13591. (unsigned)DUK_VERSION % 100,
  13592. eol);
  13593. system_info_length += (int)strlen(block);
  13594. if (system_info_length < buflen) {
  13595. strcat(buffer, block);
  13596. }
  13597. #endif
  13598. }
  13599. /* Build date */
  13600. {
  13601. mg_snprintf(
  13602. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  13603. system_info_length += (int)strlen(block);
  13604. if (system_info_length < buflen) {
  13605. strcat(buffer, block);
  13606. }
  13607. }
  13608. /* Compiler information */
  13609. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  13610. {
  13611. #if defined(_MSC_VER)
  13612. mg_snprintf(NULL,
  13613. NULL,
  13614. block,
  13615. sizeof(block),
  13616. "MSC: %u (%u)%s",
  13617. (unsigned)_MSC_VER,
  13618. (unsigned)_MSC_FULL_VER,
  13619. eol);
  13620. system_info_length += (int)strlen(block);
  13621. if (system_info_length < buflen) {
  13622. strcat(buffer, block);
  13623. }
  13624. #elif defined(__MINGW64__)
  13625. mg_snprintf(NULL,
  13626. NULL,
  13627. block,
  13628. sizeof(block),
  13629. "MinGW64: %u.%u%s",
  13630. (unsigned)__MINGW64_VERSION_MAJOR,
  13631. (unsigned)__MINGW64_VERSION_MINOR,
  13632. eol);
  13633. system_info_length += (int)strlen(block);
  13634. if (system_info_length < buflen) {
  13635. strcat(buffer, block);
  13636. }
  13637. mg_snprintf(NULL,
  13638. NULL,
  13639. block,
  13640. sizeof(block),
  13641. "MinGW32: %u.%u%s",
  13642. (unsigned)__MINGW32_MAJOR_VERSION,
  13643. (unsigned)__MINGW32_MINOR_VERSION,
  13644. eol);
  13645. system_info_length += (int)strlen(block);
  13646. if (system_info_length < buflen) {
  13647. strcat(buffer, block);
  13648. }
  13649. #elif defined(__MINGW32__)
  13650. mg_snprintf(NULL,
  13651. NULL,
  13652. block,
  13653. sizeof(block),
  13654. "MinGW32: %u.%u%s",
  13655. (unsigned)__MINGW32_MAJOR_VERSION,
  13656. (unsigned)__MINGW32_MINOR_VERSION,
  13657. eol);
  13658. system_info_length += (int)strlen(block);
  13659. if (system_info_length < buflen) {
  13660. strcat(buffer, block);
  13661. }
  13662. #elif defined(__clang__)
  13663. mg_snprintf(NULL,
  13664. NULL,
  13665. block,
  13666. sizeof(block),
  13667. "clang: %u.%u.%u (%s)%s",
  13668. __clang_major__,
  13669. __clang_minor__,
  13670. __clang_patchlevel__,
  13671. __clang_version__,
  13672. eol);
  13673. system_info_length += (int)strlen(block);
  13674. if (system_info_length < buflen) {
  13675. strcat(buffer, block);
  13676. }
  13677. #elif defined(__GNUC__)
  13678. mg_snprintf(NULL,
  13679. NULL,
  13680. block,
  13681. sizeof(block),
  13682. "gcc: %u.%u.%u%s",
  13683. (unsigned)__GNUC__,
  13684. (unsigned)__GNUC_MINOR__,
  13685. (unsigned)__GNUC_PATCHLEVEL__,
  13686. eol);
  13687. system_info_length += (int)strlen(block);
  13688. if (system_info_length < buflen) {
  13689. strcat(buffer, block);
  13690. }
  13691. #elif defined(__INTEL_COMPILER)
  13692. mg_snprintf(NULL,
  13693. NULL,
  13694. block,
  13695. sizeof(block),
  13696. "Intel C/C++: %u%s",
  13697. (unsigned)__INTEL_COMPILER,
  13698. eol);
  13699. system_info_length += (int)strlen(block);
  13700. if (system_info_length < buflen) {
  13701. strcat(buffer, block);
  13702. }
  13703. #elif defined(__BORLANDC__)
  13704. mg_snprintf(NULL,
  13705. NULL,
  13706. block,
  13707. sizeof(block),
  13708. "Borland C: 0x%x%s",
  13709. (unsigned)__BORLANDC__,
  13710. eol);
  13711. system_info_length += (int)strlen(block);
  13712. if (system_info_length < buflen) {
  13713. strcat(buffer, block);
  13714. }
  13715. #elif defined(__SUNPRO_C)
  13716. mg_snprintf(NULL,
  13717. NULL,
  13718. block,
  13719. sizeof(block),
  13720. "Solaris: 0x%x%s",
  13721. (unsigned)__SUNPRO_C,
  13722. eol);
  13723. system_info_length += (int)strlen(block);
  13724. if (system_info_length < buflen) {
  13725. strcat(buffer, block);
  13726. }
  13727. #else
  13728. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13729. system_info_length += (int)strlen(block);
  13730. if (system_info_length < buflen) {
  13731. strcat(buffer, block);
  13732. }
  13733. #endif
  13734. }
  13735. /* Determine 32/64 bit data mode.
  13736. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13737. {
  13738. mg_snprintf(NULL,
  13739. NULL,
  13740. block,
  13741. sizeof(block),
  13742. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13743. "ptr:%u, size:%u, time:%u%s",
  13744. (unsigned)sizeof(short),
  13745. (unsigned)sizeof(int),
  13746. (unsigned)sizeof(long),
  13747. (unsigned)sizeof(long long),
  13748. (unsigned)sizeof(float),
  13749. (unsigned)sizeof(double),
  13750. (unsigned)sizeof(long double),
  13751. (unsigned)sizeof(char),
  13752. (unsigned)sizeof(wchar_t),
  13753. (unsigned)sizeof(void *),
  13754. (unsigned)sizeof(size_t),
  13755. (unsigned)sizeof(time_t),
  13756. eol);
  13757. system_info_length += (int)strlen(block);
  13758. if (system_info_length < buflen) {
  13759. strcat(buffer, block);
  13760. }
  13761. }
  13762. return system_info_length;
  13763. }
  13764. #if defined(USE_SERVER_STATS)
  13765. /* Get context information. It can be printed or stored by the caller.
  13766. * Return the size of available information. */
  13767. static int
  13768. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  13769. {
  13770. char block[256];
  13771. int context_info_length = 0;
  13772. #if defined(_WIN32)
  13773. const char *eol = "\r\n";
  13774. #else
  13775. const char *eol = "\n";
  13776. #endif
  13777. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  13778. const char *eoobj = "}";
  13779. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  13780. if ((buffer == NULL) || (buflen < 10)) {
  13781. buflen = 0;
  13782. }
  13783. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  13784. context_info_length += (int)strlen(block);
  13785. if (context_info_length < buflen) {
  13786. strcat(buffer, block);
  13787. }
  13788. /* Memory information */
  13789. if (ms) {
  13790. mg_snprintf(NULL,
  13791. NULL,
  13792. block,
  13793. sizeof(block),
  13794. "\"memory\" : {%s"
  13795. "\"blocks\" : %i,%s"
  13796. "\"used\" : %" INT64_FMT ",%s"
  13797. "\"maxUsed\" : %" INT64_FMT "%s"
  13798. "}%s%s",
  13799. eol,
  13800. ms->blockCount,
  13801. eol,
  13802. ms->totalMemUsed,
  13803. eol,
  13804. ms->maxMemUsed,
  13805. eol,
  13806. (ctx ? "," : ""),
  13807. eol);
  13808. context_info_length += (int)strlen(block);
  13809. if (context_info_length + reserved_len < buflen) {
  13810. strcat(buffer, block);
  13811. }
  13812. }
  13813. /* Connections information */
  13814. if (ctx) {
  13815. mg_snprintf(NULL,
  13816. NULL,
  13817. block,
  13818. sizeof(block),
  13819. "\"connections\" : {%s"
  13820. "\"active\" : %i,%s"
  13821. "\"maxActive\" : %i,%s"
  13822. "\"total\" : %" INT64_FMT "%s"
  13823. "},%s",
  13824. eol,
  13825. ctx->active_connections,
  13826. eol,
  13827. ctx->max_connections,
  13828. eol,
  13829. ctx->total_connections,
  13830. eol,
  13831. eol);
  13832. context_info_length += (int)strlen(block);
  13833. if (context_info_length + reserved_len < buflen) {
  13834. strcat(buffer, block);
  13835. }
  13836. }
  13837. /* Requests information */
  13838. if (ctx) {
  13839. mg_snprintf(NULL,
  13840. NULL,
  13841. block,
  13842. sizeof(block),
  13843. "\"requests\" : {%s"
  13844. "\"total\" : %" INT64_FMT "%s"
  13845. "}%s",
  13846. eol,
  13847. ctx->total_requests,
  13848. eol,
  13849. eol);
  13850. context_info_length += (int)strlen(block);
  13851. if (context_info_length + reserved_len < buflen) {
  13852. strcat(buffer, block);
  13853. }
  13854. }
  13855. if ((buflen > 0) && buffer && buffer[0]) {
  13856. if (context_info_length < buflen) {
  13857. strcat(buffer, eoobj);
  13858. strcat(buffer, eol);
  13859. context_info_length += reserved_len;
  13860. }
  13861. }
  13862. return context_info_length;
  13863. }
  13864. #endif
  13865. /* Get system information. It can be printed or stored by the caller.
  13866. * Return the size of available information. */
  13867. int
  13868. mg_get_system_info(char *buffer, int buflen)
  13869. {
  13870. if ((buffer == NULL) || (buflen < 1)) {
  13871. return mg_get_system_info_impl(NULL, 0);
  13872. } else {
  13873. /* Reset buffer, so we can always use strcat. */
  13874. buffer[0] = 0;
  13875. return mg_get_system_info_impl(buffer, buflen);
  13876. }
  13877. }
  13878. /* Get context information. It can be printed or stored by the caller.
  13879. * Return the size of available information. */
  13880. int
  13881. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  13882. {
  13883. #if defined(USE_SERVER_STATS)
  13884. if ((buffer == NULL) || (buflen < 1)) {
  13885. return mg_get_context_info_impl(ctx, NULL, 0);
  13886. } else {
  13887. /* Reset buffer, so we can always use strcat. */
  13888. buffer[0] = 0;
  13889. return mg_get_context_info_impl(ctx, buffer, buflen);
  13890. }
  13891. #else
  13892. (void)ctx;
  13893. if ((buffer != NULL) && (buflen > 0)) {
  13894. buffer[0] = 0;
  13895. }
  13896. return 0;
  13897. #endif
  13898. }
  13899. /* mg_init_library counter */
  13900. static int mg_init_library_called = 0;
  13901. #if !defined(NO_SSL)
  13902. static int mg_ssl_initialized = 0;
  13903. #endif
  13904. /* Initialize this library. This function does not need to be thread safe. */
  13905. unsigned
  13906. mg_init_library(unsigned features)
  13907. {
  13908. #if !defined(NO_SSL)
  13909. char ebuf[128];
  13910. #endif
  13911. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  13912. unsigned features_inited = features_to_init;
  13913. #if !defined(NO_SSL)
  13914. if (features_to_init & 2) {
  13915. if (!mg_ssl_initialized) {
  13916. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  13917. mg_ssl_initialized = 1;
  13918. } else {
  13919. (void)ebuf;
  13920. /* TODO: print error */
  13921. features_inited &= ~(2u);
  13922. }
  13923. } else {
  13924. /* ssl already initialized */
  13925. }
  13926. }
  13927. #endif
  13928. /* Start Windows. */
  13929. if (mg_init_library_called <= 0) {
  13930. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13931. WSADATA data;
  13932. WSAStartup(MAKEWORD(2, 2), &data);
  13933. #endif /* _WIN32 && !__SYMBIAN32__ */
  13934. mg_init_library_called = 1;
  13935. } else {
  13936. mg_init_library_called++;
  13937. }
  13938. return features_inited;
  13939. }
  13940. /* Un-initialize this library. */
  13941. unsigned
  13942. mg_exit_library(void)
  13943. {
  13944. if (mg_init_library_called <= 0) {
  13945. return 0;
  13946. }
  13947. mg_init_library_called--;
  13948. if (mg_init_library_called == 0) {
  13949. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13950. (void)WSACleanup();
  13951. #endif /* _WIN32 && !__SYMBIAN32__ */
  13952. #if !defined(NO_SSL)
  13953. if (mg_ssl_initialized) {
  13954. uninitialize_ssl();
  13955. mg_ssl_initialized = 0;
  13956. }
  13957. #endif
  13958. }
  13959. return 1;
  13960. }
  13961. /* End of civetweb.c */