civetweb.c 445 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927
  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. #if defined(__GNUC__) || defined(__MINGW32__)
  109. #define FUNCTION_MAY_BE_UNUSED __attribute__((unused))
  110. #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  111. #else
  112. #define FUNCTION_MAY_BE_UNUSED
  113. #endif
  114. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  115. #include <sys/types.h>
  116. #include <sys/stat.h>
  117. #include <errno.h>
  118. #include <signal.h>
  119. #include <fcntl.h>
  120. #endif /* !_WIN32_WCE */
  121. #ifdef __clang__
  122. /* When using -Weverything, clang does not accept it's own headers
  123. * in a release build configuration. Disable what is too much in
  124. * -Weverything. */
  125. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  126. #endif
  127. #ifdef __MACH__ /* Apple OSX section */
  128. #ifdef __clang__
  129. /* Avoid warnings for Xopen 7.00 and higher */
  130. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  131. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  132. #endif
  133. #define CLOCK_MONOTONIC (1)
  134. #define CLOCK_REALTIME (2)
  135. #include <sys/errno.h>
  136. #include <sys/time.h>
  137. #include <mach/clock.h>
  138. #include <mach/mach.h>
  139. #include <mach/mach_time.h>
  140. #include <assert.h>
  141. /* clock_gettime is not implemented on OSX prior to 10.12 */
  142. static int
  143. _civet_clock_gettime(int clk_id, struct timespec *t)
  144. {
  145. memset(t, 0, sizeof(*t));
  146. if (clk_id == CLOCK_REALTIME) {
  147. struct timeval now;
  148. int rv = gettimeofday(&now, NULL);
  149. if (rv) {
  150. return rv;
  151. }
  152. t->tv_sec = now.tv_sec;
  153. t->tv_nsec = now.tv_usec * 1000;
  154. return 0;
  155. } else if (clk_id == CLOCK_MONOTONIC) {
  156. static uint64_t clock_start_time = 0;
  157. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  158. uint64_t now = mach_absolute_time();
  159. if (clock_start_time == 0) {
  160. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  161. #if defined(DEBUG)
  162. assert(mach_status == KERN_SUCCESS);
  163. #else
  164. /* appease "unused variable" warning for release builds */
  165. (void)mach_status;
  166. #endif
  167. clock_start_time = now;
  168. }
  169. now = (uint64_t)((double)(now - clock_start_time)
  170. * (double)timebase_ifo.numer
  171. / (double)timebase_ifo.denom);
  172. t->tv_sec = now / 1000000000;
  173. t->tv_nsec = now % 1000000000;
  174. return 0;
  175. }
  176. return -1; /* EINVAL - Clock ID is unknown */
  177. }
  178. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  179. #ifdef __CLOCK_AVAILABILITY
  180. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  181. * declared but it may be NULL at runtime. So we need to check before using
  182. * it. */
  183. static int
  184. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  185. {
  186. if (clock_gettime) {
  187. return clock_gettime(clk_id, t);
  188. }
  189. return _civet_clock_gettime(clk_id, t);
  190. }
  191. #define clock_gettime _civet_safe_clock_gettime
  192. #else
  193. #define clock_gettime _civet_clock_gettime
  194. #endif
  195. #endif
  196. #include <time.h>
  197. #include <stdlib.h>
  198. #include <stdarg.h>
  199. #include <assert.h>
  200. #include <string.h>
  201. #include <ctype.h>
  202. #include <limits.h>
  203. #include <stddef.h>
  204. #include <stdio.h>
  205. #include <stdint.h>
  206. #ifndef INT64_MAX
  207. #define INT64_MAX (9223372036854775807)
  208. #endif
  209. #ifndef MAX_WORKER_THREADS
  210. #define MAX_WORKER_THREADS (1024 * 64)
  211. #endif
  212. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  213. #define SOCKET_TIMEOUT_QUANTUM (2000)
  214. #endif
  215. #define SHUTDOWN_RD (0)
  216. #define SHUTDOWN_WR (1)
  217. #define SHUTDOWN_BOTH (2)
  218. mg_static_assert(MAX_WORKER_THREADS >= 1,
  219. "worker threads must be a positive number");
  220. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  221. "size_t data type size check");
  222. #if defined(_WIN32) \
  223. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  224. #include <windows.h>
  225. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  226. #include <ws2tcpip.h>
  227. typedef const char *SOCK_OPT_TYPE;
  228. #if !defined(PATH_MAX)
  229. #define PATH_MAX (MAX_PATH)
  230. #endif
  231. #if !defined(PATH_MAX)
  232. #define PATH_MAX (4096)
  233. #endif
  234. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  235. #ifndef _IN_PORT_T
  236. #ifndef in_port_t
  237. #define in_port_t u_short
  238. #endif
  239. #endif
  240. #ifndef _WIN32_WCE
  241. #include <process.h>
  242. #include <direct.h>
  243. #include <io.h>
  244. #else /* _WIN32_WCE */
  245. #define NO_CGI /* WinCE has no pipes */
  246. #define NO_POPEN /* WinCE has no popen */
  247. typedef long off_t;
  248. #define errno ((int)(GetLastError()))
  249. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  250. #endif /* _WIN32_WCE */
  251. #define MAKEUQUAD(lo, hi) \
  252. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  253. #define RATE_DIFF (10000000) /* 100 nsecs */
  254. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  255. #define SYS2UNIX_TIME(lo, hi) \
  256. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  257. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  258. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  259. * Also use _strtoui64 on modern M$ compilers */
  260. #if defined(_MSC_VER)
  261. #if (_MSC_VER < 1300)
  262. #define STRX(x) #x
  263. #define STR(x) STRX(x)
  264. #define __func__ __FILE__ ":" STR(__LINE__)
  265. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  266. #define strtoll(x, y, z) (_atoi64(x))
  267. #else
  268. #define __func__ __FUNCTION__
  269. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  270. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  271. #endif
  272. #endif /* _MSC_VER */
  273. #define ERRNO ((int)(GetLastError()))
  274. #define NO_SOCKLEN_T
  275. #if defined(_WIN64) || defined(__MINGW64__)
  276. #define SSL_LIB "ssleay64.dll"
  277. #define CRYPTO_LIB "libeay64.dll"
  278. #else
  279. #define SSL_LIB "ssleay32.dll"
  280. #define CRYPTO_LIB "libeay32.dll"
  281. #endif
  282. #define O_NONBLOCK (0)
  283. #ifndef W_OK
  284. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  285. #endif
  286. #if !defined(EWOULDBLOCK)
  287. #define EWOULDBLOCK WSAEWOULDBLOCK
  288. #endif /* !EWOULDBLOCK */
  289. #define _POSIX_
  290. #define INT64_FMT "I64d"
  291. #define UINT64_FMT "I64u"
  292. #define WINCDECL __cdecl
  293. #define vsnprintf_impl _vsnprintf
  294. #define access _access
  295. #define mg_sleep(x) (Sleep(x))
  296. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  297. #ifndef popen
  298. #define popen(x, y) (_popen(x, y))
  299. #endif
  300. #ifndef pclose
  301. #define pclose(x) (_pclose(x))
  302. #endif
  303. #define close(x) (_close(x))
  304. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  305. #define RTLD_LAZY (0)
  306. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  307. #define fdopen(x, y) (_fdopen((x), (y)))
  308. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  309. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  310. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  311. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  312. #define sleep(x) (Sleep((x)*1000))
  313. #define rmdir(x) (_rmdir(x))
  314. #define timegm(x) (_mkgmtime(x))
  315. #if !defined(fileno)
  316. #define fileno(x) (_fileno(x))
  317. #endif /* !fileno MINGW #defines fileno */
  318. typedef HANDLE pthread_mutex_t;
  319. typedef DWORD pthread_key_t;
  320. typedef HANDLE pthread_t;
  321. typedef struct {
  322. CRITICAL_SECTION threadIdSec;
  323. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  324. } pthread_cond_t;
  325. #ifndef __clockid_t_defined
  326. typedef DWORD clockid_t;
  327. #endif
  328. #ifndef CLOCK_MONOTONIC
  329. #define CLOCK_MONOTONIC (1)
  330. #endif
  331. #ifndef CLOCK_REALTIME
  332. #define CLOCK_REALTIME (2)
  333. #endif
  334. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  335. #define _TIMESPEC_DEFINED
  336. #endif
  337. #ifndef _TIMESPEC_DEFINED
  338. struct timespec {
  339. time_t tv_sec; /* seconds */
  340. long tv_nsec; /* nanoseconds */
  341. };
  342. #endif
  343. #if !defined(WIN_PTHREADS_TIME_H)
  344. #define MUST_IMPLEMENT_CLOCK_GETTIME
  345. #endif
  346. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  347. #define clock_gettime mg_clock_gettime
  348. static int
  349. clock_gettime(clockid_t clk_id, struct timespec *tp)
  350. {
  351. FILETIME ft;
  352. ULARGE_INTEGER li;
  353. BOOL ok = FALSE;
  354. double d;
  355. static double perfcnt_per_sec = 0.0;
  356. if (tp) {
  357. memset(tp, 0, sizeof(*tp));
  358. if (clk_id == CLOCK_REALTIME) {
  359. GetSystemTimeAsFileTime(&ft);
  360. li.LowPart = ft.dwLowDateTime;
  361. li.HighPart = ft.dwHighDateTime;
  362. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  363. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  364. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  365. ok = TRUE;
  366. } else if (clk_id == CLOCK_MONOTONIC) {
  367. if (perfcnt_per_sec == 0.0) {
  368. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  369. perfcnt_per_sec = 1.0 / li.QuadPart;
  370. }
  371. if (perfcnt_per_sec != 0.0) {
  372. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  373. d = li.QuadPart * perfcnt_per_sec;
  374. tp->tv_sec = (time_t)d;
  375. d -= tp->tv_sec;
  376. tp->tv_nsec = (long)(d * 1.0E9);
  377. ok = TRUE;
  378. }
  379. }
  380. }
  381. return ok ? 0 : -1;
  382. }
  383. #endif
  384. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  385. static int pthread_mutex_lock(pthread_mutex_t *);
  386. static int pthread_mutex_unlock(pthread_mutex_t *);
  387. static void path_to_unicode(const struct mg_connection *conn,
  388. const char *path,
  389. wchar_t *wbuf,
  390. size_t wbuf_len);
  391. /* All file operations need to be rewritten to solve #246. */
  392. #include "file_ops.inl"
  393. struct mg_file;
  394. static const char *
  395. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  396. /* POSIX dirent interface */
  397. struct dirent {
  398. char d_name[PATH_MAX];
  399. };
  400. typedef struct DIR {
  401. HANDLE handle;
  402. WIN32_FIND_DATAW info;
  403. struct dirent result;
  404. } DIR;
  405. #if defined(_WIN32) && !defined(POLLIN)
  406. #ifndef HAVE_POLL
  407. struct pollfd {
  408. SOCKET fd;
  409. short events;
  410. short revents;
  411. };
  412. #define POLLIN (0x0300)
  413. #endif
  414. #endif
  415. /* Mark required libraries */
  416. #if defined(_MSC_VER)
  417. #pragma comment(lib, "Ws2_32.lib")
  418. #endif
  419. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  420. WINDOWS / UNIX include block */
  421. #include <sys/wait.h>
  422. #include <sys/socket.h>
  423. #include <sys/poll.h>
  424. #include <netinet/in.h>
  425. #include <arpa/inet.h>
  426. #include <sys/time.h>
  427. #include <sys/utsname.h>
  428. #include <stdint.h>
  429. #include <inttypes.h>
  430. #include <netdb.h>
  431. #include <netinet/tcp.h>
  432. typedef const void *SOCK_OPT_TYPE;
  433. #if defined(ANDROID)
  434. typedef unsigned short int in_port_t;
  435. #endif
  436. #include <pwd.h>
  437. #include <unistd.h>
  438. #include <grp.h>
  439. #include <dirent.h>
  440. #define vsnprintf_impl vsnprintf
  441. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  442. #include <dlfcn.h>
  443. #endif
  444. #include <pthread.h>
  445. #if defined(__MACH__)
  446. #define SSL_LIB "libssl.dylib"
  447. #define CRYPTO_LIB "libcrypto.dylib"
  448. #else
  449. #if !defined(SSL_LIB)
  450. #define SSL_LIB "libssl.so"
  451. #endif
  452. #if !defined(CRYPTO_LIB)
  453. #define CRYPTO_LIB "libcrypto.so"
  454. #endif
  455. #endif
  456. #ifndef O_BINARY
  457. #define O_BINARY (0)
  458. #endif /* O_BINARY */
  459. #define closesocket(a) (close(a))
  460. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  461. #define mg_remove(conn, x) (remove(x))
  462. #define mg_sleep(x) (usleep((x)*1000))
  463. #define mg_opendir(conn, x) (opendir(x))
  464. #define mg_closedir(x) (closedir(x))
  465. #define mg_readdir(x) (readdir(x))
  466. #define ERRNO (errno)
  467. #define INVALID_SOCKET (-1)
  468. #define INT64_FMT PRId64
  469. #define UINT64_FMT PRIu64
  470. typedef int SOCKET;
  471. #define WINCDECL
  472. #if defined(__hpux)
  473. /* HPUX 11 does not have monotonic, fall back to realtime */
  474. #ifndef CLOCK_MONOTONIC
  475. #define CLOCK_MONOTONIC CLOCK_REALTIME
  476. #endif
  477. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  478. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  479. * the prototypes use int* rather than socklen_t* which matches the
  480. * actual library expectation. When called with the wrong size arg
  481. * accept() returns a zero client inet addr and check_acl() always
  482. * fails. Since socklen_t is widely used below, just force replace
  483. * their typedef with int. - DTL
  484. */
  485. #define socklen_t int
  486. #endif /* hpux */
  487. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  488. WINDOWS / UNIX include block */
  489. /* va_copy should always be a macro, C99 and C++11 - DTL */
  490. #ifndef va_copy
  491. #define va_copy(x, y) ((x) = (y))
  492. #endif
  493. #ifdef _WIN32
  494. /* Create substitutes for POSIX functions in Win32. */
  495. #if defined(__MINGW32__)
  496. /* Show no warning in case system functions are not used. */
  497. #pragma GCC diagnostic push
  498. #pragma GCC diagnostic ignored "-Wunused-function"
  499. #endif
  500. static CRITICAL_SECTION global_log_file_lock;
  501. FUNCTION_MAY_BE_UNUSED
  502. static DWORD
  503. pthread_self(void)
  504. {
  505. return GetCurrentThreadId();
  506. }
  507. FUNCTION_MAY_BE_UNUSED
  508. static int
  509. pthread_key_create(
  510. pthread_key_t *key,
  511. void (*_ignored)(void *) /* destructor not supported for Windows */
  512. )
  513. {
  514. (void)_ignored;
  515. if ((key != 0)) {
  516. *key = TlsAlloc();
  517. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  518. }
  519. return -2;
  520. }
  521. FUNCTION_MAY_BE_UNUSED
  522. static int
  523. pthread_key_delete(pthread_key_t key)
  524. {
  525. return TlsFree(key) ? 0 : 1;
  526. }
  527. FUNCTION_MAY_BE_UNUSED
  528. static int
  529. pthread_setspecific(pthread_key_t key, void *value)
  530. {
  531. return TlsSetValue(key, value) ? 0 : 1;
  532. }
  533. FUNCTION_MAY_BE_UNUSED
  534. static void *
  535. pthread_getspecific(pthread_key_t key)
  536. {
  537. return TlsGetValue(key);
  538. }
  539. #if defined(__MINGW32__)
  540. /* Enable unused function warning again */
  541. #pragma GCC diagnostic pop
  542. #endif
  543. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  544. #else
  545. static pthread_mutexattr_t pthread_mutex_attr;
  546. #endif /* _WIN32 */
  547. #define PASSWORDS_FILE_NAME ".htpasswd"
  548. #define CGI_ENVIRONMENT_SIZE (4096)
  549. #define MAX_CGI_ENVIR_VARS (256)
  550. #define MG_BUF_LEN (8192)
  551. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  552. #if defined(_WIN32_WCE)
  553. /* Create substitutes for POSIX functions in Win32. */
  554. #if defined(__MINGW32__)
  555. /* Show no warning in case system functions are not used. */
  556. #pragma GCC diagnostic push
  557. #pragma GCC diagnostic ignored "-Wunused-function"
  558. #endif
  559. FUNCTION_MAY_BE_UNUSED
  560. static time_t
  561. time(time_t *ptime)
  562. {
  563. time_t t;
  564. SYSTEMTIME st;
  565. FILETIME ft;
  566. GetSystemTime(&st);
  567. SystemTimeToFileTime(&st, &ft);
  568. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  569. if (ptime != NULL) {
  570. *ptime = t;
  571. }
  572. return t;
  573. }
  574. FUNCTION_MAY_BE_UNUSED
  575. static struct tm *
  576. localtime_s(const time_t *ptime, struct tm *ptm)
  577. {
  578. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  579. FILETIME ft, lft;
  580. SYSTEMTIME st;
  581. TIME_ZONE_INFORMATION tzinfo;
  582. if (ptm == NULL) {
  583. return NULL;
  584. }
  585. *(int64_t *)&ft = t;
  586. FileTimeToLocalFileTime(&ft, &lft);
  587. FileTimeToSystemTime(&lft, &st);
  588. ptm->tm_year = st.wYear - 1900;
  589. ptm->tm_mon = st.wMonth - 1;
  590. ptm->tm_wday = st.wDayOfWeek;
  591. ptm->tm_mday = st.wDay;
  592. ptm->tm_hour = st.wHour;
  593. ptm->tm_min = st.wMinute;
  594. ptm->tm_sec = st.wSecond;
  595. ptm->tm_yday = 0; /* hope nobody uses this */
  596. ptm->tm_isdst =
  597. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  598. return ptm;
  599. }
  600. FUNCTION_MAY_BE_UNUSED
  601. static struct tm *
  602. gmtime_s(const time_t *ptime, struct tm *ptm)
  603. {
  604. /* FIXME(lsm): fix this. */
  605. return localtime_s(ptime, ptm);
  606. }
  607. static int mg_atomic_inc(volatile int *addr);
  608. static struct tm tm_array[MAX_WORKER_THREADS];
  609. static int tm_index = 0;
  610. FUNCTION_MAY_BE_UNUSED
  611. static struct tm *
  612. localtime(const time_t *ptime)
  613. {
  614. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  615. return localtime_s(ptime, tm_array + i);
  616. }
  617. FUNCTION_MAY_BE_UNUSED
  618. static struct tm *
  619. gmtime(const time_t *ptime)
  620. {
  621. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  622. return gmtime_s(ptime, tm_array + i);
  623. }
  624. FUNCTION_MAY_BE_UNUSED
  625. static size_t
  626. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  627. {
  628. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  629. * for WinCE"); */
  630. return 0;
  631. }
  632. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  633. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  634. #define remove(f) mg_remove(NULL, f)
  635. FUNCTION_MAY_BE_UNUSED
  636. static int
  637. rename(const char *a, const char *b)
  638. {
  639. wchar_t wa[PATH_MAX];
  640. wchar_t wb[PATH_MAX];
  641. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  642. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  643. return MoveFileW(wa, wb) ? 0 : -1;
  644. }
  645. struct stat {
  646. int64_t st_size;
  647. time_t st_mtime;
  648. };
  649. FUNCTION_MAY_BE_UNUSED
  650. static int
  651. stat(const char *name, struct stat *st)
  652. {
  653. wchar_t wbuf[PATH_MAX];
  654. WIN32_FILE_ATTRIBUTE_DATA attr;
  655. time_t creation_time, write_time;
  656. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  657. memset(&attr, 0, sizeof(attr));
  658. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  659. st->st_size =
  660. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  661. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  662. attr.ftLastWriteTime.dwHighDateTime);
  663. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  664. attr.ftCreationTime.dwHighDateTime);
  665. if (creation_time > write_time) {
  666. st->st_mtime = creation_time;
  667. } else {
  668. st->st_mtime = write_time;
  669. }
  670. return 0;
  671. }
  672. #define access(x, a) 1 /* not required anyway */
  673. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  674. /* Values from errno.h in Windows SDK (Visual Studio). */
  675. #define EEXIST 17
  676. #define EACCES 13
  677. #define ENOENT 2
  678. #if defined(__MINGW32__)
  679. /* Enable unused function warning again */
  680. #pragma GCC diagnostic pop
  681. #endif
  682. #endif /* defined(_WIN32_WCE) */
  683. static pthread_mutex_t global_lock_mutex;
  684. #if defined(__GNUC__) || defined(__MINGW32__)
  685. /* Show no warning in case system functions are not used. */
  686. #define GCC_VERSION \
  687. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  688. #if GCC_VERSION >= 40500
  689. #pragma GCC diagnostic push
  690. #pragma GCC diagnostic ignored "-Wunused-function"
  691. #endif /* GCC_VERSION >= 40500 */
  692. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  693. #if defined(__clang__)
  694. /* Show no warning in case system functions are not used. */
  695. #pragma clang diagnostic push
  696. #pragma clang diagnostic ignored "-Wunused-function"
  697. #endif
  698. FUNCTION_MAY_BE_UNUSED
  699. static void
  700. mg_global_lock(void)
  701. {
  702. (void)pthread_mutex_lock(&global_lock_mutex);
  703. }
  704. FUNCTION_MAY_BE_UNUSED
  705. static void
  706. mg_global_unlock(void)
  707. {
  708. (void)pthread_mutex_unlock(&global_lock_mutex);
  709. }
  710. FUNCTION_MAY_BE_UNUSED
  711. static int
  712. mg_atomic_inc(volatile int *addr)
  713. {
  714. int ret;
  715. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  716. /* Depending on the SDK, this function uses either
  717. * (volatile unsigned int *) or (volatile LONG *),
  718. * so whatever you use, the other SDK is likely to raise a warning. */
  719. ret = InterlockedIncrement((volatile long *)addr);
  720. #elif defined(__GNUC__) \
  721. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  722. && !defined(NO_ATOMICS)
  723. ret = __sync_add_and_fetch(addr, 1);
  724. #else
  725. mg_global_lock();
  726. ret = (++(*addr));
  727. mg_global_unlock();
  728. #endif
  729. return ret;
  730. }
  731. FUNCTION_MAY_BE_UNUSED
  732. static int
  733. mg_atomic_dec(volatile int *addr)
  734. {
  735. int ret;
  736. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  737. /* Depending on the SDK, this function uses either
  738. * (volatile unsigned int *) or (volatile LONG *),
  739. * so whatever you use, the other SDK is likely to raise a warning. */
  740. ret = InterlockedDecrement((volatile long *)addr);
  741. #elif defined(__GNUC__) \
  742. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  743. && !defined(NO_ATOMICS)
  744. ret = __sync_sub_and_fetch(addr, 1);
  745. #else
  746. mg_global_lock();
  747. ret = (--(*addr));
  748. mg_global_unlock();
  749. #endif
  750. return ret;
  751. }
  752. #if defined(USE_SERVER_STATS)
  753. static int64_t
  754. mg_atomic_add(volatile int64_t *addr, int64_t value)
  755. {
  756. int64_t ret;
  757. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  758. ret = InterlockedAdd64(addr, value);
  759. #elif defined(__GNUC__) \
  760. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  761. && !defined(NO_ATOMICS)
  762. ret = __sync_add_and_fetch(addr, value);
  763. #else
  764. mg_global_lock();
  765. *addr += value;
  766. ret = (*addr);
  767. mg_global_unlock();
  768. #endif
  769. return ret;
  770. }
  771. #endif
  772. #if defined(__GNUC__)
  773. /* Show no warning in case system functions are not used. */
  774. #if GCC_VERSION >= 40500
  775. #pragma GCC diagnostic pop
  776. #endif /* GCC_VERSION >= 40500 */
  777. #endif /* defined(__GNUC__) */
  778. #if defined(__clang__)
  779. /* Show no warning in case system functions are not used. */
  780. #pragma clang diagnostic pop
  781. #endif
  782. #if defined(USE_SERVER_STATS)
  783. struct mg_memory_stat {
  784. volatile int64_t totalMemUsed;
  785. volatile int64_t maxMemUsed;
  786. volatile int blockCount;
  787. };
  788. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  789. static void *
  790. mg_malloc_ex(size_t size,
  791. struct mg_context *ctx,
  792. const char *file,
  793. unsigned line)
  794. {
  795. void *data = malloc(size + 2 * sizeof(uintptr_t));
  796. void *memory = 0;
  797. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  798. #if defined(MEMORY_DEBUGGING)
  799. char mallocStr[256];
  800. #else
  801. (void)file;
  802. (void)line;
  803. #endif
  804. if (data) {
  805. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  806. if (mmem > mstat->maxMemUsed) {
  807. /* could use atomic compare exchange, but this
  808. * seems overkill for statistics data */
  809. mstat->maxMemUsed = mmem;
  810. }
  811. mg_atomic_inc(&mstat->blockCount);
  812. ((uintptr_t *)data)[0] = size;
  813. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  814. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  815. }
  816. #if defined(MEMORY_DEBUGGING)
  817. sprintf(mallocStr,
  818. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  819. memory,
  820. (unsigned long)size,
  821. (unsigned long)mstat->totalMemUsed,
  822. (unsigned long)mstat->blockCount,
  823. file,
  824. line);
  825. #if defined(_WIN32)
  826. OutputDebugStringA(mallocStr);
  827. #else
  828. DEBUG_TRACE("%s", mallocStr);
  829. #endif
  830. #endif
  831. return memory;
  832. }
  833. static void *
  834. mg_calloc_ex(size_t count,
  835. size_t size,
  836. struct mg_context *ctx,
  837. const char *file,
  838. unsigned line)
  839. {
  840. void *data = mg_malloc_ex(size * count, ctx, file, line);
  841. if (data) {
  842. memset(data, 0, size * count);
  843. }
  844. return data;
  845. }
  846. static void
  847. mg_free_ex(void *memory, const char *file, unsigned line)
  848. {
  849. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  850. #if defined(MEMORY_DEBUGGING)
  851. char mallocStr[256];
  852. #else
  853. (void)file;
  854. (void)line;
  855. #endif
  856. if (memory) {
  857. uintptr_t size = ((uintptr_t *)data)[0];
  858. struct mg_memory_stat *mstat =
  859. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  860. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  861. mg_atomic_dec(&mstat->blockCount);
  862. #if defined(MEMORY_DEBUGGING)
  863. sprintf(mallocStr,
  864. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  865. memory,
  866. (unsigned long)size,
  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. free(data);
  878. }
  879. }
  880. static void *
  881. mg_realloc_ex(void *memory,
  882. size_t newsize,
  883. struct mg_context *ctx,
  884. const char *file,
  885. unsigned line)
  886. {
  887. void *data;
  888. void *_realloc;
  889. uintptr_t oldsize;
  890. #if defined(MEMORY_DEBUGGING)
  891. char mallocStr[256];
  892. #else
  893. (void)file;
  894. (void)line;
  895. #endif
  896. if (newsize) {
  897. if (memory) {
  898. /* Reallocate existing block */
  899. struct mg_memory_stat *mstat;
  900. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  901. oldsize = ((uintptr_t *)data)[0];
  902. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  903. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  904. if (_realloc) {
  905. data = _realloc;
  906. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  907. #if defined(MEMORY_DEBUGGING)
  908. sprintf(mallocStr,
  909. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  910. memory,
  911. (unsigned long)oldsize,
  912. (unsigned long)mstat->totalMemUsed,
  913. (unsigned long)mstat->blockCount,
  914. file,
  915. line);
  916. #if defined(_WIN32)
  917. OutputDebugStringA(mallocStr);
  918. #else
  919. DEBUG_TRACE("%s", mallocStr);
  920. #endif
  921. #endif
  922. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  923. #if defined(MEMORY_DEBUGGING)
  924. sprintf(mallocStr,
  925. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  926. memory,
  927. (unsigned long)newsize,
  928. (unsigned long)mstat->totalMemUsed,
  929. (unsigned long)mstat->blockCount,
  930. file,
  931. line);
  932. #if defined(_WIN32)
  933. OutputDebugStringA(mallocStr);
  934. #else
  935. DEBUG_TRACE("%s", mallocStr);
  936. #endif
  937. #endif
  938. *(uintptr_t *)data = newsize;
  939. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  940. } else {
  941. #if defined(MEMORY_DEBUGGING)
  942. #if defined(_WIN32)
  943. OutputDebugStringA("MEM: realloc failed\n");
  944. #else
  945. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  946. #endif
  947. #endif
  948. return _realloc;
  949. }
  950. } else {
  951. /* Allocate new block */
  952. data = mg_malloc_ex(newsize, ctx, file, line);
  953. }
  954. } else {
  955. /* Free existing block */
  956. data = 0;
  957. mg_free_ex(memory, file, line);
  958. }
  959. return data;
  960. }
  961. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  962. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  963. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  964. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  965. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  966. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  967. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  968. #else /* USE_SERVER_STATS */
  969. static __inline void *
  970. mg_malloc(size_t a)
  971. {
  972. return malloc(a);
  973. }
  974. static __inline void *
  975. mg_calloc(size_t a, size_t b)
  976. {
  977. return calloc(a, b);
  978. }
  979. static __inline void *
  980. mg_realloc(void *a, size_t b)
  981. {
  982. return realloc(a, b);
  983. }
  984. static __inline void
  985. mg_free(void *a)
  986. {
  987. free(a);
  988. }
  989. #define mg_malloc_ctx(a, c) mg_malloc(a)
  990. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  991. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  992. #define mg_free_ctx(a, c) mg_free(a)
  993. #endif /* USE_SERVER_STATS */
  994. static void mg_vsnprintf(const struct mg_connection *conn,
  995. int *truncated,
  996. char *buf,
  997. size_t buflen,
  998. const char *fmt,
  999. va_list ap);
  1000. static void mg_snprintf(const struct mg_connection *conn,
  1001. int *truncated,
  1002. char *buf,
  1003. size_t buflen,
  1004. PRINTF_FORMAT_STRING(const char *fmt),
  1005. ...) PRINTF_ARGS(5, 6);
  1006. /* This following lines are just meant as a reminder to use the mg-functions
  1007. * for memory management */
  1008. #ifdef malloc
  1009. #undef malloc
  1010. #endif
  1011. #ifdef calloc
  1012. #undef calloc
  1013. #endif
  1014. #ifdef realloc
  1015. #undef realloc
  1016. #endif
  1017. #ifdef free
  1018. #undef free
  1019. #endif
  1020. #ifdef snprintf
  1021. #undef snprintf
  1022. #endif
  1023. #ifdef vsnprintf
  1024. #undef vsnprintf
  1025. #endif
  1026. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1027. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1028. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1029. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1030. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1031. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  1032. * but this define only works well for Windows. */
  1033. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1034. #endif
  1035. /* mg_init_library counter */
  1036. static int mg_init_library_called = 0;
  1037. #if !defined(NO_SSL)
  1038. static int mg_ssl_initialized = 0;
  1039. #endif
  1040. static pthread_key_t sTlsKey; /* Thread local storage index */
  1041. static int thread_idx_max = 0;
  1042. struct mg_workerTLS {
  1043. int is_master;
  1044. unsigned long thread_idx;
  1045. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1046. HANDLE pthread_cond_helper_mutex;
  1047. struct mg_workerTLS *next_waiting_thread;
  1048. #endif
  1049. };
  1050. #if defined(__GNUC__) || defined(__MINGW32__)
  1051. /* Show no warning in case system functions are not used. */
  1052. #if GCC_VERSION >= 40500
  1053. #pragma GCC diagnostic push
  1054. #pragma GCC diagnostic ignored "-Wunused-function"
  1055. #endif /* GCC_VERSION >= 40500 */
  1056. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1057. #if defined(__clang__)
  1058. /* Show no warning in case system functions are not used. */
  1059. #pragma clang diagnostic push
  1060. #pragma clang diagnostic ignored "-Wunused-function"
  1061. #endif
  1062. /* Get a unique thread ID as unsigned long, independent from the data type
  1063. * of thread IDs defined by the operating system API.
  1064. * If two calls to mg_current_thread_id return the same value, they calls
  1065. * are done from the same thread. If they return different values, they are
  1066. * done from different threads. (Provided this function is used in the same
  1067. * process context and threads are not repeatedly created and deleted, but
  1068. * CivetWeb does not do that).
  1069. * This function must match the signature required for SSL id callbacks:
  1070. * CRYPTO_set_id_callback
  1071. */
  1072. FUNCTION_MAY_BE_UNUSED
  1073. static unsigned long
  1074. mg_current_thread_id(void)
  1075. {
  1076. #ifdef _WIN32
  1077. return GetCurrentThreadId();
  1078. #else
  1079. #ifdef __clang__
  1080. #pragma clang diagnostic push
  1081. #pragma clang diagnostic ignored "-Wunreachable-code"
  1082. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1083. * or not, so one of the two conditions will be unreachable by construction.
  1084. * Unfortunately the C standard does not define a way to check this at
  1085. * compile time, since the #if preprocessor conditions can not use the sizeof
  1086. * operator as an argument. */
  1087. #endif
  1088. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1089. /* This is the problematic case for CRYPTO_set_id_callback:
  1090. * The OS pthread_t can not be cast to unsigned long. */
  1091. struct mg_workerTLS *tls =
  1092. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1093. if (tls == NULL) {
  1094. /* SSL called from an unknown thread: Create some thread index.
  1095. */
  1096. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1097. tls->is_master = -2; /* -2 means "3rd party thread" */
  1098. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1099. pthread_setspecific(sTlsKey, tls);
  1100. }
  1101. return tls->thread_idx;
  1102. } else {
  1103. /* pthread_t may be any data type, so a simple cast to unsigned long
  1104. * can rise a warning/error, depending on the platform.
  1105. * Here memcpy is used as an anything-to-anything cast. */
  1106. unsigned long ret = 0;
  1107. pthread_t t = pthread_self();
  1108. memcpy(&ret, &t, sizeof(pthread_t));
  1109. return ret;
  1110. }
  1111. #ifdef __clang__
  1112. #pragma clang diagnostic pop
  1113. #endif
  1114. #endif
  1115. }
  1116. FUNCTION_MAY_BE_UNUSED
  1117. static uint64_t
  1118. mg_get_current_time_ns(void)
  1119. {
  1120. struct timespec tsnow;
  1121. clock_gettime(CLOCK_REALTIME, &tsnow);
  1122. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1123. }
  1124. #if defined(__GNUC__)
  1125. /* Show no warning in case system functions are not used. */
  1126. #if GCC_VERSION >= 40500
  1127. #pragma GCC diagnostic pop
  1128. #endif /* GCC_VERSION >= 40500 */
  1129. #endif /* defined(__GNUC__) */
  1130. #if defined(__clang__)
  1131. /* Show no warning in case system functions are not used. */
  1132. #pragma clang diagnostic pop
  1133. #endif
  1134. #if !defined(DEBUG_TRACE)
  1135. #if defined(DEBUG)
  1136. static void DEBUG_TRACE_FUNC(const char *func,
  1137. unsigned line,
  1138. PRINTF_FORMAT_STRING(const char *fmt),
  1139. ...) PRINTF_ARGS(3, 4);
  1140. static void
  1141. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1142. {
  1143. va_list args;
  1144. uint64_t nsnow;
  1145. static uint64_t nslast;
  1146. struct timespec tsnow;
  1147. /* Get some operating system independent thread id */
  1148. unsigned long thread_id = mg_current_thread_id();
  1149. clock_gettime(CLOCK_REALTIME, &tsnow);
  1150. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1151. + ((uint64_t)tsnow.tv_nsec);
  1152. if (!nslast) {
  1153. nslast = nsnow;
  1154. }
  1155. flockfile(stdout);
  1156. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1157. (unsigned long)tsnow.tv_sec,
  1158. (unsigned long)tsnow.tv_nsec,
  1159. nsnow - nslast,
  1160. thread_id,
  1161. func,
  1162. line);
  1163. va_start(args, fmt);
  1164. vprintf(fmt, args);
  1165. va_end(args);
  1166. putchar('\n');
  1167. fflush(stdout);
  1168. funlockfile(stdout);
  1169. nslast = nsnow;
  1170. }
  1171. #define DEBUG_TRACE(fmt, ...) \
  1172. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1173. #else
  1174. #define DEBUG_TRACE(fmt, ...) \
  1175. do { \
  1176. } while (0)
  1177. #endif /* DEBUG */
  1178. #endif /* DEBUG_TRACE */
  1179. #define MD5_STATIC static
  1180. #include "md5.inl"
  1181. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1182. #ifdef NO_SOCKLEN_T
  1183. typedef int socklen_t;
  1184. #endif /* NO_SOCKLEN_T */
  1185. #define _DARWIN_UNLIMITED_SELECT
  1186. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1187. #if !defined(MSG_NOSIGNAL)
  1188. #define MSG_NOSIGNAL (0)
  1189. #endif
  1190. #if !defined(SOMAXCONN)
  1191. #define SOMAXCONN (100)
  1192. #endif
  1193. /* Size of the accepted socket queue */
  1194. #if !defined(MGSQLEN)
  1195. #define MGSQLEN (20)
  1196. #endif
  1197. #if defined(NO_SSL)
  1198. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1199. typedef struct SSL_CTX SSL_CTX;
  1200. #else
  1201. #if defined(NO_SSL_DL)
  1202. #include <openssl/ssl.h>
  1203. #include <openssl/err.h>
  1204. #include <openssl/crypto.h>
  1205. #include <openssl/x509.h>
  1206. #include <openssl/pem.h>
  1207. #include <openssl/engine.h>
  1208. #include <openssl/conf.h>
  1209. #include <openssl/dh.h>
  1210. #include <openssl/bn.h>
  1211. #include <openssl/opensslv.h>
  1212. #else
  1213. /* SSL loaded dynamically from DLL.
  1214. * I put the prototypes here to be independent from OpenSSL source
  1215. * installation. */
  1216. typedef struct ssl_st SSL;
  1217. typedef struct ssl_method_st SSL_METHOD;
  1218. typedef struct ssl_ctx_st SSL_CTX;
  1219. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1220. typedef struct x509_name X509_NAME;
  1221. typedef struct asn1_integer ASN1_INTEGER;
  1222. typedef struct bignum BIGNUM;
  1223. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1224. typedef struct evp_md EVP_MD;
  1225. typedef struct x509 X509;
  1226. #define SSL_CTRL_OPTIONS (32)
  1227. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1228. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1229. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1230. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1231. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1232. #define SSL_VERIFY_NONE (0)
  1233. #define SSL_VERIFY_PEER (1)
  1234. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1235. #define SSL_VERIFY_CLIENT_ONCE (4)
  1236. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1237. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1238. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1239. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1240. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1241. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1242. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1243. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1244. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1245. #define SSL_ERROR_NONE (0)
  1246. #define SSL_ERROR_SSL (1)
  1247. #define SSL_ERROR_WANT_READ (2)
  1248. #define SSL_ERROR_WANT_WRITE (3)
  1249. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1250. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1251. #define SSL_ERROR_ZERO_RETURN (6)
  1252. #define SSL_ERROR_WANT_CONNECT (7)
  1253. #define SSL_ERROR_WANT_ACCEPT (8)
  1254. struct ssl_func {
  1255. const char *name; /* SSL function name */
  1256. void (*ptr)(void); /* Function pointer */
  1257. };
  1258. #ifdef OPENSSL_API_1_1
  1259. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1260. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1261. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1262. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1263. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1264. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1265. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1266. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1267. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1268. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1269. #define OPENSSL_init_ssl \
  1270. (*(int (*)(uint64_t opts, \
  1271. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1272. #define SSL_CTX_use_PrivateKey_file \
  1273. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1274. #define SSL_CTX_use_certificate_file \
  1275. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1276. #define SSL_CTX_set_default_passwd_cb \
  1277. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1278. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1279. #define SSL_CTX_use_certificate_chain_file \
  1280. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1281. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1282. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1283. #define SSL_CTX_set_verify \
  1284. (*(void (*)(SSL_CTX *, \
  1285. int, \
  1286. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1287. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1288. #define SSL_CTX_load_verify_locations \
  1289. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1290. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1291. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1292. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1293. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1294. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1295. #define SSL_CIPHER_get_name \
  1296. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1297. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1298. #define SSL_CTX_set_session_id_context \
  1299. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1300. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1301. #define SSL_CTX_set_cipher_list \
  1302. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1303. #define SSL_CTX_set_options \
  1304. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1305. #define SSL_CTX_clear_options(ctx, op) \
  1306. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1307. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1308. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1309. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1310. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1311. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1312. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1313. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1314. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1315. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1316. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1317. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1318. #define X509_NAME_oneline \
  1319. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1320. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1321. #define EVP_get_digestbyname \
  1322. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1323. #define EVP_Digest \
  1324. (*(int (*)( \
  1325. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1326. crypto_sw[10].ptr)
  1327. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1328. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1329. #define ASN1_INTEGER_to_BN \
  1330. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1331. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1332. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1333. #define OPENSSL_free(a) CRYPTO_free(a)
  1334. /* set_ssl_option() function updates this array.
  1335. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1336. * of respective functions. The macros above (like SSL_connect()) are really
  1337. * just calling these functions indirectly via the pointer. */
  1338. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1339. {"SSL_accept", NULL},
  1340. {"SSL_connect", NULL},
  1341. {"SSL_read", NULL},
  1342. {"SSL_write", NULL},
  1343. {"SSL_get_error", NULL},
  1344. {"SSL_set_fd", NULL},
  1345. {"SSL_new", NULL},
  1346. {"SSL_CTX_new", NULL},
  1347. {"TLS_server_method", NULL},
  1348. {"OPENSSL_init_ssl", NULL},
  1349. {"SSL_CTX_use_PrivateKey_file", NULL},
  1350. {"SSL_CTX_use_certificate_file", NULL},
  1351. {"SSL_CTX_set_default_passwd_cb", NULL},
  1352. {"SSL_CTX_free", NULL},
  1353. {"SSL_CTX_use_certificate_chain_file", NULL},
  1354. {"TLS_client_method", NULL},
  1355. {"SSL_pending", NULL},
  1356. {"SSL_CTX_set_verify", NULL},
  1357. {"SSL_shutdown", NULL},
  1358. {"SSL_CTX_load_verify_locations", NULL},
  1359. {"SSL_CTX_set_default_verify_paths", NULL},
  1360. {"SSL_CTX_set_verify_depth", NULL},
  1361. {"SSL_get_peer_certificate", NULL},
  1362. {"SSL_get_version", NULL},
  1363. {"SSL_get_current_cipher", NULL},
  1364. {"SSL_CIPHER_get_name", NULL},
  1365. {"SSL_CTX_check_private_key", NULL},
  1366. {"SSL_CTX_set_session_id_context", NULL},
  1367. {"SSL_CTX_ctrl", NULL},
  1368. {"SSL_CTX_set_cipher_list", NULL},
  1369. {"SSL_CTX_set_options", NULL},
  1370. {NULL, NULL}};
  1371. /* Similar array as ssl_sw. These functions could be located in different
  1372. * lib. */
  1373. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1374. {"ERR_error_string", NULL},
  1375. {"ERR_remove_state", NULL},
  1376. {"CONF_modules_unload", NULL},
  1377. {"X509_free", NULL},
  1378. {"X509_get_subject_name", NULL},
  1379. {"X509_get_issuer_name", NULL},
  1380. {"X509_NAME_oneline", NULL},
  1381. {"X509_get_serialNumber", NULL},
  1382. {"EVP_get_digestbyname", NULL},
  1383. {"EVP_Digest", NULL},
  1384. {"i2d_X509", NULL},
  1385. {"BN_bn2hex", NULL},
  1386. {"ASN1_INTEGER_to_BN", NULL},
  1387. {"BN_free", NULL},
  1388. {"CRYPTO_free", NULL},
  1389. {NULL, NULL}};
  1390. #else
  1391. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1392. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1393. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1394. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1395. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1396. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1397. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1398. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1399. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1400. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1401. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1402. #define SSL_CTX_use_PrivateKey_file \
  1403. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1404. #define SSL_CTX_use_certificate_file \
  1405. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1406. #define SSL_CTX_set_default_passwd_cb \
  1407. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1408. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1409. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1410. #define SSL_CTX_use_certificate_chain_file \
  1411. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1412. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1413. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1414. #define SSL_CTX_set_verify \
  1415. (*(void (*)(SSL_CTX *, \
  1416. int, \
  1417. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1418. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1419. #define SSL_CTX_load_verify_locations \
  1420. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1421. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1422. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1423. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1424. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1425. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1426. #define SSL_CIPHER_get_name \
  1427. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1428. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1429. #define SSL_CTX_set_session_id_context \
  1430. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1431. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1432. #define SSL_CTX_set_cipher_list \
  1433. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1434. #define SSL_CTX_set_options(ctx, op) \
  1435. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1436. #define SSL_CTX_clear_options(ctx, op) \
  1437. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1438. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1439. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1440. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1441. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1442. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1443. #define CRYPTO_set_locking_callback \
  1444. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1445. #define CRYPTO_set_id_callback \
  1446. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1447. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1448. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1449. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1450. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1451. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1452. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1453. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1454. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1455. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1456. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1457. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1458. #define X509_NAME_oneline \
  1459. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1460. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1461. #define i2c_ASN1_INTEGER \
  1462. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1463. #define EVP_get_digestbyname \
  1464. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1465. #define EVP_Digest \
  1466. (*(int (*)( \
  1467. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1468. crypto_sw[18].ptr)
  1469. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1470. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1471. #define ASN1_INTEGER_to_BN \
  1472. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1473. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1474. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1475. #define OPENSSL_free(a) CRYPTO_free(a)
  1476. /* set_ssl_option() function updates this array.
  1477. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1478. * of respective functions. The macros above (like SSL_connect()) are really
  1479. * just calling these functions indirectly via the pointer. */
  1480. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1481. {"SSL_accept", NULL},
  1482. {"SSL_connect", NULL},
  1483. {"SSL_read", NULL},
  1484. {"SSL_write", NULL},
  1485. {"SSL_get_error", NULL},
  1486. {"SSL_set_fd", NULL},
  1487. {"SSL_new", NULL},
  1488. {"SSL_CTX_new", NULL},
  1489. {"SSLv23_server_method", NULL},
  1490. {"SSL_library_init", NULL},
  1491. {"SSL_CTX_use_PrivateKey_file", NULL},
  1492. {"SSL_CTX_use_certificate_file", NULL},
  1493. {"SSL_CTX_set_default_passwd_cb", NULL},
  1494. {"SSL_CTX_free", NULL},
  1495. {"SSL_load_error_strings", NULL},
  1496. {"SSL_CTX_use_certificate_chain_file", NULL},
  1497. {"SSLv23_client_method", NULL},
  1498. {"SSL_pending", NULL},
  1499. {"SSL_CTX_set_verify", NULL},
  1500. {"SSL_shutdown", NULL},
  1501. {"SSL_CTX_load_verify_locations", NULL},
  1502. {"SSL_CTX_set_default_verify_paths", NULL},
  1503. {"SSL_CTX_set_verify_depth", NULL},
  1504. {"SSL_get_peer_certificate", NULL},
  1505. {"SSL_get_version", NULL},
  1506. {"SSL_get_current_cipher", NULL},
  1507. {"SSL_CIPHER_get_name", NULL},
  1508. {"SSL_CTX_check_private_key", NULL},
  1509. {"SSL_CTX_set_session_id_context", NULL},
  1510. {"SSL_CTX_ctrl", NULL},
  1511. {"SSL_CTX_set_cipher_list", NULL},
  1512. {NULL, NULL}};
  1513. /* Similar array as ssl_sw. These functions could be located in different
  1514. * lib. */
  1515. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1516. {"CRYPTO_set_locking_callback", NULL},
  1517. {"CRYPTO_set_id_callback", NULL},
  1518. {"ERR_get_error", NULL},
  1519. {"ERR_error_string", NULL},
  1520. {"ERR_remove_state", NULL},
  1521. {"ERR_free_strings", NULL},
  1522. {"ENGINE_cleanup", NULL},
  1523. {"CONF_modules_unload", NULL},
  1524. {"CRYPTO_cleanup_all_ex_data", NULL},
  1525. {"EVP_cleanup", NULL},
  1526. {"X509_free", NULL},
  1527. {"X509_get_subject_name", NULL},
  1528. {"X509_get_issuer_name", NULL},
  1529. {"X509_NAME_oneline", NULL},
  1530. {"X509_get_serialNumber", NULL},
  1531. {"i2c_ASN1_INTEGER", NULL},
  1532. {"EVP_get_digestbyname", NULL},
  1533. {"EVP_Digest", NULL},
  1534. {"i2d_X509", NULL},
  1535. {"BN_bn2hex", NULL},
  1536. {"ASN1_INTEGER_to_BN", NULL},
  1537. {"BN_free", NULL},
  1538. {"CRYPTO_free", NULL},
  1539. {NULL, NULL}};
  1540. #endif /* OPENSSL_API_1_1 */
  1541. #endif /* NO_SSL_DL */
  1542. #endif /* NO_SSL */
  1543. #if !defined(NO_CACHING)
  1544. static const char *month_names[] = {"Jan",
  1545. "Feb",
  1546. "Mar",
  1547. "Apr",
  1548. "May",
  1549. "Jun",
  1550. "Jul",
  1551. "Aug",
  1552. "Sep",
  1553. "Oct",
  1554. "Nov",
  1555. "Dec"};
  1556. #endif /* !NO_CACHING */
  1557. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1558. * union u. */
  1559. union usa {
  1560. struct sockaddr sa;
  1561. struct sockaddr_in sin;
  1562. #if defined(USE_IPV6)
  1563. struct sockaddr_in6 sin6;
  1564. #endif
  1565. };
  1566. /* Describes a string (chunk of memory). */
  1567. struct vec {
  1568. const char *ptr;
  1569. size_t len;
  1570. };
  1571. struct mg_file_stat {
  1572. /* File properties filled by mg_stat: */
  1573. uint64_t size;
  1574. time_t last_modified;
  1575. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1576. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1577. * case we need a "Content-Eencoding: gzip" header */
  1578. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1579. };
  1580. struct mg_file_in_memory {
  1581. char *p;
  1582. uint32_t pos;
  1583. char mode;
  1584. };
  1585. struct mg_file_access {
  1586. /* File properties filled by mg_fopen: */
  1587. FILE *fp;
  1588. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1589. * support library. Use some struct mg_file_in_memory *mf; instead of
  1590. * membuf char pointer. */
  1591. const char *membuf;
  1592. };
  1593. struct mg_file {
  1594. struct mg_file_stat stat;
  1595. struct mg_file_access access;
  1596. };
  1597. #define STRUCT_FILE_INITIALIZER \
  1598. { \
  1599. { \
  1600. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1601. } \
  1602. , \
  1603. { \
  1604. (FILE *) NULL, (const char *)NULL \
  1605. } \
  1606. }
  1607. /* Describes listening socket, or socket which was accept()-ed by the master
  1608. * thread and queued for future handling by the worker thread. */
  1609. struct socket {
  1610. SOCKET sock; /* Listening socket */
  1611. union usa lsa; /* Local socket address */
  1612. union usa rsa; /* Remote socket address */
  1613. unsigned char is_ssl; /* Is port SSL-ed */
  1614. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1615. * port */
  1616. unsigned char in_use; /* Is valid */
  1617. };
  1618. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1619. enum {
  1620. CGI_EXTENSIONS,
  1621. CGI_ENVIRONMENT,
  1622. PUT_DELETE_PASSWORDS_FILE,
  1623. CGI_INTERPRETER,
  1624. PROTECT_URI,
  1625. AUTHENTICATION_DOMAIN,
  1626. ENABLE_AUTH_DOMAIN_CHECK,
  1627. SSI_EXTENSIONS,
  1628. THROTTLE,
  1629. ACCESS_LOG_FILE,
  1630. ENABLE_DIRECTORY_LISTING,
  1631. ERROR_LOG_FILE,
  1632. GLOBAL_PASSWORDS_FILE,
  1633. INDEX_FILES,
  1634. ENABLE_KEEP_ALIVE,
  1635. ACCESS_CONTROL_LIST,
  1636. EXTRA_MIME_TYPES,
  1637. LISTENING_PORTS,
  1638. DOCUMENT_ROOT,
  1639. SSL_CERTIFICATE,
  1640. SSL_CERTIFICATE_CHAIN,
  1641. NUM_THREADS,
  1642. RUN_AS_USER,
  1643. URL_REWRITE_PATTERN,
  1644. HIDE_FILES,
  1645. REQUEST_TIMEOUT,
  1646. KEEP_ALIVE_TIMEOUT,
  1647. LINGER_TIMEOUT,
  1648. SSL_DO_VERIFY_PEER,
  1649. SSL_CA_PATH,
  1650. SSL_CA_FILE,
  1651. SSL_VERIFY_DEPTH,
  1652. SSL_DEFAULT_VERIFY_PATHS,
  1653. SSL_CIPHER_LIST,
  1654. SSL_PROTOCOL_VERSION,
  1655. SSL_SHORT_TRUST,
  1656. #if defined(USE_WEBSOCKET)
  1657. WEBSOCKET_TIMEOUT,
  1658. #endif
  1659. DECODE_URL,
  1660. #if defined(USE_LUA)
  1661. LUA_PRELOAD_FILE,
  1662. LUA_SCRIPT_EXTENSIONS,
  1663. LUA_SERVER_PAGE_EXTENSIONS,
  1664. #endif
  1665. #if defined(USE_DUKTAPE)
  1666. DUKTAPE_SCRIPT_EXTENSIONS,
  1667. #endif
  1668. #if defined(USE_WEBSOCKET)
  1669. WEBSOCKET_ROOT,
  1670. #endif
  1671. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1672. LUA_WEBSOCKET_EXTENSIONS,
  1673. #endif
  1674. ACCESS_CONTROL_ALLOW_ORIGIN,
  1675. ACCESS_CONTROL_ALLOW_METHODS,
  1676. ACCESS_CONTROL_ALLOW_HEADERS,
  1677. ERROR_PAGES,
  1678. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1679. * socket option typedef TCP_NODELAY. */
  1680. #if !defined(NO_CACHING)
  1681. STATIC_FILE_MAX_AGE,
  1682. #endif
  1683. #if !defined(NO_SSL)
  1684. STRICT_HTTPS_MAX_AGE,
  1685. #endif
  1686. #if defined(__linux__)
  1687. ALLOW_SENDFILE_CALL,
  1688. #endif
  1689. #if defined(_WIN32)
  1690. CASE_SENSITIVE_FILES,
  1691. #endif
  1692. #if defined(USE_LUA)
  1693. LUA_BACKGROUND_SCRIPT,
  1694. #endif
  1695. ADDITIONAL_HEADER,
  1696. MAX_REQUEST_SIZE,
  1697. NUM_OPTIONS
  1698. };
  1699. /* Config option name, config types, default value */
  1700. static struct mg_option config_options[] = {
  1701. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1702. {"cgi_environment", CONFIG_TYPE_STRING_LIST, NULL},
  1703. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1704. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1705. {"protect_uri", CONFIG_TYPE_STRING_LIST, NULL},
  1706. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1707. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1708. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1709. {"throttle", CONFIG_TYPE_STRING_LIST, NULL},
  1710. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1711. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1712. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1713. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1714. {"index_files",
  1715. CONFIG_TYPE_STRING_LIST,
  1716. #ifdef USE_LUA
  1717. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1718. "index.shtml,index.php"},
  1719. #else
  1720. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1721. #endif
  1722. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1723. {"access_control_list", CONFIG_TYPE_STRING_LIST, NULL},
  1724. {"extra_mime_types", CONFIG_TYPE_STRING_LIST, NULL},
  1725. {"listening_ports", CONFIG_TYPE_STRING_LIST, "8080"},
  1726. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1727. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1728. {"ssl_certificate_chain", CONFIG_TYPE_FILE, NULL},
  1729. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1730. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1731. {"url_rewrite_patterns", CONFIG_TYPE_STRING_LIST, NULL},
  1732. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1733. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1734. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1735. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1736. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1737. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1738. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1739. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1740. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1741. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1742. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1743. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1744. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1745. #if defined(USE_WEBSOCKET)
  1746. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1747. #endif
  1748. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1749. #if defined(USE_LUA)
  1750. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1751. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1752. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1753. #endif
  1754. #if defined(USE_DUKTAPE)
  1755. /* The support for duktape is still in alpha version state.
  1756. * The name of this config option might change. */
  1757. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1758. #endif
  1759. #if defined(USE_WEBSOCKET)
  1760. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1761. #endif
  1762. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1763. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1764. #endif
  1765. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1766. {"access_control_allow_methods", CONFIG_TYPE_STRING, "*"},
  1767. {"access_control_allow_headers", CONFIG_TYPE_STRING, "*"},
  1768. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1769. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1770. #if !defined(NO_CACHING)
  1771. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1772. #endif
  1773. #if !defined(NO_SSL)
  1774. {"strict_transport_security_max_age", CONFIG_TYPE_NUMBER, NULL},
  1775. #endif
  1776. #if defined(__linux__)
  1777. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1778. #endif
  1779. #if defined(_WIN32)
  1780. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1781. #endif
  1782. #if defined(USE_LUA)
  1783. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1784. #endif
  1785. {"additional_header", CONFIG_TYPE_STRING_MULTILINE, NULL},
  1786. {"max_request_size", CONFIG_TYPE_NUMBER, "16384"},
  1787. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1788. /* Check if the config_options and the corresponding enum have compatible
  1789. * sizes. */
  1790. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1791. == (NUM_OPTIONS + 1),
  1792. "config_options and enum not sync");
  1793. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1794. struct mg_handler_info {
  1795. /* Name/Pattern of the URI. */
  1796. char *uri;
  1797. size_t uri_len;
  1798. /* handler type */
  1799. int handler_type;
  1800. /* Handler for http/https or authorization requests. */
  1801. mg_request_handler handler;
  1802. /* Handler for ws/wss (websocket) requests. */
  1803. mg_websocket_connect_handler connect_handler;
  1804. mg_websocket_ready_handler ready_handler;
  1805. mg_websocket_data_handler data_handler;
  1806. mg_websocket_close_handler close_handler;
  1807. /* accepted subprotocols for ws/wss requests. */
  1808. struct mg_websocket_subprotocols *subprotocols;
  1809. /* Handler for authorization requests */
  1810. mg_authorization_handler auth_handler;
  1811. /* User supplied argument for the handler function. */
  1812. void *cbdata;
  1813. /* next handler in a linked list */
  1814. struct mg_handler_info *next;
  1815. };
  1816. struct mg_context {
  1817. volatile int stop_flag; /* Should we stop event loop */
  1818. SSL_CTX *ssl_ctx; /* SSL context */
  1819. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1820. struct mg_callbacks callbacks; /* User-defined callback function */
  1821. void *user_data; /* User-defined data */
  1822. int context_type; /* 1 = server context,
  1823. * 2 = ws/wss client context,
  1824. */
  1825. struct socket *listening_sockets;
  1826. struct pollfd *listening_socket_fds;
  1827. unsigned int num_listening_sockets;
  1828. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1829. #ifdef ALTERNATIVE_QUEUE
  1830. struct socket *client_socks;
  1831. void **client_wait_events;
  1832. #else
  1833. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1834. volatile int sq_head; /* Head of the socket queue */
  1835. volatile int sq_tail; /* Tail of the socket queue */
  1836. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1837. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1838. #endif
  1839. unsigned int max_request_size; /* The max request size */
  1840. pthread_t masterthreadid; /* The master thread ID */
  1841. unsigned int
  1842. cfg_worker_threads; /* The number of configured worker threads. */
  1843. pthread_t *worker_threadids; /* The worker thread IDs */
  1844. struct mg_connection *worker_connections; /* The connection struct, pre-
  1845. * allocated for each worker */
  1846. time_t start_time; /* Server start time, used for authentication */
  1847. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1848. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1849. unsigned long nonce_count; /* Used nonces, used for authentication */
  1850. char *systemName; /* What operating system is running */
  1851. /* linked list of uri handlers */
  1852. struct mg_handler_info *handlers;
  1853. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1854. /* linked list of shared lua websockets */
  1855. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1856. #endif
  1857. #if defined(USE_TIMERS)
  1858. struct ttimers *timers;
  1859. #endif
  1860. #if defined(USE_LUA)
  1861. void *lua_background_state;
  1862. #endif
  1863. #if defined(USE_SERVER_STATS)
  1864. int active_connections;
  1865. int max_connections;
  1866. int64_t total_connections;
  1867. int64_t total_requests;
  1868. struct mg_memory_stat ctx_memory;
  1869. #endif
  1870. };
  1871. #if defined(USE_SERVER_STATS)
  1872. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  1873. static struct mg_memory_stat *
  1874. get_memory_stat(struct mg_context *ctx)
  1875. {
  1876. if (ctx) {
  1877. return &(ctx->ctx_memory);
  1878. }
  1879. return &mg_common_memory;
  1880. }
  1881. #endif
  1882. struct mg_connection {
  1883. int connection_type; /* 0 none
  1884. * 1 request (we are server, mg_request_info valid)
  1885. * 2 response (we are client, response_info valid)
  1886. */
  1887. struct mg_request_info request_info;
  1888. struct mg_response_info response_info;
  1889. struct mg_context *ctx;
  1890. SSL *ssl; /* SSL descriptor */
  1891. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1892. struct socket client; /* Connected client */
  1893. time_t conn_birth_time; /* Time (wall clock) when connection was
  1894. * established */
  1895. struct timespec req_time; /* Time (since system start) when the request
  1896. * was received */
  1897. int64_t num_bytes_sent; /* Total bytes sent to client */
  1898. int64_t content_len; /* Content-Length header value */
  1899. int64_t consumed_content; /* How many bytes of content have been read */
  1900. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1901. * data available, 2: all data read */
  1902. size_t chunk_remainder; /* Unread data from the last chunk */
  1903. char *buf; /* Buffer for received data */
  1904. char *path_info; /* PATH_INFO part of the URL */
  1905. int must_close; /* 1 if connection must be closed */
  1906. int in_error_handler; /* 1 if in handler for user defined error
  1907. * pages */
  1908. int handled_requests; /* Number of requests handled by this connection */
  1909. int buf_size; /* Buffer size */
  1910. int request_len; /* Size of the request + headers in a buffer */
  1911. int data_len; /* Total size of data in a buffer */
  1912. int status_code; /* HTTP reply status code, e.g. 200 */
  1913. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1914. * throttle */
  1915. time_t last_throttle_time; /* Last time throttled data was sent */
  1916. int64_t last_throttle_bytes; /* Bytes sent this second */
  1917. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1918. * atomic transmissions for websockets */
  1919. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1920. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1921. #endif
  1922. int thread_index; /* Thread index within ctx */
  1923. };
  1924. /* Directory entry */
  1925. struct de {
  1926. struct mg_connection *conn;
  1927. char *file_name;
  1928. struct mg_file_stat file;
  1929. };
  1930. #if defined(USE_WEBSOCKET)
  1931. static int is_websocket_protocol(const struct mg_connection *conn);
  1932. #else
  1933. #define is_websocket_protocol(conn) (0)
  1934. #endif
  1935. #if !defined(NO_THREAD_NAME)
  1936. #if defined(_WIN32) && defined(_MSC_VER)
  1937. /* Set the thread name for debugging purposes in Visual Studio
  1938. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1939. */
  1940. #pragma pack(push, 8)
  1941. typedef struct tagTHREADNAME_INFO {
  1942. DWORD dwType; /* Must be 0x1000. */
  1943. LPCSTR szName; /* Pointer to name (in user addr space). */
  1944. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1945. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1946. } THREADNAME_INFO;
  1947. #pragma pack(pop)
  1948. #elif defined(__linux__)
  1949. #include <sys/prctl.h>
  1950. #include <sys/sendfile.h>
  1951. #ifdef ALTERNATIVE_QUEUE
  1952. #include <sys/eventfd.h>
  1953. #endif /* ALTERNATIVE_QUEUE */
  1954. #if defined(ALTERNATIVE_QUEUE)
  1955. static void *
  1956. event_create(void)
  1957. {
  1958. int ret = eventfd(0, EFD_CLOEXEC);
  1959. if (ret == -1) {
  1960. /* Linux uses -1 on error, Windows NULL. */
  1961. /* However, Linux does not return 0 on success either. */
  1962. return 0;
  1963. }
  1964. return (void *)ret;
  1965. }
  1966. static int
  1967. event_wait(void *eventhdl)
  1968. {
  1969. uint64_t u;
  1970. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1971. if (s != sizeof(uint64_t)) {
  1972. /* error */
  1973. return 0;
  1974. }
  1975. (void)u; /* the value is not required */
  1976. return 1;
  1977. }
  1978. static int
  1979. event_signal(void *eventhdl)
  1980. {
  1981. uint64_t u = 1;
  1982. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1983. if (s != sizeof(uint64_t)) {
  1984. /* error */
  1985. return 0;
  1986. }
  1987. return 1;
  1988. }
  1989. static void
  1990. event_destroy(void *eventhdl)
  1991. {
  1992. close((int)eventhdl);
  1993. }
  1994. #endif
  1995. #endif
  1996. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1997. struct posix_event {
  1998. pthread_mutex_t mutex;
  1999. pthread_cond_t cond;
  2000. };
  2001. static void *
  2002. event_create(void)
  2003. {
  2004. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2005. if (ret == 0) {
  2006. /* out of memory */
  2007. return 0;
  2008. }
  2009. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2010. /* pthread mutex not available */
  2011. mg_free(ret);
  2012. return 0;
  2013. }
  2014. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2015. /* pthread cond not available */
  2016. pthread_mutex_destroy(&(ret->mutex));
  2017. mg_free(ret);
  2018. return 0;
  2019. }
  2020. return (void *)ret;
  2021. }
  2022. static int
  2023. event_wait(void *eventhdl)
  2024. {
  2025. struct posix_event *ev = (struct posix_event *)eventhdl;
  2026. pthread_mutex_lock(&(ev->mutex));
  2027. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2028. pthread_mutex_unlock(&(ev->mutex));
  2029. return 1;
  2030. }
  2031. static int
  2032. event_signal(void *eventhdl)
  2033. {
  2034. struct posix_event *ev = (struct posix_event *)eventhdl;
  2035. pthread_mutex_lock(&(ev->mutex));
  2036. pthread_cond_signal(&(ev->cond));
  2037. pthread_mutex_unlock(&(ev->mutex));
  2038. return 1;
  2039. }
  2040. static void
  2041. event_destroy(void *eventhdl)
  2042. {
  2043. struct posix_event *ev = (struct posix_event *)eventhdl;
  2044. pthread_cond_destroy(&(ev->cond));
  2045. pthread_mutex_destroy(&(ev->mutex));
  2046. mg_free(ev);
  2047. }
  2048. #endif
  2049. static void
  2050. mg_set_thread_name(const char *name)
  2051. {
  2052. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2053. mg_snprintf(
  2054. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2055. #if defined(_WIN32)
  2056. #if defined(_MSC_VER)
  2057. /* Windows and Visual Studio Compiler */
  2058. __try
  2059. {
  2060. THREADNAME_INFO info;
  2061. info.dwType = 0x1000;
  2062. info.szName = threadName;
  2063. info.dwThreadID = ~0U;
  2064. info.dwFlags = 0;
  2065. RaiseException(0x406D1388,
  2066. 0,
  2067. sizeof(info) / sizeof(ULONG_PTR),
  2068. (ULONG_PTR *)&info);
  2069. }
  2070. __except(EXCEPTION_EXECUTE_HANDLER)
  2071. {
  2072. }
  2073. #elif defined(__MINGW32__)
  2074. /* No option known to set thread name for MinGW */
  2075. #endif
  2076. #elif defined(__GLIBC__) \
  2077. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2078. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2079. (void)pthread_setname_np(pthread_self(), threadName);
  2080. #elif defined(__linux__)
  2081. /* on linux we can use the old prctl function */
  2082. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2083. #endif
  2084. }
  2085. #else /* !defined(NO_THREAD_NAME) */
  2086. void
  2087. mg_set_thread_name(const char *threadName)
  2088. {
  2089. }
  2090. #endif
  2091. #if defined(MG_LEGACY_INTERFACE)
  2092. const char **
  2093. mg_get_valid_option_names(void)
  2094. {
  2095. /* This function is deprecated. Use mg_get_valid_options instead. */
  2096. static const char *
  2097. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2098. int i;
  2099. for (i = 0; config_options[i].name != NULL; i++) {
  2100. data[i * 2] = config_options[i].name;
  2101. data[i * 2 + 1] = config_options[i].default_value;
  2102. }
  2103. return data;
  2104. }
  2105. #endif
  2106. const struct mg_option *
  2107. mg_get_valid_options(void)
  2108. {
  2109. return config_options;
  2110. }
  2111. /* Do not open file (used in is_file_in_memory) */
  2112. #define MG_FOPEN_MODE_NONE (0)
  2113. /* Open file for read only access */
  2114. #define MG_FOPEN_MODE_READ (1)
  2115. /* Open file for writing, create and overwrite */
  2116. #define MG_FOPEN_MODE_WRITE (2)
  2117. /* Open file for writing, create and append */
  2118. #define MG_FOPEN_MODE_APPEND (4)
  2119. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2120. * output filep and return 1, otherwise return 0 and don't modify anything. */
  2121. static int
  2122. open_file_in_memory(const struct mg_connection *conn,
  2123. const char *path,
  2124. struct mg_file *filep,
  2125. int mode)
  2126. {
  2127. #if defined(MG_USE_OPEN_FILE)
  2128. size_t size = 0;
  2129. const char *buf = NULL;
  2130. if (!conn) {
  2131. return 0;
  2132. }
  2133. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2134. return 0;
  2135. }
  2136. if (conn->ctx->callbacks.open_file) {
  2137. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2138. if (buf != NULL) {
  2139. if (filep == NULL) {
  2140. /* This is a file in memory, but we cannot store the properties
  2141. * now.
  2142. * Called from "is_file_in_memory" function. */
  2143. return 1;
  2144. }
  2145. /* NOTE: override filep->size only on success. Otherwise, it might
  2146. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2147. filep->access.membuf = buf;
  2148. filep->access.fp = NULL;
  2149. /* Size was set by the callback */
  2150. filep->stat.size = size;
  2151. /* Assume the data may change during runtime by setting
  2152. * last_modified = now */
  2153. filep->stat.last_modified = time(NULL);
  2154. filep->stat.is_directory = 0;
  2155. filep->stat.is_gzipped = 0;
  2156. }
  2157. }
  2158. return (buf != NULL);
  2159. #else
  2160. (void)conn;
  2161. (void)path;
  2162. (void)filep;
  2163. (void)mode;
  2164. return 0;
  2165. #endif
  2166. }
  2167. static int
  2168. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2169. {
  2170. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2171. }
  2172. static int
  2173. is_file_opened(const struct mg_file_access *fileacc)
  2174. {
  2175. if (!fileacc) {
  2176. return 0;
  2177. }
  2178. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2179. }
  2180. static int mg_stat(const struct mg_connection *conn,
  2181. const char *path,
  2182. struct mg_file_stat *filep);
  2183. /* mg_fopen will open a file either in memory or on the disk.
  2184. * The input parameter path is a string in UTF-8 encoding.
  2185. * The input parameter mode is MG_FOPEN_MODE_*
  2186. * On success, either fp or membuf will be set in the output
  2187. * struct file. All status members will also be set.
  2188. * The function returns 1 on success, 0 on error. */
  2189. static int
  2190. mg_fopen(const struct mg_connection *conn,
  2191. const char *path,
  2192. int mode,
  2193. struct mg_file *filep)
  2194. {
  2195. int found;
  2196. if (!filep) {
  2197. return 0;
  2198. }
  2199. filep->access.fp = NULL;
  2200. filep->access.membuf = NULL;
  2201. if (!is_file_in_memory(conn, path)) {
  2202. /* filep is initialized in mg_stat: all fields with memset to,
  2203. * some fields like size and modification date with values */
  2204. found = mg_stat(conn, path, &(filep->stat));
  2205. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2206. /* file does not exist and will not be created */
  2207. return 0;
  2208. }
  2209. #ifdef _WIN32
  2210. {
  2211. wchar_t wbuf[PATH_MAX];
  2212. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2213. switch (mode) {
  2214. case MG_FOPEN_MODE_READ:
  2215. filep->access.fp = _wfopen(wbuf, L"rb");
  2216. break;
  2217. case MG_FOPEN_MODE_WRITE:
  2218. filep->access.fp = _wfopen(wbuf, L"wb");
  2219. break;
  2220. case MG_FOPEN_MODE_APPEND:
  2221. filep->access.fp = _wfopen(wbuf, L"ab");
  2222. break;
  2223. }
  2224. }
  2225. #else
  2226. /* Linux et al already use unicode. No need to convert. */
  2227. switch (mode) {
  2228. case MG_FOPEN_MODE_READ:
  2229. filep->access.fp = fopen(path, "r");
  2230. break;
  2231. case MG_FOPEN_MODE_WRITE:
  2232. filep->access.fp = fopen(path, "w");
  2233. break;
  2234. case MG_FOPEN_MODE_APPEND:
  2235. filep->access.fp = fopen(path, "a");
  2236. break;
  2237. }
  2238. #endif
  2239. if (!found) {
  2240. /* File did not exist before fopen was called.
  2241. * Maybe it has been created now. Get stat info
  2242. * like creation time now. */
  2243. found = mg_stat(conn, path, &(filep->stat));
  2244. (void)found;
  2245. }
  2246. /* file is on disk */
  2247. return (filep->access.fp != NULL);
  2248. } else {
  2249. /* is_file_in_memory returned true */
  2250. if (open_file_in_memory(conn, path, filep, mode)) {
  2251. /* file is in memory */
  2252. return (filep->access.membuf != NULL);
  2253. }
  2254. }
  2255. /* Open failed */
  2256. return 0;
  2257. }
  2258. /* return 0 on success, just like fclose */
  2259. static int
  2260. mg_fclose(struct mg_file_access *fileacc)
  2261. {
  2262. int ret = -1;
  2263. if (fileacc != NULL) {
  2264. if (fileacc->fp != NULL) {
  2265. ret = fclose(fileacc->fp);
  2266. } else if (fileacc->membuf != NULL) {
  2267. ret = 0;
  2268. }
  2269. /* reset all members of fileacc */
  2270. memset(fileacc, 0, sizeof(*fileacc));
  2271. }
  2272. return ret;
  2273. }
  2274. static void
  2275. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2276. {
  2277. for (; *src != '\0' && n > 1; n--) {
  2278. *dst++ = *src++;
  2279. }
  2280. *dst = '\0';
  2281. }
  2282. static int
  2283. lowercase(const char *s)
  2284. {
  2285. return tolower(*(const unsigned char *)s);
  2286. }
  2287. int
  2288. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2289. {
  2290. int diff = 0;
  2291. if (len > 0) {
  2292. do {
  2293. diff = lowercase(s1++) - lowercase(s2++);
  2294. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2295. }
  2296. return diff;
  2297. }
  2298. int
  2299. mg_strcasecmp(const char *s1, const char *s2)
  2300. {
  2301. int diff;
  2302. do {
  2303. diff = lowercase(s1++) - lowercase(s2++);
  2304. } while (diff == 0 && s1[-1] != '\0');
  2305. return diff;
  2306. }
  2307. static char *
  2308. mg_strndup(const char *ptr, size_t len)
  2309. {
  2310. char *p;
  2311. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2312. mg_strlcpy(p, ptr, len + 1);
  2313. }
  2314. return p;
  2315. }
  2316. static char *
  2317. mg_strdup(const char *str)
  2318. {
  2319. return mg_strndup(str, strlen(str));
  2320. }
  2321. static const char *
  2322. mg_strcasestr(const char *big_str, const char *small_str)
  2323. {
  2324. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2325. if (big_len >= small_len) {
  2326. for (i = 0; i <= (big_len - small_len); i++) {
  2327. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2328. return big_str + i;
  2329. }
  2330. }
  2331. }
  2332. return NULL;
  2333. }
  2334. /* Return null terminated string of given maximum length.
  2335. * Report errors if length is exceeded. */
  2336. static void
  2337. mg_vsnprintf(const struct mg_connection *conn,
  2338. int *truncated,
  2339. char *buf,
  2340. size_t buflen,
  2341. const char *fmt,
  2342. va_list ap)
  2343. {
  2344. int n, ok;
  2345. if (buflen == 0) {
  2346. if (truncated) {
  2347. *truncated = 1;
  2348. }
  2349. return;
  2350. }
  2351. #ifdef __clang__
  2352. #pragma clang diagnostic push
  2353. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2354. /* Using fmt as a non-literal is intended here, since it is mostly called
  2355. * indirectly by mg_snprintf */
  2356. #endif
  2357. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2358. ok = (n >= 0) && ((size_t)n < buflen);
  2359. #ifdef __clang__
  2360. #pragma clang diagnostic pop
  2361. #endif
  2362. if (ok) {
  2363. if (truncated) {
  2364. *truncated = 0;
  2365. }
  2366. } else {
  2367. if (truncated) {
  2368. *truncated = 1;
  2369. }
  2370. mg_cry(conn,
  2371. "truncating vsnprintf buffer: [%.*s]",
  2372. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2373. buf);
  2374. n = (int)buflen - 1;
  2375. }
  2376. buf[n] = '\0';
  2377. }
  2378. static void
  2379. mg_snprintf(const struct mg_connection *conn,
  2380. int *truncated,
  2381. char *buf,
  2382. size_t buflen,
  2383. const char *fmt,
  2384. ...)
  2385. {
  2386. va_list ap;
  2387. va_start(ap, fmt);
  2388. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2389. va_end(ap);
  2390. }
  2391. static int
  2392. get_option_index(const char *name)
  2393. {
  2394. int i;
  2395. for (i = 0; config_options[i].name != NULL; i++) {
  2396. if (strcmp(config_options[i].name, name) == 0) {
  2397. return i;
  2398. }
  2399. }
  2400. return -1;
  2401. }
  2402. const char *
  2403. mg_get_option(const struct mg_context *ctx, const char *name)
  2404. {
  2405. int i;
  2406. if ((i = get_option_index(name)) == -1) {
  2407. return NULL;
  2408. } else if (!ctx || ctx->config[i] == NULL) {
  2409. return "";
  2410. } else {
  2411. return ctx->config[i];
  2412. }
  2413. }
  2414. struct mg_context *
  2415. mg_get_context(const struct mg_connection *conn)
  2416. {
  2417. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2418. }
  2419. void *
  2420. mg_get_user_data(const struct mg_context *ctx)
  2421. {
  2422. return (ctx == NULL) ? NULL : ctx->user_data;
  2423. }
  2424. void
  2425. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2426. {
  2427. if (conn != NULL) {
  2428. conn->request_info.conn_data = data;
  2429. }
  2430. }
  2431. void *
  2432. mg_get_user_connection_data(const struct mg_connection *conn)
  2433. {
  2434. if (conn != NULL) {
  2435. return conn->request_info.conn_data;
  2436. }
  2437. return NULL;
  2438. }
  2439. #if defined(MG_LEGACY_INTERFACE)
  2440. /* Deprecated: Use mg_get_server_ports instead. */
  2441. size_t
  2442. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2443. {
  2444. size_t i;
  2445. if (!ctx) {
  2446. return 0;
  2447. }
  2448. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2449. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2450. ports[i] =
  2451. #if defined(USE_IPV6)
  2452. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2453. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2454. :
  2455. #endif
  2456. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2457. }
  2458. return i;
  2459. }
  2460. #endif
  2461. int
  2462. mg_get_server_ports(const struct mg_context *ctx,
  2463. int size,
  2464. struct mg_server_ports *ports)
  2465. {
  2466. int i, cnt = 0;
  2467. if (size <= 0) {
  2468. return -1;
  2469. }
  2470. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2471. if (!ctx) {
  2472. return -1;
  2473. }
  2474. if (!ctx->listening_sockets) {
  2475. return -1;
  2476. }
  2477. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2478. ports[cnt].port =
  2479. #if defined(USE_IPV6)
  2480. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2481. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2482. :
  2483. #endif
  2484. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2485. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2486. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2487. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2488. /* IPv4 */
  2489. ports[cnt].protocol = 1;
  2490. cnt++;
  2491. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2492. /* IPv6 */
  2493. ports[cnt].protocol = 3;
  2494. cnt++;
  2495. }
  2496. }
  2497. return cnt;
  2498. }
  2499. static void
  2500. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2501. {
  2502. buf[0] = '\0';
  2503. if (!usa) {
  2504. return;
  2505. }
  2506. if (usa->sa.sa_family == AF_INET) {
  2507. getnameinfo(&usa->sa,
  2508. sizeof(usa->sin),
  2509. buf,
  2510. (unsigned)len,
  2511. NULL,
  2512. 0,
  2513. NI_NUMERICHOST);
  2514. }
  2515. #if defined(USE_IPV6)
  2516. else if (usa->sa.sa_family == AF_INET6) {
  2517. getnameinfo(&usa->sa,
  2518. sizeof(usa->sin6),
  2519. buf,
  2520. (unsigned)len,
  2521. NULL,
  2522. 0,
  2523. NI_NUMERICHOST);
  2524. }
  2525. #endif
  2526. }
  2527. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2528. * included in all responses other than 100, 101, 5xx. */
  2529. static void
  2530. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2531. {
  2532. struct tm *tm;
  2533. tm = ((t != NULL) ? gmtime(t) : NULL);
  2534. if (tm != NULL) {
  2535. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2536. } else {
  2537. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2538. buf[buf_len - 1] = '\0';
  2539. }
  2540. }
  2541. /* difftime for struct timespec. Return value is in seconds. */
  2542. static double
  2543. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2544. {
  2545. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2546. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2547. }
  2548. /* Print error message to the opened error log stream. */
  2549. void
  2550. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2551. {
  2552. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2553. va_list ap;
  2554. struct mg_file fi;
  2555. time_t timestamp;
  2556. va_start(ap, fmt);
  2557. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2558. va_end(ap);
  2559. buf[sizeof(buf) - 1] = 0;
  2560. if (!conn) {
  2561. puts(buf);
  2562. return;
  2563. }
  2564. /* Do not lock when getting the callback value, here and below.
  2565. * I suppose this is fine, since function cannot disappear in the
  2566. * same way string option can. */
  2567. if ((conn->ctx->callbacks.log_message == NULL)
  2568. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2569. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2570. if (mg_fopen(conn,
  2571. conn->ctx->config[ERROR_LOG_FILE],
  2572. MG_FOPEN_MODE_APPEND,
  2573. &fi) == 0) {
  2574. fi.access.fp = NULL;
  2575. }
  2576. } else {
  2577. fi.access.fp = NULL;
  2578. }
  2579. if (fi.access.fp != NULL) {
  2580. flockfile(fi.access.fp);
  2581. timestamp = time(NULL);
  2582. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2583. fprintf(fi.access.fp,
  2584. "[%010lu] [error] [client %s] ",
  2585. (unsigned long)timestamp,
  2586. src_addr);
  2587. if (conn->request_info.request_method != NULL) {
  2588. fprintf(fi.access.fp,
  2589. "%s %s: ",
  2590. conn->request_info.request_method,
  2591. conn->request_info.request_uri
  2592. ? conn->request_info.request_uri
  2593. : "");
  2594. }
  2595. fprintf(fi.access.fp, "%s", buf);
  2596. fputc('\n', fi.access.fp);
  2597. fflush(fi.access.fp);
  2598. funlockfile(fi.access.fp);
  2599. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2600. * mg_cry here anyway ;-) */
  2601. }
  2602. }
  2603. }
  2604. /* Return fake connection structure. Used for logging, if connection
  2605. * is not applicable at the moment of logging. */
  2606. static struct mg_connection *
  2607. fc(struct mg_context *ctx)
  2608. {
  2609. static struct mg_connection fake_connection;
  2610. fake_connection.ctx = ctx;
  2611. return &fake_connection;
  2612. }
  2613. const char *
  2614. mg_version(void)
  2615. {
  2616. return CIVETWEB_VERSION;
  2617. }
  2618. const struct mg_request_info *
  2619. mg_get_request_info(const struct mg_connection *conn)
  2620. {
  2621. if (!conn) {
  2622. return NULL;
  2623. }
  2624. #if 1 /* TODO: deal with legacy */
  2625. if (conn->connection_type == 2) {
  2626. static char txt[16];
  2627. sprintf(txt, "%03i", conn->response_info.status_code);
  2628. ((struct mg_connection *)conn)->request_info.local_uri =
  2629. ((struct mg_connection *)conn)->request_info.request_uri =
  2630. txt; /* TODO: not thread safe */
  2631. ((struct mg_connection *)conn)->request_info.num_headers =
  2632. conn->response_info.num_headers;
  2633. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2634. conn->response_info.http_headers,
  2635. sizeof(conn->response_info.http_headers));
  2636. } else
  2637. #endif
  2638. if (conn->connection_type != 1) {
  2639. return NULL;
  2640. }
  2641. return &conn->request_info;
  2642. }
  2643. const struct mg_response_info *
  2644. mg_get_response_info(const struct mg_connection *conn)
  2645. {
  2646. if (!conn) {
  2647. return NULL;
  2648. }
  2649. if (conn->connection_type != 2) {
  2650. return NULL;
  2651. }
  2652. return &conn->response_info;
  2653. }
  2654. int
  2655. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2656. {
  2657. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2658. return -1;
  2659. } else {
  2660. int truncated = 0;
  2661. const struct mg_request_info *ri = &conn->request_info;
  2662. #ifdef __clang__
  2663. #pragma clang diagnostic push
  2664. #pragma clang diagnostic ignored "-Wunreachable-code"
  2665. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2666. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2667. * unreachable, but splitting into four different #ifdef clauses here is more
  2668. * complicated.
  2669. */
  2670. #endif
  2671. const char *proto =
  2672. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2673. : (ri->is_ssl ? "https" : "http"));
  2674. #ifdef __clang__
  2675. #pragma clang diagnostic pop
  2676. #endif
  2677. if (ri->local_uri == NULL) {
  2678. return -1;
  2679. }
  2680. if ((ri->request_uri != NULL)
  2681. && strcmp(ri->local_uri, ri->request_uri)) {
  2682. mg_snprintf(conn,
  2683. &truncated,
  2684. buf,
  2685. buflen,
  2686. "%s://%s",
  2687. proto,
  2688. ri->request_uri);
  2689. if (truncated) {
  2690. return -1;
  2691. }
  2692. return 0;
  2693. } else {
  2694. #if defined(USE_IPV6)
  2695. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2696. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2697. : htons(conn->client.lsa.sin.sin_port);
  2698. #else
  2699. int port = htons(conn->client.lsa.sin.sin_port);
  2700. #endif
  2701. int def_port = ri->is_ssl ? 443 : 80;
  2702. int auth_domain_check_enabled =
  2703. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2704. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2705. "yes"));
  2706. const char *server_domain =
  2707. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2708. char portstr[16];
  2709. char server_ip[48];
  2710. if (port != def_port) {
  2711. sprintf(portstr, ":%u", (unsigned)port);
  2712. } else {
  2713. portstr[0] = 0;
  2714. }
  2715. if (!auth_domain_check_enabled || !server_domain) {
  2716. sockaddr_to_string(server_ip,
  2717. sizeof(server_ip),
  2718. &conn->client.lsa);
  2719. server_domain = server_ip;
  2720. }
  2721. mg_snprintf(conn,
  2722. &truncated,
  2723. buf,
  2724. buflen,
  2725. "%s://%s%s%s",
  2726. proto,
  2727. server_domain,
  2728. portstr,
  2729. ri->local_uri);
  2730. if (truncated) {
  2731. return -1;
  2732. }
  2733. return 0;
  2734. }
  2735. }
  2736. }
  2737. /* Skip the characters until one of the delimiters characters found.
  2738. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2739. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2740. * Delimiters can be quoted with quotechar. */
  2741. static char *
  2742. skip_quoted(char **buf,
  2743. const char *delimiters,
  2744. const char *whitespace,
  2745. char quotechar)
  2746. {
  2747. char *p, *begin_word, *end_word, *end_whitespace;
  2748. begin_word = *buf;
  2749. end_word = begin_word + strcspn(begin_word, delimiters);
  2750. /* Check for quotechar */
  2751. if (end_word > begin_word) {
  2752. p = end_word - 1;
  2753. while (*p == quotechar) {
  2754. /* While the delimiter is quoted, look for the next delimiter. */
  2755. /* This happens, e.g., in calls from parse_auth_header,
  2756. * if the user name contains a " character. */
  2757. /* If there is anything beyond end_word, copy it. */
  2758. if (*end_word != '\0') {
  2759. size_t end_off = strcspn(end_word + 1, delimiters);
  2760. memmove(p, end_word, end_off + 1);
  2761. p += end_off; /* p must correspond to end_word - 1 */
  2762. end_word += end_off + 1;
  2763. } else {
  2764. *p = '\0';
  2765. break;
  2766. }
  2767. }
  2768. for (p++; p < end_word; p++) {
  2769. *p = '\0';
  2770. }
  2771. }
  2772. if (*end_word == '\0') {
  2773. *buf = end_word;
  2774. } else {
  2775. #if defined(__GNUC__) || defined(__MINGW32__)
  2776. /* Disable spurious conversion warning for GCC */
  2777. #if GCC_VERSION >= 40500
  2778. #pragma GCC diagnostic push
  2779. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2780. #endif /* GCC_VERSION >= 40500 */
  2781. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  2782. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2783. #if defined(__GNUC__) || defined(__MINGW32__)
  2784. #if GCC_VERSION >= 40500
  2785. #pragma GCC diagnostic pop
  2786. #endif /* GCC_VERSION >= 40500 */
  2787. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  2788. for (p = end_word; p < end_whitespace; p++) {
  2789. *p = '\0';
  2790. }
  2791. *buf = end_whitespace;
  2792. }
  2793. return begin_word;
  2794. }
  2795. /* Return HTTP header value, or NULL if not found. */
  2796. static const char *
  2797. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  2798. {
  2799. int i;
  2800. for (i = 0; i < num_hdr; i++) {
  2801. if (!mg_strcasecmp(name, hdr[i].name)) {
  2802. return hdr[i].value;
  2803. }
  2804. }
  2805. return NULL;
  2806. }
  2807. #if defined(USE_WEBSOCKET)
  2808. /* Retrieve requested HTTP header multiple values, and return the number of
  2809. * found occurences */
  2810. static int
  2811. get_req_headers(const struct mg_request_info *ri,
  2812. const char *name,
  2813. const char **output,
  2814. int output_max_size)
  2815. {
  2816. int i;
  2817. int cnt = 0;
  2818. if (ri) {
  2819. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  2820. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2821. output[cnt++] = ri->http_headers[i].value;
  2822. }
  2823. }
  2824. }
  2825. return cnt;
  2826. }
  2827. #endif
  2828. const char *
  2829. mg_get_header(const struct mg_connection *conn, const char *name)
  2830. {
  2831. if (!conn) {
  2832. return NULL;
  2833. }
  2834. if (conn->connection_type == 1) {
  2835. return get_header(conn->request_info.http_headers,
  2836. conn->request_info.num_headers,
  2837. name);
  2838. }
  2839. if (conn->connection_type == 2) {
  2840. return get_header(conn->response_info.http_headers,
  2841. conn->request_info.num_headers,
  2842. name);
  2843. }
  2844. return NULL;
  2845. }
  2846. static const char *
  2847. get_http_version(const struct mg_connection *conn)
  2848. {
  2849. if (!conn) {
  2850. return NULL;
  2851. }
  2852. if (conn->connection_type == 1) {
  2853. return conn->request_info.http_version;
  2854. }
  2855. if (conn->connection_type == 2) {
  2856. return conn->response_info.http_version;
  2857. }
  2858. return NULL;
  2859. }
  2860. /* A helper function for traversing a comma separated list of values.
  2861. * It returns a list pointer shifted to the next value, or NULL if the end
  2862. * of the list found.
  2863. * Value is stored in val vector. If value has form "x=y", then eq_val
  2864. * vector is initialized to point to the "y" part, and val vector length
  2865. * is adjusted to point only to "x". */
  2866. static const char *
  2867. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2868. {
  2869. int end;
  2870. reparse:
  2871. if (val == NULL || list == NULL || *list == '\0') {
  2872. /* End of the list */
  2873. list = NULL;
  2874. } else {
  2875. /* Skip over leading LWS */
  2876. while (*list == ' ' || *list == '\t')
  2877. list++;
  2878. val->ptr = list;
  2879. if ((list = strchr(val->ptr, ',')) != NULL) {
  2880. /* Comma found. Store length and shift the list ptr */
  2881. val->len = ((size_t)(list - val->ptr));
  2882. list++;
  2883. } else {
  2884. /* This value is the last one */
  2885. list = val->ptr + strlen(val->ptr);
  2886. val->len = ((size_t)(list - val->ptr));
  2887. }
  2888. /* Adjust length for trailing LWS */
  2889. end = (int)val->len - 1;
  2890. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  2891. end--;
  2892. val->len = (size_t)(end + 1);
  2893. if (val->len == 0) {
  2894. /* Ignore any empty entries. */
  2895. goto reparse;
  2896. }
  2897. if (eq_val != NULL) {
  2898. /* Value has form "x=y", adjust pointers and lengths
  2899. * so that val points to "x", and eq_val points to "y". */
  2900. eq_val->len = 0;
  2901. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2902. if (eq_val->ptr != NULL) {
  2903. eq_val->ptr++; /* Skip over '=' character */
  2904. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2905. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2906. }
  2907. }
  2908. }
  2909. return list;
  2910. }
  2911. /* A helper function for checking if a comma separated list of values contains
  2912. * the given option (case insensitvely).
  2913. * 'header' can be NULL, in which case false is returned. */
  2914. static int
  2915. header_has_option(const char *header, const char *option)
  2916. {
  2917. struct vec opt_vec;
  2918. struct vec eq_vec;
  2919. /*
  2920. assert(option != NULL);
  2921. assert(option[0] != '\0');
  2922. */
  2923. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2924. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2925. return 1;
  2926. }
  2927. return 0;
  2928. }
  2929. /* Perform case-insensitive match of string against pattern */
  2930. static int
  2931. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2932. {
  2933. const char *or_str;
  2934. size_t i;
  2935. int j, len, res;
  2936. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2937. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2938. return (res > 0) ? res : match_prefix(or_str + 1,
  2939. (size_t)((pattern + pattern_len)
  2940. - (or_str + 1)),
  2941. str);
  2942. }
  2943. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  2944. if ((pattern[i] == '?') && (str[j] != '\0')) {
  2945. continue;
  2946. } else if (pattern[i] == '$') {
  2947. return (str[j] == '\0') ? j : -1;
  2948. } else if (pattern[i] == '*') {
  2949. i++;
  2950. if (pattern[i] == '*') {
  2951. i++;
  2952. len = (int)strlen(str + j);
  2953. } else {
  2954. len = (int)strcspn(str + j, "/");
  2955. }
  2956. if (i == pattern_len) {
  2957. return j + len;
  2958. }
  2959. do {
  2960. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2961. } while (res == -1 && len-- > 0);
  2962. return (res == -1) ? -1 : j + res + len;
  2963. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2964. return -1;
  2965. }
  2966. }
  2967. return j;
  2968. }
  2969. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2970. * This function must tolerate situations when connection info is not
  2971. * set up, for example if request parsing failed. */
  2972. static int
  2973. should_keep_alive(const struct mg_connection *conn)
  2974. {
  2975. const char *http_version;
  2976. const char *header;
  2977. /* First satisfy needs of the server */
  2978. if ((conn == NULL) || conn->must_close) {
  2979. /* Close, if civetweb framework needs to close */
  2980. return 0;
  2981. }
  2982. if (mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  2983. /* Close, if keep alive is not enabled */
  2984. return 0;
  2985. }
  2986. /* Check explicit wish of the client */
  2987. header = mg_get_header(conn, "Connection");
  2988. if (header) {
  2989. /* If there is a connection header from the client, obey */
  2990. if (header_has_option(header, "keep-alive")) {
  2991. return 1;
  2992. }
  2993. return 0;
  2994. }
  2995. /* Use default of the standard */
  2996. http_version = get_http_version(conn);
  2997. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  2998. /* HTTP 1.1 default is keep alive */
  2999. return 1;
  3000. }
  3001. /* HTTP 1.0 (and earlier) default is to close the connection */
  3002. return 0;
  3003. }
  3004. static int
  3005. should_decode_url(const struct mg_connection *conn)
  3006. {
  3007. if (!conn || !conn->ctx) {
  3008. return 0;
  3009. }
  3010. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  3011. }
  3012. static const char *
  3013. suggest_connection_header(const struct mg_connection *conn)
  3014. {
  3015. return should_keep_alive(conn) ? "keep-alive" : "close";
  3016. }
  3017. static int
  3018. send_no_cache_header(struct mg_connection *conn)
  3019. {
  3020. /* Send all current and obsolete cache opt-out directives. */
  3021. return mg_printf(conn,
  3022. "Cache-Control: no-cache, no-store, "
  3023. "must-revalidate, private, max-age=0\r\n"
  3024. "Pragma: no-cache\r\n"
  3025. "Expires: 0\r\n");
  3026. }
  3027. static int
  3028. send_static_cache_header(struct mg_connection *conn)
  3029. {
  3030. #if !defined(NO_CACHING)
  3031. /* Read the server config to check how long a file may be cached.
  3032. * The configuration is in seconds. */
  3033. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  3034. if (max_age <= 0) {
  3035. /* 0 means "do not cache". All values <0 are reserved
  3036. * and may be used differently in the future. */
  3037. /* If a file should not be cached, do not only send
  3038. * max-age=0, but also pragmas and Expires headers. */
  3039. return send_no_cache_header(conn);
  3040. }
  3041. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3042. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3043. /* See also https://www.mnot.net/cache_docs/ */
  3044. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3045. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  3046. * year to 31622400 seconds. For the moment, we just send whatever has
  3047. * been configured, still the behavior for >1 year should be considered
  3048. * as undefined. */
  3049. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3050. #else /* NO_CACHING */
  3051. return send_no_cache_header(conn);
  3052. #endif /* !NO_CACHING */
  3053. }
  3054. static int
  3055. send_additional_header(struct mg_connection *conn)
  3056. {
  3057. int i = 0;
  3058. const char *header = conn->ctx->config[ADDITIONAL_HEADER];
  3059. #if !defined(NO_SSL)
  3060. if (conn->ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3061. int max_age = atoi(conn->ctx->config[STRICT_HTTPS_MAX_AGE]);
  3062. if (max_age >= 0) {
  3063. i += mg_printf(conn,
  3064. "Strict-Transport-Security: max-age=%u\r\n",
  3065. (unsigned)max_age);
  3066. }
  3067. }
  3068. #endif
  3069. if (header && header[0]) {
  3070. i += mg_printf(conn, "%s\r\n", header);
  3071. }
  3072. return i;
  3073. }
  3074. static void handle_file_based_request(struct mg_connection *conn,
  3075. const char *path,
  3076. struct mg_file *filep);
  3077. const char *
  3078. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3079. {
  3080. /* See IANA HTTP status code assignment:
  3081. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3082. */
  3083. switch (response_code) {
  3084. /* RFC2616 Section 10.1 - Informational 1xx */
  3085. case 100:
  3086. return "Continue"; /* RFC2616 Section 10.1.1 */
  3087. case 101:
  3088. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3089. case 102:
  3090. return "Processing"; /* RFC2518 Section 10.1 */
  3091. /* RFC2616 Section 10.2 - Successful 2xx */
  3092. case 200:
  3093. return "OK"; /* RFC2616 Section 10.2.1 */
  3094. case 201:
  3095. return "Created"; /* RFC2616 Section 10.2.2 */
  3096. case 202:
  3097. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3098. case 203:
  3099. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3100. case 204:
  3101. return "No Content"; /* RFC2616 Section 10.2.5 */
  3102. case 205:
  3103. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3104. case 206:
  3105. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3106. case 207:
  3107. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  3108. case 208:
  3109. return "Already Reported"; /* RFC5842 Section 7.1 */
  3110. case 226:
  3111. return "IM used"; /* RFC3229 Section 10.4.1 */
  3112. /* RFC2616 Section 10.3 - Redirection 3xx */
  3113. case 300:
  3114. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3115. case 301:
  3116. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3117. case 302:
  3118. return "Found"; /* RFC2616 Section 10.3.3 */
  3119. case 303:
  3120. return "See Other"; /* RFC2616 Section 10.3.4 */
  3121. case 304:
  3122. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3123. case 305:
  3124. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3125. case 307:
  3126. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3127. case 308:
  3128. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3129. /* RFC2616 Section 10.4 - Client Error 4xx */
  3130. case 400:
  3131. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3132. case 401:
  3133. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3134. case 402:
  3135. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3136. case 403:
  3137. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3138. case 404:
  3139. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3140. case 405:
  3141. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3142. case 406:
  3143. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3144. case 407:
  3145. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3146. case 408:
  3147. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3148. case 409:
  3149. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3150. case 410:
  3151. return "Gone"; /* RFC2616 Section 10.4.11 */
  3152. case 411:
  3153. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3154. case 412:
  3155. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3156. case 413:
  3157. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3158. case 414:
  3159. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3160. case 415:
  3161. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3162. case 416:
  3163. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  3164. case 417:
  3165. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3166. case 421:
  3167. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3168. case 422:
  3169. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3170. * Section 11.2 */
  3171. case 423:
  3172. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3173. case 424:
  3174. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3175. * Section 11.4 */
  3176. case 426:
  3177. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3178. case 428:
  3179. return "Precondition Required"; /* RFC 6585, Section 3 */
  3180. case 429:
  3181. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3182. case 431:
  3183. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3184. case 451:
  3185. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3186. * Section 3 */
  3187. /* RFC2616 Section 10.5 - Server Error 5xx */
  3188. case 500:
  3189. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3190. case 501:
  3191. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3192. case 502:
  3193. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3194. case 503:
  3195. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3196. case 504:
  3197. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3198. case 505:
  3199. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3200. case 506:
  3201. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3202. case 507:
  3203. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3204. * Section 11.5 */
  3205. case 508:
  3206. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3207. case 510:
  3208. return "Not Extended"; /* RFC 2774, Section 7 */
  3209. case 511:
  3210. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3211. /* Other status codes, not shown in the IANA HTTP status code assignment.
  3212. * E.g., "de facto" standards due to common use, ... */
  3213. case 418:
  3214. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3215. case 419:
  3216. return "Authentication Timeout"; /* common use */
  3217. case 420:
  3218. return "Enhance Your Calm"; /* common use */
  3219. case 440:
  3220. return "Login Timeout"; /* common use */
  3221. case 509:
  3222. return "Bandwidth Limit Exceeded"; /* common use */
  3223. default:
  3224. /* This error code is unknown. This should not happen. */
  3225. if (conn) {
  3226. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3227. }
  3228. /* Return at least a category according to RFC 2616 Section 10. */
  3229. if (response_code >= 100 && response_code < 200) {
  3230. /* Unknown informational status code */
  3231. return "Information";
  3232. }
  3233. if (response_code >= 200 && response_code < 300) {
  3234. /* Unknown success code */
  3235. return "Success";
  3236. }
  3237. if (response_code >= 300 && response_code < 400) {
  3238. /* Unknown redirection code */
  3239. return "Redirection";
  3240. }
  3241. if (response_code >= 400 && response_code < 500) {
  3242. /* Unknown request error code */
  3243. return "Client Error";
  3244. }
  3245. if (response_code >= 500 && response_code < 600) {
  3246. /* Unknown server error code */
  3247. return "Server Error";
  3248. }
  3249. /* Response code not even within reasonable range */
  3250. return "";
  3251. }
  3252. }
  3253. void
  3254. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3255. {
  3256. char buf[MG_BUF_LEN];
  3257. va_list ap;
  3258. int len, i, page_handler_found, scope, truncated, has_body;
  3259. char date[64];
  3260. time_t curtime = time(NULL);
  3261. const char *error_handler = NULL;
  3262. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3263. const char *error_page_file_ext, *tstr;
  3264. const char *status_text = mg_get_response_code_text(conn, status);
  3265. if (conn == NULL) {
  3266. return;
  3267. }
  3268. conn->status_code = status;
  3269. if (conn->in_error_handler || (conn->ctx->callbacks.http_error == NULL)
  3270. || conn->ctx->callbacks.http_error(conn, status)) {
  3271. if (!conn->in_error_handler) {
  3272. /* Send user defined error pages, if defined */
  3273. error_handler = conn->ctx->config[ERROR_PAGES];
  3274. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3275. page_handler_found = 0;
  3276. if (error_handler != NULL) {
  3277. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3278. switch (scope) {
  3279. case 1: /* Handler for specific error, e.g. 404 error */
  3280. mg_snprintf(conn,
  3281. &truncated,
  3282. buf,
  3283. sizeof(buf) - 32,
  3284. "%serror%03u.",
  3285. error_handler,
  3286. status);
  3287. break;
  3288. case 2: /* Handler for error group, e.g., 5xx error handler
  3289. * for all server errors (500-599) */
  3290. mg_snprintf(conn,
  3291. &truncated,
  3292. buf,
  3293. sizeof(buf) - 32,
  3294. "%serror%01uxx.",
  3295. error_handler,
  3296. status / 100);
  3297. break;
  3298. default: /* Handler for all errors */
  3299. mg_snprintf(conn,
  3300. &truncated,
  3301. buf,
  3302. sizeof(buf) - 32,
  3303. "%serror.",
  3304. error_handler);
  3305. break;
  3306. }
  3307. /* String truncation in buf may only occur if error_handler
  3308. * is too long. This string is from the config, not from a
  3309. * client. */
  3310. (void)truncated;
  3311. len = (int)strlen(buf);
  3312. tstr = strchr(error_page_file_ext, '.');
  3313. while (tstr) {
  3314. for (i = 1;
  3315. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3316. i++)
  3317. buf[len + i - 1] = tstr[i];
  3318. buf[len + i - 1] = 0;
  3319. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3320. page_handler_found = 1;
  3321. break;
  3322. }
  3323. tstr = strchr(tstr + i, '.');
  3324. }
  3325. }
  3326. }
  3327. if (page_handler_found) {
  3328. conn->in_error_handler = 1;
  3329. handle_file_based_request(conn, buf, &error_page_file);
  3330. conn->in_error_handler = 0;
  3331. return;
  3332. }
  3333. }
  3334. /* No custom error page. Send default error page. */
  3335. gmt_time_string(date, sizeof(date), &curtime);
  3336. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3337. has_body = ((status > 199) && (status != 204) && (status != 304));
  3338. conn->must_close = 1;
  3339. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3340. send_no_cache_header(conn);
  3341. send_additional_header(conn);
  3342. if (has_body) {
  3343. mg_printf(conn,
  3344. "%s",
  3345. "Content-Type: text/plain; charset=utf-8\r\n");
  3346. }
  3347. mg_printf(conn,
  3348. "Date: %s\r\n"
  3349. "Connection: close\r\n\r\n",
  3350. date);
  3351. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3352. if (has_body) {
  3353. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3354. if (fmt != NULL) {
  3355. va_start(ap, fmt);
  3356. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3357. va_end(ap);
  3358. mg_write(conn, buf, strlen(buf));
  3359. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3360. }
  3361. } else {
  3362. /* No body allowed. Close the connection. */
  3363. DEBUG_TRACE("Error %i", status);
  3364. }
  3365. }
  3366. }
  3367. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3368. /* Create substitutes for POSIX functions in Win32. */
  3369. #if defined(__MINGW32__)
  3370. /* Show no warning in case system functions are not used. */
  3371. #pragma GCC diagnostic push
  3372. #pragma GCC diagnostic ignored "-Wunused-function"
  3373. #endif
  3374. FUNCTION_MAY_BE_UNUSED
  3375. static int
  3376. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3377. {
  3378. (void)unused;
  3379. *mutex = CreateMutex(NULL, FALSE, NULL);
  3380. return (*mutex == NULL) ? -1 : 0;
  3381. }
  3382. FUNCTION_MAY_BE_UNUSED
  3383. static int
  3384. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3385. {
  3386. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3387. }
  3388. FUNCTION_MAY_BE_UNUSED
  3389. static int
  3390. pthread_mutex_lock(pthread_mutex_t *mutex)
  3391. {
  3392. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3393. }
  3394. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3395. FUNCTION_MAY_BE_UNUSED
  3396. static int
  3397. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3398. {
  3399. switch (WaitForSingleObject(*mutex, 0)) {
  3400. case WAIT_OBJECT_0:
  3401. return 0;
  3402. case WAIT_TIMEOUT:
  3403. return -2; /* EBUSY */
  3404. }
  3405. return -1;
  3406. }
  3407. #endif
  3408. FUNCTION_MAY_BE_UNUSED
  3409. static int
  3410. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3411. {
  3412. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3413. }
  3414. FUNCTION_MAY_BE_UNUSED
  3415. static int
  3416. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3417. {
  3418. (void)unused;
  3419. InitializeCriticalSection(&cv->threadIdSec);
  3420. cv->waiting_thread = NULL;
  3421. return 0;
  3422. }
  3423. FUNCTION_MAY_BE_UNUSED
  3424. static int
  3425. pthread_cond_timedwait(pthread_cond_t *cv,
  3426. pthread_mutex_t *mutex,
  3427. const struct timespec *abstime)
  3428. {
  3429. struct mg_workerTLS **ptls,
  3430. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3431. int ok;
  3432. int64_t nsnow, nswaitabs, nswaitrel;
  3433. DWORD mswaitrel;
  3434. EnterCriticalSection(&cv->threadIdSec);
  3435. /* Add this thread to cv's waiting list */
  3436. ptls = &cv->waiting_thread;
  3437. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3438. ;
  3439. tls->next_waiting_thread = NULL;
  3440. *ptls = tls;
  3441. LeaveCriticalSection(&cv->threadIdSec);
  3442. if (abstime) {
  3443. nsnow = mg_get_current_time_ns();
  3444. nswaitabs =
  3445. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3446. nswaitrel = nswaitabs - nsnow;
  3447. if (nswaitrel < 0) {
  3448. nswaitrel = 0;
  3449. }
  3450. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3451. } else {
  3452. mswaitrel = INFINITE;
  3453. }
  3454. pthread_mutex_unlock(mutex);
  3455. ok = (WAIT_OBJECT_0
  3456. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3457. if (!ok) {
  3458. ok = 1;
  3459. EnterCriticalSection(&cv->threadIdSec);
  3460. ptls = &cv->waiting_thread;
  3461. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3462. if (*ptls == tls) {
  3463. *ptls = tls->next_waiting_thread;
  3464. ok = 0;
  3465. break;
  3466. }
  3467. }
  3468. LeaveCriticalSection(&cv->threadIdSec);
  3469. if (ok) {
  3470. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3471. }
  3472. }
  3473. /* This thread has been removed from cv's waiting list */
  3474. pthread_mutex_lock(mutex);
  3475. return ok ? 0 : -1;
  3476. }
  3477. FUNCTION_MAY_BE_UNUSED
  3478. static int
  3479. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3480. {
  3481. return pthread_cond_timedwait(cv, mutex, NULL);
  3482. }
  3483. FUNCTION_MAY_BE_UNUSED
  3484. static int
  3485. pthread_cond_signal(pthread_cond_t *cv)
  3486. {
  3487. HANDLE wkup = NULL;
  3488. BOOL ok = FALSE;
  3489. EnterCriticalSection(&cv->threadIdSec);
  3490. if (cv->waiting_thread) {
  3491. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3492. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3493. ok = SetEvent(wkup);
  3494. assert(ok);
  3495. }
  3496. LeaveCriticalSection(&cv->threadIdSec);
  3497. return ok ? 0 : 1;
  3498. }
  3499. FUNCTION_MAY_BE_UNUSED
  3500. static int
  3501. pthread_cond_broadcast(pthread_cond_t *cv)
  3502. {
  3503. EnterCriticalSection(&cv->threadIdSec);
  3504. while (cv->waiting_thread) {
  3505. pthread_cond_signal(cv);
  3506. }
  3507. LeaveCriticalSection(&cv->threadIdSec);
  3508. return 0;
  3509. }
  3510. FUNCTION_MAY_BE_UNUSED
  3511. static int
  3512. pthread_cond_destroy(pthread_cond_t *cv)
  3513. {
  3514. EnterCriticalSection(&cv->threadIdSec);
  3515. assert(cv->waiting_thread == NULL);
  3516. LeaveCriticalSection(&cv->threadIdSec);
  3517. DeleteCriticalSection(&cv->threadIdSec);
  3518. return 0;
  3519. }
  3520. #ifdef ALTERNATIVE_QUEUE
  3521. FUNCTION_MAY_BE_UNUSED
  3522. static void *
  3523. event_create(void)
  3524. {
  3525. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3526. }
  3527. FUNCTION_MAY_BE_UNUSED
  3528. static int
  3529. event_wait(void *eventhdl)
  3530. {
  3531. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3532. return (res == WAIT_OBJECT_0);
  3533. }
  3534. FUNCTION_MAY_BE_UNUSED
  3535. static int
  3536. event_signal(void *eventhdl)
  3537. {
  3538. return (int)SetEvent((HANDLE)eventhdl);
  3539. }
  3540. FUNCTION_MAY_BE_UNUSED
  3541. static void
  3542. event_destroy(void *eventhdl)
  3543. {
  3544. CloseHandle((HANDLE)eventhdl);
  3545. }
  3546. #endif
  3547. #if defined(__MINGW32__)
  3548. /* Enable unused function warning again */
  3549. #pragma GCC diagnostic pop
  3550. #endif
  3551. /* For Windows, change all slashes to backslashes in path names. */
  3552. static void
  3553. change_slashes_to_backslashes(char *path)
  3554. {
  3555. int i;
  3556. for (i = 0; path[i] != '\0'; i++) {
  3557. if (path[i] == '/') {
  3558. path[i] = '\\';
  3559. }
  3560. /* remove double backslash (check i > 0 to preserve UNC paths,
  3561. * like \\server\file.txt) */
  3562. if ((path[i] == '\\') && (i > 0)) {
  3563. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3564. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3565. }
  3566. }
  3567. }
  3568. }
  3569. static int
  3570. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3571. {
  3572. int diff;
  3573. do {
  3574. diff = tolower(*s1) - tolower(*s2);
  3575. s1++;
  3576. s2++;
  3577. } while ((diff == 0) && (s1[-1] != '\0'));
  3578. return diff;
  3579. }
  3580. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3581. * wbuf and wbuf_len is a target buffer and its length. */
  3582. static void
  3583. path_to_unicode(const struct mg_connection *conn,
  3584. const char *path,
  3585. wchar_t *wbuf,
  3586. size_t wbuf_len)
  3587. {
  3588. char buf[PATH_MAX], buf2[PATH_MAX];
  3589. wchar_t wbuf2[MAX_PATH + 1];
  3590. DWORD long_len, err;
  3591. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3592. mg_strlcpy(buf, path, sizeof(buf));
  3593. change_slashes_to_backslashes(buf);
  3594. /* Convert to Unicode and back. If doubly-converted string does not
  3595. * match the original, something is fishy, reject. */
  3596. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3597. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3598. WideCharToMultiByte(
  3599. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3600. if (strcmp(buf, buf2) != 0) {
  3601. wbuf[0] = L'\0';
  3602. }
  3603. /* Windows file systems are not case sensitive, but you can still use
  3604. * uppercase and lowercase letters (on all modern file systems).
  3605. * The server can check if the URI uses the same upper/lowercase
  3606. * letters an the file system, effectively making Windows servers
  3607. * case sensitive (like Linux servers are). It is still not possible
  3608. * to use two files with the same name in different cases on Windows
  3609. * (like /a and /A) - this would be possible in Linux.
  3610. * As a default, Windows is not case sensitive, but the case sensitive
  3611. * file name check can be activated by an additional configuration. */
  3612. if (conn) {
  3613. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3614. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3615. /* Use case sensitive compare function */
  3616. fcompare = wcscmp;
  3617. }
  3618. }
  3619. (void)conn; /* conn is currently unused */
  3620. #if !defined(_WIN32_WCE)
  3621. /* Only accept a full file path, not a Windows short (8.3) path. */
  3622. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3623. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3624. if (long_len == 0) {
  3625. err = GetLastError();
  3626. if (err == ERROR_FILE_NOT_FOUND) {
  3627. /* File does not exist. This is not always a problem here. */
  3628. return;
  3629. }
  3630. }
  3631. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3632. /* Short name is used. */
  3633. wbuf[0] = L'\0';
  3634. }
  3635. #else
  3636. (void)long_len;
  3637. (void)wbuf2;
  3638. (void)err;
  3639. if (strchr(path, '~')) {
  3640. wbuf[0] = L'\0';
  3641. }
  3642. #endif
  3643. }
  3644. /* Windows happily opens files with some garbage at the end of file name.
  3645. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3646. * "a.cgi", despite one would expect an error back.
  3647. * This function returns non-0 if path ends with some garbage. */
  3648. static int
  3649. path_cannot_disclose_cgi(const char *path)
  3650. {
  3651. static const char *allowed_last_characters = "_-";
  3652. int last = path[strlen(path) - 1];
  3653. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3654. }
  3655. static int
  3656. mg_stat(const struct mg_connection *conn,
  3657. const char *path,
  3658. struct mg_file_stat *filep)
  3659. {
  3660. wchar_t wbuf[PATH_MAX];
  3661. WIN32_FILE_ATTRIBUTE_DATA info;
  3662. time_t creation_time;
  3663. if (!filep) {
  3664. return 0;
  3665. }
  3666. memset(filep, 0, sizeof(*filep));
  3667. if (conn && is_file_in_memory(conn, path)) {
  3668. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3669. * memset */
  3670. /* Quick fix (for 1.9.x): */
  3671. /* mg_stat must fill all fields, also for files in memory */
  3672. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3673. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3674. filep->size = tmp_file.stat.size;
  3675. filep->location = 2;
  3676. /* TODO: for 1.10: restructure how files in memory are handled */
  3677. /* The "file in memory" feature is a candidate for deletion.
  3678. * Please join the discussion at
  3679. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3680. */
  3681. filep->last_modified = time(NULL); /* TODO */
  3682. /* last_modified = now ... assumes the file may change during runtime,
  3683. * so every mg_fopen call may return different data */
  3684. /* last_modified = conn->ctx.start_time;
  3685. * May be used it the data does not change during runtime. This allows
  3686. * browser caching. Since we do not know, we have to assume the file
  3687. * in memory may change. */
  3688. return 1;
  3689. }
  3690. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3691. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3692. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3693. filep->last_modified =
  3694. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3695. info.ftLastWriteTime.dwHighDateTime);
  3696. /* On Windows, the file creation time can be higher than the
  3697. * modification time, e.g. when a file is copied.
  3698. * Since the Last-Modified timestamp is used for caching
  3699. * it should be based on the most recent timestamp. */
  3700. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3701. info.ftCreationTime.dwHighDateTime);
  3702. if (creation_time > filep->last_modified) {
  3703. filep->last_modified = creation_time;
  3704. }
  3705. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3706. /* If file name is fishy, reset the file structure and return
  3707. * error.
  3708. * Note it is important to reset, not just return the error, cause
  3709. * functions like is_file_opened() check the struct. */
  3710. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3711. memset(filep, 0, sizeof(*filep));
  3712. return 0;
  3713. }
  3714. return 1;
  3715. }
  3716. return 0;
  3717. }
  3718. static int
  3719. mg_remove(const struct mg_connection *conn, const char *path)
  3720. {
  3721. wchar_t wbuf[PATH_MAX];
  3722. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3723. return DeleteFileW(wbuf) ? 0 : -1;
  3724. }
  3725. static int
  3726. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3727. {
  3728. wchar_t wbuf[PATH_MAX];
  3729. (void)mode;
  3730. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3731. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3732. }
  3733. /* Create substitutes for POSIX functions in Win32. */
  3734. #if defined(__MINGW32__)
  3735. /* Show no warning in case system functions are not used. */
  3736. #pragma GCC diagnostic push
  3737. #pragma GCC diagnostic ignored "-Wunused-function"
  3738. #endif
  3739. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3740. FUNCTION_MAY_BE_UNUSED
  3741. static DIR *
  3742. mg_opendir(const struct mg_connection *conn, const char *name)
  3743. {
  3744. DIR *dir = NULL;
  3745. wchar_t wpath[PATH_MAX];
  3746. DWORD attrs;
  3747. if (name == NULL) {
  3748. SetLastError(ERROR_BAD_ARGUMENTS);
  3749. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3750. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3751. } else {
  3752. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3753. attrs = GetFileAttributesW(wpath);
  3754. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3755. == FILE_ATTRIBUTE_DIRECTORY)) {
  3756. (void)wcscat(wpath, L"\\*");
  3757. dir->handle = FindFirstFileW(wpath, &dir->info);
  3758. dir->result.d_name[0] = '\0';
  3759. } else {
  3760. mg_free(dir);
  3761. dir = NULL;
  3762. }
  3763. }
  3764. return dir;
  3765. }
  3766. FUNCTION_MAY_BE_UNUSED
  3767. static int
  3768. mg_closedir(DIR *dir)
  3769. {
  3770. int result = 0;
  3771. if (dir != NULL) {
  3772. if (dir->handle != INVALID_HANDLE_VALUE)
  3773. result = FindClose(dir->handle) ? 0 : -1;
  3774. mg_free(dir);
  3775. } else {
  3776. result = -1;
  3777. SetLastError(ERROR_BAD_ARGUMENTS);
  3778. }
  3779. return result;
  3780. }
  3781. FUNCTION_MAY_BE_UNUSED
  3782. static struct dirent *
  3783. mg_readdir(DIR *dir)
  3784. {
  3785. struct dirent *result = 0;
  3786. if (dir) {
  3787. if (dir->handle != INVALID_HANDLE_VALUE) {
  3788. result = &dir->result;
  3789. (void)WideCharToMultiByte(CP_UTF8,
  3790. 0,
  3791. dir->info.cFileName,
  3792. -1,
  3793. result->d_name,
  3794. sizeof(result->d_name),
  3795. NULL,
  3796. NULL);
  3797. if (!FindNextFileW(dir->handle, &dir->info)) {
  3798. (void)FindClose(dir->handle);
  3799. dir->handle = INVALID_HANDLE_VALUE;
  3800. }
  3801. } else {
  3802. SetLastError(ERROR_FILE_NOT_FOUND);
  3803. }
  3804. } else {
  3805. SetLastError(ERROR_BAD_ARGUMENTS);
  3806. }
  3807. return result;
  3808. }
  3809. #ifndef HAVE_POLL
  3810. FUNCTION_MAY_BE_UNUSED
  3811. static int
  3812. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3813. {
  3814. struct timeval tv;
  3815. fd_set set;
  3816. unsigned int i;
  3817. int result;
  3818. SOCKET maxfd = 0;
  3819. memset(&tv, 0, sizeof(tv));
  3820. tv.tv_sec = milliseconds / 1000;
  3821. tv.tv_usec = (milliseconds % 1000) * 1000;
  3822. FD_ZERO(&set);
  3823. for (i = 0; i < n; i++) {
  3824. FD_SET((SOCKET)pfd[i].fd, &set);
  3825. pfd[i].revents = 0;
  3826. if (pfd[i].fd > maxfd) {
  3827. maxfd = pfd[i].fd;
  3828. }
  3829. }
  3830. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3831. for (i = 0; i < n; i++) {
  3832. if (FD_ISSET(pfd[i].fd, &set)) {
  3833. pfd[i].revents = POLLIN;
  3834. }
  3835. }
  3836. }
  3837. /* We should subtract the time used in select from remaining
  3838. * "milliseconds", in particular if called from mg_poll with a
  3839. * timeout quantum.
  3840. * Unfortunately, the remaining time is not stored in "tv" in all
  3841. * implementations, so the result in "tv" must be considered undefined.
  3842. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3843. return result;
  3844. }
  3845. #endif /* HAVE_POLL */
  3846. #if defined(__MINGW32__)
  3847. /* Enable unused function warning again */
  3848. #pragma GCC diagnostic pop
  3849. #endif
  3850. static void
  3851. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3852. {
  3853. (void)conn; /* Unused. */
  3854. #if defined(_WIN32_WCE)
  3855. (void)sock;
  3856. #else
  3857. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3858. #endif
  3859. }
  3860. int
  3861. mg_start_thread(mg_thread_func_t f, void *p)
  3862. {
  3863. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3864. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3865. */
  3866. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3867. == ((uintptr_t)(-1L)))
  3868. ? -1
  3869. : 0);
  3870. #else
  3871. return (
  3872. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3873. ? -1
  3874. : 0);
  3875. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3876. }
  3877. /* Start a thread storing the thread context. */
  3878. static int
  3879. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3880. void *p,
  3881. pthread_t *threadidptr)
  3882. {
  3883. uintptr_t uip;
  3884. HANDLE threadhandle;
  3885. int result = -1;
  3886. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3887. threadhandle = (HANDLE)uip;
  3888. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3889. *threadidptr = threadhandle;
  3890. result = 0;
  3891. }
  3892. return result;
  3893. }
  3894. /* Wait for a thread to finish. */
  3895. static int
  3896. mg_join_thread(pthread_t threadid)
  3897. {
  3898. int result;
  3899. DWORD dwevent;
  3900. result = -1;
  3901. dwevent = WaitForSingleObject(threadid, INFINITE);
  3902. if (dwevent == WAIT_FAILED) {
  3903. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3904. } else {
  3905. if (dwevent == WAIT_OBJECT_0) {
  3906. CloseHandle(threadid);
  3907. result = 0;
  3908. }
  3909. }
  3910. return result;
  3911. }
  3912. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3913. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3914. /* Create substitutes for POSIX functions in Win32. */
  3915. #if defined(__MINGW32__)
  3916. /* Show no warning in case system functions are not used. */
  3917. #pragma GCC diagnostic push
  3918. #pragma GCC diagnostic ignored "-Wunused-function"
  3919. #endif
  3920. FUNCTION_MAY_BE_UNUSED
  3921. static HANDLE
  3922. dlopen(const char *dll_name, int flags)
  3923. {
  3924. wchar_t wbuf[PATH_MAX];
  3925. (void)flags;
  3926. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3927. return LoadLibraryW(wbuf);
  3928. }
  3929. FUNCTION_MAY_BE_UNUSED
  3930. static int
  3931. dlclose(void *handle)
  3932. {
  3933. int result;
  3934. if (FreeLibrary((HMODULE)handle) != 0) {
  3935. result = 0;
  3936. } else {
  3937. result = -1;
  3938. }
  3939. return result;
  3940. }
  3941. #if defined(__MINGW32__)
  3942. /* Enable unused function warning again */
  3943. #pragma GCC diagnostic pop
  3944. #endif
  3945. #endif
  3946. #if !defined(NO_CGI)
  3947. #define SIGKILL (0)
  3948. static int
  3949. kill(pid_t pid, int sig_num)
  3950. {
  3951. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3952. (void)CloseHandle((HANDLE)pid);
  3953. return 0;
  3954. }
  3955. static void
  3956. trim_trailing_whitespaces(char *s)
  3957. {
  3958. char *e = s + strlen(s) - 1;
  3959. while ((e > s) && isspace(*(unsigned char *)e)) {
  3960. *e-- = '\0';
  3961. }
  3962. }
  3963. static pid_t
  3964. spawn_process(struct mg_connection *conn,
  3965. const char *prog,
  3966. char *envblk,
  3967. char *envp[],
  3968. int fdin[2],
  3969. int fdout[2],
  3970. int fderr[2],
  3971. const char *dir)
  3972. {
  3973. HANDLE me;
  3974. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3975. cmdline[PATH_MAX], buf[PATH_MAX];
  3976. int truncated;
  3977. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3978. STARTUPINFOA si;
  3979. PROCESS_INFORMATION pi = {0};
  3980. (void)envp;
  3981. memset(&si, 0, sizeof(si));
  3982. si.cb = sizeof(si);
  3983. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3984. si.wShowWindow = SW_HIDE;
  3985. me = GetCurrentProcess();
  3986. DuplicateHandle(me,
  3987. (HANDLE)_get_osfhandle(fdin[0]),
  3988. me,
  3989. &si.hStdInput,
  3990. 0,
  3991. TRUE,
  3992. DUPLICATE_SAME_ACCESS);
  3993. DuplicateHandle(me,
  3994. (HANDLE)_get_osfhandle(fdout[1]),
  3995. me,
  3996. &si.hStdOutput,
  3997. 0,
  3998. TRUE,
  3999. DUPLICATE_SAME_ACCESS);
  4000. DuplicateHandle(me,
  4001. (HANDLE)_get_osfhandle(fderr[1]),
  4002. me,
  4003. &si.hStdError,
  4004. 0,
  4005. TRUE,
  4006. DUPLICATE_SAME_ACCESS);
  4007. /* Mark handles that should not be inherited. See
  4008. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4009. */
  4010. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4011. HANDLE_FLAG_INHERIT,
  4012. 0);
  4013. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4014. HANDLE_FLAG_INHERIT,
  4015. 0);
  4016. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4017. HANDLE_FLAG_INHERIT,
  4018. 0);
  4019. /* If CGI file is a script, try to read the interpreter line */
  4020. interp = conn->ctx->config[CGI_INTERPRETER];
  4021. if (interp == NULL) {
  4022. buf[0] = buf[1] = '\0';
  4023. /* Read the first line of the script into the buffer */
  4024. mg_snprintf(
  4025. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4026. if (truncated) {
  4027. pi.hProcess = (pid_t)-1;
  4028. goto spawn_cleanup;
  4029. }
  4030. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4031. p = (char *)file.access.membuf;
  4032. mg_fgets(buf, sizeof(buf), &file, &p);
  4033. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4034. buf[sizeof(buf) - 1] = '\0';
  4035. }
  4036. if ((buf[0] == '#') && (buf[1] == '!')) {
  4037. trim_trailing_whitespaces(buf + 2);
  4038. } else {
  4039. buf[2] = '\0';
  4040. }
  4041. interp = buf + 2;
  4042. }
  4043. if (interp[0] != '\0') {
  4044. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4045. interp = full_interp;
  4046. }
  4047. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4048. if (interp[0] != '\0') {
  4049. mg_snprintf(conn,
  4050. &truncated,
  4051. cmdline,
  4052. sizeof(cmdline),
  4053. "\"%s\" \"%s\\%s\"",
  4054. interp,
  4055. full_dir,
  4056. prog);
  4057. } else {
  4058. mg_snprintf(conn,
  4059. &truncated,
  4060. cmdline,
  4061. sizeof(cmdline),
  4062. "\"%s\\%s\"",
  4063. full_dir,
  4064. prog);
  4065. }
  4066. if (truncated) {
  4067. pi.hProcess = (pid_t)-1;
  4068. goto spawn_cleanup;
  4069. }
  4070. DEBUG_TRACE("Running [%s]", cmdline);
  4071. if (CreateProcessA(NULL,
  4072. cmdline,
  4073. NULL,
  4074. NULL,
  4075. TRUE,
  4076. CREATE_NEW_PROCESS_GROUP,
  4077. envblk,
  4078. NULL,
  4079. &si,
  4080. &pi) == 0) {
  4081. mg_cry(
  4082. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4083. pi.hProcess = (pid_t)-1;
  4084. /* goto spawn_cleanup; */
  4085. }
  4086. spawn_cleanup:
  4087. (void)CloseHandle(si.hStdOutput);
  4088. (void)CloseHandle(si.hStdError);
  4089. (void)CloseHandle(si.hStdInput);
  4090. if (pi.hThread != NULL) {
  4091. (void)CloseHandle(pi.hThread);
  4092. }
  4093. return (pid_t)pi.hProcess;
  4094. }
  4095. #endif /* !NO_CGI */
  4096. static int
  4097. set_blocking_mode(SOCKET sock, int blocking)
  4098. {
  4099. unsigned long non_blocking = !blocking;
  4100. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4101. }
  4102. #else
  4103. static int
  4104. mg_stat(const struct mg_connection *conn,
  4105. const char *path,
  4106. struct mg_file_stat *filep)
  4107. {
  4108. struct stat st;
  4109. if (!filep) {
  4110. return 0;
  4111. }
  4112. memset(filep, 0, sizeof(*filep));
  4113. if (conn && is_file_in_memory(conn, path)) {
  4114. /* Quick fix (for 1.9.x): */
  4115. /* mg_stat must fill all fields, also for files in memory */
  4116. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4117. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4118. filep->size = tmp_file.stat.size;
  4119. filep->last_modified = time(NULL);
  4120. filep->location = 2;
  4121. /* TODO: for 1.10: restructure how files in memory are handled */
  4122. return 1;
  4123. }
  4124. if (0 == stat(path, &st)) {
  4125. filep->size = (uint64_t)(st.st_size);
  4126. filep->last_modified = st.st_mtime;
  4127. filep->is_directory = S_ISDIR(st.st_mode);
  4128. return 1;
  4129. }
  4130. return 0;
  4131. }
  4132. static void
  4133. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4134. {
  4135. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4136. if (conn) {
  4137. mg_cry(conn,
  4138. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4139. __func__,
  4140. strerror(ERRNO));
  4141. }
  4142. }
  4143. }
  4144. int
  4145. mg_start_thread(mg_thread_func_t func, void *param)
  4146. {
  4147. pthread_t thread_id;
  4148. pthread_attr_t attr;
  4149. int result;
  4150. (void)pthread_attr_init(&attr);
  4151. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4152. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4153. /* Compile-time option to control stack size,
  4154. * e.g. -DUSE_STACK_SIZE=16384 */
  4155. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4156. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4157. result = pthread_create(&thread_id, &attr, func, param);
  4158. pthread_attr_destroy(&attr);
  4159. return result;
  4160. }
  4161. /* Start a thread storing the thread context. */
  4162. static int
  4163. mg_start_thread_with_id(mg_thread_func_t func,
  4164. void *param,
  4165. pthread_t *threadidptr)
  4166. {
  4167. pthread_t thread_id;
  4168. pthread_attr_t attr;
  4169. int result;
  4170. (void)pthread_attr_init(&attr);
  4171. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4172. /* Compile-time option to control stack size,
  4173. * e.g. -DUSE_STACK_SIZE=16384 */
  4174. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4175. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4176. result = pthread_create(&thread_id, &attr, func, param);
  4177. pthread_attr_destroy(&attr);
  4178. if ((result == 0) && (threadidptr != NULL)) {
  4179. *threadidptr = thread_id;
  4180. }
  4181. return result;
  4182. }
  4183. /* Wait for a thread to finish. */
  4184. static int
  4185. mg_join_thread(pthread_t threadid)
  4186. {
  4187. int result;
  4188. result = pthread_join(threadid, NULL);
  4189. return result;
  4190. }
  4191. #ifndef NO_CGI
  4192. static pid_t
  4193. spawn_process(struct mg_connection *conn,
  4194. const char *prog,
  4195. char *envblk,
  4196. char *envp[],
  4197. int fdin[2],
  4198. int fdout[2],
  4199. int fderr[2],
  4200. const char *dir)
  4201. {
  4202. pid_t pid;
  4203. const char *interp;
  4204. (void)envblk;
  4205. if (conn == NULL) {
  4206. return 0;
  4207. }
  4208. if ((pid = fork()) == -1) {
  4209. /* Parent */
  4210. mg_send_http_error(conn,
  4211. 500,
  4212. "Error: Creating CGI process\nfork(): %s",
  4213. strerror(ERRNO));
  4214. } else if (pid == 0) {
  4215. /* Child */
  4216. if (chdir(dir) != 0) {
  4217. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4218. } else if (dup2(fdin[0], 0) == -1) {
  4219. mg_cry(conn,
  4220. "%s: dup2(%d, 0): %s",
  4221. __func__,
  4222. fdin[0],
  4223. strerror(ERRNO));
  4224. } else if (dup2(fdout[1], 1) == -1) {
  4225. mg_cry(conn,
  4226. "%s: dup2(%d, 1): %s",
  4227. __func__,
  4228. fdout[1],
  4229. strerror(ERRNO));
  4230. } else if (dup2(fderr[1], 2) == -1) {
  4231. mg_cry(conn,
  4232. "%s: dup2(%d, 2): %s",
  4233. __func__,
  4234. fderr[1],
  4235. strerror(ERRNO));
  4236. } else {
  4237. /* Keep stderr and stdout in two different pipes.
  4238. * Stdout will be sent back to the client,
  4239. * stderr should go into a server error log. */
  4240. (void)close(fdin[0]);
  4241. (void)close(fdout[1]);
  4242. (void)close(fderr[1]);
  4243. /* Close write end fdin and read end fdout and fderr */
  4244. (void)close(fdin[1]);
  4245. (void)close(fdout[0]);
  4246. (void)close(fderr[0]);
  4247. /* After exec, all signal handlers are restored to their default
  4248. * values, with one exception of SIGCHLD. According to
  4249. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4250. * leave unchanged after exec if it was set to be ignored. Restore
  4251. * it to default action. */
  4252. signal(SIGCHLD, SIG_DFL);
  4253. interp = conn->ctx->config[CGI_INTERPRETER];
  4254. if (interp == NULL) {
  4255. (void)execle(prog, prog, NULL, envp);
  4256. mg_cry(conn,
  4257. "%s: execle(%s): %s",
  4258. __func__,
  4259. prog,
  4260. strerror(ERRNO));
  4261. } else {
  4262. (void)execle(interp, interp, prog, NULL, envp);
  4263. mg_cry(conn,
  4264. "%s: execle(%s %s): %s",
  4265. __func__,
  4266. interp,
  4267. prog,
  4268. strerror(ERRNO));
  4269. }
  4270. }
  4271. exit(EXIT_FAILURE);
  4272. }
  4273. return pid;
  4274. }
  4275. #endif /* !NO_CGI */
  4276. static int
  4277. set_blocking_mode(SOCKET sock, int blocking)
  4278. {
  4279. int flags;
  4280. flags = fcntl(sock, F_GETFL, 0);
  4281. if (blocking) {
  4282. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  4283. } else {
  4284. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  4285. }
  4286. return 0;
  4287. }
  4288. #endif /* _WIN32 */
  4289. /* End of initial operating system specific define block. */
  4290. /* Get a random number (independent of C rand function) */
  4291. static uint64_t
  4292. get_random(void)
  4293. {
  4294. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4295. static uint64_t lcg = 0; /* Linear congruential generator */
  4296. uint64_t now = mg_get_current_time_ns();
  4297. if (lfsr == 0) {
  4298. /* lfsr will be only 0 if has not been initialized,
  4299. * so this code is called only once. */
  4300. lfsr = mg_get_current_time_ns();
  4301. lcg = mg_get_current_time_ns();
  4302. } else {
  4303. /* Get the next step of both random number generators. */
  4304. lfsr = (lfsr >> 1)
  4305. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4306. << 63);
  4307. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4308. }
  4309. /* Combining two pseudo-random number generators and a high resolution part
  4310. * of the current server time will make it hard (impossible?) to guess the
  4311. * next number. */
  4312. return (lfsr ^ lcg ^ now);
  4313. }
  4314. static int
  4315. mg_poll(struct pollfd *pfd,
  4316. unsigned int n,
  4317. int milliseconds,
  4318. volatile int *stop_server)
  4319. {
  4320. int ms_now, result;
  4321. /* Call poll, but only for a maximum time of a few seconds.
  4322. * This will allow to stop the server after some seconds, instead
  4323. * of having to wait for a long socket timeout. */
  4324. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4325. do {
  4326. if (*stop_server) {
  4327. /* Shut down signal */
  4328. return -2;
  4329. }
  4330. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4331. ms_now = milliseconds;
  4332. }
  4333. result = poll(pfd, n, ms_now);
  4334. if (result != 0) {
  4335. /* Poll returned either success (1) or error (-1).
  4336. * Forward both to the caller. */
  4337. return result;
  4338. }
  4339. /* Poll returned timeout (0). */
  4340. if (milliseconds > 0) {
  4341. milliseconds -= ms_now;
  4342. }
  4343. } while (milliseconds != 0);
  4344. return result;
  4345. }
  4346. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4347. * descriptor.
  4348. * Return value:
  4349. * >=0 .. number of bytes successfully written
  4350. * -1 .. timeout
  4351. * -2 .. error
  4352. */
  4353. static int
  4354. push_inner(struct mg_context *ctx,
  4355. FILE *fp,
  4356. SOCKET sock,
  4357. SSL *ssl,
  4358. const char *buf,
  4359. int len,
  4360. double timeout)
  4361. {
  4362. uint64_t start = 0, now = 0, timeout_ns = 0;
  4363. int n, err;
  4364. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4365. #ifdef _WIN32
  4366. typedef int len_t;
  4367. #else
  4368. typedef size_t len_t;
  4369. #endif
  4370. if (timeout > 0) {
  4371. now = mg_get_current_time_ns();
  4372. start = now;
  4373. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4374. }
  4375. if (ctx == NULL) {
  4376. return -2;
  4377. }
  4378. #ifdef NO_SSL
  4379. if (ssl) {
  4380. return -2;
  4381. }
  4382. #endif
  4383. /* Try to read until it succeeds, fails, times out, or the server
  4384. * shuts down. */
  4385. for (;;) {
  4386. #ifndef NO_SSL
  4387. if (ssl != NULL) {
  4388. n = SSL_write(ssl, buf, len);
  4389. if (n <= 0) {
  4390. err = SSL_get_error(ssl, n);
  4391. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4392. err = ERRNO;
  4393. } else if ((err == SSL_ERROR_WANT_READ)
  4394. || (err == SSL_ERROR_WANT_WRITE)) {
  4395. n = 0;
  4396. } else {
  4397. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4398. return -2;
  4399. }
  4400. } else {
  4401. err = 0;
  4402. }
  4403. } else
  4404. #endif
  4405. if (fp != NULL) {
  4406. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4407. if (ferror(fp)) {
  4408. n = -1;
  4409. err = ERRNO;
  4410. } else {
  4411. err = 0;
  4412. }
  4413. } else {
  4414. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4415. err = (n < 0) ? ERRNO : 0;
  4416. #ifdef _WIN32
  4417. if (err == WSAEWOULDBLOCK) {
  4418. err = 0;
  4419. n = 0;
  4420. }
  4421. #else
  4422. if (err == EWOULDBLOCK) {
  4423. err = 0;
  4424. n = 0;
  4425. }
  4426. #endif
  4427. if (n < 0) {
  4428. /* shutdown of the socket at client side */
  4429. return -2;
  4430. }
  4431. }
  4432. if (ctx->stop_flag) {
  4433. return -2;
  4434. }
  4435. if ((n > 0) || ((n == 0) && (len == 0))) {
  4436. /* some data has been read, or no data was requested */
  4437. return n;
  4438. }
  4439. if (n < 0) {
  4440. /* socket error - check errno */
  4441. DEBUG_TRACE("send() failed, error %d", err);
  4442. /* TODO (mid): error handling depending on the error code.
  4443. * These codes are different between Windows and Linux.
  4444. * Currently there is no problem with failing send calls,
  4445. * if there is a reproducible situation, it should be
  4446. * investigated in detail.
  4447. */
  4448. return -2;
  4449. }
  4450. /* Only in case n=0 (timeout), repeat calling the write function */
  4451. /* If send failed, wait before retry */
  4452. if (fp != NULL) {
  4453. /* For files, just wait a fixed time,
  4454. * maybe an average disk seek time. */
  4455. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4456. } else {
  4457. /* For sockets, wait for the socket using select */
  4458. fd_set wfds;
  4459. struct timeval tv;
  4460. int sret;
  4461. #if defined(__GNUC__) || defined(__MINGW32__)
  4462. /* GCC seems to have a flaw with it's own socket macros:
  4463. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4464. */
  4465. #pragma GCC diagnostic push
  4466. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4467. #endif
  4468. FD_ZERO(&wfds);
  4469. FD_SET(sock, &wfds);
  4470. tv.tv_sec = (time_t)(ms_wait / 1000);
  4471. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4472. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4473. #if defined(__GNUC__) || defined(__MINGW32__)
  4474. #pragma GCC diagnostic pop
  4475. #endif
  4476. if (sret > 0) {
  4477. /* We got ready to write. Don't check the timeout
  4478. * but directly go back to write again. */
  4479. continue;
  4480. }
  4481. }
  4482. if (timeout > 0) {
  4483. now = mg_get_current_time_ns();
  4484. if ((now - start) > timeout_ns) {
  4485. /* Timeout */
  4486. break;
  4487. }
  4488. }
  4489. }
  4490. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4491. used */
  4492. return -1;
  4493. }
  4494. static int64_t
  4495. push_all(struct mg_context *ctx,
  4496. FILE *fp,
  4497. SOCKET sock,
  4498. SSL *ssl,
  4499. const char *buf,
  4500. int64_t len)
  4501. {
  4502. double timeout = -1.0;
  4503. int64_t n, nwritten = 0;
  4504. if (ctx == NULL) {
  4505. return -1;
  4506. }
  4507. if (ctx->config[REQUEST_TIMEOUT]) {
  4508. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4509. }
  4510. while ((len > 0) && (ctx->stop_flag == 0)) {
  4511. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4512. if (n < 0) {
  4513. if (nwritten == 0) {
  4514. nwritten = n; /* Propagate the error */
  4515. }
  4516. break;
  4517. } else if (n == 0) {
  4518. break; /* No more data to write */
  4519. } else {
  4520. nwritten += n;
  4521. len -= n;
  4522. }
  4523. }
  4524. return nwritten;
  4525. }
  4526. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4527. * Return value:
  4528. * >=0 .. number of bytes successfully read
  4529. * -1 .. timeout
  4530. * -2 .. error
  4531. */
  4532. static int
  4533. pull_inner(FILE *fp,
  4534. struct mg_connection *conn,
  4535. char *buf,
  4536. int len,
  4537. double timeout)
  4538. {
  4539. int nread, err = 0;
  4540. #ifdef _WIN32
  4541. typedef int len_t;
  4542. #else
  4543. typedef size_t len_t;
  4544. #endif
  4545. #ifndef NO_SSL
  4546. int ssl_pending;
  4547. #endif
  4548. /* We need an additional wait loop around this, because in some cases
  4549. * with TLSwe may get data from the socket but not from SSL_read.
  4550. * In this case we need to repeat at least once.
  4551. */
  4552. if (fp != NULL) {
  4553. #if !defined(_WIN32_WCE)
  4554. /* Use read() instead of fread(), because if we're reading from the
  4555. * CGI pipe, fread() may block until IO buffer is filled up. We
  4556. * cannot afford to block and must pass all read bytes immediately
  4557. * to the client. */
  4558. nread = (int)read(fileno(fp), buf, (size_t)len);
  4559. #else
  4560. /* WinCE does not support CGI pipes */
  4561. nread = (int)fread(buf, 1, (size_t)len, fp);
  4562. #endif
  4563. err = (nread < 0) ? ERRNO : 0;
  4564. #ifndef NO_SSL
  4565. } else if ((conn->ssl != NULL)
  4566. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4567. /* We already know there is no more data buffered in conn->buf
  4568. * but there is more available in the SSL layer. So don't poll
  4569. * conn->client.sock yet. */
  4570. if (ssl_pending > len) {
  4571. ssl_pending = len;
  4572. }
  4573. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4574. if (nread <= 0) {
  4575. err = SSL_get_error(conn->ssl, nread);
  4576. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4577. err = ERRNO;
  4578. } else if ((err == SSL_ERROR_WANT_READ)
  4579. || (err == SSL_ERROR_WANT_WRITE)) {
  4580. nread = 0;
  4581. } else {
  4582. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4583. return -1;
  4584. }
  4585. } else {
  4586. err = 0;
  4587. }
  4588. } else if (conn->ssl != NULL) {
  4589. struct pollfd pfd[1];
  4590. int pollres;
  4591. pfd[0].fd = conn->client.sock;
  4592. pfd[0].events = POLLIN;
  4593. pollres =
  4594. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4595. if (conn->ctx->stop_flag) {
  4596. return -2;
  4597. }
  4598. if (pollres > 0) {
  4599. nread = SSL_read(conn->ssl, buf, len);
  4600. if (nread <= 0) {
  4601. err = SSL_get_error(conn->ssl, nread);
  4602. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4603. err = ERRNO;
  4604. } else if ((err == SSL_ERROR_WANT_READ)
  4605. || (err == SSL_ERROR_WANT_WRITE)) {
  4606. nread = 0;
  4607. } else {
  4608. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4609. return -2;
  4610. }
  4611. } else {
  4612. err = 0;
  4613. }
  4614. } else if (pollres < 0) {
  4615. /* Error */
  4616. return -2;
  4617. } else {
  4618. /* pollres = 0 means timeout */
  4619. nread = 0;
  4620. }
  4621. #endif
  4622. } else {
  4623. struct pollfd pfd[1];
  4624. int pollres;
  4625. pfd[0].fd = conn->client.sock;
  4626. pfd[0].events = POLLIN;
  4627. pollres =
  4628. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4629. if (conn->ctx->stop_flag) {
  4630. return -2;
  4631. }
  4632. if (pollres > 0) {
  4633. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4634. err = (nread < 0) ? ERRNO : 0;
  4635. if (nread <= 0) {
  4636. /* shutdown of the socket at client side */
  4637. return -2;
  4638. }
  4639. } else if (pollres < 0) {
  4640. /* error callint poll */
  4641. return -2;
  4642. } else {
  4643. /* pollres = 0 means timeout */
  4644. nread = 0;
  4645. }
  4646. }
  4647. if (conn->ctx->stop_flag) {
  4648. return -2;
  4649. }
  4650. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  4651. /* some data has been read, or no data was requested */
  4652. return nread;
  4653. }
  4654. if (nread < 0) {
  4655. /* socket error - check errno */
  4656. #ifdef _WIN32
  4657. if (err == WSAEWOULDBLOCK) {
  4658. /* TODO (low): check if this is still required */
  4659. /* standard case if called from close_socket_gracefully */
  4660. return -2;
  4661. } else if (err == WSAETIMEDOUT) {
  4662. /* TODO (low): check if this is still required */
  4663. /* timeout is handled by the while loop */
  4664. return 0;
  4665. } else if (err == WSAECONNABORTED) {
  4666. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4667. return -2;
  4668. } else {
  4669. DEBUG_TRACE("recv() failed, error %d", err);
  4670. return -2;
  4671. }
  4672. #else
  4673. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4674. * if the timeout is reached and if the socket was set to non-
  4675. * blocking in close_socket_gracefully, so we can not distinguish
  4676. * here. We have to wait for the timeout in both cases for now.
  4677. */
  4678. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  4679. /* TODO (low): check if this is still required */
  4680. /* EAGAIN/EWOULDBLOCK:
  4681. * standard case if called from close_socket_gracefully
  4682. * => should return -1 */
  4683. /* or timeout occured
  4684. * => the code must stay in the while loop */
  4685. /* EINTR can be generated on a socket with a timeout set even
  4686. * when SA_RESTART is effective for all relevant signals
  4687. * (see signal(7)).
  4688. * => stay in the while loop */
  4689. } else {
  4690. DEBUG_TRACE("recv() failed, error %d", err);
  4691. return -2;
  4692. }
  4693. #endif
  4694. }
  4695. /* Timeout occured, but no data available. */
  4696. return -1;
  4697. }
  4698. static int
  4699. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4700. {
  4701. int n, nread = 0;
  4702. double timeout = -1.0;
  4703. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4704. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4705. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4706. }
  4707. if (timeout >= 0.0) {
  4708. start_time = mg_get_current_time_ns();
  4709. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4710. }
  4711. while ((len > 0) && (conn->ctx->stop_flag == 0)) {
  4712. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4713. if (n == -2) {
  4714. if (nread == 0) {
  4715. nread = -1; /* Propagate the error */
  4716. }
  4717. break;
  4718. } else if (n == -1) {
  4719. /* timeout */
  4720. if (timeout >= 0.0) {
  4721. now = mg_get_current_time_ns();
  4722. if ((now - start_time) <= timeout_ns) {
  4723. continue;
  4724. }
  4725. }
  4726. break;
  4727. } else if (n == 0) {
  4728. break; /* No more data to read */
  4729. } else {
  4730. conn->consumed_content += n;
  4731. nread += n;
  4732. len -= n;
  4733. }
  4734. }
  4735. return nread;
  4736. }
  4737. static void
  4738. discard_unread_request_data(struct mg_connection *conn)
  4739. {
  4740. char buf[MG_BUF_LEN];
  4741. size_t to_read;
  4742. int nread;
  4743. if (conn == NULL) {
  4744. return;
  4745. }
  4746. to_read = sizeof(buf);
  4747. if (conn->is_chunked) {
  4748. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4749. * completely */
  4750. while (conn->is_chunked == 1) {
  4751. nread = mg_read(conn, buf, to_read);
  4752. if (nread <= 0) {
  4753. break;
  4754. }
  4755. }
  4756. } else {
  4757. /* Not chunked: content length is known */
  4758. while (conn->consumed_content < conn->content_len) {
  4759. if (to_read
  4760. > (size_t)(conn->content_len - conn->consumed_content)) {
  4761. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4762. }
  4763. nread = mg_read(conn, buf, to_read);
  4764. if (nread <= 0) {
  4765. break;
  4766. }
  4767. }
  4768. }
  4769. }
  4770. static int
  4771. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4772. {
  4773. int64_t n, buffered_len, nread;
  4774. int64_t len64 =
  4775. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4776. * int, we may not read more
  4777. * bytes */
  4778. const char *body;
  4779. if (conn == NULL) {
  4780. return 0;
  4781. }
  4782. /* If Content-Length is not set for a PUT or POST request, read until
  4783. * socket is closed */
  4784. if ((conn->consumed_content) == 0 && (conn->content_len == -1)) {
  4785. conn->content_len = INT64_MAX;
  4786. conn->must_close = 1;
  4787. }
  4788. nread = 0;
  4789. if (conn->consumed_content < conn->content_len) {
  4790. /* Adjust number of bytes to read. */
  4791. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4792. if (left_to_read < len64) {
  4793. /* Do not read more than the total content length of the request.
  4794. */
  4795. len64 = left_to_read;
  4796. }
  4797. /* Return buffered data */
  4798. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4799. - conn->consumed_content;
  4800. if (buffered_len > 0) {
  4801. if (len64 < buffered_len) {
  4802. buffered_len = len64;
  4803. }
  4804. body = conn->buf + conn->request_len + conn->consumed_content;
  4805. memcpy(buf, body, (size_t)buffered_len);
  4806. len64 -= buffered_len;
  4807. conn->consumed_content += buffered_len;
  4808. nread += buffered_len;
  4809. buf = (char *)buf + buffered_len;
  4810. }
  4811. /* We have returned all buffered data. Read new data from the remote
  4812. * socket.
  4813. */
  4814. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4815. nread += n;
  4816. } else {
  4817. nread = ((nread > 0) ? nread : n);
  4818. }
  4819. }
  4820. return (int)nread;
  4821. }
  4822. static char
  4823. mg_getc(struct mg_connection *conn)
  4824. {
  4825. char c;
  4826. if (conn == NULL) {
  4827. return 0;
  4828. }
  4829. conn->content_len++;
  4830. if (mg_read_inner(conn, &c, 1) <= 0) {
  4831. return (char)0;
  4832. }
  4833. return c;
  4834. }
  4835. int
  4836. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4837. {
  4838. if (len > INT_MAX) {
  4839. len = INT_MAX;
  4840. }
  4841. if (conn == NULL) {
  4842. return 0;
  4843. }
  4844. if (conn->is_chunked) {
  4845. size_t all_read = 0;
  4846. while (len > 0) {
  4847. if (conn->is_chunked == 2) {
  4848. /* No more data left to read */
  4849. return 0;
  4850. }
  4851. if (conn->chunk_remainder) {
  4852. /* copy from the remainder of the last received chunk */
  4853. long read_ret;
  4854. size_t read_now =
  4855. ((conn->chunk_remainder > len) ? (len)
  4856. : (conn->chunk_remainder));
  4857. conn->content_len += (int)read_now;
  4858. read_ret =
  4859. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4860. if (read_ret < 1) {
  4861. /* read error */
  4862. return -1;
  4863. }
  4864. all_read += (size_t)read_ret;
  4865. conn->chunk_remainder -= (size_t)read_ret;
  4866. len -= (size_t)read_ret;
  4867. if (conn->chunk_remainder == 0) {
  4868. /* Add data bytes in the current chunk have been read,
  4869. * so we are expecting \r\n now. */
  4870. char x1 = mg_getc(conn);
  4871. char x2 = mg_getc(conn);
  4872. if ((x1 != '\r') || (x2 != '\n')) {
  4873. /* Protocol violation */
  4874. return -1;
  4875. }
  4876. }
  4877. } else {
  4878. /* fetch a new chunk */
  4879. int i = 0;
  4880. char lenbuf[64];
  4881. char *end = 0;
  4882. unsigned long chunkSize = 0;
  4883. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4884. lenbuf[i] = mg_getc(conn);
  4885. if ((i > 0) && (lenbuf[i] == '\r')
  4886. && (lenbuf[i - 1] != '\r')) {
  4887. continue;
  4888. }
  4889. if ((i > 1) && (lenbuf[i] == '\n')
  4890. && (lenbuf[i - 1] == '\r')) {
  4891. lenbuf[i + 1] = 0;
  4892. chunkSize = strtoul(lenbuf, &end, 16);
  4893. if (chunkSize == 0) {
  4894. /* regular end of content */
  4895. conn->is_chunked = 2;
  4896. }
  4897. break;
  4898. }
  4899. if (!isxdigit(lenbuf[i])) {
  4900. /* illegal character for chunk length */
  4901. return -1;
  4902. }
  4903. }
  4904. if ((end == NULL) || (*end != '\r')) {
  4905. /* chunksize not set correctly */
  4906. return -1;
  4907. }
  4908. if (chunkSize == 0) {
  4909. break;
  4910. }
  4911. conn->chunk_remainder = chunkSize;
  4912. }
  4913. }
  4914. return (int)all_read;
  4915. }
  4916. return mg_read_inner(conn, buf, len);
  4917. }
  4918. int
  4919. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4920. {
  4921. time_t now;
  4922. int64_t n, total, allowed;
  4923. if (conn == NULL) {
  4924. return 0;
  4925. }
  4926. if (conn->throttle > 0) {
  4927. if ((now = time(NULL)) != conn->last_throttle_time) {
  4928. conn->last_throttle_time = now;
  4929. conn->last_throttle_bytes = 0;
  4930. }
  4931. allowed = conn->throttle - conn->last_throttle_bytes;
  4932. if (allowed > (int64_t)len) {
  4933. allowed = (int64_t)len;
  4934. }
  4935. if ((total = push_all(conn->ctx,
  4936. NULL,
  4937. conn->client.sock,
  4938. conn->ssl,
  4939. (const char *)buf,
  4940. (int64_t)allowed)) == allowed) {
  4941. buf = (const char *)buf + total;
  4942. conn->last_throttle_bytes += total;
  4943. while ((total < (int64_t)len) && (conn->ctx->stop_flag == 0)) {
  4944. allowed = (conn->throttle > ((int64_t)len - total))
  4945. ? (int64_t)len - total
  4946. : conn->throttle;
  4947. if ((n = push_all(conn->ctx,
  4948. NULL,
  4949. conn->client.sock,
  4950. conn->ssl,
  4951. (const char *)buf,
  4952. (int64_t)allowed)) != allowed) {
  4953. break;
  4954. }
  4955. sleep(1);
  4956. conn->last_throttle_bytes = allowed;
  4957. conn->last_throttle_time = time(NULL);
  4958. buf = (const char *)buf + n;
  4959. total += n;
  4960. }
  4961. }
  4962. } else {
  4963. total = push_all(conn->ctx,
  4964. NULL,
  4965. conn->client.sock,
  4966. conn->ssl,
  4967. (const char *)buf,
  4968. (int64_t)len);
  4969. }
  4970. if (total > 0) {
  4971. conn->num_bytes_sent += total;
  4972. }
  4973. return (int)total;
  4974. }
  4975. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  4976. int
  4977. mg_send_chunk(struct mg_connection *conn,
  4978. const char *chunk,
  4979. unsigned int chunk_len)
  4980. {
  4981. char lenbuf[16];
  4982. size_t lenbuf_len;
  4983. int ret;
  4984. int t;
  4985. /* First store the length information in a text buffer. */
  4986. sprintf(lenbuf, "%x\r\n", chunk_len);
  4987. lenbuf_len = strlen(lenbuf);
  4988. /* Then send length information, chunk and terminating \r\n. */
  4989. ret = mg_write(conn, lenbuf, lenbuf_len);
  4990. if (ret != (int)lenbuf_len) {
  4991. return -1;
  4992. }
  4993. t = ret;
  4994. ret = mg_write(conn, chunk, chunk_len);
  4995. if (ret != (int)chunk_len) {
  4996. return -1;
  4997. }
  4998. t += ret;
  4999. ret = mg_write(conn, "\r\n", 2);
  5000. if (ret != 2) {
  5001. return -1;
  5002. }
  5003. t += ret;
  5004. return t;
  5005. }
  5006. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5007. static int
  5008. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5009. {
  5010. va_list ap_copy;
  5011. size_t size = MG_BUF_LEN / 4;
  5012. int len = -1;
  5013. *buf = NULL;
  5014. while (len < 0) {
  5015. if (*buf) {
  5016. mg_free(*buf);
  5017. }
  5018. size *= 4;
  5019. *buf = (char *)mg_malloc(size);
  5020. if (!*buf) {
  5021. break;
  5022. }
  5023. va_copy(ap_copy, ap);
  5024. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5025. va_end(ap_copy);
  5026. (*buf)[size - 1] = 0;
  5027. }
  5028. return len;
  5029. }
  5030. /* Print message to buffer. If buffer is large enough to hold the message,
  5031. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  5032. * and return allocated buffer. */
  5033. static int
  5034. alloc_vprintf(char **out_buf,
  5035. char *prealloc_buf,
  5036. size_t prealloc_size,
  5037. const char *fmt,
  5038. va_list ap)
  5039. {
  5040. va_list ap_copy;
  5041. int len;
  5042. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5043. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5044. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5045. * Therefore, we make two passes: on first pass, get required message
  5046. * length.
  5047. * On second pass, actually print the message. */
  5048. va_copy(ap_copy, ap);
  5049. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5050. va_end(ap_copy);
  5051. if (len < 0) {
  5052. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5053. * Switch to alternative code path that uses incremental allocations.
  5054. */
  5055. va_copy(ap_copy, ap);
  5056. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5057. va_end(ap_copy);
  5058. } else if ((size_t)(len) >= prealloc_size) {
  5059. /* The pre-allocated buffer not large enough. */
  5060. /* Allocate a new buffer. */
  5061. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5062. if (!*out_buf) {
  5063. /* Allocation failed. Return -1 as "out of memory" error. */
  5064. return -1;
  5065. }
  5066. /* Buffer allocation successful. Store the string there. */
  5067. va_copy(ap_copy, ap);
  5068. IGNORE_UNUSED_RESULT(
  5069. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5070. va_end(ap_copy);
  5071. } else {
  5072. /* The pre-allocated buffer is large enough.
  5073. * Use it to store the string and return the address. */
  5074. va_copy(ap_copy, ap);
  5075. IGNORE_UNUSED_RESULT(
  5076. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5077. va_end(ap_copy);
  5078. *out_buf = prealloc_buf;
  5079. }
  5080. return len;
  5081. }
  5082. static int
  5083. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5084. {
  5085. char mem[MG_BUF_LEN];
  5086. char *buf = NULL;
  5087. int len;
  5088. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5089. len = mg_write(conn, buf, (size_t)len);
  5090. }
  5091. if ((buf != mem) && (buf != NULL)) {
  5092. mg_free(buf);
  5093. }
  5094. return len;
  5095. }
  5096. int
  5097. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5098. {
  5099. va_list ap;
  5100. int result;
  5101. va_start(ap, fmt);
  5102. result = mg_vprintf(conn, fmt, ap);
  5103. va_end(ap);
  5104. return result;
  5105. }
  5106. int
  5107. mg_url_decode(const char *src,
  5108. int src_len,
  5109. char *dst,
  5110. int dst_len,
  5111. int is_form_url_encoded)
  5112. {
  5113. int i, j, a, b;
  5114. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5115. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5116. if ((i < src_len - 2) && (src[i] == '%')
  5117. && isxdigit(*(const unsigned char *)(src + i + 1))
  5118. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5119. a = tolower(*(const unsigned char *)(src + i + 1));
  5120. b = tolower(*(const unsigned char *)(src + i + 2));
  5121. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5122. i += 2;
  5123. } else if (is_form_url_encoded && (src[i] == '+')) {
  5124. dst[j] = ' ';
  5125. } else {
  5126. dst[j] = src[i];
  5127. }
  5128. }
  5129. dst[j] = '\0'; /* Null-terminate the destination */
  5130. return (i >= src_len) ? j : -1;
  5131. }
  5132. int
  5133. mg_get_var(const char *data,
  5134. size_t data_len,
  5135. const char *name,
  5136. char *dst,
  5137. size_t dst_len)
  5138. {
  5139. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5140. }
  5141. int
  5142. mg_get_var2(const char *data,
  5143. size_t data_len,
  5144. const char *name,
  5145. char *dst,
  5146. size_t dst_len,
  5147. size_t occurrence)
  5148. {
  5149. const char *p, *e, *s;
  5150. size_t name_len;
  5151. int len;
  5152. if ((dst == NULL) || (dst_len == 0)) {
  5153. len = -2;
  5154. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5155. len = -1;
  5156. dst[0] = '\0';
  5157. } else {
  5158. name_len = strlen(name);
  5159. e = data + data_len;
  5160. len = -1;
  5161. dst[0] = '\0';
  5162. /* data is "var1=val1&var2=val2...". Find variable first */
  5163. for (p = data; p + name_len < e; p++) {
  5164. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5165. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5166. /* Point p to variable value */
  5167. p += name_len + 1;
  5168. /* Point s to the end of the value */
  5169. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5170. if (s == NULL) {
  5171. s = e;
  5172. }
  5173. /* assert(s >= p); */
  5174. if (s < p) {
  5175. return -3;
  5176. }
  5177. /* Decode variable into destination buffer */
  5178. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5179. /* Redirect error code from -1 to -2 (destination buffer too
  5180. * small). */
  5181. if (len == -1) {
  5182. len = -2;
  5183. }
  5184. break;
  5185. }
  5186. }
  5187. }
  5188. return len;
  5189. }
  5190. /* HCP24: some changes to compare hole var_name */
  5191. int
  5192. mg_get_cookie(const char *cookie_header,
  5193. const char *var_name,
  5194. char *dst,
  5195. size_t dst_size)
  5196. {
  5197. const char *s, *p, *end;
  5198. int name_len, len = -1;
  5199. if ((dst == NULL) || (dst_size == 0)) {
  5200. return -2;
  5201. }
  5202. dst[0] = '\0';
  5203. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5204. return -1;
  5205. }
  5206. name_len = (int)strlen(var_name);
  5207. end = s + strlen(s);
  5208. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5209. if (s[name_len] == '=') {
  5210. /* HCP24: now check is it a substring or a full cookie name */
  5211. if ((s == cookie_header) || (s[-1] == ' ')) {
  5212. s += name_len + 1;
  5213. if ((p = strchr(s, ' ')) == NULL) {
  5214. p = end;
  5215. }
  5216. if (p[-1] == ';') {
  5217. p--;
  5218. }
  5219. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5220. s++;
  5221. p--;
  5222. }
  5223. if ((size_t)(p - s) < dst_size) {
  5224. len = (int)(p - s);
  5225. mg_strlcpy(dst, s, (size_t)len + 1);
  5226. } else {
  5227. len = -3;
  5228. }
  5229. break;
  5230. }
  5231. }
  5232. }
  5233. return len;
  5234. }
  5235. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5236. static void
  5237. base64_encode(const unsigned char *src, int src_len, char *dst)
  5238. {
  5239. static const char *b64 =
  5240. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5241. int i, j, a, b, c;
  5242. for (i = j = 0; i < src_len; i += 3) {
  5243. a = src[i];
  5244. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5245. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5246. dst[j++] = b64[a >> 2];
  5247. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5248. if (i + 1 < src_len) {
  5249. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5250. }
  5251. if (i + 2 < src_len) {
  5252. dst[j++] = b64[c & 63];
  5253. }
  5254. }
  5255. while (j % 4 != 0) {
  5256. dst[j++] = '=';
  5257. }
  5258. dst[j++] = '\0';
  5259. }
  5260. #endif
  5261. #if defined(USE_LUA)
  5262. static unsigned char
  5263. b64reverse(char letter)
  5264. {
  5265. if ((letter >= 'A') && (letter <= 'Z')) {
  5266. return letter - 'A';
  5267. }
  5268. if ((letter >= 'a') && (letter <= 'z')) {
  5269. return letter - 'a' + 26;
  5270. }
  5271. if ((letter >= '0') && (letter <= '9')) {
  5272. return letter - '0' + 52;
  5273. }
  5274. if (letter == '+') {
  5275. return 62;
  5276. }
  5277. if (letter == '/') {
  5278. return 63;
  5279. }
  5280. if (letter == '=') {
  5281. return 255; /* normal end */
  5282. }
  5283. return 254; /* error */
  5284. }
  5285. static int
  5286. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5287. {
  5288. int i;
  5289. unsigned char a, b, c, d;
  5290. *dst_len = 0;
  5291. for (i = 0; i < src_len; i += 4) {
  5292. a = b64reverse(src[i]);
  5293. if (a >= 254) {
  5294. return i;
  5295. }
  5296. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5297. if (b >= 254) {
  5298. return i + 1;
  5299. }
  5300. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5301. if (c == 254) {
  5302. return i + 2;
  5303. }
  5304. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5305. if (d == 254) {
  5306. return i + 3;
  5307. }
  5308. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5309. if (c != 255) {
  5310. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5311. if (d != 255) {
  5312. dst[(*dst_len)++] = (c << 6) + d;
  5313. }
  5314. }
  5315. }
  5316. return -1;
  5317. }
  5318. #endif
  5319. static int
  5320. is_put_or_delete_method(const struct mg_connection *conn)
  5321. {
  5322. if (conn) {
  5323. const char *s = conn->request_info.request_method;
  5324. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5325. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5326. }
  5327. return 0;
  5328. }
  5329. #if !defined(NO_FILES)
  5330. static int
  5331. extention_matches_script(
  5332. struct mg_connection *conn, /* in: request (must be valid) */
  5333. const char *filename /* in: filename (must be valid) */
  5334. )
  5335. {
  5336. #if !defined(NO_CGI)
  5337. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5338. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5339. filename) > 0) {
  5340. return 1;
  5341. }
  5342. #endif
  5343. #if defined(USE_LUA)
  5344. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5345. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5346. filename) > 0) {
  5347. return 1;
  5348. }
  5349. #endif
  5350. #if defined(USE_DUKTAPE)
  5351. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5352. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5353. filename) > 0) {
  5354. return 1;
  5355. }
  5356. #endif
  5357. /* filename and conn could be unused, if all preocessor conditions
  5358. * are false (no script language supported). */
  5359. (void)filename;
  5360. (void)conn;
  5361. return 0;
  5362. }
  5363. /* For given directory path, substitute it to valid index file.
  5364. * Return 1 if index file has been found, 0 if not found.
  5365. * If the file is found, it's stats is returned in stp. */
  5366. static int
  5367. substitute_index_file(struct mg_connection *conn,
  5368. char *path,
  5369. size_t path_len,
  5370. struct mg_file_stat *filestat)
  5371. {
  5372. const char *list = conn->ctx->config[INDEX_FILES];
  5373. struct vec filename_vec;
  5374. size_t n = strlen(path);
  5375. int found = 0;
  5376. /* The 'path' given to us points to the directory. Remove all trailing
  5377. * directory separator characters from the end of the path, and
  5378. * then append single directory separator character. */
  5379. while ((n > 0) && (path[n - 1] == '/')) {
  5380. n--;
  5381. }
  5382. path[n] = '/';
  5383. /* Traverse index files list. For each entry, append it to the given
  5384. * path and see if the file exists. If it exists, break the loop */
  5385. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5386. /* Ignore too long entries that may overflow path buffer */
  5387. if (filename_vec.len > (path_len - (n + 2))) {
  5388. continue;
  5389. }
  5390. /* Prepare full path to the index file */
  5391. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5392. /* Does it exist? */
  5393. if (mg_stat(conn, path, filestat)) {
  5394. /* Yes it does, break the loop */
  5395. found = 1;
  5396. break;
  5397. }
  5398. }
  5399. /* If no index file exists, restore directory path */
  5400. if (!found) {
  5401. path[n] = '\0';
  5402. }
  5403. return found;
  5404. }
  5405. #endif
  5406. static void
  5407. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5408. char *filename, /* out: filename */
  5409. size_t filename_buf_len, /* in: size of filename buffer */
  5410. struct mg_file_stat *filestat, /* out: file status structure */
  5411. int *is_found, /* out: file found (directly) */
  5412. int *is_script_resource, /* out: handled by a script? */
  5413. int *is_websocket_request, /* out: websocket connetion? */
  5414. int *is_put_or_delete_request /* out: put/delete a file? */
  5415. )
  5416. {
  5417. #if !defined(NO_FILES)
  5418. const char *uri = conn->request_info.local_uri;
  5419. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5420. const char *rewrite;
  5421. struct vec a, b;
  5422. int match_len;
  5423. char gz_path[PATH_MAX];
  5424. char const *accept_encoding;
  5425. int truncated;
  5426. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5427. char *tmp_str;
  5428. size_t tmp_str_len, sep_pos;
  5429. #endif
  5430. #else
  5431. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5432. #endif
  5433. /* Step 1: Set all initially unknown outputs to zero */
  5434. memset(filestat, 0, sizeof(*filestat));
  5435. *filename = 0;
  5436. *is_found = 0;
  5437. *is_script_resource = 0;
  5438. /* Step 2: Check if the request attempts to modify the file system */
  5439. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5440. /* Step 3: Check if it is a websocket request, and modify the document
  5441. * root if required */
  5442. #if defined(USE_WEBSOCKET)
  5443. *is_websocket_request = is_websocket_protocol(conn);
  5444. #if !defined(NO_FILES)
  5445. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5446. root = conn->ctx->config[WEBSOCKET_ROOT];
  5447. }
  5448. #endif /* !NO_FILES */
  5449. #else /* USE_WEBSOCKET */
  5450. *is_websocket_request = 0;
  5451. #endif /* USE_WEBSOCKET */
  5452. #if !defined(NO_FILES)
  5453. /* Step 4: If there is no root directory, don't look for files. */
  5454. /* Note that root == NULL is a regular use case here. This occurs,
  5455. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5456. * config is not required. */
  5457. if (root == NULL) {
  5458. /* all file related outputs have already been set to 0, just return
  5459. */
  5460. return;
  5461. }
  5462. /* Step 5: Determine the local file path from the root path and the
  5463. * request uri. */
  5464. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5465. * part of the path one byte on the right. */
  5466. mg_snprintf(
  5467. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5468. if (truncated) {
  5469. goto interpret_cleanup;
  5470. }
  5471. /* Step 6: URI rewriting */
  5472. rewrite = conn->ctx->config[URL_REWRITE_PATTERN];
  5473. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5474. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5475. mg_snprintf(conn,
  5476. &truncated,
  5477. filename,
  5478. filename_buf_len - 1,
  5479. "%.*s%s",
  5480. (int)b.len,
  5481. b.ptr,
  5482. uri + match_len);
  5483. break;
  5484. }
  5485. }
  5486. if (truncated) {
  5487. goto interpret_cleanup;
  5488. }
  5489. /* Step 7: Check if the file exists at the server */
  5490. /* Local file path and name, corresponding to requested URI
  5491. * is now stored in "filename" variable. */
  5492. if (mg_stat(conn, filename, filestat)) {
  5493. /* 7.1: File exists. */
  5494. *is_found = 1;
  5495. /* 7.2: Check if it is a script type. */
  5496. if (extention_matches_script(conn, filename)) {
  5497. /* The request addresses a CGI resource, Lua script or
  5498. * server-side javascript.
  5499. * The URI corresponds to the script itself (like
  5500. * /path/script.cgi), and there is no additional resource
  5501. * path (like /path/script.cgi/something).
  5502. * Requests that modify (replace or delete) a resource, like
  5503. * PUT and DELETE requests, should replace/delete the script
  5504. * file.
  5505. * Requests that read or write from/to a resource, like GET and
  5506. * POST requests, should call the script and return the
  5507. * generated response. */
  5508. *is_script_resource = (!*is_put_or_delete_request);
  5509. }
  5510. /* 7.3: If the request target is a directory, there could be
  5511. * a substitute file (index.html, index.cgi, ...). */
  5512. if (filestat->is_directory) {
  5513. /* Use a local copy here, since substitute_index_file will
  5514. * change the content of the file status */
  5515. struct mg_file_stat tmp_filestat;
  5516. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5517. if (substitute_index_file(
  5518. conn, filename, filename_buf_len, &tmp_filestat)) {
  5519. /* Substitute file found. Copy stat to the output, then
  5520. * check if the file is a script file */
  5521. *filestat = tmp_filestat;
  5522. if (extention_matches_script(conn, filename)) {
  5523. /* Substitute file is a script file */
  5524. *is_script_resource = 1;
  5525. } else {
  5526. /* Substitute file is a regular file */
  5527. *is_script_resource = 0;
  5528. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5529. }
  5530. }
  5531. /* If there is no substitute file, the server could return
  5532. * a directory listing in a later step */
  5533. }
  5534. return;
  5535. }
  5536. /* Step 8: Check for zipped files: */
  5537. /* If we can't find the actual file, look for the file
  5538. * with the same name but a .gz extension. If we find it,
  5539. * use that and set the gzipped flag in the file struct
  5540. * to indicate that the response need to have the content-
  5541. * encoding: gzip header.
  5542. * We can only do this if the browser declares support. */
  5543. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5544. if (strstr(accept_encoding, "gzip") != NULL) {
  5545. mg_snprintf(
  5546. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5547. if (truncated) {
  5548. goto interpret_cleanup;
  5549. }
  5550. if (mg_stat(conn, gz_path, filestat)) {
  5551. if (filestat) {
  5552. filestat->is_gzipped = 1;
  5553. *is_found = 1;
  5554. }
  5555. /* Currently gz files can not be scripts. */
  5556. return;
  5557. }
  5558. }
  5559. }
  5560. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5561. /* Step 9: Script resources may handle sub-resources */
  5562. /* Support PATH_INFO for CGI scripts. */
  5563. tmp_str_len = strlen(filename);
  5564. tmp_str = mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->ctx);
  5565. if (!tmp_str) {
  5566. /* Out of memory */
  5567. goto interpret_cleanup;
  5568. }
  5569. memcpy(tmp_str, filename, tmp_str_len + 1);
  5570. sep_pos = tmp_str_len;
  5571. while (sep_pos > 0) {
  5572. sep_pos--;
  5573. if (tmp_str[sep_pos] == '/') {
  5574. int is_script = 0, does_exist = 0;
  5575. tmp_str[sep_pos] = 0;
  5576. if (tmp_str[0]) {
  5577. is_script = extention_matches_script(conn, tmp_str);
  5578. does_exist = mg_stat(conn, tmp_str, filestat);
  5579. }
  5580. if (does_exist && is_script) {
  5581. filename[sep_pos] = 0;
  5582. memmove(filename + sep_pos + 2,
  5583. filename + sep_pos + 1,
  5584. strlen(filename + sep_pos + 1) + 1);
  5585. conn->path_info = filename + sep_pos + 1;
  5586. filename[sep_pos + 1] = '/';
  5587. *is_script_resource = 1;
  5588. *is_found = 1;
  5589. break;
  5590. }
  5591. if (substitute_index_file(
  5592. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5593. /* some intermediate directory has an index file */
  5594. if (extention_matches_script(conn, tmp_str)) {
  5595. /* this index file is a script */
  5596. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5597. mg_snprintf(conn,
  5598. &truncated,
  5599. filename,
  5600. filename_buf_len,
  5601. "%s//%s",
  5602. tmp_str,
  5603. tmp_str2);
  5604. mg_free(tmp_str2);
  5605. if (truncated) {
  5606. mg_free(tmp_str);
  5607. goto interpret_cleanup;
  5608. }
  5609. sep_pos = strlen(tmp_str);
  5610. filename[sep_pos] = 0;
  5611. conn->path_info = filename + sep_pos + 1;
  5612. *is_script_resource = 1;
  5613. *is_found = 1;
  5614. break;
  5615. } else {
  5616. /* non-script files will not have sub-resources */
  5617. filename[sep_pos] = 0;
  5618. conn->path_info = 0;
  5619. *is_script_resource = 0;
  5620. *is_found = 0;
  5621. break;
  5622. }
  5623. }
  5624. tmp_str[sep_pos] = '/';
  5625. }
  5626. }
  5627. mg_free(tmp_str);
  5628. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5629. #endif /* !defined(NO_FILES) */
  5630. return;
  5631. #if !defined(NO_FILES)
  5632. /* Reset all outputs */
  5633. interpret_cleanup:
  5634. memset(filestat, 0, sizeof(*filestat));
  5635. *filename = 0;
  5636. *is_found = 0;
  5637. *is_script_resource = 0;
  5638. *is_websocket_request = 0;
  5639. *is_put_or_delete_request = 0;
  5640. #endif /* !defined(NO_FILES) */
  5641. }
  5642. /* Check whether full request is buffered. Return:
  5643. * -1 if request or response is malformed
  5644. * 0 if request or response is not yet fully buffered
  5645. * >0 actual request length, including last \r\n\r\n */
  5646. static int
  5647. get_http_header_len(const char *buf, int buflen)
  5648. {
  5649. int i;
  5650. for (i = 0; i < buflen; i++) {
  5651. /* Do an unsigned comparison in some conditions below */
  5652. const unsigned char c = ((const unsigned char *)buf)[i];
  5653. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  5654. && !isprint(c)) {
  5655. /* abort scan as soon as one malformed character is found */
  5656. return -1;
  5657. }
  5658. if (i < buflen - 1) {
  5659. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  5660. /* Two newline, no carriage return - not standard compliant, but
  5661. * it
  5662. * should be accepted */
  5663. return i + 2;
  5664. }
  5665. }
  5666. if (i < buflen - 3) {
  5667. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  5668. && (buf[i + 3] == '\n')) {
  5669. /* Two \r\n - standard compliant */
  5670. return i + 4;
  5671. }
  5672. }
  5673. }
  5674. return 0;
  5675. }
  5676. #if !defined(NO_CACHING)
  5677. /* Convert month to the month number. Return -1 on error, or month number */
  5678. static int
  5679. get_month_index(const char *s)
  5680. {
  5681. size_t i;
  5682. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5683. if (!strcmp(s, month_names[i])) {
  5684. return (int)i;
  5685. }
  5686. }
  5687. return -1;
  5688. }
  5689. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5690. static time_t
  5691. parse_date_string(const char *datetime)
  5692. {
  5693. char month_str[32] = {0};
  5694. int second, minute, hour, day, month, year;
  5695. time_t result = (time_t)0;
  5696. struct tm tm;
  5697. if ((sscanf(datetime,
  5698. "%d/%3s/%d %d:%d:%d",
  5699. &day,
  5700. month_str,
  5701. &year,
  5702. &hour,
  5703. &minute,
  5704. &second) == 6) || (sscanf(datetime,
  5705. "%d %3s %d %d:%d:%d",
  5706. &day,
  5707. month_str,
  5708. &year,
  5709. &hour,
  5710. &minute,
  5711. &second) == 6)
  5712. || (sscanf(datetime,
  5713. "%*3s, %d %3s %d %d:%d:%d",
  5714. &day,
  5715. month_str,
  5716. &year,
  5717. &hour,
  5718. &minute,
  5719. &second) == 6) || (sscanf(datetime,
  5720. "%d-%3s-%d %d:%d:%d",
  5721. &day,
  5722. month_str,
  5723. &year,
  5724. &hour,
  5725. &minute,
  5726. &second) == 6)) {
  5727. month = get_month_index(month_str);
  5728. if ((month >= 0) && (year >= 1970)) {
  5729. memset(&tm, 0, sizeof(tm));
  5730. tm.tm_year = year - 1900;
  5731. tm.tm_mon = month;
  5732. tm.tm_mday = day;
  5733. tm.tm_hour = hour;
  5734. tm.tm_min = minute;
  5735. tm.tm_sec = second;
  5736. result = timegm(&tm);
  5737. }
  5738. }
  5739. return result;
  5740. }
  5741. #endif /* !NO_CACHING */
  5742. /* Protect against directory disclosure attack by removing '..',
  5743. * excessive '/' and '\' characters */
  5744. static void
  5745. remove_double_dots_and_double_slashes(char *s)
  5746. {
  5747. char *p = s;
  5748. while ((s[0] == '.') && (s[1] == '.')) {
  5749. s++;
  5750. }
  5751. while (*s != '\0') {
  5752. *p++ = *s++;
  5753. if ((s[-1] == '/') || (s[-1] == '\\')) {
  5754. /* Skip all following slashes, backslashes and double-dots */
  5755. while (s[0] != '\0') {
  5756. if ((s[0] == '/') || (s[0] == '\\')) {
  5757. s++;
  5758. } else if ((s[0] == '.') && (s[1] == '.')) {
  5759. s += 2;
  5760. } else {
  5761. break;
  5762. }
  5763. }
  5764. }
  5765. }
  5766. *p = '\0';
  5767. }
  5768. static const struct {
  5769. const char *extension;
  5770. size_t ext_len;
  5771. const char *mime_type;
  5772. } builtin_mime_types[] = {
  5773. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5774. * application types */
  5775. {".doc", 4, "application/msword"},
  5776. {".eps", 4, "application/postscript"},
  5777. {".exe", 4, "application/octet-stream"},
  5778. {".js", 3, "application/javascript"},
  5779. {".json", 5, "application/json"},
  5780. {".pdf", 4, "application/pdf"},
  5781. {".ps", 3, "application/postscript"},
  5782. {".rtf", 4, "application/rtf"},
  5783. {".xhtml", 6, "application/xhtml+xml"},
  5784. {".xsl", 4, "application/xml"},
  5785. {".xslt", 5, "application/xml"},
  5786. /* fonts */
  5787. {".ttf", 4, "application/font-sfnt"},
  5788. {".cff", 4, "application/font-sfnt"},
  5789. {".otf", 4, "application/font-sfnt"},
  5790. {".aat", 4, "application/font-sfnt"},
  5791. {".sil", 4, "application/font-sfnt"},
  5792. {".pfr", 4, "application/font-tdpfr"},
  5793. {".woff", 5, "application/font-woff"},
  5794. /* audio */
  5795. {".mp3", 4, "audio/mpeg"},
  5796. {".oga", 4, "audio/ogg"},
  5797. {".ogg", 4, "audio/ogg"},
  5798. /* image */
  5799. {".gif", 4, "image/gif"},
  5800. {".ief", 4, "image/ief"},
  5801. {".jpeg", 5, "image/jpeg"},
  5802. {".jpg", 4, "image/jpeg"},
  5803. {".jpm", 4, "image/jpm"},
  5804. {".jpx", 4, "image/jpx"},
  5805. {".png", 4, "image/png"},
  5806. {".svg", 4, "image/svg+xml"},
  5807. {".tif", 4, "image/tiff"},
  5808. {".tiff", 5, "image/tiff"},
  5809. /* model */
  5810. {".wrl", 4, "model/vrml"},
  5811. /* text */
  5812. {".css", 4, "text/css"},
  5813. {".csv", 4, "text/csv"},
  5814. {".htm", 4, "text/html"},
  5815. {".html", 5, "text/html"},
  5816. {".sgm", 4, "text/sgml"},
  5817. {".shtm", 5, "text/html"},
  5818. {".shtml", 6, "text/html"},
  5819. {".txt", 4, "text/plain"},
  5820. {".xml", 4, "text/xml"},
  5821. /* video */
  5822. {".mov", 4, "video/quicktime"},
  5823. {".mp4", 4, "video/mp4"},
  5824. {".mpeg", 5, "video/mpeg"},
  5825. {".mpg", 4, "video/mpeg"},
  5826. {".ogv", 4, "video/ogg"},
  5827. {".qt", 3, "video/quicktime"},
  5828. /* not registered types
  5829. * (http://reference.sitepoint.com/html/mime-types-full,
  5830. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5831. {".arj", 4, "application/x-arj-compressed"},
  5832. {".gz", 3, "application/x-gunzip"},
  5833. {".rar", 4, "application/x-arj-compressed"},
  5834. {".swf", 4, "application/x-shockwave-flash"},
  5835. {".tar", 4, "application/x-tar"},
  5836. {".tgz", 4, "application/x-tar-gz"},
  5837. {".torrent", 8, "application/x-bittorrent"},
  5838. {".ppt", 4, "application/x-mspowerpoint"},
  5839. {".xls", 4, "application/x-msexcel"},
  5840. {".zip", 4, "application/x-zip-compressed"},
  5841. {".aac",
  5842. 4,
  5843. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5844. {".aif", 4, "audio/x-aif"},
  5845. {".m3u", 4, "audio/x-mpegurl"},
  5846. {".mid", 4, "audio/x-midi"},
  5847. {".ra", 3, "audio/x-pn-realaudio"},
  5848. {".ram", 4, "audio/x-pn-realaudio"},
  5849. {".wav", 4, "audio/x-wav"},
  5850. {".bmp", 4, "image/bmp"},
  5851. {".ico", 4, "image/x-icon"},
  5852. {".pct", 4, "image/x-pct"},
  5853. {".pict", 5, "image/pict"},
  5854. {".rgb", 4, "image/x-rgb"},
  5855. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5856. {".asf", 4, "video/x-ms-asf"},
  5857. {".avi", 4, "video/x-msvideo"},
  5858. {".m4v", 4, "video/x-m4v"},
  5859. {NULL, 0, NULL}};
  5860. const char *
  5861. mg_get_builtin_mime_type(const char *path)
  5862. {
  5863. const char *ext;
  5864. size_t i, path_len;
  5865. path_len = strlen(path);
  5866. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5867. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5868. if ((path_len > builtin_mime_types[i].ext_len)
  5869. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  5870. return builtin_mime_types[i].mime_type;
  5871. }
  5872. }
  5873. return "text/plain";
  5874. }
  5875. /* Look at the "path" extension and figure what mime type it has.
  5876. * Store mime type in the vector. */
  5877. static void
  5878. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5879. {
  5880. struct vec ext_vec, mime_vec;
  5881. const char *list, *ext;
  5882. size_t path_len;
  5883. path_len = strlen(path);
  5884. if ((ctx == NULL) || (vec == NULL)) {
  5885. if (vec != NULL) {
  5886. memset(vec, '\0', sizeof(struct vec));
  5887. }
  5888. return;
  5889. }
  5890. /* Scan user-defined mime types first, in case user wants to
  5891. * override default mime types. */
  5892. list = ctx->config[EXTRA_MIME_TYPES];
  5893. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5894. /* ext now points to the path suffix */
  5895. ext = path + path_len - ext_vec.len;
  5896. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5897. *vec = mime_vec;
  5898. return;
  5899. }
  5900. }
  5901. vec->ptr = mg_get_builtin_mime_type(path);
  5902. vec->len = strlen(vec->ptr);
  5903. }
  5904. /* Stringify binary data. Output buffer must be twice as big as input,
  5905. * because each byte takes 2 bytes in string representation */
  5906. static void
  5907. bin2str(char *to, const unsigned char *p, size_t len)
  5908. {
  5909. static const char *hex = "0123456789abcdef";
  5910. for (; len--; p++) {
  5911. *to++ = hex[p[0] >> 4];
  5912. *to++ = hex[p[0] & 0x0f];
  5913. }
  5914. *to = '\0';
  5915. }
  5916. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5917. char *
  5918. mg_md5(char buf[33], ...)
  5919. {
  5920. md5_byte_t hash[16];
  5921. const char *p;
  5922. va_list ap;
  5923. md5_state_t ctx;
  5924. md5_init(&ctx);
  5925. va_start(ap, buf);
  5926. while ((p = va_arg(ap, const char *)) != NULL) {
  5927. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5928. }
  5929. va_end(ap);
  5930. md5_finish(&ctx, hash);
  5931. bin2str(buf, hash, sizeof(hash));
  5932. return buf;
  5933. }
  5934. /* Check the user's password, return 1 if OK */
  5935. static int
  5936. check_password(const char *method,
  5937. const char *ha1,
  5938. const char *uri,
  5939. const char *nonce,
  5940. const char *nc,
  5941. const char *cnonce,
  5942. const char *qop,
  5943. const char *response)
  5944. {
  5945. char ha2[32 + 1], expected_response[32 + 1];
  5946. /* Some of the parameters may be NULL */
  5947. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  5948. || (qop == NULL) || (response == NULL)) {
  5949. return 0;
  5950. }
  5951. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5952. if (strlen(response) != 32) {
  5953. return 0;
  5954. }
  5955. mg_md5(ha2, method, ":", uri, NULL);
  5956. mg_md5(expected_response,
  5957. ha1,
  5958. ":",
  5959. nonce,
  5960. ":",
  5961. nc,
  5962. ":",
  5963. cnonce,
  5964. ":",
  5965. qop,
  5966. ":",
  5967. ha2,
  5968. NULL);
  5969. return mg_strcasecmp(response, expected_response) == 0;
  5970. }
  5971. /* Use the global passwords file, if specified by auth_gpass option,
  5972. * or search for .htpasswd in the requested directory. */
  5973. static void
  5974. open_auth_file(struct mg_connection *conn,
  5975. const char *path,
  5976. struct mg_file *filep)
  5977. {
  5978. if ((conn != NULL) && (conn->ctx != NULL)) {
  5979. char name[PATH_MAX];
  5980. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5981. int truncated;
  5982. if (gpass != NULL) {
  5983. /* Use global passwords file */
  5984. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5985. #ifdef DEBUG
  5986. /* Use mg_cry here, since gpass has been configured. */
  5987. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5988. #endif
  5989. }
  5990. /* Important: using local struct mg_file to test path for
  5991. * is_directory flag. If filep is used, mg_stat() makes it
  5992. * appear as if auth file was opened.
  5993. * TODO(mid): Check if this is still required after rewriting
  5994. * mg_stat */
  5995. } else if (mg_stat(conn, path, &filep->stat)
  5996. && filep->stat.is_directory) {
  5997. mg_snprintf(conn,
  5998. &truncated,
  5999. name,
  6000. sizeof(name),
  6001. "%s/%s",
  6002. path,
  6003. PASSWORDS_FILE_NAME);
  6004. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6005. #ifdef DEBUG
  6006. /* Don't use mg_cry here, but only a trace, since this is
  6007. * a typical case. It will occur for every directory
  6008. * without a password file. */
  6009. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6010. #endif
  6011. }
  6012. } else {
  6013. /* Try to find .htpasswd in requested directory. */
  6014. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6015. if (e[0] == '/') {
  6016. break;
  6017. }
  6018. }
  6019. mg_snprintf(conn,
  6020. &truncated,
  6021. name,
  6022. sizeof(name),
  6023. "%.*s/%s",
  6024. (int)(e - p),
  6025. p,
  6026. PASSWORDS_FILE_NAME);
  6027. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6028. #ifdef DEBUG
  6029. /* Don't use mg_cry here, but only a trace, since this is
  6030. * a typical case. It will occur for every directory
  6031. * without a password file. */
  6032. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6033. #endif
  6034. }
  6035. }
  6036. }
  6037. }
  6038. /* Parsed Authorization header */
  6039. struct ah {
  6040. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6041. };
  6042. /* Return 1 on success. Always initializes the ah structure. */
  6043. static int
  6044. parse_auth_header(struct mg_connection *conn,
  6045. char *buf,
  6046. size_t buf_size,
  6047. struct ah *ah)
  6048. {
  6049. char *name, *value, *s;
  6050. const char *auth_header;
  6051. uint64_t nonce;
  6052. if (!ah || !conn) {
  6053. return 0;
  6054. }
  6055. (void)memset(ah, 0, sizeof(*ah));
  6056. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6057. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6058. return 0;
  6059. }
  6060. /* Make modifiable copy of the auth header */
  6061. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6062. s = buf;
  6063. /* Parse authorization header */
  6064. for (;;) {
  6065. /* Gobble initial spaces */
  6066. while (isspace(*(unsigned char *)s)) {
  6067. s++;
  6068. }
  6069. name = skip_quoted(&s, "=", " ", 0);
  6070. /* Value is either quote-delimited, or ends at first comma or space. */
  6071. if (s[0] == '\"') {
  6072. s++;
  6073. value = skip_quoted(&s, "\"", " ", '\\');
  6074. if (s[0] == ',') {
  6075. s++;
  6076. }
  6077. } else {
  6078. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6079. * spaces */
  6080. }
  6081. if (*name == '\0') {
  6082. break;
  6083. }
  6084. if (!strcmp(name, "username")) {
  6085. ah->user = value;
  6086. } else if (!strcmp(name, "cnonce")) {
  6087. ah->cnonce = value;
  6088. } else if (!strcmp(name, "response")) {
  6089. ah->response = value;
  6090. } else if (!strcmp(name, "uri")) {
  6091. ah->uri = value;
  6092. } else if (!strcmp(name, "qop")) {
  6093. ah->qop = value;
  6094. } else if (!strcmp(name, "nc")) {
  6095. ah->nc = value;
  6096. } else if (!strcmp(name, "nonce")) {
  6097. ah->nonce = value;
  6098. }
  6099. }
  6100. #ifndef NO_NONCE_CHECK
  6101. /* Read the nonce from the response. */
  6102. if (ah->nonce == NULL) {
  6103. return 0;
  6104. }
  6105. s = NULL;
  6106. nonce = strtoull(ah->nonce, &s, 10);
  6107. if ((s == NULL) || (*s != 0)) {
  6108. return 0;
  6109. }
  6110. /* Convert the nonce from the client to a number. */
  6111. nonce ^= conn->ctx->auth_nonce_mask;
  6112. /* The converted number corresponds to the time the nounce has been
  6113. * created. This should not be earlier than the server start. */
  6114. /* Server side nonce check is valuable in all situations but one:
  6115. * if the server restarts frequently, but the client should not see
  6116. * that, so the server should accept nonces from previous starts. */
  6117. /* However, the reasonable default is to not accept a nonce from a
  6118. * previous start, so if anyone changed the access rights between
  6119. * two restarts, a new login is required. */
  6120. if (nonce < (uint64_t)conn->ctx->start_time) {
  6121. /* nonce is from a previous start of the server and no longer valid
  6122. * (replay attack?) */
  6123. return 0;
  6124. }
  6125. /* Check if the nonce is too high, so it has not (yet) been used by the
  6126. * server. */
  6127. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  6128. return 0;
  6129. }
  6130. #else
  6131. (void)nonce;
  6132. #endif
  6133. /* CGI needs it as REMOTE_USER */
  6134. if (ah->user != NULL) {
  6135. conn->request_info.remote_user = mg_strdup(ah->user);
  6136. } else {
  6137. return 0;
  6138. }
  6139. return 1;
  6140. }
  6141. static const char *
  6142. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6143. {
  6144. const char *eof;
  6145. size_t len;
  6146. const char *memend;
  6147. if (!filep) {
  6148. return NULL;
  6149. }
  6150. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6151. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6152. /* Search for \n from p till the end of stream */
  6153. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6154. if (eof != NULL) {
  6155. eof += 1; /* Include \n */
  6156. } else {
  6157. eof = memend; /* Copy remaining data */
  6158. }
  6159. len =
  6160. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6161. memcpy(buf, *p, len);
  6162. buf[len] = '\0';
  6163. *p += len;
  6164. return len ? eof : NULL;
  6165. } else if (filep->access.fp != NULL) {
  6166. return fgets(buf, (int)size, filep->access.fp);
  6167. } else {
  6168. return NULL;
  6169. }
  6170. }
  6171. /* Define the initial recursion depth for procesesing htpasswd files that
  6172. * include other htpasswd
  6173. * (or even the same) files. It is not difficult to provide a file or files
  6174. * s.t. they force civetweb
  6175. * to infinitely recurse and then crash.
  6176. */
  6177. #define INITIAL_DEPTH 9
  6178. #if INITIAL_DEPTH <= 0
  6179. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6180. #endif
  6181. struct read_auth_file_struct {
  6182. struct mg_connection *conn;
  6183. struct ah ah;
  6184. char *domain;
  6185. char buf[256 + 256 + 40];
  6186. char *f_user;
  6187. char *f_domain;
  6188. char *f_ha1;
  6189. };
  6190. static int
  6191. read_auth_file(struct mg_file *filep,
  6192. struct read_auth_file_struct *workdata,
  6193. int depth)
  6194. {
  6195. char *p;
  6196. int is_authorized = 0;
  6197. struct mg_file fp;
  6198. size_t l;
  6199. if (!filep || !workdata || (0 == depth)) {
  6200. return 0;
  6201. }
  6202. /* Loop over passwords file */
  6203. p = (char *)filep->access.membuf;
  6204. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6205. l = strlen(workdata->buf);
  6206. while (l > 0) {
  6207. if (isspace(workdata->buf[l - 1])
  6208. || iscntrl(workdata->buf[l - 1])) {
  6209. l--;
  6210. workdata->buf[l] = 0;
  6211. } else
  6212. break;
  6213. }
  6214. if (l < 1) {
  6215. continue;
  6216. }
  6217. workdata->f_user = workdata->buf;
  6218. if (workdata->f_user[0] == ':') {
  6219. /* user names may not contain a ':' and may not be empty,
  6220. * so lines starting with ':' may be used for a special purpose */
  6221. if (workdata->f_user[1] == '#') {
  6222. /* :# is a comment */
  6223. continue;
  6224. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6225. if (mg_fopen(workdata->conn,
  6226. workdata->f_user + 9,
  6227. MG_FOPEN_MODE_READ,
  6228. &fp)) {
  6229. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6230. (void)mg_fclose(
  6231. &fp.access); /* ignore error on read only file */
  6232. /* No need to continue processing files once we have a
  6233. * match, since nothing will reset it back
  6234. * to 0.
  6235. */
  6236. if (is_authorized) {
  6237. return is_authorized;
  6238. }
  6239. } else {
  6240. mg_cry(workdata->conn,
  6241. "%s: cannot open authorization file: %s",
  6242. __func__,
  6243. workdata->buf);
  6244. }
  6245. continue;
  6246. }
  6247. /* everything is invalid for the moment (might change in the
  6248. * future) */
  6249. mg_cry(workdata->conn,
  6250. "%s: syntax error in authorization file: %s",
  6251. __func__,
  6252. workdata->buf);
  6253. continue;
  6254. }
  6255. workdata->f_domain = strchr(workdata->f_user, ':');
  6256. if (workdata->f_domain == NULL) {
  6257. mg_cry(workdata->conn,
  6258. "%s: syntax error in authorization file: %s",
  6259. __func__,
  6260. workdata->buf);
  6261. continue;
  6262. }
  6263. *(workdata->f_domain) = 0;
  6264. (workdata->f_domain)++;
  6265. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6266. if (workdata->f_ha1 == NULL) {
  6267. mg_cry(workdata->conn,
  6268. "%s: syntax error in authorization file: %s",
  6269. __func__,
  6270. workdata->buf);
  6271. continue;
  6272. }
  6273. *(workdata->f_ha1) = 0;
  6274. (workdata->f_ha1)++;
  6275. if (!strcmp(workdata->ah.user, workdata->f_user)
  6276. && !strcmp(workdata->domain, workdata->f_domain)) {
  6277. return check_password(workdata->conn->request_info.request_method,
  6278. workdata->f_ha1,
  6279. workdata->ah.uri,
  6280. workdata->ah.nonce,
  6281. workdata->ah.nc,
  6282. workdata->ah.cnonce,
  6283. workdata->ah.qop,
  6284. workdata->ah.response);
  6285. }
  6286. }
  6287. return is_authorized;
  6288. }
  6289. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6290. static int
  6291. authorize(struct mg_connection *conn, struct mg_file *filep)
  6292. {
  6293. struct read_auth_file_struct workdata;
  6294. char buf[MG_BUF_LEN];
  6295. if (!conn || !conn->ctx) {
  6296. return 0;
  6297. }
  6298. memset(&workdata, 0, sizeof(workdata));
  6299. workdata.conn = conn;
  6300. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6301. return 0;
  6302. }
  6303. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6304. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6305. }
  6306. /* Return 1 if request is authorised, 0 otherwise. */
  6307. static int
  6308. check_authorization(struct mg_connection *conn, const char *path)
  6309. {
  6310. char fname[PATH_MAX];
  6311. struct vec uri_vec, filename_vec;
  6312. const char *list;
  6313. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6314. int authorized = 1, truncated;
  6315. if (!conn || !conn->ctx) {
  6316. return 0;
  6317. }
  6318. list = conn->ctx->config[PROTECT_URI];
  6319. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6320. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6321. mg_snprintf(conn,
  6322. &truncated,
  6323. fname,
  6324. sizeof(fname),
  6325. "%.*s",
  6326. (int)filename_vec.len,
  6327. filename_vec.ptr);
  6328. if (truncated
  6329. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6330. mg_cry(conn,
  6331. "%s: cannot open %s: %s",
  6332. __func__,
  6333. fname,
  6334. strerror(errno));
  6335. }
  6336. break;
  6337. }
  6338. }
  6339. if (!is_file_opened(&file.access)) {
  6340. open_auth_file(conn, path, &file);
  6341. }
  6342. if (is_file_opened(&file.access)) {
  6343. authorized = authorize(conn, &file);
  6344. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6345. }
  6346. return authorized;
  6347. }
  6348. static void
  6349. send_authorization_request(struct mg_connection *conn)
  6350. {
  6351. char date[64];
  6352. time_t curtime = time(NULL);
  6353. if (conn && conn->ctx) {
  6354. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6355. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6356. nonce += conn->ctx->nonce_count;
  6357. ++conn->ctx->nonce_count;
  6358. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6359. nonce ^= conn->ctx->auth_nonce_mask;
  6360. conn->status_code = 401;
  6361. conn->must_close = 1;
  6362. gmt_time_string(date, sizeof(date), &curtime);
  6363. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6364. send_no_cache_header(conn);
  6365. send_additional_header(conn);
  6366. mg_printf(conn,
  6367. "Date: %s\r\n"
  6368. "Connection: %s\r\n"
  6369. "Content-Length: 0\r\n"
  6370. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6371. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6372. date,
  6373. suggest_connection_header(conn),
  6374. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6375. nonce);
  6376. }
  6377. }
  6378. #if !defined(NO_FILES)
  6379. static int
  6380. is_authorized_for_put(struct mg_connection *conn)
  6381. {
  6382. if (conn) {
  6383. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6384. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6385. int ret = 0;
  6386. if (passfile != NULL
  6387. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6388. ret = authorize(conn, &file);
  6389. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6390. }
  6391. return ret;
  6392. }
  6393. return 0;
  6394. }
  6395. #endif
  6396. int
  6397. mg_modify_passwords_file(const char *fname,
  6398. const char *domain,
  6399. const char *user,
  6400. const char *pass)
  6401. {
  6402. int found, i;
  6403. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6404. FILE *fp, *fp2;
  6405. found = 0;
  6406. fp = fp2 = NULL;
  6407. /* Regard empty password as no password - remove user record. */
  6408. if ((pass != NULL) && (pass[0] == '\0')) {
  6409. pass = NULL;
  6410. }
  6411. /* Other arguments must not be empty */
  6412. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6413. return 0;
  6414. }
  6415. /* Using the given file format, user name and domain must not contain ':'
  6416. */
  6417. if (strchr(user, ':') != NULL) {
  6418. return 0;
  6419. }
  6420. if (strchr(domain, ':') != NULL) {
  6421. return 0;
  6422. }
  6423. /* Do not allow control characters like newline in user name and domain.
  6424. * Do not allow excessively long names either. */
  6425. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6426. if (iscntrl(user[i])) {
  6427. return 0;
  6428. }
  6429. }
  6430. if (user[i]) {
  6431. return 0;
  6432. }
  6433. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6434. if (iscntrl(domain[i])) {
  6435. return 0;
  6436. }
  6437. }
  6438. if (domain[i]) {
  6439. return 0;
  6440. }
  6441. /* The maximum length of the path to the password file is limited */
  6442. if ((strlen(fname) + 4) >= PATH_MAX) {
  6443. return 0;
  6444. }
  6445. /* Create a temporary file name. Length has been checked before. */
  6446. strcpy(tmp, fname);
  6447. strcat(tmp, ".tmp");
  6448. /* Create the file if does not exist */
  6449. /* Use of fopen here is OK, since fname is only ASCII */
  6450. if ((fp = fopen(fname, "a+")) != NULL) {
  6451. (void)fclose(fp);
  6452. }
  6453. /* Open the given file and temporary file */
  6454. if ((fp = fopen(fname, "r")) == NULL) {
  6455. return 0;
  6456. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6457. fclose(fp);
  6458. return 0;
  6459. }
  6460. /* Copy the stuff to temporary file */
  6461. while (fgets(line, sizeof(line), fp) != NULL) {
  6462. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6463. continue;
  6464. }
  6465. u[255] = 0;
  6466. d[255] = 0;
  6467. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6468. found++;
  6469. if (pass != NULL) {
  6470. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6471. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6472. }
  6473. } else {
  6474. fprintf(fp2, "%s", line);
  6475. }
  6476. }
  6477. /* If new user, just add it */
  6478. if (!found && (pass != NULL)) {
  6479. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6480. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6481. }
  6482. /* Close files */
  6483. fclose(fp);
  6484. fclose(fp2);
  6485. /* Put the temp file in place of real file */
  6486. IGNORE_UNUSED_RESULT(remove(fname));
  6487. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6488. return 1;
  6489. }
  6490. static int
  6491. is_valid_port(unsigned long port)
  6492. {
  6493. return (port <= 0xffff);
  6494. }
  6495. static int
  6496. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6497. {
  6498. struct addrinfo hints, *res, *ressave;
  6499. int func_ret = 0;
  6500. int gai_ret;
  6501. memset(&hints, 0, sizeof(struct addrinfo));
  6502. hints.ai_family = af;
  6503. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6504. if (gai_ret != 0) {
  6505. /* gai_strerror could be used to convert gai_ret to a string */
  6506. /* POSIX return values: see
  6507. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6508. */
  6509. /* Windows return values: see
  6510. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6511. */
  6512. return 0;
  6513. }
  6514. ressave = res;
  6515. while (res) {
  6516. if (dstlen >= (size_t)res->ai_addrlen) {
  6517. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6518. func_ret = 1;
  6519. }
  6520. res = res->ai_next;
  6521. }
  6522. freeaddrinfo(ressave);
  6523. return func_ret;
  6524. }
  6525. static int
  6526. connect_socket(struct mg_context *ctx /* may be NULL */,
  6527. const char *host,
  6528. int port,
  6529. int use_ssl,
  6530. char *ebuf,
  6531. size_t ebuf_len,
  6532. SOCKET *sock /* output: socket, must not be NULL */,
  6533. union usa *sa /* output: socket address, must not be NULL */
  6534. )
  6535. {
  6536. int ip_ver = 0;
  6537. *sock = INVALID_SOCKET;
  6538. memset(sa, 0, sizeof(*sa));
  6539. if (ebuf_len > 0) {
  6540. *ebuf = 0;
  6541. }
  6542. if (host == NULL) {
  6543. mg_snprintf(NULL,
  6544. NULL, /* No truncation check for ebuf */
  6545. ebuf,
  6546. ebuf_len,
  6547. "%s",
  6548. "NULL host");
  6549. return 0;
  6550. }
  6551. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  6552. mg_snprintf(NULL,
  6553. NULL, /* No truncation check for ebuf */
  6554. ebuf,
  6555. ebuf_len,
  6556. "%s",
  6557. "invalid port");
  6558. return 0;
  6559. }
  6560. #if !defined(NO_SSL)
  6561. #if !defined(NO_SSL_DL)
  6562. #ifdef OPENSSL_API_1_1
  6563. if (use_ssl && (TLS_client_method == NULL)) {
  6564. mg_snprintf(NULL,
  6565. NULL, /* No truncation check for ebuf */
  6566. ebuf,
  6567. ebuf_len,
  6568. "%s",
  6569. "SSL is not initialized");
  6570. return 0;
  6571. }
  6572. #else
  6573. if (use_ssl && (SSLv23_client_method == NULL)) {
  6574. mg_snprintf(NULL,
  6575. NULL, /* No truncation check for ebuf */
  6576. ebuf,
  6577. ebuf_len,
  6578. "%s",
  6579. "SSL is not initialized");
  6580. return 0;
  6581. }
  6582. #endif /* OPENSSL_API_1_1 */
  6583. #else
  6584. (void)use_ssl;
  6585. #endif /* NO_SSL_DL */
  6586. #else
  6587. (void)use_ssl;
  6588. #endif /* !defined(NO_SSL) */
  6589. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6590. sa->sin.sin_family = AF_INET;
  6591. sa->sin.sin_port = htons((uint16_t)port);
  6592. ip_ver = 4;
  6593. #ifdef USE_IPV6
  6594. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6595. sa->sin6.sin6_family = AF_INET6;
  6596. sa->sin6.sin6_port = htons((uint16_t)port);
  6597. ip_ver = 6;
  6598. } else if (host[0] == '[') {
  6599. /* While getaddrinfo on Windows will work with [::1],
  6600. * getaddrinfo on Linux only works with ::1 (without []). */
  6601. size_t l = strlen(host + 1);
  6602. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6603. if (h) {
  6604. h[l - 1] = 0;
  6605. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6606. sa->sin6.sin6_family = AF_INET6;
  6607. sa->sin6.sin6_port = htons((uint16_t)port);
  6608. ip_ver = 6;
  6609. }
  6610. mg_free(h);
  6611. }
  6612. #endif
  6613. }
  6614. if (ip_ver == 0) {
  6615. mg_snprintf(NULL,
  6616. NULL, /* No truncation check for ebuf */
  6617. ebuf,
  6618. ebuf_len,
  6619. "%s",
  6620. "host not found");
  6621. return 0;
  6622. }
  6623. if (ip_ver == 4) {
  6624. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6625. }
  6626. #ifdef USE_IPV6
  6627. else if (ip_ver == 6) {
  6628. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6629. }
  6630. #endif
  6631. if (*sock == INVALID_SOCKET) {
  6632. mg_snprintf(NULL,
  6633. NULL, /* No truncation check for ebuf */
  6634. ebuf,
  6635. ebuf_len,
  6636. "socket(): %s",
  6637. strerror(ERRNO));
  6638. return 0;
  6639. }
  6640. set_close_on_exec(*sock, fc(ctx));
  6641. if ((ip_ver == 4)
  6642. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6643. == 0)) {
  6644. /* connected with IPv4 */
  6645. set_blocking_mode(*sock, 0);
  6646. return 1;
  6647. }
  6648. #ifdef USE_IPV6
  6649. if ((ip_ver == 6)
  6650. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6651. == 0)) {
  6652. /* connected with IPv6 */
  6653. set_blocking_mode(*sock, 0);
  6654. return 1;
  6655. }
  6656. #endif
  6657. /* Not connected */
  6658. mg_snprintf(NULL,
  6659. NULL, /* No truncation check for ebuf */
  6660. ebuf,
  6661. ebuf_len,
  6662. "connect(%s:%d): %s",
  6663. host,
  6664. port,
  6665. strerror(ERRNO));
  6666. closesocket(*sock);
  6667. *sock = INVALID_SOCKET;
  6668. return 0;
  6669. }
  6670. int
  6671. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6672. {
  6673. static const char *dont_escape = "._-$,;~()";
  6674. static const char *hex = "0123456789abcdef";
  6675. char *pos = dst;
  6676. const char *end = dst + dst_len - 1;
  6677. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  6678. if (isalnum(*(const unsigned char *)src)
  6679. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  6680. *pos = *src;
  6681. } else if (pos + 2 < end) {
  6682. pos[0] = '%';
  6683. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6684. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6685. pos += 2;
  6686. } else {
  6687. break;
  6688. }
  6689. }
  6690. *pos = '\0';
  6691. return (*src == '\0') ? (int)(pos - dst) : -1;
  6692. }
  6693. /* Return 0 on success, non-zero if an error occurs. */
  6694. static int
  6695. print_dir_entry(struct de *de)
  6696. {
  6697. size_t hrefsize;
  6698. char *href;
  6699. char size[64], mod[64];
  6700. struct tm *tm;
  6701. hrefsize = PATH_MAX * 3; /* worst case */
  6702. href = mg_malloc(hrefsize);
  6703. if (href == NULL) {
  6704. return -1;
  6705. }
  6706. if (de->file.is_directory) {
  6707. mg_snprintf(de->conn,
  6708. NULL, /* Buffer is big enough */
  6709. size,
  6710. sizeof(size),
  6711. "%s",
  6712. "[DIRECTORY]");
  6713. } else {
  6714. /* We use (signed) cast below because MSVC 6 compiler cannot
  6715. * convert unsigned __int64 to double. Sigh. */
  6716. if (de->file.size < 1024) {
  6717. mg_snprintf(de->conn,
  6718. NULL, /* Buffer is big enough */
  6719. size,
  6720. sizeof(size),
  6721. "%d",
  6722. (int)de->file.size);
  6723. } else if (de->file.size < 0x100000) {
  6724. mg_snprintf(de->conn,
  6725. NULL, /* Buffer is big enough */
  6726. size,
  6727. sizeof(size),
  6728. "%.1fk",
  6729. (double)de->file.size / 1024.0);
  6730. } else if (de->file.size < 0x40000000) {
  6731. mg_snprintf(de->conn,
  6732. NULL, /* Buffer is big enough */
  6733. size,
  6734. sizeof(size),
  6735. "%.1fM",
  6736. (double)de->file.size / 1048576);
  6737. } else {
  6738. mg_snprintf(de->conn,
  6739. NULL, /* Buffer is big enough */
  6740. size,
  6741. sizeof(size),
  6742. "%.1fG",
  6743. (double)de->file.size / 1073741824);
  6744. }
  6745. }
  6746. /* Note: mg_snprintf will not cause a buffer overflow above.
  6747. * So, string truncation checks are not required here. */
  6748. tm = localtime(&de->file.last_modified);
  6749. if (tm != NULL) {
  6750. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6751. } else {
  6752. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6753. mod[sizeof(mod) - 1] = '\0';
  6754. }
  6755. mg_url_encode(de->file_name, href, hrefsize);
  6756. mg_printf(de->conn,
  6757. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6758. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6759. de->conn->request_info.local_uri,
  6760. href,
  6761. de->file.is_directory ? "/" : "",
  6762. de->file_name,
  6763. de->file.is_directory ? "/" : "",
  6764. mod,
  6765. size);
  6766. mg_free(href);
  6767. return 0;
  6768. }
  6769. /* This function is called from send_directory() and used for
  6770. * sorting directory entries by size, or name, or modification time.
  6771. * On windows, __cdecl specification is needed in case if project is built
  6772. * with __stdcall convention. qsort always requires __cdels callback. */
  6773. static int WINCDECL
  6774. compare_dir_entries(const void *p1, const void *p2)
  6775. {
  6776. if (p1 && p2) {
  6777. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6778. const char *query_string = a->conn->request_info.query_string;
  6779. int cmp_result = 0;
  6780. if (query_string == NULL) {
  6781. query_string = "na";
  6782. }
  6783. if (a->file.is_directory && !b->file.is_directory) {
  6784. return -1; /* Always put directories on top */
  6785. } else if (!a->file.is_directory && b->file.is_directory) {
  6786. return 1; /* Always put directories on top */
  6787. } else if (*query_string == 'n') {
  6788. cmp_result = strcmp(a->file_name, b->file_name);
  6789. } else if (*query_string == 's') {
  6790. cmp_result = (a->file.size == b->file.size)
  6791. ? 0
  6792. : ((a->file.size > b->file.size) ? 1 : -1);
  6793. } else if (*query_string == 'd') {
  6794. cmp_result =
  6795. (a->file.last_modified == b->file.last_modified)
  6796. ? 0
  6797. : ((a->file.last_modified > b->file.last_modified) ? 1
  6798. : -1);
  6799. }
  6800. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6801. }
  6802. return 0;
  6803. }
  6804. static int
  6805. must_hide_file(struct mg_connection *conn, const char *path)
  6806. {
  6807. if (conn && conn->ctx) {
  6808. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6809. const char *pattern = conn->ctx->config[HIDE_FILES];
  6810. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  6811. || ((pattern != NULL)
  6812. && (match_prefix(pattern, strlen(pattern), path) > 0));
  6813. }
  6814. return 0;
  6815. }
  6816. static int
  6817. scan_directory(struct mg_connection *conn,
  6818. const char *dir,
  6819. void *data,
  6820. int (*cb)(struct de *, void *))
  6821. {
  6822. char path[PATH_MAX];
  6823. struct dirent *dp;
  6824. DIR *dirp;
  6825. struct de de;
  6826. int truncated;
  6827. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6828. return 0;
  6829. } else {
  6830. de.conn = conn;
  6831. while ((dp = mg_readdir(dirp)) != NULL) {
  6832. /* Do not show current dir and hidden files */
  6833. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6834. || must_hide_file(conn, dp->d_name)) {
  6835. continue;
  6836. }
  6837. mg_snprintf(
  6838. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6839. /* If we don't memset stat structure to zero, mtime will have
  6840. * garbage and strftime() will segfault later on in
  6841. * print_dir_entry(). memset is required only if mg_stat()
  6842. * fails. For more details, see
  6843. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6844. memset(&de.file, 0, sizeof(de.file));
  6845. if (truncated) {
  6846. /* If the path is not complete, skip processing. */
  6847. continue;
  6848. }
  6849. if (!mg_stat(conn, path, &de.file)) {
  6850. mg_cry(conn,
  6851. "%s: mg_stat(%s) failed: %s",
  6852. __func__,
  6853. path,
  6854. strerror(ERRNO));
  6855. }
  6856. de.file_name = dp->d_name;
  6857. cb(&de, data);
  6858. }
  6859. (void)mg_closedir(dirp);
  6860. }
  6861. return 1;
  6862. }
  6863. #if !defined(NO_FILES)
  6864. static int
  6865. remove_directory(struct mg_connection *conn, const char *dir)
  6866. {
  6867. char path[PATH_MAX];
  6868. struct dirent *dp;
  6869. DIR *dirp;
  6870. struct de de;
  6871. int truncated;
  6872. int ok = 1;
  6873. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6874. return 0;
  6875. } else {
  6876. de.conn = conn;
  6877. while ((dp = mg_readdir(dirp)) != NULL) {
  6878. /* Do not show current dir (but show hidden files as they will
  6879. * also be removed) */
  6880. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6881. continue;
  6882. }
  6883. mg_snprintf(
  6884. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6885. /* If we don't memset stat structure to zero, mtime will have
  6886. * garbage and strftime() will segfault later on in
  6887. * print_dir_entry(). memset is required only if mg_stat()
  6888. * fails. For more details, see
  6889. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6890. memset(&de.file, 0, sizeof(de.file));
  6891. if (truncated) {
  6892. /* Do not delete anything shorter */
  6893. ok = 0;
  6894. continue;
  6895. }
  6896. if (!mg_stat(conn, path, &de.file)) {
  6897. mg_cry(conn,
  6898. "%s: mg_stat(%s) failed: %s",
  6899. __func__,
  6900. path,
  6901. strerror(ERRNO));
  6902. ok = 0;
  6903. }
  6904. if (de.file.is_directory) {
  6905. if (remove_directory(conn, path) == 0) {
  6906. ok = 0;
  6907. }
  6908. } else {
  6909. /* This will fail file is the file is in memory */
  6910. if (mg_remove(conn, path) == 0) {
  6911. ok = 0;
  6912. }
  6913. }
  6914. }
  6915. (void)mg_closedir(dirp);
  6916. IGNORE_UNUSED_RESULT(rmdir(dir));
  6917. }
  6918. return ok;
  6919. }
  6920. #endif
  6921. struct dir_scan_data {
  6922. struct de *entries;
  6923. unsigned int num_entries;
  6924. unsigned int arr_size;
  6925. };
  6926. /* Behaves like realloc(), but frees original pointer on failure */
  6927. static void *
  6928. realloc2(void *ptr, size_t size)
  6929. {
  6930. void *new_ptr = mg_realloc(ptr, size);
  6931. if (new_ptr == NULL) {
  6932. mg_free(ptr);
  6933. }
  6934. return new_ptr;
  6935. }
  6936. static int
  6937. dir_scan_callback(struct de *de, void *data)
  6938. {
  6939. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6940. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  6941. dsd->arr_size *= 2;
  6942. dsd->entries =
  6943. (struct de *)realloc2(dsd->entries,
  6944. dsd->arr_size * sizeof(dsd->entries[0]));
  6945. }
  6946. if (dsd->entries == NULL) {
  6947. /* TODO(lsm, low): propagate an error to the caller */
  6948. dsd->num_entries = 0;
  6949. } else {
  6950. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6951. dsd->entries[dsd->num_entries].file = de->file;
  6952. dsd->entries[dsd->num_entries].conn = de->conn;
  6953. dsd->num_entries++;
  6954. }
  6955. return 0;
  6956. }
  6957. static void
  6958. handle_directory_request(struct mg_connection *conn, const char *dir)
  6959. {
  6960. unsigned int i;
  6961. int sort_direction;
  6962. struct dir_scan_data data = {NULL, 0, 128};
  6963. char date[64];
  6964. time_t curtime = time(NULL);
  6965. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6966. mg_send_http_error(conn,
  6967. 500,
  6968. "Error: Cannot open directory\nopendir(%s): %s",
  6969. dir,
  6970. strerror(ERRNO));
  6971. return;
  6972. }
  6973. gmt_time_string(date, sizeof(date), &curtime);
  6974. if (!conn) {
  6975. return;
  6976. }
  6977. sort_direction = ((conn->request_info.query_string != NULL)
  6978. && (conn->request_info.query_string[1] == 'd'))
  6979. ? 'a'
  6980. : 'd';
  6981. conn->must_close = 1;
  6982. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6983. send_static_cache_header(conn);
  6984. send_additional_header(conn);
  6985. mg_printf(conn,
  6986. "Date: %s\r\n"
  6987. "Connection: close\r\n"
  6988. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6989. date);
  6990. mg_printf(conn,
  6991. "<html><head><title>Index of %s</title>"
  6992. "<style>th {text-align: left;}</style></head>"
  6993. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6994. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6995. "<th><a href=\"?d%c\">Modified</a></th>"
  6996. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6997. "<tr><td colspan=\"3\"><hr></td></tr>",
  6998. conn->request_info.local_uri,
  6999. conn->request_info.local_uri,
  7000. sort_direction,
  7001. sort_direction,
  7002. sort_direction);
  7003. /* Print first entry - link to a parent directory */
  7004. mg_printf(conn,
  7005. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7006. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7007. conn->request_info.local_uri,
  7008. "..",
  7009. "Parent directory",
  7010. "-",
  7011. "-");
  7012. /* Sort and print directory entries */
  7013. if (data.entries != NULL) {
  7014. qsort(data.entries,
  7015. (size_t)data.num_entries,
  7016. sizeof(data.entries[0]),
  7017. compare_dir_entries);
  7018. for (i = 0; i < data.num_entries; i++) {
  7019. print_dir_entry(&data.entries[i]);
  7020. mg_free(data.entries[i].file_name);
  7021. }
  7022. mg_free(data.entries);
  7023. }
  7024. mg_printf(conn, "%s", "</table></body></html>");
  7025. conn->status_code = 200;
  7026. }
  7027. /* Send len bytes from the opened file to the client. */
  7028. static void
  7029. send_file_data(struct mg_connection *conn,
  7030. struct mg_file *filep,
  7031. int64_t offset,
  7032. int64_t len)
  7033. {
  7034. char buf[MG_BUF_LEN];
  7035. int to_read, num_read, num_written;
  7036. int64_t size;
  7037. if (!filep || !conn) {
  7038. return;
  7039. }
  7040. /* Sanity check the offset */
  7041. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7042. : (int64_t)(filep->stat.size);
  7043. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7044. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7045. /* file stored in memory */
  7046. if (len > size - offset) {
  7047. len = size - offset;
  7048. }
  7049. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7050. } else if (len > 0 && filep->access.fp != NULL) {
  7051. /* file stored on disk */
  7052. #if defined(__linux__)
  7053. /* sendfile is only available for Linux */
  7054. if ((conn->ssl == 0) && (conn->throttle == 0)
  7055. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  7056. "yes"))) {
  7057. off_t sf_offs = (off_t)offset;
  7058. ssize_t sf_sent;
  7059. int sf_file = fileno(filep->access.fp);
  7060. int loop_cnt = 0;
  7061. do {
  7062. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7063. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7064. size_t sf_tosend =
  7065. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7066. sf_sent =
  7067. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7068. if (sf_sent > 0) {
  7069. len -= sf_sent;
  7070. offset += sf_sent;
  7071. } else if (loop_cnt == 0) {
  7072. /* This file can not be sent using sendfile.
  7073. * This might be the case for pseudo-files in the
  7074. * /sys/ and /proc/ file system.
  7075. * Use the regular user mode copy code instead. */
  7076. break;
  7077. } else if (sf_sent == 0) {
  7078. /* No error, but 0 bytes sent. May be EOF? */
  7079. return;
  7080. }
  7081. loop_cnt++;
  7082. } while ((len > 0) && (sf_sent >= 0));
  7083. if (sf_sent > 0) {
  7084. return; /* OK */
  7085. }
  7086. /* sf_sent<0 means error, thus fall back to the classic way */
  7087. /* This is always the case, if sf_file is not a "normal" file,
  7088. * e.g., for sending data from the output of a CGI process. */
  7089. offset = (int64_t)sf_offs;
  7090. }
  7091. #endif
  7092. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7093. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  7094. mg_send_http_error(
  7095. conn,
  7096. 500,
  7097. "%s",
  7098. "Error: Unable to access file at requested position.");
  7099. } else {
  7100. while (len > 0) {
  7101. /* Calculate how much to read from the file in the buffer */
  7102. to_read = sizeof(buf);
  7103. if ((int64_t)to_read > len) {
  7104. to_read = (int)len;
  7105. }
  7106. /* Read from file, exit the loop on error */
  7107. if ((num_read =
  7108. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7109. <= 0) {
  7110. break;
  7111. }
  7112. /* Send read bytes to the client, exit the loop on error */
  7113. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7114. != num_read) {
  7115. break;
  7116. }
  7117. /* Both read and were successful, adjust counters */
  7118. len -= num_written;
  7119. }
  7120. }
  7121. }
  7122. }
  7123. static int
  7124. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7125. {
  7126. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7127. }
  7128. static void
  7129. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7130. {
  7131. if ((filestat != NULL) && (buf != NULL)) {
  7132. mg_snprintf(NULL,
  7133. NULL, /* All calls to construct_etag use 64 byte buffer */
  7134. buf,
  7135. buf_len,
  7136. "\"%lx.%" INT64_FMT "\"",
  7137. (unsigned long)filestat->last_modified,
  7138. filestat->size);
  7139. }
  7140. }
  7141. static void
  7142. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7143. {
  7144. if (filep != NULL && filep->fp != NULL) {
  7145. #ifdef _WIN32
  7146. (void)conn; /* Unused. */
  7147. #else
  7148. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7149. mg_cry(conn,
  7150. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7151. __func__,
  7152. strerror(ERRNO));
  7153. }
  7154. #endif
  7155. }
  7156. }
  7157. static void
  7158. handle_static_file_request(struct mg_connection *conn,
  7159. const char *path,
  7160. struct mg_file *filep,
  7161. const char *mime_type,
  7162. const char *additional_headers)
  7163. {
  7164. char date[64], lm[64], etag[64];
  7165. char range[128]; /* large enough, so there will be no overflow */
  7166. const char *msg = "OK", *hdr;
  7167. time_t curtime = time(NULL);
  7168. int64_t cl, r1, r2;
  7169. struct vec mime_vec;
  7170. int n, truncated;
  7171. char gz_path[PATH_MAX];
  7172. const char *encoding = "";
  7173. const char *cors1, *cors2, *cors3;
  7174. if ((conn == NULL) || (conn->ctx == NULL) || (filep == NULL)) {
  7175. return;
  7176. }
  7177. if (mime_type == NULL) {
  7178. get_mime_type(conn->ctx, path, &mime_vec);
  7179. } else {
  7180. mime_vec.ptr = mime_type;
  7181. mime_vec.len = strlen(mime_type);
  7182. }
  7183. if (filep->stat.size > INT64_MAX) {
  7184. mg_send_http_error(conn,
  7185. 500,
  7186. "Error: File size is too large to send\n%" INT64_FMT,
  7187. filep->stat.size);
  7188. return;
  7189. }
  7190. cl = (int64_t)filep->stat.size;
  7191. conn->status_code = 200;
  7192. range[0] = '\0';
  7193. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7194. * it's important to rewrite the filename after resolving
  7195. * the mime type from it, to preserve the actual file's type */
  7196. if (filep->stat.is_gzipped) {
  7197. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7198. if (truncated) {
  7199. mg_send_http_error(conn,
  7200. 500,
  7201. "Error: Path of zipped file too long (%s)",
  7202. path);
  7203. return;
  7204. }
  7205. path = gz_path;
  7206. encoding = "Content-Encoding: gzip\r\n";
  7207. }
  7208. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7209. mg_send_http_error(conn,
  7210. 500,
  7211. "Error: Cannot open file\nfopen(%s): %s",
  7212. path,
  7213. strerror(ERRNO));
  7214. return;
  7215. }
  7216. fclose_on_exec(&filep->access, conn);
  7217. /* If Range: header specified, act accordingly */
  7218. r1 = r2 = 0;
  7219. hdr = mg_get_header(conn, "Range");
  7220. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7221. && (r1 >= 0) && (r2 >= 0)) {
  7222. /* actually, range requests don't play well with a pre-gzipped
  7223. * file (since the range is specified in the uncompressed space) */
  7224. if (filep->stat.is_gzipped) {
  7225. mg_send_http_error(
  7226. conn,
  7227. 416, /* 416 = Range Not Satisfiable */
  7228. "%s",
  7229. "Error: Range requests in gzipped files are not supported");
  7230. (void)mg_fclose(
  7231. &filep->access); /* ignore error on read only file */
  7232. return;
  7233. }
  7234. conn->status_code = 206;
  7235. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7236. mg_snprintf(conn,
  7237. NULL, /* range buffer is big enough */
  7238. range,
  7239. sizeof(range),
  7240. "Content-Range: bytes "
  7241. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7242. r1,
  7243. r1 + cl - 1,
  7244. filep->stat.size);
  7245. msg = "Partial Content";
  7246. }
  7247. hdr = mg_get_header(conn, "Origin");
  7248. if (hdr) {
  7249. /* Cross-origin resource sharing (CORS), see
  7250. * http://www.html5rocks.com/en/tutorials/cors/,
  7251. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  7252. * preflight is not supported for files. */
  7253. cors1 = "Access-Control-Allow-Origin: ";
  7254. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7255. cors3 = "\r\n";
  7256. } else {
  7257. cors1 = cors2 = cors3 = "";
  7258. }
  7259. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  7260. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7261. gmt_time_string(date, sizeof(date), &curtime);
  7262. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7263. construct_etag(etag, sizeof(etag), &filep->stat);
  7264. (void)mg_printf(conn,
  7265. "HTTP/1.1 %d %s\r\n"
  7266. "%s%s%s"
  7267. "Date: %s\r\n",
  7268. conn->status_code,
  7269. msg,
  7270. cors1,
  7271. cors2,
  7272. cors3,
  7273. date);
  7274. send_static_cache_header(conn);
  7275. send_additional_header(conn);
  7276. (void)mg_printf(conn,
  7277. "Last-Modified: %s\r\n"
  7278. "Etag: %s\r\n"
  7279. "Content-Type: %.*s\r\n"
  7280. "Content-Length: %" INT64_FMT "\r\n"
  7281. "Connection: %s\r\n"
  7282. "Accept-Ranges: bytes\r\n"
  7283. "%s%s",
  7284. lm,
  7285. etag,
  7286. (int)mime_vec.len,
  7287. mime_vec.ptr,
  7288. cl,
  7289. suggest_connection_header(conn),
  7290. range,
  7291. encoding);
  7292. /* The previous code must not add any header starting with X- to make
  7293. * sure no one of the additional_headers is included twice */
  7294. if (additional_headers != NULL) {
  7295. (void)mg_printf(conn,
  7296. "%.*s\r\n\r\n",
  7297. (int)strlen(additional_headers),
  7298. additional_headers);
  7299. } else {
  7300. (void)mg_printf(conn, "\r\n");
  7301. }
  7302. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7303. send_file_data(conn, filep, r1, cl);
  7304. }
  7305. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7306. }
  7307. #if !defined(NO_CACHING)
  7308. static void
  7309. handle_not_modified_static_file_request(struct mg_connection *conn,
  7310. struct mg_file *filep)
  7311. {
  7312. char date[64], lm[64], etag[64];
  7313. time_t curtime = time(NULL);
  7314. if ((conn == NULL) || (filep == NULL)) {
  7315. return;
  7316. }
  7317. conn->status_code = 304;
  7318. gmt_time_string(date, sizeof(date), &curtime);
  7319. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7320. construct_etag(etag, sizeof(etag), &filep->stat);
  7321. (void)mg_printf(conn,
  7322. "HTTP/1.1 %d %s\r\n"
  7323. "Date: %s\r\n",
  7324. conn->status_code,
  7325. mg_get_response_code_text(conn, conn->status_code),
  7326. date);
  7327. send_static_cache_header(conn);
  7328. send_additional_header(conn);
  7329. (void)mg_printf(conn,
  7330. "Last-Modified: %s\r\n"
  7331. "Etag: %s\r\n"
  7332. "Connection: %s\r\n"
  7333. "\r\n",
  7334. lm,
  7335. etag,
  7336. suggest_connection_header(conn));
  7337. }
  7338. #endif
  7339. void
  7340. mg_send_file(struct mg_connection *conn, const char *path)
  7341. {
  7342. mg_send_mime_file(conn, path, NULL);
  7343. }
  7344. void
  7345. mg_send_mime_file(struct mg_connection *conn,
  7346. const char *path,
  7347. const char *mime_type)
  7348. {
  7349. mg_send_mime_file2(conn, path, mime_type, NULL);
  7350. }
  7351. void
  7352. mg_send_mime_file2(struct mg_connection *conn,
  7353. const char *path,
  7354. const char *mime_type,
  7355. const char *additional_headers)
  7356. {
  7357. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7358. if (mg_stat(conn, path, &file.stat)) {
  7359. if (file.stat.is_directory) {
  7360. if (!conn) {
  7361. return;
  7362. }
  7363. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7364. "yes")) {
  7365. handle_directory_request(conn, path);
  7366. } else {
  7367. mg_send_http_error(conn,
  7368. 403,
  7369. "%s",
  7370. "Error: Directory listing denied");
  7371. }
  7372. } else {
  7373. handle_static_file_request(
  7374. conn, path, &file, mime_type, additional_headers);
  7375. }
  7376. } else {
  7377. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7378. }
  7379. }
  7380. /* For a given PUT path, create all intermediate subdirectories.
  7381. * Return 0 if the path itself is a directory.
  7382. * Return 1 if the path leads to a file.
  7383. * Return -1 for if the path is too long.
  7384. * Return -2 if path can not be created.
  7385. */
  7386. static int
  7387. put_dir(struct mg_connection *conn, const char *path)
  7388. {
  7389. char buf[PATH_MAX];
  7390. const char *s, *p;
  7391. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7392. size_t len;
  7393. int res = 1;
  7394. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7395. len = (size_t)(p - path);
  7396. if (len >= sizeof(buf)) {
  7397. /* path too long */
  7398. res = -1;
  7399. break;
  7400. }
  7401. memcpy(buf, path, len);
  7402. buf[len] = '\0';
  7403. /* Try to create intermediate directory */
  7404. DEBUG_TRACE("mkdir(%s)", buf);
  7405. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7406. /* path does not exixt and can not be created */
  7407. res = -2;
  7408. break;
  7409. }
  7410. /* Is path itself a directory? */
  7411. if (p[1] == '\0') {
  7412. res = 0;
  7413. }
  7414. }
  7415. return res;
  7416. }
  7417. static void
  7418. remove_bad_file(const struct mg_connection *conn, const char *path)
  7419. {
  7420. int r = mg_remove(conn, path);
  7421. if (r != 0) {
  7422. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7423. }
  7424. }
  7425. long long
  7426. mg_store_body(struct mg_connection *conn, const char *path)
  7427. {
  7428. char buf[MG_BUF_LEN];
  7429. long long len = 0;
  7430. int ret, n;
  7431. struct mg_file fi;
  7432. if (conn->consumed_content != 0) {
  7433. mg_cry(conn, "%s: Contents already consumed", __func__);
  7434. return -11;
  7435. }
  7436. ret = put_dir(conn, path);
  7437. if (ret < 0) {
  7438. /* -1 for path too long,
  7439. * -2 for path can not be created. */
  7440. return ret;
  7441. }
  7442. if (ret != 1) {
  7443. /* Return 0 means, path itself is a directory. */
  7444. return 0;
  7445. }
  7446. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7447. return -12;
  7448. }
  7449. ret = mg_read(conn, buf, sizeof(buf));
  7450. while (ret > 0) {
  7451. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7452. if (n != ret) {
  7453. (void)mg_fclose(
  7454. &fi.access); /* File is bad and will be removed anyway. */
  7455. remove_bad_file(conn, path);
  7456. return -13;
  7457. }
  7458. len += ret;
  7459. ret = mg_read(conn, buf, sizeof(buf));
  7460. }
  7461. /* File is open for writing. If fclose fails, there was probably an
  7462. * error flushing the buffer to disk, so the file on disk might be
  7463. * broken. Delete it and return an error to the caller. */
  7464. if (mg_fclose(&fi.access) != 0) {
  7465. remove_bad_file(conn, path);
  7466. return -14;
  7467. }
  7468. return len;
  7469. }
  7470. /* Parse a buffer:
  7471. * Forward the string pointer till the end of a word, then
  7472. * terminate it and forward till the begin of the next word.
  7473. */
  7474. static int
  7475. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  7476. {
  7477. /* Forward until a space is found - use isgraph here */
  7478. /* See http://www.cplusplus.com/reference/cctype/ */
  7479. while (isgraph(**ppw)) {
  7480. (*ppw)++;
  7481. }
  7482. /* Check end of word */
  7483. if (eol) {
  7484. /* must be a end of line */
  7485. if ((**ppw != '\r') && (**ppw != '\n')) {
  7486. return -1;
  7487. }
  7488. } else {
  7489. /* must be a end of a word, but not a line */
  7490. if (**ppw != ' ') {
  7491. return -1;
  7492. }
  7493. }
  7494. /* Terminate and forward to the next word */
  7495. do {
  7496. **ppw = 0;
  7497. (*ppw)++;
  7498. } while ((**ppw) && isspace(**ppw));
  7499. /* Check after term */
  7500. if (!eol) {
  7501. /* if it's not the end of line, there must be a next word */
  7502. if (!isgraph(**ppw)) {
  7503. return -1;
  7504. }
  7505. }
  7506. /* ok */
  7507. return 1;
  7508. }
  7509. /* Parse HTTP headers from the given buffer, advance buf pointer
  7510. * to the point where parsing stopped.
  7511. * All parameters must be valid pointers (not NULL).
  7512. * Return <0 on error. */
  7513. static int
  7514. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  7515. {
  7516. int i;
  7517. int num_headers = 0;
  7518. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  7519. char *dp = *buf;
  7520. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7521. dp++;
  7522. }
  7523. if (dp == *buf) {
  7524. /* End of headers reached. */
  7525. break;
  7526. }
  7527. if (*dp != ':') {
  7528. /* This is not a valid field. */
  7529. return -1;
  7530. }
  7531. /* End of header key (*dp == ':') */
  7532. /* Truncate here and set the key name */
  7533. *dp = 0;
  7534. hdr[i].name = *buf;
  7535. do {
  7536. dp++;
  7537. } while (*dp == ' ');
  7538. /* The rest of the line is the value */
  7539. hdr[i].value = dp;
  7540. *buf = dp + strcspn(dp, "\r\n");
  7541. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7542. *buf = NULL;
  7543. }
  7544. num_headers = i + 1;
  7545. if (*buf) {
  7546. (*buf)[0] = 0;
  7547. (*buf)[1] = 0;
  7548. *buf += 2;
  7549. } else {
  7550. *buf = dp;
  7551. break;
  7552. }
  7553. if ((*buf)[0] == '\r') {
  7554. /* This is the end of the header */
  7555. break;
  7556. }
  7557. }
  7558. return num_headers;
  7559. }
  7560. static int
  7561. is_valid_http_method(const char *method)
  7562. {
  7563. /* Check if the method is known to the server. The list of all known
  7564. * HTTP methods can be found here at
  7565. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7566. */
  7567. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7568. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7569. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7570. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7571. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7572. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7573. /* TRACE method (RFC 2616) is not supported for security reasons */
  7574. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7575. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7576. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7577. /* Unsupported WEBDAV Methods: */
  7578. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7579. /* + 11 methods from RFC 3253 */
  7580. /* ORDERPATCH (RFC 3648) */
  7581. /* ACL (RFC 3744) */
  7582. /* SEARCH (RFC 5323) */
  7583. /* + MicroSoft extensions
  7584. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7585. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7586. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7587. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7588. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7589. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7590. * to be useful for REST in case a "GET request with body" is
  7591. * required. */
  7592. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7593. ;
  7594. }
  7595. /* Parse HTTP request, fill in mg_request_info structure.
  7596. * This function modifies the buffer by NUL-terminating
  7597. * HTTP request components, header names and header values.
  7598. * Parameters:
  7599. * buf (in/out): pointer to the HTTP header to parse and split
  7600. * len (in): length of HTTP header buffer
  7601. * re (out): parsed header as mg_request_info
  7602. * buf and ri must be valid pointers (not NULL), len>0.
  7603. * Returns <0 on error. */
  7604. static int
  7605. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  7606. {
  7607. int request_length;
  7608. int init_skip = 0;
  7609. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7610. * remote_port */
  7611. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  7612. NULL;
  7613. ri->num_headers = 0;
  7614. /* RFC says that all initial whitespaces should be ingored */
  7615. /* This included all leading \r and \n (isspace) */
  7616. /* See table: http://www.cplusplus.com/reference/cctype/ */
  7617. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  7618. buf++;
  7619. len--;
  7620. init_skip++;
  7621. }
  7622. if (len == 0) {
  7623. /* Incomplete request */
  7624. return 0;
  7625. }
  7626. /* Control characters are not allowed, including zero */
  7627. if (iscntrl(*(unsigned char *)buf)) {
  7628. return -1;
  7629. }
  7630. /* Find end of HTTP header */
  7631. request_length = get_http_header_len(buf, len);
  7632. if (request_length <= 0) {
  7633. return request_length;
  7634. }
  7635. buf[request_length - 1] = '\0';
  7636. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  7637. return -1;
  7638. }
  7639. /* The first word has to be the HTTP method */
  7640. ri->request_method = buf;
  7641. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7642. return -1;
  7643. }
  7644. /* Check for a valid http method */
  7645. if (!is_valid_http_method(ri->request_method)) {
  7646. return -1;
  7647. }
  7648. /* The second word is the URI */
  7649. ri->request_uri = buf;
  7650. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7651. return -1;
  7652. }
  7653. /* Next would be the HTTP version */
  7654. ri->http_version = buf;
  7655. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  7656. return -1;
  7657. }
  7658. /* Check for a valid HTTP version key */
  7659. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  7660. /* Invalid request */
  7661. return -1;
  7662. }
  7663. ri->http_version += 5;
  7664. /* Parse all HTTP headers */
  7665. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  7666. if (ri->num_headers < 0) {
  7667. /* Error while parsing headers */
  7668. return -1;
  7669. }
  7670. return request_length + init_skip;
  7671. }
  7672. static int
  7673. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  7674. {
  7675. int response_length;
  7676. int init_skip = 0;
  7677. char *tmp, *tmp2;
  7678. long l;
  7679. /* Initialize elements. */
  7680. ri->http_version = ri->status_text = NULL;
  7681. ri->num_headers = ri->status_code = 0;
  7682. /* RFC says that all initial whitespaces should be ingored */
  7683. /* This included all leading \r and \n (isspace) */
  7684. /* See table: http://www.cplusplus.com/reference/cctype/ */
  7685. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  7686. buf++;
  7687. len--;
  7688. init_skip++;
  7689. }
  7690. if (len == 0) {
  7691. /* Incomplete request */
  7692. return 0;
  7693. }
  7694. /* Control characters are not allowed, including zero */
  7695. if (iscntrl(*(unsigned char *)buf)) {
  7696. return -1;
  7697. }
  7698. /* Find end of HTTP header */
  7699. response_length = get_http_header_len(buf, len);
  7700. if (response_length <= 0) {
  7701. return response_length;
  7702. }
  7703. buf[response_length - 1] = '\0';
  7704. /* TODO: Define mg_response_info and implement parsing */
  7705. (void)buf;
  7706. (void)len;
  7707. (void)ri;
  7708. /* RFC says that all initial whitespaces should be ingored */
  7709. while ((*buf != '\0') && isspace(*(unsigned char *)buf)) {
  7710. buf++;
  7711. }
  7712. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  7713. return -1;
  7714. }
  7715. /* The first word is the HTTP version */
  7716. /* Check for a valid HTTP version key */
  7717. if (strncmp(buf, "HTTP/", 5) != 0) {
  7718. /* Invalid request */
  7719. return -1;
  7720. }
  7721. buf += 5;
  7722. if (!isgraph(buf[0])) {
  7723. /* Invalid request */
  7724. return -1;
  7725. }
  7726. ri->http_version = buf;
  7727. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7728. return -1;
  7729. }
  7730. /* The second word is the status as a number */
  7731. tmp = buf;
  7732. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7733. return -1;
  7734. }
  7735. l = strtol(tmp, &tmp2, 10);
  7736. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  7737. /* Everything else but a 3 digit code is invalid */
  7738. return -1;
  7739. }
  7740. ri->status_code = (int)l;
  7741. /* The rest of the line is the status text */
  7742. ri->status_text = buf;
  7743. /* Find end of status text */
  7744. /* isgraph or isspace = isprint */
  7745. while (isprint(*buf)) {
  7746. buf++;
  7747. }
  7748. if ((*buf != '\r') && (*buf != '\n')) {
  7749. return -1;
  7750. }
  7751. /* Terminate string and forward buf to next line */
  7752. do {
  7753. *buf = 0;
  7754. buf++;
  7755. } while ((*buf) && isspace(*buf));
  7756. /* Parse all HTTP headers */
  7757. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  7758. if (ri->num_headers < 0) {
  7759. /* Error while parsing headers */
  7760. return -1;
  7761. }
  7762. return response_length + init_skip;
  7763. }
  7764. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7765. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7766. * buffer (which marks the end of HTTP request). Buffer buf may already
  7767. * have some data. The length of the data is stored in nread.
  7768. * Upon every read operation, increase nread by the number of bytes read. */
  7769. static int
  7770. read_message(FILE *fp,
  7771. struct mg_connection *conn,
  7772. char *buf,
  7773. int bufsiz,
  7774. int *nread)
  7775. {
  7776. int request_len, n = 0;
  7777. struct timespec last_action_time;
  7778. double request_timeout;
  7779. if (!conn) {
  7780. return 0;
  7781. }
  7782. memset(&last_action_time, 0, sizeof(last_action_time));
  7783. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7784. /* value of request_timeout is in seconds, config in milliseconds */
  7785. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7786. } else {
  7787. request_timeout = -1.0;
  7788. }
  7789. if (conn->handled_requests > 0) {
  7790. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7791. request_timeout =
  7792. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7793. }
  7794. }
  7795. request_len = get_http_header_len(buf, *nread);
  7796. /* first time reading from this connection */
  7797. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7798. while (request_len == 0) {
  7799. /* Full request not yet received */
  7800. if (conn->ctx->stop_flag != 0) {
  7801. /* Server is to be stopped. */
  7802. return -1;
  7803. }
  7804. if (*nread >= bufsiz) {
  7805. /* Request too long */
  7806. return -2;
  7807. }
  7808. n = pull_inner(
  7809. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7810. if (n == -2) {
  7811. /* Receive error */
  7812. return -1;
  7813. }
  7814. if (n > 0) {
  7815. *nread += n;
  7816. request_len = get_http_header_len(buf, *nread);
  7817. } else {
  7818. request_len = 0;
  7819. }
  7820. if ((request_len == 0) && (request_timeout >= 0)) {
  7821. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7822. > request_timeout) {
  7823. /* Timeout */
  7824. return -1;
  7825. }
  7826. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7827. }
  7828. }
  7829. return request_len;
  7830. }
  7831. #if !defined(NO_CACHING)
  7832. /* Return True if we should reply 304 Not Modified. */
  7833. static int
  7834. is_not_modified(const struct mg_connection *conn,
  7835. const struct mg_file_stat *filestat)
  7836. {
  7837. char etag[64];
  7838. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7839. const char *inm = mg_get_header(conn, "If-None-Match");
  7840. construct_etag(etag, sizeof(etag), filestat);
  7841. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  7842. || ((ims != NULL)
  7843. && (filestat->last_modified <= parse_date_string(ims)));
  7844. }
  7845. #endif /* !NO_CACHING */
  7846. #if !defined(NO_CGI) || !defined(NO_FILES)
  7847. static int
  7848. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7849. {
  7850. const char *expect, *body;
  7851. char buf[MG_BUF_LEN];
  7852. int to_read, nread, success = 0;
  7853. int64_t buffered_len;
  7854. double timeout = -1.0;
  7855. if (!conn) {
  7856. return 0;
  7857. }
  7858. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7859. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7860. }
  7861. expect = mg_get_header(conn, "Expect");
  7862. /* assert(fp != NULL); */
  7863. if (!fp) {
  7864. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  7865. return 0;
  7866. }
  7867. if ((conn->content_len == -1) && !conn->is_chunked) {
  7868. /* Content length is not specified by the client. */
  7869. mg_send_http_error(conn,
  7870. 411,
  7871. "%s",
  7872. "Error: Client did not specify content length");
  7873. } else if ((expect != NULL)
  7874. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7875. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7876. mg_send_http_error(conn,
  7877. 417,
  7878. "Error: Can not fulfill expectation %s",
  7879. expect);
  7880. } else {
  7881. if (expect != NULL) {
  7882. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7883. conn->status_code = 100;
  7884. } else {
  7885. conn->status_code = 200;
  7886. }
  7887. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7888. - conn->consumed_content;
  7889. /* assert(buffered_len >= 0); */
  7890. /* assert(conn->consumed_content == 0); */
  7891. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7892. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7893. return 0;
  7894. }
  7895. if (buffered_len > 0) {
  7896. if ((int64_t)buffered_len > conn->content_len) {
  7897. buffered_len = (int)conn->content_len;
  7898. }
  7899. body = conn->buf + conn->request_len + conn->consumed_content;
  7900. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7901. conn->consumed_content += buffered_len;
  7902. }
  7903. nread = 0;
  7904. while (conn->consumed_content < conn->content_len) {
  7905. to_read = sizeof(buf);
  7906. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7907. to_read = (int)(conn->content_len - conn->consumed_content);
  7908. }
  7909. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7910. if (nread == -2) {
  7911. /* error */
  7912. break;
  7913. }
  7914. if (nread > 0) {
  7915. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7916. break;
  7917. }
  7918. }
  7919. conn->consumed_content += nread;
  7920. }
  7921. if (conn->consumed_content == conn->content_len) {
  7922. success = (nread >= 0);
  7923. }
  7924. /* Each error code path in this function must send an error */
  7925. if (!success) {
  7926. /* NOTE: Maybe some data has already been sent. */
  7927. /* TODO (low): If some data has been sent, a correct error
  7928. * reply can no longer be sent, so just close the connection */
  7929. mg_send_http_error(conn, 500, "%s", "");
  7930. }
  7931. }
  7932. return success;
  7933. }
  7934. #endif
  7935. #if !defined(NO_CGI)
  7936. /* This structure helps to create an environment for the spawned CGI program.
  7937. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7938. * last element must be NULL.
  7939. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7940. * strings must reside in a contiguous buffer. The end of the buffer is
  7941. * marked by two '\0' characters.
  7942. * We satisfy both worlds: we create an envp array (which is vars), all
  7943. * entries are actually pointers inside buf. */
  7944. struct cgi_environment {
  7945. struct mg_connection *conn;
  7946. /* Data block */
  7947. char *buf; /* Environment buffer */
  7948. size_t buflen; /* Space available in buf */
  7949. size_t bufused; /* Space taken in buf */
  7950. /* Index block */
  7951. char **var; /* char **envp */
  7952. size_t varlen; /* Number of variables available in var */
  7953. size_t varused; /* Number of variables stored in var */
  7954. };
  7955. static void addenv(struct cgi_environment *env,
  7956. PRINTF_FORMAT_STRING(const char *fmt),
  7957. ...) PRINTF_ARGS(2, 3);
  7958. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7959. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7960. static void
  7961. addenv(struct cgi_environment *env, const char *fmt, ...)
  7962. {
  7963. size_t n, space;
  7964. int truncated = 0;
  7965. char *added;
  7966. va_list ap;
  7967. /* Calculate how much space is left in the buffer */
  7968. space = (env->buflen - env->bufused);
  7969. /* Calculate an estimate for the required space */
  7970. n = strlen(fmt) + 2 + 128;
  7971. do {
  7972. if (space <= n) {
  7973. /* Allocate new buffer */
  7974. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7975. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  7976. if (!added) {
  7977. /* Out of memory */
  7978. mg_cry(env->conn,
  7979. "%s: Cannot allocate memory for CGI variable [%s]",
  7980. __func__,
  7981. fmt);
  7982. return;
  7983. }
  7984. env->buf = added;
  7985. env->buflen = n;
  7986. space = (env->buflen - env->bufused);
  7987. }
  7988. /* Make a pointer to the free space int the buffer */
  7989. added = env->buf + env->bufused;
  7990. /* Copy VARIABLE=VALUE\0 string into the free space */
  7991. va_start(ap, fmt);
  7992. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7993. va_end(ap);
  7994. /* Do not add truncated strings to the environment */
  7995. if (truncated) {
  7996. /* Reallocate the buffer */
  7997. space = 0;
  7998. n = 1;
  7999. }
  8000. } while (truncated);
  8001. /* Calculate number of bytes added to the environment */
  8002. n = strlen(added) + 1;
  8003. env->bufused += n;
  8004. /* Now update the variable index */
  8005. space = (env->varlen - env->varused);
  8006. if (space < 2) {
  8007. mg_cry(env->conn,
  8008. "%s: Cannot register CGI variable [%s]",
  8009. __func__,
  8010. fmt);
  8011. return;
  8012. }
  8013. /* Append a pointer to the added string into the envp array */
  8014. env->var[env->varused] = added;
  8015. env->varused++;
  8016. }
  8017. /* Return 0 on success, non-zero if an error occurs. */
  8018. static int
  8019. prepare_cgi_environment(struct mg_connection *conn,
  8020. const char *prog,
  8021. struct cgi_environment *env)
  8022. {
  8023. const char *s;
  8024. struct vec var_vec;
  8025. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8026. int i, truncated, uri_len;
  8027. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8028. return -1;
  8029. }
  8030. env->conn = conn;
  8031. env->buflen = CGI_ENVIRONMENT_SIZE;
  8032. env->bufused = 0;
  8033. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  8034. if (env->buf == NULL) {
  8035. mg_cry(conn,
  8036. "%s: Not enough memory for environmental buffer",
  8037. __func__);
  8038. return -1;
  8039. }
  8040. env->varlen = MAX_CGI_ENVIR_VARS;
  8041. env->varused = 0;
  8042. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  8043. if (env->var == NULL) {
  8044. mg_cry(conn,
  8045. "%s: Not enough memory for environmental variables",
  8046. __func__);
  8047. mg_free(env->buf);
  8048. return -1;
  8049. }
  8050. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  8051. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8052. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8053. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8054. /* Prepare the environment block */
  8055. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8056. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8057. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8058. #if defined(USE_IPV6)
  8059. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8060. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8061. } else
  8062. #endif
  8063. {
  8064. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8065. }
  8066. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8067. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8068. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8069. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8070. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8071. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8072. /* SCRIPT_NAME */
  8073. uri_len = (int)strlen(conn->request_info.local_uri);
  8074. if (conn->path_info == NULL) {
  8075. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8076. /* URI: /path_to_script/script.cgi */
  8077. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8078. } else {
  8079. /* URI: /path_to_script/ ... using index.cgi */
  8080. const char *index_file = strrchr(prog, '/');
  8081. if (index_file) {
  8082. addenv(env,
  8083. "SCRIPT_NAME=%s%s",
  8084. conn->request_info.local_uri,
  8085. index_file + 1);
  8086. }
  8087. }
  8088. } else {
  8089. /* URI: /path_to_script/script.cgi/path_info */
  8090. addenv(env,
  8091. "SCRIPT_NAME=%.*s",
  8092. uri_len - (int)strlen(conn->path_info),
  8093. conn->request_info.local_uri);
  8094. }
  8095. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8096. if (conn->path_info == NULL) {
  8097. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8098. } else {
  8099. addenv(env,
  8100. "PATH_TRANSLATED=%s%s",
  8101. conn->ctx->config[DOCUMENT_ROOT],
  8102. conn->path_info);
  8103. }
  8104. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8105. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8106. addenv(env, "CONTENT_TYPE=%s", s);
  8107. }
  8108. if (conn->request_info.query_string != NULL) {
  8109. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8110. }
  8111. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8112. addenv(env, "CONTENT_LENGTH=%s", s);
  8113. }
  8114. if ((s = getenv("PATH")) != NULL) {
  8115. addenv(env, "PATH=%s", s);
  8116. }
  8117. if (conn->path_info != NULL) {
  8118. addenv(env, "PATH_INFO=%s", conn->path_info);
  8119. }
  8120. if (conn->status_code > 0) {
  8121. /* CGI error handler should show the status code */
  8122. addenv(env, "STATUS=%d", conn->status_code);
  8123. }
  8124. #if defined(_WIN32)
  8125. if ((s = getenv("COMSPEC")) != NULL) {
  8126. addenv(env, "COMSPEC=%s", s);
  8127. }
  8128. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8129. addenv(env, "SYSTEMROOT=%s", s);
  8130. }
  8131. if ((s = getenv("SystemDrive")) != NULL) {
  8132. addenv(env, "SystemDrive=%s", s);
  8133. }
  8134. if ((s = getenv("ProgramFiles")) != NULL) {
  8135. addenv(env, "ProgramFiles=%s", s);
  8136. }
  8137. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8138. addenv(env, "ProgramFiles(x86)=%s", s);
  8139. }
  8140. #else
  8141. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8142. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8143. }
  8144. #endif /* _WIN32 */
  8145. if ((s = getenv("PERLLIB")) != NULL) {
  8146. addenv(env, "PERLLIB=%s", s);
  8147. }
  8148. if (conn->request_info.remote_user != NULL) {
  8149. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8150. addenv(env, "%s", "AUTH_TYPE=Digest");
  8151. }
  8152. /* Add all headers as HTTP_* variables */
  8153. for (i = 0; i < conn->request_info.num_headers; i++) {
  8154. (void)mg_snprintf(conn,
  8155. &truncated,
  8156. http_var_name,
  8157. sizeof(http_var_name),
  8158. "HTTP_%s",
  8159. conn->request_info.http_headers[i].name);
  8160. if (truncated) {
  8161. mg_cry(conn,
  8162. "%s: HTTP header variable too long [%s]",
  8163. __func__,
  8164. conn->request_info.http_headers[i].name);
  8165. continue;
  8166. }
  8167. /* Convert variable name into uppercase, and change - to _ */
  8168. for (p = http_var_name; *p != '\0'; p++) {
  8169. if (*p == '-') {
  8170. *p = '_';
  8171. }
  8172. *p = (char)toupper(*(unsigned char *)p);
  8173. }
  8174. addenv(env,
  8175. "%s=%s",
  8176. http_var_name,
  8177. conn->request_info.http_headers[i].value);
  8178. }
  8179. /* Add user-specified variables */
  8180. s = conn->ctx->config[CGI_ENVIRONMENT];
  8181. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8182. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8183. }
  8184. env->var[env->varused] = NULL;
  8185. env->buf[env->bufused] = '\0';
  8186. return 0;
  8187. }
  8188. static void
  8189. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8190. {
  8191. char *buf;
  8192. size_t buflen;
  8193. int headers_len, data_len, i, truncated;
  8194. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8195. const char *status, *status_text, *connection_state;
  8196. char *pbuf, dir[PATH_MAX], *p;
  8197. struct mg_request_info ri;
  8198. struct cgi_environment blk;
  8199. FILE *in = NULL, *out = NULL, *err = NULL;
  8200. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8201. pid_t pid = (pid_t)-1;
  8202. if (conn == NULL) {
  8203. return;
  8204. }
  8205. buf = NULL;
  8206. buflen = 16384;
  8207. i = prepare_cgi_environment(conn, prog, &blk);
  8208. if (i != 0) {
  8209. blk.buf = NULL;
  8210. blk.var = NULL;
  8211. goto done;
  8212. }
  8213. /* CGI must be executed in its own directory. 'dir' must point to the
  8214. * directory containing executable program, 'p' must point to the
  8215. * executable program name relative to 'dir'. */
  8216. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8217. if (truncated) {
  8218. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  8219. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8220. goto done;
  8221. }
  8222. if ((p = strrchr(dir, '/')) != NULL) {
  8223. *p++ = '\0';
  8224. } else {
  8225. dir[0] = '.', dir[1] = '\0';
  8226. p = (char *)prog;
  8227. }
  8228. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8229. status = strerror(ERRNO);
  8230. mg_cry(conn,
  8231. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8232. prog,
  8233. status);
  8234. mg_send_http_error(conn,
  8235. 500,
  8236. "Error: Cannot create CGI pipe: %s",
  8237. status);
  8238. goto done;
  8239. }
  8240. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8241. if (pid == (pid_t)-1) {
  8242. status = strerror(ERRNO);
  8243. mg_cry(conn,
  8244. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8245. prog,
  8246. status);
  8247. mg_send_http_error(conn,
  8248. 500,
  8249. "Error: Cannot spawn CGI process [%s]: %s",
  8250. prog,
  8251. status);
  8252. goto done;
  8253. }
  8254. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  8255. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8256. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8257. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8258. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8259. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8260. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8261. /* Parent closes only one side of the pipes.
  8262. * If we don't mark them as closed, close() attempt before
  8263. * return from this function throws an exception on Windows.
  8264. * Windows does not like when closed descriptor is closed again. */
  8265. (void)close(fdin[0]);
  8266. (void)close(fdout[1]);
  8267. (void)close(fderr[1]);
  8268. fdin[0] = fdout[1] = fderr[1] = -1;
  8269. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8270. status = strerror(ERRNO);
  8271. mg_cry(conn,
  8272. "Error: CGI program \"%s\": Can not open stdin: %s",
  8273. prog,
  8274. status);
  8275. mg_send_http_error(conn,
  8276. 500,
  8277. "Error: CGI can not open fdin\nfopen: %s",
  8278. status);
  8279. goto done;
  8280. }
  8281. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8282. status = strerror(ERRNO);
  8283. mg_cry(conn,
  8284. "Error: CGI program \"%s\": Can not open stdout: %s",
  8285. prog,
  8286. status);
  8287. mg_send_http_error(conn,
  8288. 500,
  8289. "Error: CGI can not open fdout\nfopen: %s",
  8290. status);
  8291. goto done;
  8292. }
  8293. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8294. status = strerror(ERRNO);
  8295. mg_cry(conn,
  8296. "Error: CGI program \"%s\": Can not open stderr: %s",
  8297. prog,
  8298. status);
  8299. mg_send_http_error(conn,
  8300. 500,
  8301. "Error: CGI can not open fdout\nfopen: %s",
  8302. status);
  8303. goto done;
  8304. }
  8305. setbuf(in, NULL);
  8306. setbuf(out, NULL);
  8307. setbuf(err, NULL);
  8308. fout.access.fp = out;
  8309. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  8310. /* This is a POST/PUT request, or another request with body data. */
  8311. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8312. /* Error sending the body data */
  8313. mg_cry(conn,
  8314. "Error: CGI program \"%s\": Forward body data failed",
  8315. prog);
  8316. goto done;
  8317. }
  8318. }
  8319. /* Close so child gets an EOF. */
  8320. fclose(in);
  8321. in = NULL;
  8322. fdin[1] = -1;
  8323. /* Now read CGI reply into a buffer. We need to set correct
  8324. * status code, thus we need to see all HTTP headers first.
  8325. * Do not send anything back to client, until we buffer in all
  8326. * HTTP headers. */
  8327. data_len = 0;
  8328. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  8329. if (buf == NULL) {
  8330. mg_send_http_error(conn,
  8331. 500,
  8332. "Error: Not enough memory for CGI buffer (%u bytes)",
  8333. (unsigned int)buflen);
  8334. mg_cry(conn,
  8335. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  8336. "bytes)",
  8337. prog,
  8338. (unsigned int)buflen);
  8339. goto done;
  8340. }
  8341. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  8342. if (headers_len <= 0) {
  8343. /* Could not parse the CGI response. Check if some error message on
  8344. * stderr. */
  8345. i = pull_all(err, conn, buf, (int)buflen);
  8346. if (i > 0) {
  8347. mg_cry(conn,
  8348. "Error: CGI program \"%s\" sent error "
  8349. "message: [%.*s]",
  8350. prog,
  8351. i,
  8352. buf);
  8353. mg_send_http_error(conn,
  8354. 500,
  8355. "Error: CGI program \"%s\" sent error "
  8356. "message: [%.*s]",
  8357. prog,
  8358. i,
  8359. buf);
  8360. } else {
  8361. mg_cry(conn,
  8362. "Error: CGI program sent malformed or too big "
  8363. "(>%u bytes) HTTP headers: [%.*s]",
  8364. (unsigned)buflen,
  8365. data_len,
  8366. buf);
  8367. mg_send_http_error(conn,
  8368. 500,
  8369. "Error: CGI program sent malformed or too big "
  8370. "(>%u bytes) HTTP headers: [%.*s]",
  8371. (unsigned)buflen,
  8372. data_len,
  8373. buf);
  8374. }
  8375. goto done;
  8376. }
  8377. pbuf = buf;
  8378. buf[headers_len - 1] = '\0';
  8379. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  8380. /* Make up and send the status line */
  8381. status_text = "OK";
  8382. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  8383. != NULL) {
  8384. conn->status_code = atoi(status);
  8385. status_text = status;
  8386. while (isdigit(*(const unsigned char *)status_text)
  8387. || *status_text == ' ') {
  8388. status_text++;
  8389. }
  8390. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  8391. != NULL) {
  8392. conn->status_code = 302;
  8393. } else {
  8394. conn->status_code = 200;
  8395. }
  8396. connection_state =
  8397. get_header(ri.http_headers, ri.num_headers, "Connection");
  8398. if (!header_has_option(connection_state, "keep-alive")) {
  8399. conn->must_close = 1;
  8400. }
  8401. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  8402. /* Send headers */
  8403. for (i = 0; i < ri.num_headers; i++) {
  8404. mg_printf(conn,
  8405. "%s: %s\r\n",
  8406. ri.http_headers[i].name,
  8407. ri.http_headers[i].value);
  8408. }
  8409. mg_write(conn, "\r\n", 2);
  8410. /* Send chunk of data that may have been read after the headers */
  8411. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  8412. /* Read the rest of CGI output and send to the client */
  8413. send_file_data(conn, &fout, 0, INT64_MAX);
  8414. done:
  8415. mg_free(blk.var);
  8416. mg_free(blk.buf);
  8417. if (pid != (pid_t)-1) {
  8418. kill(pid, SIGKILL);
  8419. #if !defined(_WIN32)
  8420. {
  8421. int st;
  8422. while (waitpid(pid, &st, 0) != -1)
  8423. ; /* clean zombies */
  8424. }
  8425. #endif
  8426. }
  8427. if (fdin[0] != -1) {
  8428. close(fdin[0]);
  8429. }
  8430. if (fdout[1] != -1) {
  8431. close(fdout[1]);
  8432. }
  8433. if (in != NULL) {
  8434. fclose(in);
  8435. } else if (fdin[1] != -1) {
  8436. close(fdin[1]);
  8437. }
  8438. if (out != NULL) {
  8439. fclose(out);
  8440. } else if (fdout[0] != -1) {
  8441. close(fdout[0]);
  8442. }
  8443. if (err != NULL) {
  8444. fclose(err);
  8445. } else if (fderr[0] != -1) {
  8446. close(fderr[0]);
  8447. }
  8448. if (buf != NULL) {
  8449. mg_free(buf);
  8450. }
  8451. }
  8452. #endif /* !NO_CGI */
  8453. #if !defined(NO_FILES)
  8454. static void
  8455. mkcol(struct mg_connection *conn, const char *path)
  8456. {
  8457. int rc, body_len;
  8458. struct de de;
  8459. char date[64];
  8460. time_t curtime = time(NULL);
  8461. if (conn == NULL) {
  8462. return;
  8463. }
  8464. /* TODO (mid): Check the mg_send_http_error situations in this function */
  8465. memset(&de.file, 0, sizeof(de.file));
  8466. if (!mg_stat(conn, path, &de.file)) {
  8467. mg_cry(conn,
  8468. "%s: mg_stat(%s) failed: %s",
  8469. __func__,
  8470. path,
  8471. strerror(ERRNO));
  8472. }
  8473. if (de.file.last_modified) {
  8474. /* TODO (mid): This check does not seem to make any sense ! */
  8475. /* TODO (mid): Add a webdav unit test first, before changing
  8476. * anything here. */
  8477. mg_send_http_error(
  8478. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8479. return;
  8480. }
  8481. body_len = conn->data_len - conn->request_len;
  8482. if (body_len > 0) {
  8483. mg_send_http_error(
  8484. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8485. return;
  8486. }
  8487. rc = mg_mkdir(conn, path, 0755);
  8488. if (rc == 0) {
  8489. conn->status_code = 201;
  8490. gmt_time_string(date, sizeof(date), &curtime);
  8491. mg_printf(conn,
  8492. "HTTP/1.1 %d Created\r\n"
  8493. "Date: %s\r\n",
  8494. conn->status_code,
  8495. date);
  8496. send_static_cache_header(conn);
  8497. send_additional_header(conn);
  8498. mg_printf(conn,
  8499. "Content-Length: 0\r\n"
  8500. "Connection: %s\r\n\r\n",
  8501. suggest_connection_header(conn));
  8502. } else if (rc == -1) {
  8503. if (errno == EEXIST) {
  8504. mg_send_http_error(
  8505. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8506. } else if (errno == EACCES) {
  8507. mg_send_http_error(
  8508. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8509. } else if (errno == ENOENT) {
  8510. mg_send_http_error(
  8511. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8512. } else {
  8513. mg_send_http_error(
  8514. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8515. }
  8516. }
  8517. }
  8518. static void
  8519. put_file(struct mg_connection *conn, const char *path)
  8520. {
  8521. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8522. const char *range;
  8523. int64_t r1, r2;
  8524. int rc;
  8525. char date[64];
  8526. time_t curtime = time(NULL);
  8527. if (conn == NULL) {
  8528. return;
  8529. }
  8530. if (mg_stat(conn, path, &file.stat)) {
  8531. /* File already exists */
  8532. conn->status_code = 200;
  8533. if (file.stat.is_directory) {
  8534. /* This is an already existing directory,
  8535. * so there is nothing to do for the server. */
  8536. rc = 0;
  8537. } else {
  8538. /* File exists and is not a directory. */
  8539. /* Can it be replaced? */
  8540. if (file.access.membuf != NULL) {
  8541. /* This is an "in-memory" file, that can not be replaced */
  8542. mg_send_http_error(
  8543. conn,
  8544. 405,
  8545. "Error: Put not possible\nReplacing %s is not supported",
  8546. path);
  8547. return;
  8548. }
  8549. /* Check if the server may write this file */
  8550. if (access(path, W_OK) == 0) {
  8551. /* Access granted */
  8552. conn->status_code = 200;
  8553. rc = 1;
  8554. } else {
  8555. mg_send_http_error(
  8556. conn,
  8557. 403,
  8558. "Error: Put not possible\nReplacing %s is not allowed",
  8559. path);
  8560. return;
  8561. }
  8562. }
  8563. } else {
  8564. /* File should be created */
  8565. conn->status_code = 201;
  8566. rc = put_dir(conn, path);
  8567. }
  8568. if (rc == 0) {
  8569. /* put_dir returns 0 if path is a directory */
  8570. gmt_time_string(date, sizeof(date), &curtime);
  8571. mg_printf(conn,
  8572. "HTTP/1.1 %d %s\r\n",
  8573. conn->status_code,
  8574. mg_get_response_code_text(NULL, conn->status_code));
  8575. send_no_cache_header(conn);
  8576. send_additional_header(conn);
  8577. mg_printf(conn,
  8578. "Date: %s\r\n"
  8579. "Content-Length: 0\r\n"
  8580. "Connection: %s\r\n\r\n",
  8581. date,
  8582. suggest_connection_header(conn));
  8583. /* Request to create a directory has been fulfilled successfully.
  8584. * No need to put a file. */
  8585. return;
  8586. }
  8587. if (rc == -1) {
  8588. /* put_dir returns -1 if the path is too long */
  8589. mg_send_http_error(conn,
  8590. 414,
  8591. "Error: Path too long\nput_dir(%s): %s",
  8592. path,
  8593. strerror(ERRNO));
  8594. return;
  8595. }
  8596. if (rc == -2) {
  8597. /* put_dir returns -2 if the directory can not be created */
  8598. mg_send_http_error(conn,
  8599. 500,
  8600. "Error: Can not create directory\nput_dir(%s): %s",
  8601. path,
  8602. strerror(ERRNO));
  8603. return;
  8604. }
  8605. /* A file should be created or overwritten. */
  8606. /* Currently CivetWeb does not nead read+write access. */
  8607. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8608. || file.access.fp == NULL) {
  8609. (void)mg_fclose(&file.access);
  8610. mg_send_http_error(conn,
  8611. 500,
  8612. "Error: Can not create file\nfopen(%s): %s",
  8613. path,
  8614. strerror(ERRNO));
  8615. return;
  8616. }
  8617. fclose_on_exec(&file.access, conn);
  8618. range = mg_get_header(conn, "Content-Range");
  8619. r1 = r2 = 0;
  8620. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  8621. conn->status_code = 206; /* Partial content */
  8622. fseeko(file.access.fp, r1, SEEK_SET);
  8623. }
  8624. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8625. /* forward_body_data failed.
  8626. * The error code has already been sent to the client,
  8627. * and conn->status_code is already set. */
  8628. (void)mg_fclose(&file.access);
  8629. return;
  8630. }
  8631. if (mg_fclose(&file.access) != 0) {
  8632. /* fclose failed. This might have different reasons, but a likely
  8633. * one is "no space on disk", http 507. */
  8634. conn->status_code = 507;
  8635. }
  8636. gmt_time_string(date, sizeof(date), &curtime);
  8637. mg_printf(conn,
  8638. "HTTP/1.1 %d %s\r\n",
  8639. conn->status_code,
  8640. mg_get_response_code_text(NULL, conn->status_code));
  8641. send_no_cache_header(conn);
  8642. send_additional_header(conn);
  8643. mg_printf(conn,
  8644. "Date: %s\r\n"
  8645. "Content-Length: 0\r\n"
  8646. "Connection: %s\r\n\r\n",
  8647. date,
  8648. suggest_connection_header(conn));
  8649. }
  8650. static void
  8651. delete_file(struct mg_connection *conn, const char *path)
  8652. {
  8653. struct de de;
  8654. memset(&de.file, 0, sizeof(de.file));
  8655. if (!mg_stat(conn, path, &de.file)) {
  8656. /* mg_stat returns 0 if the file does not exist */
  8657. mg_send_http_error(conn,
  8658. 404,
  8659. "Error: Cannot delete file\nFile %s not found",
  8660. path);
  8661. return;
  8662. }
  8663. #if 0 /* Ignore if a file in memory is inside a folder */
  8664. if (de.access.membuf != NULL) {
  8665. /* the file is cached in memory */
  8666. mg_send_http_error(
  8667. conn,
  8668. 405,
  8669. "Error: Delete not possible\nDeleting %s is not supported",
  8670. path);
  8671. return;
  8672. }
  8673. #endif
  8674. if (de.file.is_directory) {
  8675. if (remove_directory(conn, path)) {
  8676. /* Delete is successful: Return 204 without content. */
  8677. mg_send_http_error(conn, 204, "%s", "");
  8678. } else {
  8679. /* Delete is not successful: Return 500 (Server error). */
  8680. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8681. }
  8682. return;
  8683. }
  8684. /* This is an existing file (not a directory).
  8685. * Check if write permission is granted. */
  8686. if (access(path, W_OK) != 0) {
  8687. /* File is read only */
  8688. mg_send_http_error(
  8689. conn,
  8690. 403,
  8691. "Error: Delete not possible\nDeleting %s is not allowed",
  8692. path);
  8693. return;
  8694. }
  8695. /* Try to delete it. */
  8696. if (mg_remove(conn, path) == 0) {
  8697. /* Delete was successful: Return 204 without content. */
  8698. mg_send_http_error(conn, 204, "%s", "");
  8699. } else {
  8700. /* Delete not successful (file locked). */
  8701. mg_send_http_error(conn,
  8702. 423,
  8703. "Error: Cannot delete file\nremove(%s): %s",
  8704. path,
  8705. strerror(ERRNO));
  8706. }
  8707. }
  8708. #endif /* !NO_FILES */
  8709. static void
  8710. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8711. static void
  8712. do_ssi_include(struct mg_connection *conn,
  8713. const char *ssi,
  8714. char *tag,
  8715. int include_level)
  8716. {
  8717. char file_name[MG_BUF_LEN], path[512], *p;
  8718. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8719. size_t len;
  8720. int truncated = 0;
  8721. if (conn == NULL) {
  8722. return;
  8723. }
  8724. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8725. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8726. * always < MG_BUF_LEN. */
  8727. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8728. /* File name is relative to the webserver root */
  8729. file_name[511] = 0;
  8730. (void)mg_snprintf(conn,
  8731. &truncated,
  8732. path,
  8733. sizeof(path),
  8734. "%s/%s",
  8735. conn->ctx->config[DOCUMENT_ROOT],
  8736. file_name);
  8737. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8738. /* File name is relative to the webserver working directory
  8739. * or it is absolute system path */
  8740. file_name[511] = 0;
  8741. (void)
  8742. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8743. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  8744. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  8745. /* File name is relative to the currect document */
  8746. file_name[511] = 0;
  8747. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8748. if (!truncated) {
  8749. if ((p = strrchr(path, '/')) != NULL) {
  8750. p[1] = '\0';
  8751. }
  8752. len = strlen(path);
  8753. (void)mg_snprintf(conn,
  8754. &truncated,
  8755. path + len,
  8756. sizeof(path) - len,
  8757. "%s",
  8758. file_name);
  8759. }
  8760. } else {
  8761. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8762. return;
  8763. }
  8764. if (truncated) {
  8765. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8766. return;
  8767. }
  8768. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8769. mg_cry(conn,
  8770. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8771. tag,
  8772. path,
  8773. strerror(ERRNO));
  8774. } else {
  8775. fclose_on_exec(&file.access, conn);
  8776. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8777. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8778. path) > 0) {
  8779. send_ssi_file(conn, path, &file, include_level + 1);
  8780. } else {
  8781. send_file_data(conn, &file, 0, INT64_MAX);
  8782. }
  8783. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8784. }
  8785. }
  8786. #if !defined(NO_POPEN)
  8787. static void
  8788. do_ssi_exec(struct mg_connection *conn, char *tag)
  8789. {
  8790. char cmd[1024] = "";
  8791. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8792. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8793. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8794. } else {
  8795. cmd[1023] = 0;
  8796. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8797. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8798. } else {
  8799. send_file_data(conn, &file, 0, INT64_MAX);
  8800. pclose(file.access.fp);
  8801. }
  8802. }
  8803. }
  8804. #endif /* !NO_POPEN */
  8805. static int
  8806. mg_fgetc(struct mg_file *filep, int offset)
  8807. {
  8808. if (filep == NULL) {
  8809. return EOF;
  8810. }
  8811. if ((filep->access.membuf != NULL) && (offset >= 0)
  8812. && (((unsigned int)(offset)) < filep->stat.size)) {
  8813. return ((const unsigned char *)filep->access.membuf)[offset];
  8814. } else if (filep->access.fp != NULL) {
  8815. return fgetc(filep->access.fp);
  8816. } else {
  8817. return EOF;
  8818. }
  8819. }
  8820. static void
  8821. send_ssi_file(struct mg_connection *conn,
  8822. const char *path,
  8823. struct mg_file *filep,
  8824. int include_level)
  8825. {
  8826. char buf[MG_BUF_LEN];
  8827. int ch, offset, len, in_tag, in_ssi_tag;
  8828. if (include_level > 10) {
  8829. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8830. return;
  8831. }
  8832. in_tag = in_ssi_tag = len = offset = 0;
  8833. /* Read file, byte by byte, and look for SSI include tags */
  8834. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  8835. if (in_tag) {
  8836. /* We are in a tag, either SSI tag or html tag */
  8837. if (ch == '>') {
  8838. /* Tag is closing */
  8839. buf[len++] = '>';
  8840. if (in_ssi_tag) {
  8841. /* Handle SSI tag */
  8842. buf[len] = 0;
  8843. if (!memcmp(buf + 5, "include", 7)) {
  8844. do_ssi_include(conn, path, buf + 12, include_level + 1);
  8845. #if !defined(NO_POPEN)
  8846. } else if (!memcmp(buf + 5, "exec", 4)) {
  8847. do_ssi_exec(conn, buf + 9);
  8848. #endif /* !NO_POPEN */
  8849. } else {
  8850. mg_cry(conn,
  8851. "%s: unknown SSI "
  8852. "command: \"%s\"",
  8853. path,
  8854. buf);
  8855. }
  8856. len = 0;
  8857. in_ssi_tag = in_tag = 0;
  8858. } else {
  8859. /* Not an SSI tag */
  8860. /* Flush buffer */
  8861. (void)mg_write(conn, buf, (size_t)len);
  8862. len = 0;
  8863. in_tag = 0;
  8864. }
  8865. } else {
  8866. /* Tag is still open */
  8867. buf[len++] = (char)(ch & 0xff);
  8868. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  8869. /* All SSI tags start with <!--# */
  8870. in_ssi_tag = 1;
  8871. }
  8872. if ((len + 2) > (int)sizeof(buf)) {
  8873. /* Tag to long for buffer */
  8874. mg_cry(conn, "%s: tag is too large", path);
  8875. len = 0;
  8876. return;
  8877. }
  8878. }
  8879. } else {
  8880. /* We are not in a tag yet. */
  8881. if (ch == '<') {
  8882. /* Tag is opening */
  8883. in_tag = 1;
  8884. /* Flush current buffer */
  8885. (void)mg_write(conn, buf, (size_t)len);
  8886. /* Store the < */
  8887. len = 1;
  8888. buf[0] = '<';
  8889. } else {
  8890. /* No Tag */
  8891. /* Add data to buffer */
  8892. buf[len++] = (char)(ch & 0xff);
  8893. /* Flush if buffer is full */
  8894. if (len == (int)sizeof(buf)) {
  8895. mg_write(conn, buf, (size_t)len);
  8896. len = 0;
  8897. }
  8898. }
  8899. }
  8900. }
  8901. /* Send the rest of buffered data */
  8902. if (len > 0) {
  8903. mg_write(conn, buf, (size_t)len);
  8904. }
  8905. }
  8906. static void
  8907. handle_ssi_file_request(struct mg_connection *conn,
  8908. const char *path,
  8909. struct mg_file *filep)
  8910. {
  8911. char date[64];
  8912. time_t curtime = time(NULL);
  8913. const char *cors1, *cors2, *cors3;
  8914. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  8915. return;
  8916. }
  8917. if (mg_get_header(conn, "Origin")) {
  8918. /* Cross-origin resource sharing (CORS). */
  8919. cors1 = "Access-Control-Allow-Origin: ";
  8920. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8921. cors3 = "\r\n";
  8922. } else {
  8923. cors1 = cors2 = cors3 = "";
  8924. }
  8925. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8926. /* File exists (precondition for calling this function),
  8927. * but can not be opened by the server. */
  8928. mg_send_http_error(conn,
  8929. 500,
  8930. "Error: Cannot read file\nfopen(%s): %s",
  8931. path,
  8932. strerror(ERRNO));
  8933. } else {
  8934. conn->must_close = 1;
  8935. gmt_time_string(date, sizeof(date), &curtime);
  8936. fclose_on_exec(&filep->access, conn);
  8937. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8938. send_no_cache_header(conn);
  8939. send_additional_header(conn);
  8940. mg_printf(conn,
  8941. "%s%s%s"
  8942. "Date: %s\r\n"
  8943. "Content-Type: text/html\r\n"
  8944. "Connection: %s\r\n\r\n",
  8945. cors1,
  8946. cors2,
  8947. cors3,
  8948. date,
  8949. suggest_connection_header(conn));
  8950. send_ssi_file(conn, path, filep, 0);
  8951. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8952. }
  8953. }
  8954. #if !defined(NO_FILES)
  8955. static void
  8956. send_options(struct mg_connection *conn)
  8957. {
  8958. char date[64];
  8959. time_t curtime = time(NULL);
  8960. if (!conn) {
  8961. return;
  8962. }
  8963. conn->status_code = 200;
  8964. conn->must_close = 1;
  8965. gmt_time_string(date, sizeof(date), &curtime);
  8966. /* We do not set a "Cache-Control" header here, but leave the default.
  8967. * Since browsers do not send an OPTIONS request, we can not test the
  8968. * effect anyway. */
  8969. mg_printf(conn,
  8970. "HTTP/1.1 200 OK\r\n"
  8971. "Date: %s\r\n"
  8972. "Connection: %s\r\n"
  8973. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8974. "PROPFIND, MKCOL\r\n"
  8975. "DAV: 1\r\n",
  8976. date,
  8977. suggest_connection_header(conn));
  8978. send_additional_header(conn);
  8979. mg_printf(conn, "\r\n");
  8980. }
  8981. /* Writes PROPFIND properties for a collection element */
  8982. static void
  8983. print_props(struct mg_connection *conn,
  8984. const char *uri,
  8985. struct mg_file_stat *filep)
  8986. {
  8987. char mtime[64];
  8988. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  8989. return;
  8990. }
  8991. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8992. mg_printf(conn,
  8993. "<d:response>"
  8994. "<d:href>%s</d:href>"
  8995. "<d:propstat>"
  8996. "<d:prop>"
  8997. "<d:resourcetype>%s</d:resourcetype>"
  8998. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8999. "<d:getlastmodified>%s</d:getlastmodified>"
  9000. "</d:prop>"
  9001. "<d:status>HTTP/1.1 200 OK</d:status>"
  9002. "</d:propstat>"
  9003. "</d:response>\n",
  9004. uri,
  9005. filep->is_directory ? "<d:collection/>" : "",
  9006. filep->size,
  9007. mtime);
  9008. }
  9009. static int
  9010. print_dav_dir_entry(struct de *de, void *data)
  9011. {
  9012. char href[PATH_MAX];
  9013. int truncated;
  9014. struct mg_connection *conn = (struct mg_connection *)data;
  9015. if (!de || !conn) {
  9016. return -1;
  9017. }
  9018. mg_snprintf(conn,
  9019. &truncated,
  9020. href,
  9021. sizeof(href),
  9022. "%s%s",
  9023. conn->request_info.local_uri,
  9024. de->file_name);
  9025. if (!truncated) {
  9026. size_t href_encoded_size;
  9027. char *href_encoded;
  9028. href_encoded_size = PATH_MAX * 3; /* worst case */
  9029. href_encoded = mg_malloc(href_encoded_size);
  9030. if (href_encoded == NULL) {
  9031. return -1;
  9032. }
  9033. mg_url_encode(href, href_encoded, href_encoded_size);
  9034. print_props(conn, href_encoded, &de->file);
  9035. mg_free(href_encoded);
  9036. }
  9037. return 0;
  9038. }
  9039. static void
  9040. handle_propfind(struct mg_connection *conn,
  9041. const char *path,
  9042. struct mg_file_stat *filep)
  9043. {
  9044. const char *depth = mg_get_header(conn, "Depth");
  9045. char date[64];
  9046. time_t curtime = time(NULL);
  9047. gmt_time_string(date, sizeof(date), &curtime);
  9048. if (!conn || !path || !filep || !conn->ctx) {
  9049. return;
  9050. }
  9051. conn->must_close = 1;
  9052. conn->status_code = 207;
  9053. mg_printf(conn,
  9054. "HTTP/1.1 207 Multi-Status\r\n"
  9055. "Date: %s\r\n",
  9056. date);
  9057. send_static_cache_header(conn);
  9058. send_additional_header(conn);
  9059. mg_printf(conn,
  9060. "Connection: %s\r\n"
  9061. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9062. suggest_connection_header(conn));
  9063. mg_printf(conn,
  9064. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9065. "<d:multistatus xmlns:d='DAV:'>\n");
  9066. /* Print properties for the requested resource itself */
  9067. print_props(conn, conn->request_info.local_uri, filep);
  9068. /* If it is a directory, print directory entries too if Depth is not 0 */
  9069. if (filep && filep->is_directory
  9070. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  9071. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9072. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9073. }
  9074. mg_printf(conn, "%s\n", "</d:multistatus>");
  9075. }
  9076. #endif
  9077. void
  9078. mg_lock_connection(struct mg_connection *conn)
  9079. {
  9080. if (conn) {
  9081. (void)pthread_mutex_lock(&conn->mutex);
  9082. }
  9083. }
  9084. void
  9085. mg_unlock_connection(struct mg_connection *conn)
  9086. {
  9087. if (conn) {
  9088. (void)pthread_mutex_unlock(&conn->mutex);
  9089. }
  9090. }
  9091. void
  9092. mg_lock_context(struct mg_context *ctx)
  9093. {
  9094. if (ctx) {
  9095. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9096. }
  9097. }
  9098. void
  9099. mg_unlock_context(struct mg_context *ctx)
  9100. {
  9101. if (ctx) {
  9102. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9103. }
  9104. }
  9105. #if defined(USE_TIMERS)
  9106. #define TIMER_API static
  9107. #include "timer.inl"
  9108. #endif /* USE_TIMERS */
  9109. #ifdef USE_LUA
  9110. #include "mod_lua.inl"
  9111. #endif /* USE_LUA */
  9112. #ifdef USE_DUKTAPE
  9113. #include "mod_duktape.inl"
  9114. #endif /* USE_DUKTAPE */
  9115. #if defined(USE_WEBSOCKET)
  9116. #if !defined(NO_SSL_DL)
  9117. #define SHA_API static
  9118. #include "sha1.inl"
  9119. #endif
  9120. static int
  9121. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9122. {
  9123. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9124. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9125. SHA_CTX sha_ctx;
  9126. int truncated;
  9127. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9128. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9129. if (truncated) {
  9130. conn->must_close = 1;
  9131. return 0;
  9132. }
  9133. SHA1_Init(&sha_ctx);
  9134. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9135. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9136. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9137. mg_printf(conn,
  9138. "HTTP/1.1 101 Switching Protocols\r\n"
  9139. "Upgrade: websocket\r\n"
  9140. "Connection: Upgrade\r\n"
  9141. "Sec-WebSocket-Accept: %s\r\n",
  9142. b64_sha);
  9143. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9144. mg_printf(conn,
  9145. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9146. conn->request_info.acceptedWebSocketSubprotocol);
  9147. } else {
  9148. mg_printf(conn, "%s", "\r\n");
  9149. }
  9150. return 1;
  9151. }
  9152. static void
  9153. read_websocket(struct mg_connection *conn,
  9154. mg_websocket_data_handler ws_data_handler,
  9155. void *callback_data)
  9156. {
  9157. /* Pointer to the beginning of the portion of the incoming websocket
  9158. * message queue.
  9159. * The original websocket upgrade request is never removed, so the queue
  9160. * begins after it. */
  9161. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9162. int n, error, exit_by_callback;
  9163. /* body_len is the length of the entire queue in bytes
  9164. * len is the length of the current message
  9165. * data_len is the length of the current message's data payload
  9166. * header_len is the length of the current message's header */
  9167. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  9168. /* "The masking key is a 32-bit value chosen at random by the client."
  9169. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9170. */
  9171. unsigned char mask[4];
  9172. /* data points to the place where the message is stored when passed to
  9173. * the
  9174. * websocket_data callback. This is either mem on the stack, or a
  9175. * dynamically allocated buffer if it is too large. */
  9176. unsigned char mem[4096];
  9177. unsigned char *data = mem;
  9178. unsigned char mop; /* mask flag and opcode */
  9179. double timeout = -1.0;
  9180. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  9181. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9182. }
  9183. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  9184. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9185. }
  9186. mg_set_thread_name("wsock");
  9187. /* Loop continuously, reading messages from the socket, invoking the
  9188. * callback, and waiting repeatedly until an error occurs. */
  9189. while (!conn->ctx->stop_flag) {
  9190. header_len = 0;
  9191. assert(conn->data_len >= conn->request_len);
  9192. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9193. len = buf[1] & 127;
  9194. mask_len = (buf[1] & 128) ? 4 : 0;
  9195. if ((len < 126) && (body_len >= mask_len)) {
  9196. /* inline 7-bit length field */
  9197. data_len = len;
  9198. header_len = 2 + mask_len;
  9199. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9200. /* 16-bit length field */
  9201. header_len = 4 + mask_len;
  9202. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9203. } else if (body_len >= (10 + mask_len)) {
  9204. /* 64-bit length field */
  9205. uint32_t l1, l2;
  9206. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9207. memcpy(&l2, &buf[6], 4);
  9208. header_len = 10 + mask_len;
  9209. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9210. if (data_len > (uint64_t)0x7FFF0000ul) {
  9211. /* no can do */
  9212. mg_cry(conn, "websocket out of memory; closing connection");
  9213. break;
  9214. }
  9215. }
  9216. }
  9217. if ((header_len > 0) && (body_len >= header_len)) {
  9218. /* Allocate space to hold websocket payload */
  9219. data = mem;
  9220. if (data_len > sizeof(mem)) {
  9221. data = (unsigned char *)mg_malloc_ctx(data_len, conn->ctx);
  9222. if (data == NULL) {
  9223. /* Allocation failed, exit the loop and then close the
  9224. * connection */
  9225. mg_cry(conn, "websocket out of memory; closing connection");
  9226. break;
  9227. }
  9228. }
  9229. /* Copy the mask before we shift the queue and destroy it */
  9230. if (mask_len > 0) {
  9231. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9232. } else {
  9233. memset(mask, 0, sizeof(mask));
  9234. }
  9235. /* Read frame payload from the first message in the queue into
  9236. * data and advance the queue by moving the memory in place. */
  9237. assert(body_len >= header_len);
  9238. if (data_len + header_len > body_len) {
  9239. mop = buf[0]; /* current mask and opcode */
  9240. /* Overflow case */
  9241. len = body_len - header_len;
  9242. memcpy(data, buf + header_len, len);
  9243. error = 0;
  9244. while (len < data_len) {
  9245. n = pull_inner(NULL,
  9246. conn,
  9247. (char *)(data + len),
  9248. (int)(data_len - len),
  9249. timeout);
  9250. if (n <= -2) {
  9251. error = 1;
  9252. break;
  9253. } else if (n > 0) {
  9254. len += (size_t)n;
  9255. } else {
  9256. /* Timeout: should retry */
  9257. /* TODO: retry condition */
  9258. }
  9259. }
  9260. if (error) {
  9261. mg_cry(conn, "Websocket pull failed; closing connection");
  9262. break;
  9263. }
  9264. conn->data_len = conn->request_len;
  9265. } else {
  9266. mop = buf[0]; /* current mask and opcode, overwritten by
  9267. * memmove() */
  9268. /* Length of the message being read at the front of the
  9269. * queue */
  9270. len = data_len + header_len;
  9271. /* Copy the data payload into the data pointer for the
  9272. * callback */
  9273. memcpy(data, buf + header_len, data_len);
  9274. /* Move the queue forward len bytes */
  9275. memmove(buf, buf + len, body_len - len);
  9276. /* Mark the queue as advanced */
  9277. conn->data_len -= (int)len;
  9278. }
  9279. /* Apply mask if necessary */
  9280. if (mask_len > 0) {
  9281. for (i = 0; i < data_len; ++i) {
  9282. data[i] ^= mask[i & 3];
  9283. }
  9284. }
  9285. /* Exit the loop if callback signals to exit (server side),
  9286. * or "connection close" opcode received (client side). */
  9287. exit_by_callback = 0;
  9288. if ((ws_data_handler != NULL)
  9289. && !ws_data_handler(
  9290. conn, mop, (char *)data, data_len, callback_data)) {
  9291. exit_by_callback = 1;
  9292. }
  9293. if (data != mem) {
  9294. mg_free(data);
  9295. }
  9296. if (exit_by_callback
  9297. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9298. /* Opcode == 8, connection close */
  9299. break;
  9300. }
  9301. /* Not breaking the loop, process next websocket frame. */
  9302. } else {
  9303. /* Read from the socket into the next available location in the
  9304. * message queue. */
  9305. n = pull_inner(NULL,
  9306. conn,
  9307. conn->buf + conn->data_len,
  9308. conn->buf_size - conn->data_len,
  9309. timeout);
  9310. if (n <= -2) {
  9311. /* Error, no bytes read */
  9312. break;
  9313. }
  9314. if (n > 0) {
  9315. conn->data_len += n;
  9316. } else {
  9317. /* Timeout: should retry */
  9318. /* TODO: get timeout def */
  9319. }
  9320. }
  9321. }
  9322. mg_set_thread_name("worker");
  9323. }
  9324. static int
  9325. mg_websocket_write_exec(struct mg_connection *conn,
  9326. int opcode,
  9327. const char *data,
  9328. size_t dataLen,
  9329. uint32_t masking_key)
  9330. {
  9331. unsigned char header[14];
  9332. size_t headerLen = 1;
  9333. int retval = -1;
  9334. #if defined(__GNUC__) || defined(__MINGW32__)
  9335. /* Disable spurious conversion warning for GCC */
  9336. #pragma GCC diagnostic push
  9337. #pragma GCC diagnostic ignored "-Wconversion"
  9338. #endif
  9339. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  9340. #if defined(__GNUC__) || defined(__MINGW32__)
  9341. #pragma GCC diagnostic pop
  9342. #endif
  9343. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  9344. if (dataLen < 126) {
  9345. /* inline 7-bit length field */
  9346. header[1] = (unsigned char)dataLen;
  9347. headerLen = 2;
  9348. } else if (dataLen <= 0xFFFF) {
  9349. /* 16-bit length field */
  9350. uint16_t len = htons((uint16_t)dataLen);
  9351. header[1] = 126;
  9352. memcpy(header + 2, &len, 2);
  9353. headerLen = 4;
  9354. } else {
  9355. /* 64-bit length field */
  9356. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  9357. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  9358. header[1] = 127;
  9359. memcpy(header + 2, &len1, 4);
  9360. memcpy(header + 6, &len2, 4);
  9361. headerLen = 10;
  9362. }
  9363. if (masking_key) {
  9364. /* add mask */
  9365. header[1] |= 0x80;
  9366. memcpy(header + headerLen, &masking_key, 4);
  9367. headerLen += 4;
  9368. }
  9369. /* Note that POSIX/Winsock's send() is threadsafe
  9370. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  9371. * but mongoose's mg_printf/mg_write is not (because of the loop in
  9372. * push(), although that is only a problem if the packet is large or
  9373. * outgoing buffer is full). */
  9374. /* TODO: Check if this lock should be moved to user land.
  9375. * Currently the server sets this lock for websockets, but
  9376. * not for any other connection. It must be set for every
  9377. * conn read/written by more than one thread, no matter if
  9378. * it is a websocket or regular connection. */
  9379. (void)mg_lock_connection(conn);
  9380. retval = mg_write(conn, header, headerLen);
  9381. if (dataLen > 0) {
  9382. retval = mg_write(conn, data, dataLen);
  9383. }
  9384. /* TODO: Remove this unlock as well, when lock is moved. */
  9385. mg_unlock_connection(conn);
  9386. return retval;
  9387. }
  9388. int
  9389. mg_websocket_write(struct mg_connection *conn,
  9390. int opcode,
  9391. const char *data,
  9392. size_t dataLen)
  9393. {
  9394. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  9395. }
  9396. static void
  9397. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  9398. {
  9399. size_t i = 0;
  9400. i = 0;
  9401. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  9402. /* Convert in 32 bit words, if data is 4 byte aligned */
  9403. while (i < (in_len - 3)) {
  9404. *(uint32_t *)(void *)(out + i) =
  9405. *(uint32_t *)(void *)(in + i) ^ masking_key;
  9406. i += 4;
  9407. }
  9408. }
  9409. if (i != in_len) {
  9410. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  9411. while (i < in_len) {
  9412. *(uint8_t *)(void *)(out + i) =
  9413. *(uint8_t *)(void *)(in + i)
  9414. ^ *(((uint8_t *)&masking_key) + (i % 4));
  9415. i++;
  9416. }
  9417. }
  9418. }
  9419. int
  9420. mg_websocket_client_write(struct mg_connection *conn,
  9421. int opcode,
  9422. const char *data,
  9423. size_t dataLen)
  9424. {
  9425. int retval = -1;
  9426. char *masked_data =
  9427. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  9428. uint32_t masking_key = (uint32_t)get_random();
  9429. if (masked_data == NULL) {
  9430. /* Return -1 in an error case */
  9431. mg_cry(conn,
  9432. "Cannot allocate buffer for masked websocket response: "
  9433. "Out of memory");
  9434. return -1;
  9435. }
  9436. mask_data(data, dataLen, masking_key, masked_data);
  9437. retval = mg_websocket_write_exec(
  9438. conn, opcode, masked_data, dataLen, masking_key);
  9439. mg_free(masked_data);
  9440. return retval;
  9441. }
  9442. static void
  9443. handle_websocket_request(struct mg_connection *conn,
  9444. const char *path,
  9445. int is_callback_resource,
  9446. struct mg_websocket_subprotocols *subprotocols,
  9447. mg_websocket_connect_handler ws_connect_handler,
  9448. mg_websocket_ready_handler ws_ready_handler,
  9449. mg_websocket_data_handler ws_data_handler,
  9450. mg_websocket_close_handler ws_close_handler,
  9451. void *cbData)
  9452. {
  9453. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  9454. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  9455. int lua_websock = 0;
  9456. #if !defined(USE_LUA)
  9457. (void)path;
  9458. #endif
  9459. /* Step 1: Check websocket protocol version. */
  9460. /* Step 1.1: Check Sec-WebSocket-Key. */
  9461. if (!websock_key) {
  9462. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  9463. * requires a Sec-WebSocket-Key header.
  9464. */
  9465. /* It could be the hixie draft version
  9466. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  9467. */
  9468. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  9469. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  9470. char key3[8];
  9471. if ((key1 != NULL) && (key2 != NULL)) {
  9472. /* This version uses 8 byte body data in a GET request */
  9473. conn->content_len = 8;
  9474. if (8 == mg_read(conn, key3, 8)) {
  9475. /* This is the hixie version */
  9476. mg_send_http_error(conn,
  9477. 426,
  9478. "%s",
  9479. "Protocol upgrade to RFC 6455 required");
  9480. return;
  9481. }
  9482. }
  9483. /* This is an unknown version */
  9484. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  9485. return;
  9486. }
  9487. /* Step 1.2: Check websocket protocol version. */
  9488. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  9489. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  9490. /* Reject wrong versions */
  9491. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  9492. return;
  9493. }
  9494. /* Step 1.3: Could check for "Host", but we do not really nead this
  9495. * value for anything, so just ignore it. */
  9496. /* Step 2: If a callback is responsible, call it. */
  9497. if (is_callback_resource) {
  9498. /* Step 2.1 check and select subprotocol */
  9499. const char *protocols[64]; // max 64 headers
  9500. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  9501. "Sec-WebSocket-Protocol",
  9502. protocols,
  9503. 64);
  9504. if ((nbSubprotocolHeader > 0) && subprotocols) {
  9505. int cnt = 0;
  9506. int idx;
  9507. unsigned long len;
  9508. const char *sep, *curSubProtocol,
  9509. *acceptedWebSocketSubprotocol = NULL;
  9510. /* look for matching subprotocol */
  9511. do {
  9512. const char *protocol = protocols[cnt];
  9513. do {
  9514. sep = strchr(protocol, ',');
  9515. curSubProtocol = protocol;
  9516. len = sep ? (unsigned long)(sep - protocol)
  9517. : (unsigned long)strlen(protocol);
  9518. while (sep && isspace(*++sep))
  9519. ; // ignore leading whitespaces
  9520. protocol = sep;
  9521. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  9522. if ((strlen(subprotocols->subprotocols[idx]) == len)
  9523. && (strncmp(curSubProtocol,
  9524. subprotocols->subprotocols[idx],
  9525. len) == 0)) {
  9526. acceptedWebSocketSubprotocol =
  9527. subprotocols->subprotocols[idx];
  9528. break;
  9529. }
  9530. }
  9531. } while (sep && !acceptedWebSocketSubprotocol);
  9532. } while (++cnt < nbSubprotocolHeader
  9533. && !acceptedWebSocketSubprotocol);
  9534. conn->request_info.acceptedWebSocketSubprotocol =
  9535. acceptedWebSocketSubprotocol;
  9536. } else if (nbSubprotocolHeader > 0) {
  9537. /* keep legacy behavior */
  9538. const char *protocol = protocols[0];
  9539. /* The protocol is a comma separated list of names. */
  9540. /* The server must only return one value from this list. */
  9541. /* First check if it is a list or just a single value. */
  9542. const char *sep = strrchr(protocol, ',');
  9543. if (sep == NULL) {
  9544. /* Just a single protocol -> accept it. */
  9545. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  9546. } else {
  9547. /* Multiple protocols -> accept the last one. */
  9548. /* This is just a quick fix if the client offers multiple
  9549. * protocols. The handler should have a list of accepted
  9550. * protocols on his own
  9551. * and use it to select one protocol among those the client has
  9552. * offered.
  9553. */
  9554. while (isspace(*++sep)) {
  9555. ; /* ignore leading whitespaces */
  9556. }
  9557. conn->request_info.acceptedWebSocketSubprotocol = sep;
  9558. }
  9559. }
  9560. if ((ws_connect_handler != NULL)
  9561. && (ws_connect_handler(conn, cbData) != 0)) {
  9562. /* C callback has returned non-zero, do not proceed with
  9563. * handshake.
  9564. */
  9565. /* Note that C callbacks are no longer called when Lua is
  9566. * responsible, so C can no longer filter callbacks for Lua. */
  9567. return;
  9568. }
  9569. }
  9570. #if defined(USE_LUA)
  9571. /* Step 3: No callback. Check if Lua is responsible. */
  9572. else {
  9573. /* Step 3.1: Check if Lua is responsible. */
  9574. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  9575. lua_websock =
  9576. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  9577. strlen(
  9578. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  9579. path);
  9580. }
  9581. if (lua_websock) {
  9582. /* Step 3.2: Lua is responsible: call it. */
  9583. conn->lua_websocket_state = lua_websocket_new(path, conn);
  9584. if (!conn->lua_websocket_state) {
  9585. /* Lua rejected the new client */
  9586. return;
  9587. }
  9588. }
  9589. }
  9590. #endif
  9591. /* Step 4: Check if there is a responsible websocket handler. */
  9592. if (!is_callback_resource && !lua_websock) {
  9593. /* There is no callback, and Lua is not responsible either. */
  9594. /* Reply with a 404 Not Found. We are still at a standard
  9595. * HTTP request here, before the websocket handshake, so
  9596. * we can still send standard HTTP error replies. */
  9597. mg_send_http_error(conn, 404, "%s", "Not found");
  9598. return;
  9599. }
  9600. /* Step 5: The websocket connection has been accepted */
  9601. if (!send_websocket_handshake(conn, websock_key)) {
  9602. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  9603. return;
  9604. }
  9605. /* Step 6: Call the ready handler */
  9606. if (is_callback_resource) {
  9607. if (ws_ready_handler != NULL) {
  9608. ws_ready_handler(conn, cbData);
  9609. }
  9610. #if defined(USE_LUA)
  9611. } else if (lua_websock) {
  9612. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9613. /* the ready handler returned false */
  9614. return;
  9615. }
  9616. #endif
  9617. }
  9618. /* Step 7: Enter the read loop */
  9619. if (is_callback_resource) {
  9620. read_websocket(conn, ws_data_handler, cbData);
  9621. #if defined(USE_LUA)
  9622. } else if (lua_websock) {
  9623. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9624. #endif
  9625. }
  9626. /* Step 8: Call the close handler */
  9627. if (ws_close_handler) {
  9628. ws_close_handler(conn, cbData);
  9629. }
  9630. }
  9631. static int
  9632. is_websocket_protocol(const struct mg_connection *conn)
  9633. {
  9634. const char *upgrade, *connection;
  9635. /* A websocket protocoll has the following HTTP headers:
  9636. *
  9637. * Connection: Upgrade
  9638. * Upgrade: Websocket
  9639. */
  9640. upgrade = mg_get_header(conn, "Upgrade");
  9641. if (upgrade == NULL) {
  9642. return 0; /* fail early, don't waste time checking other header
  9643. * fields
  9644. */
  9645. }
  9646. if (!mg_strcasestr(upgrade, "websocket")) {
  9647. return 0;
  9648. }
  9649. connection = mg_get_header(conn, "Connection");
  9650. if (connection == NULL) {
  9651. return 0;
  9652. }
  9653. if (!mg_strcasestr(connection, "upgrade")) {
  9654. return 0;
  9655. }
  9656. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9657. * "Sec-WebSocket-Version" are also required.
  9658. * Don't check them here, since even an unsupported websocket protocol
  9659. * request still IS a websocket request (in contrast to a standard HTTP
  9660. * request). It will fail later in handle_websocket_request.
  9661. */
  9662. return 1;
  9663. }
  9664. #endif /* !USE_WEBSOCKET */
  9665. static int
  9666. isbyte(int n)
  9667. {
  9668. return (n >= 0) && (n <= 255);
  9669. }
  9670. static int
  9671. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9672. {
  9673. int n, a, b, c, d, slash = 32, len = 0;
  9674. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  9675. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  9676. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  9677. && (slash < 33)) {
  9678. len = n;
  9679. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9680. | (uint32_t)d;
  9681. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9682. }
  9683. return len;
  9684. }
  9685. static int
  9686. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9687. {
  9688. int throttle = 0;
  9689. struct vec vec, val;
  9690. uint32_t net, mask;
  9691. char mult;
  9692. double v;
  9693. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9694. mult = ',';
  9695. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9696. || (v < 0) || ((lowercase(&mult) != 'k')
  9697. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9698. continue;
  9699. }
  9700. v *= (lowercase(&mult) == 'k')
  9701. ? 1024
  9702. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9703. if (vec.len == 1 && vec.ptr[0] == '*') {
  9704. throttle = (int)v;
  9705. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9706. if ((remote_ip & mask) == net) {
  9707. throttle = (int)v;
  9708. }
  9709. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9710. throttle = (int)v;
  9711. }
  9712. }
  9713. return throttle;
  9714. }
  9715. static uint32_t
  9716. get_remote_ip(const struct mg_connection *conn)
  9717. {
  9718. if (!conn) {
  9719. return 0;
  9720. }
  9721. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9722. }
  9723. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9724. #include "handle_form.inl"
  9725. #if defined(MG_LEGACY_INTERFACE)
  9726. /* Implement the deprecated mg_upload function by calling the new
  9727. * mg_handle_form_request function. While mg_upload could only handle
  9728. * HTML forms sent as POST request in multipart/form-data format
  9729. * containing only file input elements, mg_handle_form_request can
  9730. * handle all form input elements and all standard request methods. */
  9731. struct mg_upload_user_data {
  9732. struct mg_connection *conn;
  9733. const char *destination_dir;
  9734. int num_uploaded_files;
  9735. };
  9736. /* Helper function for deprecated mg_upload. */
  9737. static int
  9738. mg_upload_field_found(const char *key,
  9739. const char *filename,
  9740. char *path,
  9741. size_t pathlen,
  9742. void *user_data)
  9743. {
  9744. int truncated = 0;
  9745. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9746. (void)key;
  9747. if (!filename) {
  9748. mg_cry(fud->conn, "%s: No filename set", __func__);
  9749. return FORM_FIELD_STORAGE_ABORT;
  9750. }
  9751. mg_snprintf(fud->conn,
  9752. &truncated,
  9753. path,
  9754. pathlen - 1,
  9755. "%s/%s",
  9756. fud->destination_dir,
  9757. filename);
  9758. if (!truncated) {
  9759. mg_cry(fud->conn, "%s: File path too long", __func__);
  9760. return FORM_FIELD_STORAGE_ABORT;
  9761. }
  9762. return FORM_FIELD_STORAGE_STORE;
  9763. }
  9764. /* Helper function for deprecated mg_upload. */
  9765. static int
  9766. mg_upload_field_get(const char *key,
  9767. const char *value,
  9768. size_t value_size,
  9769. void *user_data)
  9770. {
  9771. /* Function should never be called */
  9772. (void)key;
  9773. (void)value;
  9774. (void)value_size;
  9775. (void)user_data;
  9776. return 0;
  9777. }
  9778. /* Helper function for deprecated mg_upload. */
  9779. static int
  9780. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9781. {
  9782. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9783. (void)file_size;
  9784. fud->num_uploaded_files++;
  9785. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9786. return 0;
  9787. }
  9788. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9789. int
  9790. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9791. {
  9792. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9793. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9794. mg_upload_field_get,
  9795. mg_upload_field_stored,
  9796. 0};
  9797. int ret;
  9798. fdh.user_data = (void *)&fud;
  9799. ret = mg_handle_form_request(conn, &fdh);
  9800. if (ret < 0) {
  9801. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9802. }
  9803. return fud.num_uploaded_files;
  9804. }
  9805. #endif
  9806. static int
  9807. get_first_ssl_listener_index(const struct mg_context *ctx)
  9808. {
  9809. unsigned int i;
  9810. int idx = -1;
  9811. if (ctx) {
  9812. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  9813. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9814. }
  9815. }
  9816. return idx;
  9817. }
  9818. static void
  9819. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9820. {
  9821. char host[1025];
  9822. const char *host_header;
  9823. size_t hostlen;
  9824. host_header = mg_get_header(conn, "Host");
  9825. hostlen = sizeof(host);
  9826. if (host_header != NULL) {
  9827. char *pos;
  9828. mg_strlcpy(host, host_header, hostlen);
  9829. host[hostlen - 1] = '\0';
  9830. pos = strchr(host, ':');
  9831. if (pos != NULL) {
  9832. *pos = '\0';
  9833. }
  9834. } else {
  9835. /* Cannot get host from the Host: header.
  9836. * Fallback to our IP address. */
  9837. if (conn) {
  9838. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9839. }
  9840. }
  9841. /* Send host, port, uri and (if it exists) ?query_string */
  9842. if (conn) {
  9843. mg_printf(conn,
  9844. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9845. host,
  9846. #if defined(USE_IPV6)
  9847. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9848. == AF_INET6)
  9849. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9850. .lsa.sin6.sin6_port)
  9851. :
  9852. #endif
  9853. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9854. .lsa.sin.sin_port),
  9855. conn->request_info.local_uri,
  9856. (conn->request_info.query_string == NULL) ? "" : "?",
  9857. (conn->request_info.query_string == NULL)
  9858. ? ""
  9859. : conn->request_info.query_string);
  9860. }
  9861. }
  9862. static void
  9863. mg_set_handler_type(struct mg_context *ctx,
  9864. const char *uri,
  9865. int handler_type,
  9866. int is_delete_request,
  9867. mg_request_handler handler,
  9868. struct mg_websocket_subprotocols *subprotocols,
  9869. mg_websocket_connect_handler connect_handler,
  9870. mg_websocket_ready_handler ready_handler,
  9871. mg_websocket_data_handler data_handler,
  9872. mg_websocket_close_handler close_handler,
  9873. mg_authorization_handler auth_handler,
  9874. void *cbdata)
  9875. {
  9876. struct mg_handler_info *tmp_rh, **lastref;
  9877. size_t urilen = strlen(uri);
  9878. if (handler_type == WEBSOCKET_HANDLER) {
  9879. /* assert(handler == NULL); */
  9880. /* assert(is_delete_request || connect_handler!=NULL ||
  9881. * ready_handler!=NULL || data_handler!=NULL ||
  9882. * close_handler!=NULL);
  9883. */
  9884. /* assert(auth_handler == NULL); */
  9885. if (handler != NULL) {
  9886. return;
  9887. }
  9888. if (!is_delete_request && (connect_handler == NULL)
  9889. && (ready_handler == NULL) && (data_handler == NULL)
  9890. && (close_handler == NULL)) {
  9891. return;
  9892. }
  9893. if (auth_handler != NULL) {
  9894. return;
  9895. }
  9896. } else if (handler_type == REQUEST_HANDLER) {
  9897. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9898. * data_handler==NULL && close_handler==NULL); */
  9899. /* assert(is_delete_request || (handler!=NULL));
  9900. */
  9901. /* assert(auth_handler == NULL); */
  9902. if ((connect_handler != NULL) || (ready_handler != NULL)
  9903. || (data_handler != NULL) || (close_handler != NULL)) {
  9904. return;
  9905. }
  9906. if (!is_delete_request && (handler == NULL)) {
  9907. return;
  9908. }
  9909. if (auth_handler != NULL) {
  9910. return;
  9911. }
  9912. } else { /* AUTH_HANDLER */
  9913. /* assert(handler == NULL); */
  9914. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9915. * data_handler==NULL && close_handler==NULL); */
  9916. /* assert(auth_handler != NULL); */
  9917. if (handler != NULL) {
  9918. return;
  9919. }
  9920. if ((connect_handler != NULL) || (ready_handler != NULL)
  9921. || (data_handler != NULL) || (close_handler != NULL)) {
  9922. return;
  9923. }
  9924. if (!is_delete_request && (auth_handler == NULL)) {
  9925. return;
  9926. }
  9927. }
  9928. if (!ctx) {
  9929. return;
  9930. }
  9931. mg_lock_context(ctx);
  9932. /* first try to find an existing handler */
  9933. lastref = &(ctx->handlers);
  9934. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9935. if (tmp_rh->handler_type == handler_type) {
  9936. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  9937. if (!is_delete_request) {
  9938. /* update existing handler */
  9939. if (handler_type == REQUEST_HANDLER) {
  9940. tmp_rh->handler = handler;
  9941. } else if (handler_type == WEBSOCKET_HANDLER) {
  9942. tmp_rh->subprotocols = subprotocols;
  9943. tmp_rh->connect_handler = connect_handler;
  9944. tmp_rh->ready_handler = ready_handler;
  9945. tmp_rh->data_handler = data_handler;
  9946. tmp_rh->close_handler = close_handler;
  9947. } else { /* AUTH_HANDLER */
  9948. tmp_rh->auth_handler = auth_handler;
  9949. }
  9950. tmp_rh->cbdata = cbdata;
  9951. } else {
  9952. /* remove existing handler */
  9953. *lastref = tmp_rh->next;
  9954. mg_free(tmp_rh->uri);
  9955. mg_free(tmp_rh);
  9956. }
  9957. mg_unlock_context(ctx);
  9958. return;
  9959. }
  9960. }
  9961. lastref = &(tmp_rh->next);
  9962. }
  9963. if (is_delete_request) {
  9964. /* no handler to set, this was a remove request to a non-existing
  9965. * handler */
  9966. mg_unlock_context(ctx);
  9967. return;
  9968. }
  9969. tmp_rh =
  9970. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  9971. 1,
  9972. ctx);
  9973. if (tmp_rh == NULL) {
  9974. mg_unlock_context(ctx);
  9975. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9976. return;
  9977. }
  9978. tmp_rh->uri = mg_strdup(uri);
  9979. if (!tmp_rh->uri) {
  9980. mg_unlock_context(ctx);
  9981. mg_free(tmp_rh);
  9982. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9983. return;
  9984. }
  9985. tmp_rh->uri_len = urilen;
  9986. if (handler_type == REQUEST_HANDLER) {
  9987. tmp_rh->handler = handler;
  9988. } else if (handler_type == WEBSOCKET_HANDLER) {
  9989. tmp_rh->subprotocols = subprotocols;
  9990. tmp_rh->connect_handler = connect_handler;
  9991. tmp_rh->ready_handler = ready_handler;
  9992. tmp_rh->data_handler = data_handler;
  9993. tmp_rh->close_handler = close_handler;
  9994. } else { /* AUTH_HANDLER */
  9995. tmp_rh->auth_handler = auth_handler;
  9996. }
  9997. tmp_rh->cbdata = cbdata;
  9998. tmp_rh->handler_type = handler_type;
  9999. tmp_rh->next = NULL;
  10000. *lastref = tmp_rh;
  10001. mg_unlock_context(ctx);
  10002. }
  10003. void
  10004. mg_set_request_handler(struct mg_context *ctx,
  10005. const char *uri,
  10006. mg_request_handler handler,
  10007. void *cbdata)
  10008. {
  10009. mg_set_handler_type(ctx,
  10010. uri,
  10011. REQUEST_HANDLER,
  10012. handler == NULL,
  10013. handler,
  10014. NULL,
  10015. NULL,
  10016. NULL,
  10017. NULL,
  10018. NULL,
  10019. NULL,
  10020. cbdata);
  10021. }
  10022. void
  10023. mg_set_websocket_handler(struct mg_context *ctx,
  10024. const char *uri,
  10025. mg_websocket_connect_handler connect_handler,
  10026. mg_websocket_ready_handler ready_handler,
  10027. mg_websocket_data_handler data_handler,
  10028. mg_websocket_close_handler close_handler,
  10029. void *cbdata)
  10030. {
  10031. mg_set_websocket_handler_with_subprotocols(ctx,
  10032. uri,
  10033. NULL,
  10034. connect_handler,
  10035. ready_handler,
  10036. data_handler,
  10037. close_handler,
  10038. cbdata);
  10039. }
  10040. void
  10041. mg_set_websocket_handler_with_subprotocols(
  10042. struct mg_context *ctx,
  10043. const char *uri,
  10044. struct mg_websocket_subprotocols *subprotocols,
  10045. mg_websocket_connect_handler connect_handler,
  10046. mg_websocket_ready_handler ready_handler,
  10047. mg_websocket_data_handler data_handler,
  10048. mg_websocket_close_handler close_handler,
  10049. void *cbdata)
  10050. {
  10051. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  10052. && (data_handler == NULL)
  10053. && (close_handler == NULL);
  10054. mg_set_handler_type(ctx,
  10055. uri,
  10056. WEBSOCKET_HANDLER,
  10057. is_delete_request,
  10058. NULL,
  10059. subprotocols,
  10060. connect_handler,
  10061. ready_handler,
  10062. data_handler,
  10063. close_handler,
  10064. NULL,
  10065. cbdata);
  10066. }
  10067. void
  10068. mg_set_auth_handler(struct mg_context *ctx,
  10069. const char *uri,
  10070. mg_request_handler handler,
  10071. void *cbdata)
  10072. {
  10073. mg_set_handler_type(ctx,
  10074. uri,
  10075. AUTH_HANDLER,
  10076. handler == NULL,
  10077. NULL,
  10078. NULL,
  10079. NULL,
  10080. NULL,
  10081. NULL,
  10082. NULL,
  10083. handler,
  10084. cbdata);
  10085. }
  10086. static int
  10087. get_request_handler(struct mg_connection *conn,
  10088. int handler_type,
  10089. mg_request_handler *handler,
  10090. struct mg_websocket_subprotocols **subprotocols,
  10091. mg_websocket_connect_handler *connect_handler,
  10092. mg_websocket_ready_handler *ready_handler,
  10093. mg_websocket_data_handler *data_handler,
  10094. mg_websocket_close_handler *close_handler,
  10095. mg_authorization_handler *auth_handler,
  10096. void **cbdata)
  10097. {
  10098. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10099. if (request_info) {
  10100. const char *uri = request_info->local_uri;
  10101. size_t urilen = strlen(uri);
  10102. struct mg_handler_info *tmp_rh;
  10103. if (!conn || !conn->ctx) {
  10104. return 0;
  10105. }
  10106. mg_lock_context(conn->ctx);
  10107. /* first try for an exact match */
  10108. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10109. tmp_rh = tmp_rh->next) {
  10110. if (tmp_rh->handler_type == handler_type) {
  10111. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10112. if (handler_type == WEBSOCKET_HANDLER) {
  10113. *subprotocols = tmp_rh->subprotocols;
  10114. *connect_handler = tmp_rh->connect_handler;
  10115. *ready_handler = tmp_rh->ready_handler;
  10116. *data_handler = tmp_rh->data_handler;
  10117. *close_handler = tmp_rh->close_handler;
  10118. } else if (handler_type == REQUEST_HANDLER) {
  10119. *handler = tmp_rh->handler;
  10120. } else { /* AUTH_HANDLER */
  10121. *auth_handler = tmp_rh->auth_handler;
  10122. }
  10123. *cbdata = tmp_rh->cbdata;
  10124. mg_unlock_context(conn->ctx);
  10125. return 1;
  10126. }
  10127. }
  10128. }
  10129. /* next try for a partial match, we will accept uri/something */
  10130. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10131. tmp_rh = tmp_rh->next) {
  10132. if (tmp_rh->handler_type == handler_type) {
  10133. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10134. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  10135. if (handler_type == WEBSOCKET_HANDLER) {
  10136. *subprotocols = tmp_rh->subprotocols;
  10137. *connect_handler = tmp_rh->connect_handler;
  10138. *ready_handler = tmp_rh->ready_handler;
  10139. *data_handler = tmp_rh->data_handler;
  10140. *close_handler = tmp_rh->close_handler;
  10141. } else if (handler_type == REQUEST_HANDLER) {
  10142. *handler = tmp_rh->handler;
  10143. } else { /* AUTH_HANDLER */
  10144. *auth_handler = tmp_rh->auth_handler;
  10145. }
  10146. *cbdata = tmp_rh->cbdata;
  10147. mg_unlock_context(conn->ctx);
  10148. return 1;
  10149. }
  10150. }
  10151. }
  10152. /* finally try for pattern match */
  10153. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10154. tmp_rh = tmp_rh->next) {
  10155. if (tmp_rh->handler_type == handler_type) {
  10156. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10157. if (handler_type == WEBSOCKET_HANDLER) {
  10158. *subprotocols = tmp_rh->subprotocols;
  10159. *connect_handler = tmp_rh->connect_handler;
  10160. *ready_handler = tmp_rh->ready_handler;
  10161. *data_handler = tmp_rh->data_handler;
  10162. *close_handler = tmp_rh->close_handler;
  10163. } else if (handler_type == REQUEST_HANDLER) {
  10164. *handler = tmp_rh->handler;
  10165. } else { /* AUTH_HANDLER */
  10166. *auth_handler = tmp_rh->auth_handler;
  10167. }
  10168. *cbdata = tmp_rh->cbdata;
  10169. mg_unlock_context(conn->ctx);
  10170. return 1;
  10171. }
  10172. }
  10173. }
  10174. mg_unlock_context(conn->ctx);
  10175. }
  10176. return 0; /* none found */
  10177. }
  10178. /* Check if the script file is in a path, allowed for script files.
  10179. * This can be used if uploading files is possible not only for the server
  10180. * admin, and the upload mechanism does not check the file extension.
  10181. */
  10182. static int
  10183. is_in_script_path(const struct mg_connection *conn, const char *path)
  10184. {
  10185. /* TODO (Feature): Add config value for allowed script path.
  10186. * Default: All allowed. */
  10187. (void)conn;
  10188. (void)path;
  10189. return 1;
  10190. }
  10191. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10192. static int
  10193. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10194. void *cbdata)
  10195. {
  10196. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10197. if (pcallbacks->websocket_connect) {
  10198. return pcallbacks->websocket_connect(conn);
  10199. }
  10200. /* No handler set - assume "OK" */
  10201. return 0;
  10202. }
  10203. static void
  10204. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10205. {
  10206. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10207. if (pcallbacks->websocket_ready) {
  10208. pcallbacks->websocket_ready(conn);
  10209. }
  10210. }
  10211. static int
  10212. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10213. int bits,
  10214. char *data,
  10215. size_t len,
  10216. void *cbdata)
  10217. {
  10218. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10219. if (pcallbacks->websocket_data) {
  10220. return pcallbacks->websocket_data(conn, bits, data, len);
  10221. }
  10222. /* No handler set - assume "OK" */
  10223. return 1;
  10224. }
  10225. #endif
  10226. /* This is the heart of the Civetweb's logic.
  10227. * This function is called when the request is read, parsed and validated,
  10228. * and Civetweb must decide what action to take: serve a file, or
  10229. * a directory, or call embedded function, etcetera. */
  10230. static void
  10231. handle_request(struct mg_connection *conn)
  10232. {
  10233. struct mg_request_info *ri = &conn->request_info;
  10234. char path[PATH_MAX];
  10235. int uri_len, ssl_index;
  10236. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  10237. is_put_or_delete_request = 0, is_callback_resource = 0;
  10238. int i;
  10239. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10240. mg_request_handler callback_handler = NULL;
  10241. struct mg_websocket_subprotocols *subprotocols;
  10242. mg_websocket_connect_handler ws_connect_handler = NULL;
  10243. mg_websocket_ready_handler ws_ready_handler = NULL;
  10244. mg_websocket_data_handler ws_data_handler = NULL;
  10245. mg_websocket_close_handler ws_close_handler = NULL;
  10246. void *callback_data = NULL;
  10247. mg_authorization_handler auth_handler = NULL;
  10248. void *auth_callback_data = NULL;
  10249. int handler_type;
  10250. time_t curtime = time(NULL);
  10251. char date[64];
  10252. path[0] = 0;
  10253. /* 1. get the request url */
  10254. /* 1.1. split into url and query string */
  10255. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  10256. != NULL) {
  10257. *((char *)conn->request_info.query_string++) = '\0';
  10258. }
  10259. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  10260. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  10261. ssl_index = get_first_ssl_listener_index(conn->ctx);
  10262. if (ssl_index >= 0) {
  10263. redirect_to_https_port(conn, ssl_index);
  10264. } else {
  10265. /* A http to https forward port has been specified,
  10266. * but no https port to forward to. */
  10267. mg_send_http_error(conn,
  10268. 503,
  10269. "%s",
  10270. "Error: SSL forward not configured properly");
  10271. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  10272. }
  10273. return;
  10274. }
  10275. uri_len = (int)strlen(ri->local_uri);
  10276. /* 1.3. decode url (if config says so) */
  10277. if (should_decode_url(conn)) {
  10278. mg_url_decode(
  10279. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  10280. }
  10281. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  10282. * not possible */
  10283. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  10284. /* step 1. completed, the url is known now */
  10285. uri_len = (int)strlen(ri->local_uri);
  10286. DEBUG_TRACE("URL: %s", ri->local_uri);
  10287. /* 2. if this ip has limited speed, set it for this connection */
  10288. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  10289. get_remote_ip(conn),
  10290. ri->local_uri);
  10291. /* 3. call a "handle everything" callback, if registered */
  10292. if (conn->ctx->callbacks.begin_request != NULL) {
  10293. /* Note that since V1.7 the "begin_request" function is called
  10294. * before an authorization check. If an authorization check is
  10295. * required, use a request_handler instead. */
  10296. i = conn->ctx->callbacks.begin_request(conn);
  10297. if (i > 0) {
  10298. /* callback already processed the request. Store the
  10299. return value as a status code for the access log. */
  10300. conn->status_code = i;
  10301. discard_unread_request_data(conn);
  10302. return;
  10303. } else if (i == 0) {
  10304. /* civetweb should process the request */
  10305. } else {
  10306. /* unspecified - may change with the next version */
  10307. return;
  10308. }
  10309. }
  10310. /* request not yet handled by a handler or redirect, so the request
  10311. * is processed here */
  10312. /* 4. Check for CORS preflight requests and handle them (if configured).
  10313. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  10314. */
  10315. if (!strcmp(ri->request_method, "OPTIONS")) {
  10316. /* Send a response to CORS preflights only if
  10317. * access_control_allow_methods is not NULL and not an empty string.
  10318. * In this case, scripts can still handle CORS. */
  10319. const char *cors_meth_cfg =
  10320. conn->ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  10321. const char *cors_orig_cfg =
  10322. conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10323. const char *cors_origin =
  10324. get_header(ri->http_headers, ri->num_headers, "Origin");
  10325. const char *cors_acrm = get_header(ri->http_headers,
  10326. ri->num_headers,
  10327. "Access-Control-Request-Method");
  10328. /* Todo: check if cors_origin is in cors_orig_cfg.
  10329. * Or, let the client check this. */
  10330. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  10331. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  10332. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  10333. /* This is a valid CORS preflight, and the server is configured to
  10334. * handle it automatically. */
  10335. const char *cors_acrh =
  10336. get_header(ri->http_headers,
  10337. ri->num_headers,
  10338. "Access-Control-Request-Headers");
  10339. gmt_time_string(date, sizeof(date), &curtime);
  10340. mg_printf(conn,
  10341. "HTTP/1.1 200 OK\r\n"
  10342. "Date: %s\r\n"
  10343. "Access-Control-Allow-Origin: %s\r\n"
  10344. "Access-Control-Allow-Methods: %s\r\n"
  10345. "Content-Length: 0\r\n"
  10346. "Connection: %s\r\n",
  10347. date,
  10348. cors_orig_cfg,
  10349. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  10350. suggest_connection_header(conn));
  10351. if (cors_acrh != NULL) {
  10352. /* CORS request is asking for additional headers */
  10353. const char *cors_hdr_cfg =
  10354. conn->ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  10355. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  10356. /* Allow only if access_control_allow_headers is
  10357. * not NULL and not an empty string. If this
  10358. * configuration is set to *, allow everything.
  10359. * Otherwise this configuration must be a list
  10360. * of allowed HTTP header names. */
  10361. mg_printf(conn,
  10362. "Access-Control-Allow-Headers: %s\r\n",
  10363. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  10364. : cors_hdr_cfg));
  10365. }
  10366. }
  10367. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  10368. mg_printf(conn, "\r\n");
  10369. return;
  10370. }
  10371. }
  10372. /* 5. interpret the url to find out how the request must be handled
  10373. */
  10374. /* 5.1. first test, if the request targets the regular http(s)://
  10375. * protocol namespace or the websocket ws(s):// protocol namespace.
  10376. */
  10377. is_websocket_request = is_websocket_protocol(conn);
  10378. #if defined(USE_WEBSOCKET)
  10379. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  10380. #else
  10381. handler_type = REQUEST_HANDLER;
  10382. #endif /* defined(USE_WEBSOCKET) */
  10383. /* 5.2. check if the request will be handled by a callback */
  10384. if (get_request_handler(conn,
  10385. handler_type,
  10386. &callback_handler,
  10387. &subprotocols,
  10388. &ws_connect_handler,
  10389. &ws_ready_handler,
  10390. &ws_data_handler,
  10391. &ws_close_handler,
  10392. NULL,
  10393. &callback_data)) {
  10394. /* 5.2.1. A callback will handle this request. All requests
  10395. * handled
  10396. * by a callback have to be considered as requests to a script
  10397. * resource. */
  10398. is_callback_resource = 1;
  10399. is_script_resource = 1;
  10400. is_put_or_delete_request = is_put_or_delete_method(conn);
  10401. } else {
  10402. no_callback_resource:
  10403. /* 5.2.2. No callback is responsible for this request. The URI
  10404. * addresses a file based resource (static content or Lua/cgi
  10405. * scripts in the file system). */
  10406. is_callback_resource = 0;
  10407. interpret_uri(conn,
  10408. path,
  10409. sizeof(path),
  10410. &file.stat,
  10411. &is_found,
  10412. &is_script_resource,
  10413. &is_websocket_request,
  10414. &is_put_or_delete_request);
  10415. }
  10416. /* 6. authorization check */
  10417. /* 6.1. a custom authorization handler is installed */
  10418. if (get_request_handler(conn,
  10419. AUTH_HANDLER,
  10420. NULL,
  10421. NULL,
  10422. NULL,
  10423. NULL,
  10424. NULL,
  10425. NULL,
  10426. &auth_handler,
  10427. &auth_callback_data)) {
  10428. if (!auth_handler(conn, auth_callback_data)) {
  10429. return;
  10430. }
  10431. } else if (is_put_or_delete_request && !is_script_resource
  10432. && !is_callback_resource) {
  10433. /* 6.2. this request is a PUT/DELETE to a real file */
  10434. /* 6.2.1. thus, the server must have real files */
  10435. #if defined(NO_FILES)
  10436. if (1) {
  10437. #else
  10438. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10439. #endif
  10440. /* This server does not have any real files, thus the
  10441. * PUT/DELETE methods are not valid. */
  10442. mg_send_http_error(conn,
  10443. 405,
  10444. "%s method not allowed",
  10445. conn->request_info.request_method);
  10446. return;
  10447. }
  10448. #if !defined(NO_FILES)
  10449. /* 6.2.2. Check if put authorization for static files is
  10450. * available.
  10451. */
  10452. if (!is_authorized_for_put(conn)) {
  10453. send_authorization_request(conn);
  10454. return;
  10455. }
  10456. #endif
  10457. } else {
  10458. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  10459. * or it is a PUT or DELETE request to a resource that does not
  10460. * correspond to a file. Check authorization. */
  10461. if (!check_authorization(conn, path)) {
  10462. send_authorization_request(conn);
  10463. return;
  10464. }
  10465. }
  10466. /* request is authorized or does not need authorization */
  10467. /* 7. check if there are request handlers for this uri */
  10468. if (is_callback_resource) {
  10469. if (!is_websocket_request) {
  10470. i = callback_handler(conn, callback_data);
  10471. if (i > 0) {
  10472. /* Do nothing, callback has served the request. Store
  10473. * then return value as status code for the log and discard
  10474. * all data from the client not used by the callback. */
  10475. conn->status_code = i;
  10476. discard_unread_request_data(conn);
  10477. } else {
  10478. /* The handler did NOT handle the request. */
  10479. /* Some proper reactions would be:
  10480. * a) close the connections without sending anything
  10481. * b) send a 404 not found
  10482. * c) try if there is a file matching the URI
  10483. * It would be possible to do a, b or c in the callback
  10484. * implementation, and return 1 - we cannot do anything
  10485. * here, that is not possible in the callback.
  10486. *
  10487. * TODO: What would be the best reaction here?
  10488. * (Note: The reaction may change, if there is a better idea.)
  10489. */
  10490. /* For the moment, use option c: We look for a proper file,
  10491. * but since a file request is not always a script resource,
  10492. * the authorization check might be different. */
  10493. interpret_uri(conn,
  10494. path,
  10495. sizeof(path),
  10496. &file.stat,
  10497. &is_found,
  10498. &is_script_resource,
  10499. &is_websocket_request,
  10500. &is_put_or_delete_request);
  10501. callback_handler = NULL;
  10502. /* Here we are at a dead end:
  10503. * According to URI matching, a callback should be
  10504. * responsible for handling the request,
  10505. * we called it, but the callback declared itself
  10506. * not responsible.
  10507. * We use a goto here, to get out of this dead end,
  10508. * and continue with the default handling.
  10509. * A goto here is simpler and better to understand
  10510. * than some curious loop. */
  10511. goto no_callback_resource;
  10512. }
  10513. } else {
  10514. #if defined(USE_WEBSOCKET)
  10515. handle_websocket_request(conn,
  10516. path,
  10517. is_callback_resource,
  10518. subprotocols,
  10519. ws_connect_handler,
  10520. ws_ready_handler,
  10521. ws_data_handler,
  10522. ws_close_handler,
  10523. callback_data);
  10524. #endif
  10525. }
  10526. return;
  10527. }
  10528. /* 8. handle websocket requests */
  10529. #if defined(USE_WEBSOCKET)
  10530. if (is_websocket_request) {
  10531. if (is_script_resource) {
  10532. if (is_in_script_path(conn, path)) {
  10533. /* Websocket Lua script */
  10534. handle_websocket_request(conn,
  10535. path,
  10536. 0 /* Lua Script */,
  10537. NULL,
  10538. NULL,
  10539. NULL,
  10540. NULL,
  10541. NULL,
  10542. &conn->ctx->callbacks);
  10543. } else {
  10544. /* Script was in an illegal path */
  10545. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10546. }
  10547. } else {
  10548. #if defined(MG_LEGACY_INTERFACE)
  10549. handle_websocket_request(
  10550. conn,
  10551. path,
  10552. !is_script_resource /* could be deprecated global callback */,
  10553. NULL,
  10554. deprecated_websocket_connect_wrapper,
  10555. deprecated_websocket_ready_wrapper,
  10556. deprecated_websocket_data_wrapper,
  10557. NULL,
  10558. &conn->ctx->callbacks);
  10559. #else
  10560. mg_send_http_error(conn, 404, "%s", "Not found");
  10561. #endif
  10562. }
  10563. return;
  10564. } else
  10565. #endif
  10566. #if defined(NO_FILES)
  10567. /* 9a. In case the server uses only callbacks, this uri is
  10568. * unknown.
  10569. * Then, all request handling ends here. */
  10570. mg_send_http_error(conn, 404, "%s", "Not Found");
  10571. #else
  10572. /* 9b. This request is either for a static file or resource handled
  10573. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  10574. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10575. mg_send_http_error(conn, 404, "%s", "Not Found");
  10576. return;
  10577. }
  10578. /* 10. Request is handled by a script */
  10579. if (is_script_resource) {
  10580. handle_file_based_request(conn, path, &file);
  10581. return;
  10582. }
  10583. /* 11. Handle put/delete/mkcol requests */
  10584. if (is_put_or_delete_request) {
  10585. /* 11.1. PUT method */
  10586. if (!strcmp(ri->request_method, "PUT")) {
  10587. put_file(conn, path);
  10588. return;
  10589. }
  10590. /* 11.2. DELETE method */
  10591. if (!strcmp(ri->request_method, "DELETE")) {
  10592. delete_file(conn, path);
  10593. return;
  10594. }
  10595. /* 11.3. MKCOL method */
  10596. if (!strcmp(ri->request_method, "MKCOL")) {
  10597. mkcol(conn, path);
  10598. return;
  10599. }
  10600. /* 11.4. PATCH method
  10601. * This method is not supported for static resources,
  10602. * only for scripts (Lua, CGI) and callbacks. */
  10603. mg_send_http_error(conn,
  10604. 405,
  10605. "%s method not allowed",
  10606. conn->request_info.request_method);
  10607. return;
  10608. }
  10609. /* 11. File does not exist, or it was configured that it should be
  10610. * hidden */
  10611. if (!is_found || (must_hide_file(conn, path))) {
  10612. mg_send_http_error(conn, 404, "%s", "Not found");
  10613. return;
  10614. }
  10615. /* 12. Directory uris should end with a slash */
  10616. if (file.stat.is_directory && (uri_len > 0)
  10617. && (ri->local_uri[uri_len - 1] != '/')) {
  10618. gmt_time_string(date, sizeof(date), &curtime);
  10619. mg_printf(conn,
  10620. "HTTP/1.1 301 Moved Permanently\r\n"
  10621. "Location: %s/\r\n"
  10622. "Date: %s\r\n"
  10623. /* "Cache-Control: private\r\n" (= default) */
  10624. "Content-Length: 0\r\n"
  10625. "Connection: %s\r\n",
  10626. ri->request_uri,
  10627. date,
  10628. suggest_connection_header(conn));
  10629. send_additional_header(conn);
  10630. mg_printf(conn, "\r\n");
  10631. return;
  10632. }
  10633. /* 13. Handle other methods than GET/HEAD */
  10634. /* 13.1. Handle PROPFIND */
  10635. if (!strcmp(ri->request_method, "PROPFIND")) {
  10636. handle_propfind(conn, path, &file.stat);
  10637. return;
  10638. }
  10639. /* 13.2. Handle OPTIONS for files */
  10640. if (!strcmp(ri->request_method, "OPTIONS")) {
  10641. /* This standard handler is only used for real files.
  10642. * Scripts should support the OPTIONS method themselves, to allow a
  10643. * maximum flexibility.
  10644. * Lua and CGI scripts may fully support CORS this way (including
  10645. * preflights). */
  10646. send_options(conn);
  10647. return;
  10648. }
  10649. /* 13.3. everything but GET and HEAD (e.g. POST) */
  10650. if ((0 != strcmp(ri->request_method, "GET"))
  10651. && (0 != strcmp(ri->request_method, "HEAD"))) {
  10652. mg_send_http_error(conn,
  10653. 405,
  10654. "%s method not allowed",
  10655. conn->request_info.request_method);
  10656. return;
  10657. }
  10658. /* 14. directories */
  10659. if (file.stat.is_directory) {
  10660. /* Substitute files have already been handled above. */
  10661. /* Here we can either generate and send a directory listing,
  10662. * or send an "access denied" error. */
  10663. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  10664. "yes")) {
  10665. handle_directory_request(conn, path);
  10666. } else {
  10667. mg_send_http_error(conn,
  10668. 403,
  10669. "%s",
  10670. "Error: Directory listing denied");
  10671. }
  10672. return;
  10673. }
  10674. handle_file_based_request(conn, path, &file);
  10675. #endif /* !defined(NO_FILES) */
  10676. #if 0
  10677. /* Perform redirect and auth checks before calling begin_request()
  10678. * handler.
  10679. * Otherwise, begin_request() would need to perform auth checks and
  10680. * redirects. */
  10681. #endif
  10682. }
  10683. static void
  10684. handle_file_based_request(struct mg_connection *conn,
  10685. const char *path,
  10686. struct mg_file *file)
  10687. {
  10688. if (!conn || !conn->ctx) {
  10689. return;
  10690. }
  10691. if (0) {
  10692. #ifdef USE_LUA
  10693. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10694. strlen(
  10695. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10696. path) > 0) {
  10697. if (is_in_script_path(conn, path)) {
  10698. /* Lua server page: an SSI like page containing mostly plain html
  10699. * code
  10700. * plus some tags with server generated contents. */
  10701. handle_lsp_request(conn, path, file, NULL);
  10702. } else {
  10703. /* Script was in an illegal path */
  10704. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10705. }
  10706. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10707. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10708. path) > 0) {
  10709. if (is_in_script_path(conn, path)) {
  10710. /* Lua in-server module script: a CGI like script used to generate
  10711. * the
  10712. * entire reply. */
  10713. mg_exec_lua_script(conn, path, NULL);
  10714. } else {
  10715. /* Script was in an illegal path */
  10716. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10717. }
  10718. #endif
  10719. #if defined(USE_DUKTAPE)
  10720. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10721. strlen(
  10722. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10723. path) > 0) {
  10724. if (is_in_script_path(conn, path)) {
  10725. /* Call duktape to generate the page */
  10726. mg_exec_duktape_script(conn, path);
  10727. } else {
  10728. /* Script was in an illegal path */
  10729. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10730. }
  10731. #endif
  10732. #if !defined(NO_CGI)
  10733. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10734. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10735. path) > 0) {
  10736. if (is_in_script_path(conn, path)) {
  10737. /* CGI scripts may support all HTTP methods */
  10738. handle_cgi_request(conn, path);
  10739. } else {
  10740. /* Script was in an illegal path */
  10741. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10742. }
  10743. #endif /* !NO_CGI */
  10744. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10745. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10746. path) > 0) {
  10747. if (is_in_script_path(conn, path)) {
  10748. handle_ssi_file_request(conn, path, file);
  10749. } else {
  10750. /* Script was in an illegal path */
  10751. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10752. }
  10753. #if !defined(NO_CACHING)
  10754. } else if ((!conn->in_error_handler)
  10755. && is_not_modified(conn, &file->stat)) {
  10756. /* Send 304 "Not Modified" - this must not send any body data */
  10757. handle_not_modified_static_file_request(conn, file);
  10758. #endif /* !NO_CACHING */
  10759. } else {
  10760. handle_static_file_request(conn, path, file, NULL, NULL);
  10761. }
  10762. }
  10763. static void
  10764. close_all_listening_sockets(struct mg_context *ctx)
  10765. {
  10766. unsigned int i;
  10767. if (!ctx) {
  10768. return;
  10769. }
  10770. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10771. closesocket(ctx->listening_sockets[i].sock);
  10772. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10773. }
  10774. mg_free(ctx->listening_sockets);
  10775. ctx->listening_sockets = NULL;
  10776. mg_free(ctx->listening_socket_fds);
  10777. ctx->listening_socket_fds = NULL;
  10778. }
  10779. /* Valid listening port specification is: [ip_address:]port[s]
  10780. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10781. * Examples for IPv6: [::]:80, [::1]:80,
  10782. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10783. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10784. * In order to bind to both, IPv4 and IPv6, you can either add
  10785. * both ports using 8080,[::]:8080, or the short form +8080.
  10786. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10787. * one only accepting IPv4 the other only IPv6. +8080 creates
  10788. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10789. * environment, they might work differently, or might not work
  10790. * at all - it must be tested what options work best in the
  10791. * relevant network environment.
  10792. */
  10793. static int
  10794. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10795. {
  10796. unsigned int a, b, c, d, port;
  10797. int ch, len;
  10798. char *cb;
  10799. #if defined(USE_IPV6)
  10800. char buf[100] = {0};
  10801. #endif
  10802. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10803. * Also, all-zeroes in the socket address means binding to all addresses
  10804. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10805. memset(so, 0, sizeof(*so));
  10806. so->lsa.sin.sin_family = AF_INET;
  10807. *ip_version = 0;
  10808. /* Initialize port and len as invalid. */
  10809. port = 0;
  10810. len = 0;
  10811. /* Test for different ways to format this string */
  10812. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10813. == 5) {
  10814. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10815. so->lsa.sin.sin_addr.s_addr =
  10816. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10817. so->lsa.sin.sin_port = htons((uint16_t)port);
  10818. *ip_version = 4;
  10819. #if defined(USE_IPV6)
  10820. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10821. && mg_inet_pton(
  10822. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10823. /* IPv6 address, examples: see above */
  10824. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10825. */
  10826. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10827. *ip_version = 6;
  10828. #endif
  10829. } else if ((vec->ptr[0] == '+')
  10830. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10831. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10832. /* Add 1 to len for the + character we skipped before */
  10833. len++;
  10834. #if defined(USE_IPV6)
  10835. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10836. so->lsa.sin6.sin6_family = AF_INET6;
  10837. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10838. *ip_version = 4 + 6;
  10839. #else
  10840. /* Bind to IPv4 only, since IPv6 is not built in. */
  10841. so->lsa.sin.sin_port = htons((uint16_t)port);
  10842. *ip_version = 4;
  10843. #endif
  10844. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10845. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10846. so->lsa.sin.sin_port = htons((uint16_t)port);
  10847. *ip_version = 4;
  10848. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  10849. /* Could be a hostname */
  10850. /* Will only work for RFC 952 compliant hostnames,
  10851. * starting with a letter, containing only letters,
  10852. * digits and hyphen ('-'). Newer specs may allow
  10853. * more, but this is not guaranteed here, since it
  10854. * may interfere with rules for port option lists. */
  10855. *cb = 0;
  10856. if (mg_inet_pton(
  10857. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  10858. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  10859. *ip_version = 4;
  10860. so->lsa.sin.sin_family = AF_INET;
  10861. so->lsa.sin.sin_port = htons((uint16_t)port);
  10862. len += (int)(cb - vec->ptr) + 1;
  10863. } else {
  10864. port = 0;
  10865. len = 0;
  10866. }
  10867. #if defined(USE_IPV6)
  10868. } else if (mg_inet_pton(AF_INET6,
  10869. vec->ptr,
  10870. &so->lsa.sin6,
  10871. sizeof(so->lsa.sin6))) {
  10872. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  10873. *ip_version = 6;
  10874. so->lsa.sin6.sin6_family = AF_INET6;
  10875. so->lsa.sin.sin_port = htons((uint16_t)port);
  10876. len += (int)(cb - vec->ptr) + 1;
  10877. } else {
  10878. port = 0;
  10879. len = 0;
  10880. }
  10881. #endif
  10882. }
  10883. *cb = ':';
  10884. } else {
  10885. /* Parsing failure. */
  10886. }
  10887. /* sscanf and the option splitting code ensure the following condition
  10888. */
  10889. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  10890. *ip_version = 0;
  10891. return 0;
  10892. }
  10893. ch = vec->ptr[len]; /* Next character after the port number */
  10894. so->is_ssl = (ch == 's');
  10895. so->ssl_redir = (ch == 'r');
  10896. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  10897. if (is_valid_port(port)
  10898. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  10899. return 1;
  10900. }
  10901. /* Reset ip_version to 0 of there is an error */
  10902. *ip_version = 0;
  10903. return 0;
  10904. }
  10905. static int
  10906. set_ports_option(struct mg_context *ctx)
  10907. {
  10908. const char *list;
  10909. int on = 1;
  10910. #if defined(USE_IPV6)
  10911. int off = 0;
  10912. #endif
  10913. struct vec vec;
  10914. struct socket so, *ptr;
  10915. struct pollfd *pfd;
  10916. union usa usa;
  10917. socklen_t len;
  10918. int ip_version;
  10919. int portsTotal = 0;
  10920. int portsOk = 0;
  10921. if (!ctx) {
  10922. return 0;
  10923. }
  10924. memset(&so, 0, sizeof(so));
  10925. memset(&usa, 0, sizeof(usa));
  10926. len = sizeof(usa);
  10927. list = ctx->config[LISTENING_PORTS];
  10928. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10929. portsTotal++;
  10930. if (!parse_port_string(&vec, &so, &ip_version)) {
  10931. mg_cry(fc(ctx),
  10932. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  10933. (int)vec.len,
  10934. vec.ptr,
  10935. portsTotal,
  10936. "[IP_ADDRESS:]PORT[s|r]");
  10937. continue;
  10938. }
  10939. #if !defined(NO_SSL)
  10940. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10941. mg_cry(fc(ctx),
  10942. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10943. "option set?",
  10944. portsTotal);
  10945. continue;
  10946. }
  10947. #endif
  10948. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10949. == INVALID_SOCKET) {
  10950. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10951. continue;
  10952. }
  10953. #ifdef _WIN32
  10954. /* Windows SO_REUSEADDR lets many procs binds to a
  10955. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10956. * if someone already has the socket -- DTL */
  10957. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10958. * Windows might need a few seconds before
  10959. * the same port can be used again in the
  10960. * same process, so a short Sleep may be
  10961. * required between mg_stop and mg_start.
  10962. */
  10963. if (setsockopt(so.sock,
  10964. SOL_SOCKET,
  10965. SO_EXCLUSIVEADDRUSE,
  10966. (SOCK_OPT_TYPE)&on,
  10967. sizeof(on)) != 0) {
  10968. /* Set reuse option, but don't abort on errors. */
  10969. mg_cry(fc(ctx),
  10970. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10971. portsTotal);
  10972. }
  10973. #else
  10974. if (setsockopt(so.sock,
  10975. SOL_SOCKET,
  10976. SO_REUSEADDR,
  10977. (SOCK_OPT_TYPE)&on,
  10978. sizeof(on)) != 0) {
  10979. /* Set reuse option, but don't abort on errors. */
  10980. mg_cry(fc(ctx),
  10981. "cannot set socket option SO_REUSEADDR (entry %i)",
  10982. portsTotal);
  10983. }
  10984. #endif
  10985. if (ip_version > 4) {
  10986. #if defined(USE_IPV6)
  10987. if (ip_version == 6) {
  10988. if (so.lsa.sa.sa_family == AF_INET6
  10989. && setsockopt(so.sock,
  10990. IPPROTO_IPV6,
  10991. IPV6_V6ONLY,
  10992. (void *)&off,
  10993. sizeof(off)) != 0) {
  10994. /* Set IPv6 only option, but don't abort on errors. */
  10995. mg_cry(fc(ctx),
  10996. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10997. portsTotal);
  10998. }
  10999. }
  11000. #else
  11001. mg_cry(fc(ctx), "IPv6 not available");
  11002. closesocket(so.sock);
  11003. so.sock = INVALID_SOCKET;
  11004. continue;
  11005. #endif
  11006. }
  11007. if (so.lsa.sa.sa_family == AF_INET) {
  11008. len = sizeof(so.lsa.sin);
  11009. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11010. mg_cry(fc(ctx),
  11011. "cannot bind to %.*s: %d (%s)",
  11012. (int)vec.len,
  11013. vec.ptr,
  11014. (int)ERRNO,
  11015. strerror(errno));
  11016. closesocket(so.sock);
  11017. so.sock = INVALID_SOCKET;
  11018. continue;
  11019. }
  11020. }
  11021. #if defined(USE_IPV6)
  11022. else if (so.lsa.sa.sa_family == AF_INET6) {
  11023. len = sizeof(so.lsa.sin6);
  11024. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11025. mg_cry(fc(ctx),
  11026. "cannot bind to IPv6 %.*s: %d (%s)",
  11027. (int)vec.len,
  11028. vec.ptr,
  11029. (int)ERRNO,
  11030. strerror(errno));
  11031. closesocket(so.sock);
  11032. so.sock = INVALID_SOCKET;
  11033. continue;
  11034. }
  11035. }
  11036. #endif
  11037. else {
  11038. mg_cry(fc(ctx),
  11039. "cannot bind: address family not supported (entry %i)",
  11040. portsTotal);
  11041. closesocket(so.sock);
  11042. so.sock = INVALID_SOCKET;
  11043. continue;
  11044. }
  11045. if (listen(so.sock, SOMAXCONN) != 0) {
  11046. mg_cry(fc(ctx),
  11047. "cannot listen to %.*s: %d (%s)",
  11048. (int)vec.len,
  11049. vec.ptr,
  11050. (int)ERRNO,
  11051. strerror(errno));
  11052. closesocket(so.sock);
  11053. so.sock = INVALID_SOCKET;
  11054. continue;
  11055. }
  11056. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  11057. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  11058. int err = (int)ERRNO;
  11059. mg_cry(fc(ctx),
  11060. "call to getsockname failed %.*s: %d (%s)",
  11061. (int)vec.len,
  11062. vec.ptr,
  11063. err,
  11064. strerror(errno));
  11065. closesocket(so.sock);
  11066. so.sock = INVALID_SOCKET;
  11067. continue;
  11068. }
  11069. /* Update lsa port in case of random free ports */
  11070. #if defined(USE_IPV6)
  11071. if (so.lsa.sa.sa_family == AF_INET6) {
  11072. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  11073. } else
  11074. #endif
  11075. {
  11076. so.lsa.sin.sin_port = usa.sin.sin_port;
  11077. }
  11078. if ((ptr = (struct socket *)
  11079. mg_realloc_ctx(ctx->listening_sockets,
  11080. (ctx->num_listening_sockets + 1)
  11081. * sizeof(ctx->listening_sockets[0]),
  11082. ctx)) == NULL) {
  11083. mg_cry(fc(ctx), "%s", "Out of memory");
  11084. closesocket(so.sock);
  11085. so.sock = INVALID_SOCKET;
  11086. continue;
  11087. }
  11088. if ((pfd = (struct pollfd *)
  11089. mg_realloc_ctx(ctx->listening_socket_fds,
  11090. (ctx->num_listening_sockets + 1)
  11091. * sizeof(ctx->listening_socket_fds[0]),
  11092. ctx)) == NULL) {
  11093. mg_cry(fc(ctx), "%s", "Out of memory");
  11094. closesocket(so.sock);
  11095. so.sock = INVALID_SOCKET;
  11096. mg_free(ptr);
  11097. continue;
  11098. }
  11099. set_close_on_exec(so.sock, fc(ctx));
  11100. ctx->listening_sockets = ptr;
  11101. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  11102. ctx->listening_socket_fds = pfd;
  11103. ctx->num_listening_sockets++;
  11104. portsOk++;
  11105. }
  11106. if (portsOk != portsTotal) {
  11107. close_all_listening_sockets(ctx);
  11108. portsOk = 0;
  11109. }
  11110. return portsOk;
  11111. }
  11112. static const char *
  11113. header_val(const struct mg_connection *conn, const char *header)
  11114. {
  11115. const char *header_value;
  11116. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11117. return "-";
  11118. } else {
  11119. return header_value;
  11120. }
  11121. }
  11122. static void
  11123. log_access(const struct mg_connection *conn)
  11124. {
  11125. const struct mg_request_info *ri;
  11126. struct mg_file fi;
  11127. char date[64], src_addr[IP_ADDR_STR_LEN];
  11128. struct tm *tm;
  11129. const char *referer;
  11130. const char *user_agent;
  11131. char buf[4096];
  11132. if (!conn || !conn->ctx) {
  11133. return;
  11134. }
  11135. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  11136. if (mg_fopen(conn,
  11137. conn->ctx->config[ACCESS_LOG_FILE],
  11138. MG_FOPEN_MODE_APPEND,
  11139. &fi) == 0) {
  11140. fi.access.fp = NULL;
  11141. }
  11142. } else {
  11143. fi.access.fp = NULL;
  11144. }
  11145. /* Log is written to a file and/or a callback. If both are not set,
  11146. * executing the rest of the function is pointless. */
  11147. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  11148. return;
  11149. }
  11150. tm = localtime(&conn->conn_birth_time);
  11151. if (tm != NULL) {
  11152. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11153. } else {
  11154. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11155. date[sizeof(date) - 1] = '\0';
  11156. }
  11157. ri = &conn->request_info;
  11158. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11159. referer = header_val(conn, "Referer");
  11160. user_agent = header_val(conn, "User-Agent");
  11161. mg_snprintf(conn,
  11162. NULL, /* Ignore truncation in access log */
  11163. buf,
  11164. sizeof(buf),
  11165. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11166. src_addr,
  11167. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11168. date,
  11169. ri->request_method ? ri->request_method : "-",
  11170. ri->request_uri ? ri->request_uri : "-",
  11171. ri->query_string ? "?" : "",
  11172. ri->query_string ? ri->query_string : "",
  11173. ri->http_version,
  11174. conn->status_code,
  11175. conn->num_bytes_sent,
  11176. referer,
  11177. user_agent);
  11178. if (conn->ctx->callbacks.log_access) {
  11179. conn->ctx->callbacks.log_access(conn, buf);
  11180. }
  11181. if (fi.access.fp) {
  11182. int ok = 1;
  11183. flockfile(fi.access.fp);
  11184. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11185. ok = 0;
  11186. }
  11187. if (fflush(fi.access.fp) != 0) {
  11188. ok = 0;
  11189. }
  11190. funlockfile(fi.access.fp);
  11191. if (mg_fclose(&fi.access) != 0) {
  11192. ok = 0;
  11193. }
  11194. if (!ok) {
  11195. mg_cry(conn,
  11196. "Error writing log file %s",
  11197. conn->ctx->config[ACCESS_LOG_FILE]);
  11198. }
  11199. }
  11200. }
  11201. /* Verify given socket address against the ACL.
  11202. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  11203. */
  11204. static int
  11205. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  11206. {
  11207. int allowed, flag;
  11208. uint32_t net, mask;
  11209. struct vec vec;
  11210. if (ctx) {
  11211. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  11212. /* If any ACL is set, deny by default */
  11213. allowed = (list == NULL) ? '+' : '-';
  11214. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11215. flag = vec.ptr[0];
  11216. if ((flag != '+' && flag != '-')
  11217. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  11218. mg_cry(fc(ctx),
  11219. "%s: subnet must be [+|-]x.x.x.x[/x]",
  11220. __func__);
  11221. return -1;
  11222. }
  11223. if (net == (remote_ip & mask)) {
  11224. allowed = flag;
  11225. }
  11226. }
  11227. return allowed == '+';
  11228. }
  11229. return -1;
  11230. }
  11231. #if !defined(_WIN32)
  11232. static int
  11233. set_uid_option(struct mg_context *ctx)
  11234. {
  11235. struct passwd *pw;
  11236. if (ctx) {
  11237. const char *uid = ctx->config[RUN_AS_USER];
  11238. int success = 0;
  11239. if (uid == NULL) {
  11240. success = 1;
  11241. } else {
  11242. if ((pw = getpwnam(uid)) == NULL) {
  11243. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  11244. } else if (setgid(pw->pw_gid) == -1) {
  11245. mg_cry(fc(ctx),
  11246. "%s: setgid(%s): %s",
  11247. __func__,
  11248. uid,
  11249. strerror(errno));
  11250. } else if (setgroups(0, NULL)) {
  11251. mg_cry(fc(ctx),
  11252. "%s: setgroups(): %s",
  11253. __func__,
  11254. strerror(errno));
  11255. } else if (setuid(pw->pw_uid) == -1) {
  11256. mg_cry(fc(ctx),
  11257. "%s: setuid(%s): %s",
  11258. __func__,
  11259. uid,
  11260. strerror(errno));
  11261. } else {
  11262. success = 1;
  11263. }
  11264. }
  11265. return success;
  11266. }
  11267. return 0;
  11268. }
  11269. #endif /* !_WIN32 */
  11270. static void
  11271. tls_dtor(void *key)
  11272. {
  11273. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  11274. /* key == pthread_getspecific(sTlsKey); */
  11275. if (tls) {
  11276. if (tls->is_master == 2) {
  11277. tls->is_master = -3; /* Mark memory as dead */
  11278. mg_free(tls);
  11279. }
  11280. }
  11281. pthread_setspecific(sTlsKey, NULL);
  11282. }
  11283. #if !defined(NO_SSL)
  11284. static int
  11285. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  11286. static const char *ssl_error(void);
  11287. static int
  11288. refresh_trust(struct mg_connection *conn)
  11289. {
  11290. static int reload_lock = 0;
  11291. static long int data_check = 0;
  11292. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  11293. struct stat cert_buf;
  11294. long int t;
  11295. const char *pem;
  11296. const char *chain;
  11297. int should_verify_peer;
  11298. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  11299. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  11300. * refresh_trust still can not work. */
  11301. return 0;
  11302. }
  11303. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  11304. if (chain == NULL) {
  11305. /* pem is not NULL here */
  11306. chain = pem;
  11307. }
  11308. if (*chain == 0) {
  11309. chain = NULL;
  11310. }
  11311. t = data_check;
  11312. if (stat(pem, &cert_buf) != -1) {
  11313. t = (long int)cert_buf.st_mtime;
  11314. }
  11315. if (data_check != t) {
  11316. data_check = t;
  11317. should_verify_peer = 0;
  11318. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11319. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  11320. == 0) {
  11321. should_verify_peer = 1;
  11322. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  11323. "optional") == 0) {
  11324. should_verify_peer = 1;
  11325. }
  11326. }
  11327. if (should_verify_peer) {
  11328. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  11329. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  11330. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  11331. ca_file,
  11332. ca_path) != 1) {
  11333. mg_cry(fc(conn->ctx),
  11334. "SSL_CTX_load_verify_locations error: %s "
  11335. "ssl_verify_peer requires setting "
  11336. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11337. "present in "
  11338. "the .conf file?",
  11339. ssl_error());
  11340. return 0;
  11341. }
  11342. }
  11343. if (1 == mg_atomic_inc(p_reload_lock)) {
  11344. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  11345. return 0;
  11346. }
  11347. *p_reload_lock = 0;
  11348. }
  11349. }
  11350. /* lock while cert is reloading */
  11351. while (*p_reload_lock) {
  11352. sleep(1);
  11353. }
  11354. return 1;
  11355. }
  11356. #ifdef OPENSSL_API_1_1
  11357. #else
  11358. static pthread_mutex_t *ssl_mutexes;
  11359. #endif /* OPENSSL_API_1_1 */
  11360. static int
  11361. sslize(struct mg_connection *conn,
  11362. SSL_CTX *s,
  11363. int (*func)(SSL *),
  11364. volatile int *stop_server)
  11365. {
  11366. int ret, err;
  11367. int short_trust;
  11368. unsigned i;
  11369. if (!conn) {
  11370. return 0;
  11371. }
  11372. short_trust =
  11373. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  11374. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  11375. if (short_trust) {
  11376. int trust_ret = refresh_trust(conn);
  11377. if (!trust_ret) {
  11378. return trust_ret;
  11379. }
  11380. }
  11381. conn->ssl = SSL_new(s);
  11382. if (conn->ssl == NULL) {
  11383. return 0;
  11384. }
  11385. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  11386. if (ret != 1) {
  11387. err = SSL_get_error(conn->ssl, ret);
  11388. (void)err; /* TODO: set some error message */
  11389. SSL_free(conn->ssl);
  11390. conn->ssl = NULL;
  11391. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11392. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11393. #ifndef OPENSSL_API_1_1
  11394. ERR_remove_state(0);
  11395. #endif
  11396. return 0;
  11397. }
  11398. /* SSL functions may fail and require to be called again:
  11399. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  11400. * Here "func" could be SSL_connect or SSL_accept. */
  11401. for (i = 16; i <= 1024; i *= 2) {
  11402. ret = func(conn->ssl);
  11403. if (ret != 1) {
  11404. err = SSL_get_error(conn->ssl, ret);
  11405. if ((err == SSL_ERROR_WANT_CONNECT)
  11406. || (err == SSL_ERROR_WANT_ACCEPT)
  11407. || (err == SSL_ERROR_WANT_READ)
  11408. || (err == SSL_ERROR_WANT_WRITE)) {
  11409. /* Need to retry the function call "later".
  11410. * See https://linux.die.net/man/3/ssl_get_error
  11411. * This is typical for non-blocking sockets. */
  11412. if (*stop_server) {
  11413. /* Don't wait if the server is going to be stopped. */
  11414. break;
  11415. }
  11416. mg_sleep(i);
  11417. } else if (err == SSL_ERROR_SYSCALL) {
  11418. /* This is an IO error. Look at errno. */
  11419. err = errno;
  11420. /* TODO: set some error message */
  11421. (void)err;
  11422. break;
  11423. } else {
  11424. /* This is an SSL specific error */
  11425. /* TODO: set some error message */
  11426. break;
  11427. }
  11428. } else {
  11429. /* success */
  11430. break;
  11431. }
  11432. }
  11433. if (ret != 1) {
  11434. SSL_free(conn->ssl);
  11435. conn->ssl = NULL;
  11436. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11437. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11438. #ifndef OPENSSL_API_1_1
  11439. ERR_remove_state(0);
  11440. #endif
  11441. return 0;
  11442. }
  11443. return 1;
  11444. }
  11445. /* Return OpenSSL error message (from CRYPTO lib) */
  11446. static const char *
  11447. ssl_error(void)
  11448. {
  11449. unsigned long err;
  11450. err = ERR_get_error();
  11451. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  11452. }
  11453. static int
  11454. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  11455. {
  11456. int i;
  11457. const char hexdigit[] = "0123456789abcdef";
  11458. if ((memlen <= 0) || (buflen <= 0)) {
  11459. return 0;
  11460. }
  11461. if (buflen < (3 * memlen)) {
  11462. return 0;
  11463. }
  11464. for (i = 0; i < memlen; i++) {
  11465. if (i > 0) {
  11466. buf[3 * i - 1] = ' ';
  11467. }
  11468. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  11469. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  11470. }
  11471. buf[3 * memlen - 1] = 0;
  11472. return 1;
  11473. }
  11474. static void
  11475. ssl_get_client_cert_info(struct mg_connection *conn)
  11476. {
  11477. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  11478. if (cert) {
  11479. char str_subject[1024];
  11480. char str_issuer[1024];
  11481. char str_finger[1024];
  11482. unsigned char buf[256];
  11483. char *str_serial = NULL;
  11484. unsigned int ulen;
  11485. int ilen;
  11486. unsigned char *tmp_buf;
  11487. unsigned char *tmp_p;
  11488. /* Handle to algorithm used for fingerprint */
  11489. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  11490. /* Get Subject and issuer */
  11491. X509_NAME *subj = X509_get_subject_name(cert);
  11492. X509_NAME *iss = X509_get_issuer_name(cert);
  11493. /* Get serial number */
  11494. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  11495. /* Translate serial number to a hex string */
  11496. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  11497. str_serial = BN_bn2hex(serial_bn);
  11498. BN_free(serial_bn);
  11499. /* Translate subject and issuer to a string */
  11500. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  11501. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  11502. /* Calculate SHA1 fingerprint and store as a hex string */
  11503. ulen = 0;
  11504. /* ASN1_digest is deprecated. Do the calculation manually,
  11505. * using EVP_Digest. */
  11506. ilen = i2d_X509((void *)cert, NULL);
  11507. tmp_buf =
  11508. (ilen > 0)
  11509. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  11510. : NULL;
  11511. if (tmp_buf) {
  11512. tmp_p = tmp_buf;
  11513. (void)i2d_X509((void *)cert, &tmp_p);
  11514. if (!EVP_Digest(
  11515. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  11516. ulen = 0;
  11517. }
  11518. mg_free(tmp_buf);
  11519. }
  11520. if (!hexdump2string(
  11521. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  11522. *str_finger = 0;
  11523. }
  11524. conn->request_info.client_cert =
  11525. (struct client_cert *)mg_malloc_ctx(sizeof(struct client_cert),
  11526. conn->ctx);
  11527. if (conn->request_info.client_cert) {
  11528. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  11529. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  11530. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  11531. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  11532. } else {
  11533. mg_cry(
  11534. conn,
  11535. "Out of memory: Cannot allocate memory for client certificate");
  11536. }
  11537. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  11538. * see https://linux.die.net/man/3/bn_bn2hex */
  11539. OPENSSL_free(str_serial);
  11540. /* Free certificate memory */
  11541. X509_free(cert);
  11542. }
  11543. }
  11544. #ifdef OPENSSL_API_1_1
  11545. #else
  11546. static void
  11547. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  11548. {
  11549. (void)line;
  11550. (void)file;
  11551. if (mode & 1) {
  11552. /* 1 is CRYPTO_LOCK */
  11553. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  11554. } else {
  11555. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  11556. }
  11557. }
  11558. #endif /* OPENSSL_API_1_1 */
  11559. #if !defined(NO_SSL_DL)
  11560. static void *
  11561. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  11562. {
  11563. union {
  11564. void *p;
  11565. void (*fp)(void);
  11566. } u;
  11567. void *dll_handle;
  11568. struct ssl_func *fp;
  11569. int ok;
  11570. int truncated = 0;
  11571. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  11572. mg_snprintf(NULL,
  11573. NULL, /* No truncation check for ebuf */
  11574. ebuf,
  11575. ebuf_len,
  11576. "%s: cannot load %s",
  11577. __func__,
  11578. dll_name);
  11579. return NULL;
  11580. }
  11581. ok = 1;
  11582. for (fp = sw; fp->name != NULL; fp++) {
  11583. #ifdef _WIN32
  11584. /* GetProcAddress() returns pointer to function */
  11585. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  11586. #else
  11587. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  11588. * pointers to function pointers. We need to use a union to make a
  11589. * cast. */
  11590. u.p = dlsym(dll_handle, fp->name);
  11591. #endif /* _WIN32 */
  11592. if (u.fp == NULL) {
  11593. if (ok) {
  11594. mg_snprintf(NULL,
  11595. &truncated,
  11596. ebuf,
  11597. ebuf_len,
  11598. "%s: %s: cannot find %s",
  11599. __func__,
  11600. dll_name,
  11601. fp->name);
  11602. ok = 0;
  11603. } else {
  11604. size_t cur_len = strlen(ebuf);
  11605. if (!truncated) {
  11606. mg_snprintf(NULL,
  11607. &truncated,
  11608. ebuf + cur_len,
  11609. ebuf_len - cur_len - 3,
  11610. ", %s",
  11611. fp->name);
  11612. if (truncated) {
  11613. /* If truncated, add "..." */
  11614. strcat(ebuf, "...");
  11615. }
  11616. }
  11617. }
  11618. /* Debug:
  11619. * printf("Missing function: %s\n", fp->name); */
  11620. } else {
  11621. fp->ptr = u.fp;
  11622. }
  11623. }
  11624. if (!ok) {
  11625. (void)dlclose(dll_handle);
  11626. return NULL;
  11627. }
  11628. return dll_handle;
  11629. }
  11630. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  11631. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  11632. #endif /* NO_SSL_DL */
  11633. #if defined(SSL_ALREADY_INITIALIZED)
  11634. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  11635. #else
  11636. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  11637. #endif
  11638. static int
  11639. initialize_ssl(char *ebuf, size_t ebuf_len)
  11640. {
  11641. #ifdef OPENSSL_API_1_1
  11642. if (ebuf_len > 0) {
  11643. ebuf[0] = 0;
  11644. }
  11645. #if !defined(NO_SSL_DL)
  11646. if (!cryptolib_dll_handle) {
  11647. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11648. if (!cryptolib_dll_handle) {
  11649. return 0;
  11650. }
  11651. }
  11652. #endif /* NO_SSL_DL */
  11653. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11654. return 1;
  11655. }
  11656. #else /* not OPENSSL_API_1_1 */
  11657. int i;
  11658. size_t size;
  11659. if (ebuf_len > 0) {
  11660. ebuf[0] = 0;
  11661. }
  11662. #if !defined(NO_SSL_DL)
  11663. if (!cryptolib_dll_handle) {
  11664. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11665. if (!cryptolib_dll_handle) {
  11666. return 0;
  11667. }
  11668. }
  11669. #endif /* NO_SSL_DL */
  11670. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11671. return 1;
  11672. }
  11673. /* Initialize locking callbacks, needed for thread safety.
  11674. * http://www.openssl.org/support/faq.html#PROG1
  11675. */
  11676. i = CRYPTO_num_locks();
  11677. if (i < 0) {
  11678. i = 0;
  11679. }
  11680. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  11681. if (size == 0) {
  11682. ssl_mutexes = NULL;
  11683. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  11684. mg_snprintf(NULL,
  11685. NULL, /* No truncation check for ebuf */
  11686. ebuf,
  11687. ebuf_len,
  11688. "%s: cannot allocate mutexes: %s",
  11689. __func__,
  11690. ssl_error());
  11691. return 0;
  11692. }
  11693. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11694. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  11695. }
  11696. CRYPTO_set_locking_callback(&ssl_locking_callback);
  11697. CRYPTO_set_id_callback(&mg_current_thread_id);
  11698. #endif /* OPENSSL_API_1_1 */
  11699. return 1;
  11700. }
  11701. static int
  11702. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  11703. {
  11704. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  11705. mg_cry(fc(ctx),
  11706. "%s: cannot open certificate file %s: %s",
  11707. __func__,
  11708. pem,
  11709. ssl_error());
  11710. return 0;
  11711. }
  11712. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  11713. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  11714. mg_cry(fc(ctx),
  11715. "%s: cannot open private key file %s: %s",
  11716. __func__,
  11717. pem,
  11718. ssl_error());
  11719. return 0;
  11720. }
  11721. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  11722. mg_cry(fc(ctx),
  11723. "%s: certificate and private key do not match: %s",
  11724. __func__,
  11725. pem);
  11726. return 0;
  11727. }
  11728. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11729. * chain files that contain private keys and certificates in
  11730. * SSL_CTX_use_certificate_chain_file.
  11731. * The CivetWeb-Server used pem-Files that contained both information.
  11732. * In order to make wolfSSL work, it is split in two files.
  11733. * One file that contains key and certificate used by the server and
  11734. * an optional chain file for the ssl stack.
  11735. */
  11736. if (chain) {
  11737. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11738. mg_cry(fc(ctx),
  11739. "%s: cannot use certificate chain file %s: %s",
  11740. __func__,
  11741. pem,
  11742. ssl_error());
  11743. return 0;
  11744. }
  11745. }
  11746. return 1;
  11747. }
  11748. #ifdef OPENSSL_API_1_1
  11749. static unsigned long
  11750. ssl_get_protocol(int version_id)
  11751. {
  11752. long unsigned ret = SSL_OP_ALL;
  11753. if (version_id > 0)
  11754. ret |= SSL_OP_NO_SSLv2;
  11755. if (version_id > 1)
  11756. ret |= SSL_OP_NO_SSLv3;
  11757. if (version_id > 2)
  11758. ret |= SSL_OP_NO_TLSv1;
  11759. if (version_id > 3)
  11760. ret |= SSL_OP_NO_TLSv1_1;
  11761. return ret;
  11762. }
  11763. #else
  11764. static long
  11765. ssl_get_protocol(int version_id)
  11766. {
  11767. long ret = SSL_OP_ALL;
  11768. if (version_id > 0)
  11769. ret |= SSL_OP_NO_SSLv2;
  11770. if (version_id > 1)
  11771. ret |= SSL_OP_NO_SSLv3;
  11772. if (version_id > 2)
  11773. ret |= SSL_OP_NO_TLSv1;
  11774. if (version_id > 3)
  11775. ret |= SSL_OP_NO_TLSv1_1;
  11776. return ret;
  11777. }
  11778. #endif /* OPENSSL_API_1_1 */
  11779. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11780. static int
  11781. set_ssl_option(struct mg_context *ctx)
  11782. {
  11783. const char *pem;
  11784. const char *chain;
  11785. int callback_ret;
  11786. int should_verify_peer;
  11787. int peer_certificate_optional;
  11788. const char *ca_path;
  11789. const char *ca_file;
  11790. int use_default_verify_paths;
  11791. int verify_depth;
  11792. time_t now_rt = time(NULL);
  11793. struct timespec now_mt;
  11794. md5_byte_t ssl_context_id[16];
  11795. md5_state_t md5state;
  11796. int protocol_ver;
  11797. char ebuf[128];
  11798. /* If PEM file is not specified and the init_ssl callback
  11799. * is not specified, skip SSL initialization. */
  11800. if (!ctx) {
  11801. return 0;
  11802. }
  11803. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11804. && ctx->callbacks.init_ssl == NULL) {
  11805. return 1;
  11806. }
  11807. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11808. if (chain == NULL) {
  11809. chain = pem;
  11810. }
  11811. if ((chain != NULL) && (*chain == 0)) {
  11812. chain = NULL;
  11813. }
  11814. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11815. mg_cry(fc(ctx), "%s", ebuf);
  11816. return 0;
  11817. }
  11818. #if !defined(NO_SSL_DL)
  11819. if (!ssllib_dll_handle) {
  11820. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11821. if (!ssllib_dll_handle) {
  11822. mg_cry(fc(ctx), "%s", ebuf);
  11823. return 0;
  11824. }
  11825. }
  11826. #endif /* NO_SSL_DL */
  11827. #ifdef OPENSSL_API_1_1
  11828. /* Initialize SSL library */
  11829. OPENSSL_init_ssl(0, NULL);
  11830. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11831. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11832. NULL);
  11833. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11834. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11835. return 0;
  11836. }
  11837. #else
  11838. /* Initialize SSL library */
  11839. SSL_library_init();
  11840. SSL_load_error_strings();
  11841. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11842. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11843. return 0;
  11844. }
  11845. #endif /* OPENSSL_API_1_1 */
  11846. SSL_CTX_clear_options(ctx->ssl_ctx,
  11847. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11848. | SSL_OP_NO_TLSv1_1);
  11849. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11850. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11851. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11852. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11853. #if !defined(NO_SSL_DL)
  11854. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11855. #endif /* NO_SSL_DL */
  11856. /* If a callback has been specified, call it. */
  11857. callback_ret =
  11858. (ctx->callbacks.init_ssl == NULL)
  11859. ? 0
  11860. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11861. /* If callback returns 0, civetweb sets up the SSL certificate.
  11862. * If it returns 1, civetweb assumes the calback already did this.
  11863. * If it returns -1, initializing ssl fails. */
  11864. if (callback_ret < 0) {
  11865. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11866. return 0;
  11867. }
  11868. if (callback_ret > 0) {
  11869. if (pem != NULL) {
  11870. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11871. }
  11872. return 1;
  11873. }
  11874. /* Use some UID as session context ID. */
  11875. md5_init(&md5state);
  11876. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  11877. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  11878. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  11879. md5_append(&md5state,
  11880. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  11881. strlen(ctx->config[LISTENING_PORTS]));
  11882. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  11883. md5_finish(&md5state, ssl_context_id);
  11884. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  11885. (const unsigned char *)&ssl_context_id,
  11886. sizeof(ssl_context_id));
  11887. if (pem != NULL) {
  11888. if (!ssl_use_pem_file(ctx, pem, chain)) {
  11889. return 0;
  11890. }
  11891. }
  11892. /* Should we support client certificates? */
  11893. /* Default is "no". */
  11894. should_verify_peer = 0;
  11895. peer_certificate_optional = 0;
  11896. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11897. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  11898. /* Yes, they are mandatory */
  11899. should_verify_peer = 1;
  11900. peer_certificate_optional = 0;
  11901. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  11902. == 0) {
  11903. /* Yes, they are optional */
  11904. should_verify_peer = 1;
  11905. peer_certificate_optional = 1;
  11906. }
  11907. }
  11908. use_default_verify_paths =
  11909. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  11910. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  11911. if (should_verify_peer) {
  11912. ca_path = ctx->config[SSL_CA_PATH];
  11913. ca_file = ctx->config[SSL_CA_FILE];
  11914. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  11915. != 1) {
  11916. mg_cry(fc(ctx),
  11917. "SSL_CTX_load_verify_locations error: %s "
  11918. "ssl_verify_peer requires setting "
  11919. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11920. "present in "
  11921. "the .conf file?",
  11922. ssl_error());
  11923. return 0;
  11924. }
  11925. if (peer_certificate_optional) {
  11926. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  11927. } else {
  11928. SSL_CTX_set_verify(ctx->ssl_ctx,
  11929. SSL_VERIFY_PEER
  11930. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11931. NULL);
  11932. }
  11933. if (use_default_verify_paths
  11934. && (SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1)) {
  11935. mg_cry(fc(ctx),
  11936. "SSL_CTX_set_default_verify_paths error: %s",
  11937. ssl_error());
  11938. return 0;
  11939. }
  11940. if (ctx->config[SSL_VERIFY_DEPTH]) {
  11941. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  11942. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  11943. }
  11944. }
  11945. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  11946. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  11947. != 1) {
  11948. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  11949. }
  11950. }
  11951. return 1;
  11952. }
  11953. static void
  11954. uninitialize_ssl(void)
  11955. {
  11956. #ifdef OPENSSL_API_1_1
  11957. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11958. /* Shutdown according to
  11959. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11960. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11961. */
  11962. CONF_modules_unload(1);
  11963. #else
  11964. int i;
  11965. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11966. /* Shutdown according to
  11967. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11968. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11969. */
  11970. CRYPTO_set_locking_callback(NULL);
  11971. CRYPTO_set_id_callback(NULL);
  11972. ENGINE_cleanup();
  11973. CONF_modules_unload(1);
  11974. ERR_free_strings();
  11975. EVP_cleanup();
  11976. CRYPTO_cleanup_all_ex_data();
  11977. ERR_remove_state(0);
  11978. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11979. pthread_mutex_destroy(&ssl_mutexes[i]);
  11980. }
  11981. mg_free(ssl_mutexes);
  11982. ssl_mutexes = NULL;
  11983. #endif /* OPENSSL_API_1_1 */
  11984. }
  11985. }
  11986. #endif /* !NO_SSL */
  11987. static int
  11988. set_gpass_option(struct mg_context *ctx)
  11989. {
  11990. if (ctx) {
  11991. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11992. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  11993. if ((path != NULL) && !mg_stat(fc(ctx), path, &file.stat)) {
  11994. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  11995. return 0;
  11996. }
  11997. return 1;
  11998. }
  11999. return 0;
  12000. }
  12001. static int
  12002. set_acl_option(struct mg_context *ctx)
  12003. {
  12004. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  12005. }
  12006. static void
  12007. reset_per_request_attributes(struct mg_connection *conn)
  12008. {
  12009. if (!conn) {
  12010. return;
  12011. }
  12012. conn->connection_type = 0; /* Not yet a valid request/response */
  12013. conn->path_info = NULL;
  12014. conn->num_bytes_sent = conn->consumed_content = 0;
  12015. conn->status_code = -1;
  12016. conn->is_chunked = 0;
  12017. conn->must_close = 0;
  12018. conn->request_len = 0;
  12019. conn->throttle = 0;
  12020. conn->data_len = 0;
  12021. conn->chunk_remainder = 0;
  12022. conn->response_info.content_length = conn->request_info.content_length = -1;
  12023. conn->response_info.http_version = conn->request_info.http_version = NULL;
  12024. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  12025. conn->response_info.status_text = NULL;
  12026. conn->response_info.status_code = 0;
  12027. conn->request_info.remote_user = NULL;
  12028. conn->request_info.request_method = NULL;
  12029. conn->request_info.request_uri = NULL;
  12030. conn->request_info.local_uri = NULL;
  12031. #if defined(MG_LEGACY_INTERFACE)
  12032. /* Legacy before split into local_uri and request_uri */
  12033. conn->request_info.uri = NULL;
  12034. #endif
  12035. }
  12036. #if 0
  12037. /* Note: set_sock_timeout is not required for non-blocking sockets.
  12038. * Leave this function here (commented out) for reference until
  12039. * CivetWeb 1.9 is tested, and the tests confirme this function is
  12040. * no longer required.
  12041. */
  12042. static int
  12043. set_sock_timeout(SOCKET sock, int milliseconds)
  12044. {
  12045. int r0 = 0, r1, r2;
  12046. #ifdef _WIN32
  12047. /* Windows specific */
  12048. DWORD tv = (DWORD)milliseconds;
  12049. #else
  12050. /* Linux, ... (not Windows) */
  12051. struct timeval tv;
  12052. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  12053. * max. time waiting for the acknowledged of TCP data before the connection
  12054. * will be forcefully closed and ETIMEDOUT is returned to the application.
  12055. * If this option is not set, the default timeout of 20-30 minutes is used.
  12056. */
  12057. /* #define TCP_USER_TIMEOUT (18) */
  12058. #if defined(TCP_USER_TIMEOUT)
  12059. unsigned int uto = (unsigned int)milliseconds;
  12060. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  12061. #endif
  12062. memset(&tv, 0, sizeof(tv));
  12063. tv.tv_sec = milliseconds / 1000;
  12064. tv.tv_usec = (milliseconds * 1000) % 1000000;
  12065. #endif /* _WIN32 */
  12066. r1 = setsockopt(
  12067. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12068. r2 = setsockopt(
  12069. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12070. return r0 || r1 || r2;
  12071. }
  12072. #endif
  12073. static int
  12074. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  12075. {
  12076. if (setsockopt(sock,
  12077. IPPROTO_TCP,
  12078. TCP_NODELAY,
  12079. (SOCK_OPT_TYPE)&nodelay_on,
  12080. sizeof(nodelay_on)) != 0) {
  12081. /* Error */
  12082. return 1;
  12083. }
  12084. /* OK */
  12085. return 0;
  12086. }
  12087. static void
  12088. close_socket_gracefully(struct mg_connection *conn)
  12089. {
  12090. #if defined(_WIN32)
  12091. char buf[MG_BUF_LEN];
  12092. int n;
  12093. #endif
  12094. struct linger linger;
  12095. int error_code = 0;
  12096. int linger_timeout = -2;
  12097. socklen_t opt_len = sizeof(error_code);
  12098. if (!conn) {
  12099. return;
  12100. }
  12101. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  12102. * "Note that enabling a nonzero timeout on a nonblocking socket
  12103. * is not recommended.", so set it to blocking now */
  12104. set_blocking_mode(conn->client.sock, 1);
  12105. /* Send FIN to the client */
  12106. shutdown(conn->client.sock, SHUTDOWN_WR);
  12107. #if defined(_WIN32)
  12108. /* Read and discard pending incoming data. If we do not do that and
  12109. * close
  12110. * the socket, the data in the send buffer may be discarded. This
  12111. * behaviour is seen on Windows, when client keeps sending data
  12112. * when server decides to close the connection; then when client
  12113. * does recv() it gets no data back. */
  12114. do {
  12115. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  12116. } while (n > 0);
  12117. #endif
  12118. if (conn->ctx->config[LINGER_TIMEOUT]) {
  12119. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  12120. }
  12121. /* Set linger option according to configuration */
  12122. if (linger_timeout >= 0) {
  12123. /* Set linger option to avoid socket hanging out after close. This
  12124. * prevent ephemeral port exhaust problem under high QPS. */
  12125. linger.l_onoff = 1;
  12126. #if defined(_MSC_VER)
  12127. #pragma warning(push)
  12128. #pragma warning(disable : 4244)
  12129. #endif
  12130. linger.l_linger = (linger_timeout + 999) / 1000;
  12131. #if defined(_MSC_VER)
  12132. #pragma warning(pop)
  12133. #endif
  12134. } else {
  12135. linger.l_onoff = 0;
  12136. linger.l_linger = 0;
  12137. }
  12138. if (linger_timeout < -1) {
  12139. /* Default: don't configure any linger */
  12140. } else if (getsockopt(conn->client.sock,
  12141. SOL_SOCKET,
  12142. SO_ERROR,
  12143. (char *)&error_code,
  12144. &opt_len) != 0) {
  12145. /* Cannot determine if socket is already closed. This should
  12146. * not occur and never did in a test. Log an error message
  12147. * and continue. */
  12148. mg_cry(conn,
  12149. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  12150. __func__,
  12151. strerror(ERRNO));
  12152. } else if (error_code == ECONNRESET) {
  12153. /* Socket already closed by client/peer, close socket without linger */
  12154. } else {
  12155. /* Set linger timeout */
  12156. if (setsockopt(conn->client.sock,
  12157. SOL_SOCKET,
  12158. SO_LINGER,
  12159. (char *)&linger,
  12160. sizeof(linger)) != 0) {
  12161. mg_cry(conn,
  12162. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  12163. __func__,
  12164. linger.l_onoff,
  12165. linger.l_linger,
  12166. strerror(ERRNO));
  12167. }
  12168. }
  12169. /* Now we know that our FIN is ACK-ed, safe to close */
  12170. closesocket(conn->client.sock);
  12171. conn->client.sock = INVALID_SOCKET;
  12172. }
  12173. static void
  12174. close_connection(struct mg_connection *conn)
  12175. {
  12176. if (!conn || !conn->ctx) {
  12177. return;
  12178. }
  12179. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12180. if (conn->lua_websocket_state) {
  12181. lua_websocket_close(conn, conn->lua_websocket_state);
  12182. conn->lua_websocket_state = NULL;
  12183. }
  12184. #endif
  12185. /* call the connection_close callback if assigned */
  12186. if ((conn->ctx->callbacks.connection_close != NULL)
  12187. && (conn->ctx->context_type == 1)) {
  12188. conn->ctx->callbacks.connection_close(conn);
  12189. }
  12190. mg_lock_connection(conn);
  12191. conn->must_close = 1;
  12192. #ifndef NO_SSL
  12193. if (conn->ssl != NULL) {
  12194. /* Run SSL_shutdown twice to ensure completly close SSL connection
  12195. */
  12196. SSL_shutdown(conn->ssl);
  12197. SSL_free(conn->ssl);
  12198. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12199. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12200. #ifndef OPENSSL_API_1_1
  12201. ERR_remove_state(0);
  12202. #endif
  12203. conn->ssl = NULL;
  12204. }
  12205. #endif
  12206. if (conn->client.sock != INVALID_SOCKET) {
  12207. close_socket_gracefully(conn);
  12208. conn->client.sock = INVALID_SOCKET;
  12209. }
  12210. mg_unlock_connection(conn);
  12211. }
  12212. void
  12213. mg_close_connection(struct mg_connection *conn)
  12214. {
  12215. #if defined(USE_WEBSOCKET)
  12216. struct mg_context *client_ctx = NULL;
  12217. #endif /* defined(USE_WEBSOCKET) */
  12218. if (conn == NULL) {
  12219. return;
  12220. }
  12221. #if defined(USE_WEBSOCKET)
  12222. if (conn->ctx->context_type == 2) {
  12223. unsigned int i;
  12224. /* ws/wss client */
  12225. client_ctx = conn->ctx;
  12226. /* client context: loops must end */
  12227. conn->ctx->stop_flag = 1;
  12228. /* We need to get the client thread out of the select/recv call here. */
  12229. /* Since we use a sleep quantum of some seconds to check for recv
  12230. * timeouts, we will just wait a few seconds in mg_join_thread. */
  12231. /* join worker thread */
  12232. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  12233. if (client_ctx->worker_threadids[i] != 0) {
  12234. mg_join_thread(client_ctx->worker_threadids[i]);
  12235. }
  12236. }
  12237. }
  12238. #endif /* defined(USE_WEBSOCKET) */
  12239. close_connection(conn);
  12240. #ifndef NO_SSL
  12241. if (conn->client_ssl_ctx != NULL) {
  12242. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  12243. }
  12244. #endif
  12245. #if defined(USE_WEBSOCKET)
  12246. if (client_ctx != NULL) {
  12247. /* free context */
  12248. mg_free(client_ctx->worker_threadids);
  12249. mg_free(client_ctx);
  12250. (void)pthread_mutex_destroy(&conn->mutex);
  12251. mg_free(conn);
  12252. } else if (conn->ctx->context_type == 0) { /* Client */
  12253. mg_free(conn);
  12254. }
  12255. #else
  12256. if (conn->ctx->context_type == 0) { /* Client */
  12257. mg_free(conn);
  12258. }
  12259. #endif /* defined(USE_WEBSOCKET) */
  12260. }
  12261. static struct mg_context common_client_context;
  12262. static struct mg_connection *
  12263. mg_connect_client_impl(const struct mg_client_options *client_options,
  12264. int use_ssl,
  12265. char *ebuf,
  12266. size_t ebuf_len)
  12267. {
  12268. struct mg_connection *conn = NULL;
  12269. SOCKET sock;
  12270. union usa sa;
  12271. unsigned max_req_size =
  12272. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  12273. if (!connect_socket(&common_client_context,
  12274. client_options->host,
  12275. client_options->port,
  12276. use_ssl,
  12277. ebuf,
  12278. ebuf_len,
  12279. &sock,
  12280. &sa)) {
  12281. return NULL;
  12282. }
  12283. if ((conn = (struct mg_connection *)mg_calloc_ctx(
  12284. 1, sizeof(*conn) + max_req_size, &common_client_context))
  12285. == NULL) {
  12286. mg_snprintf(NULL,
  12287. NULL, /* No truncation check for ebuf */
  12288. ebuf,
  12289. ebuf_len,
  12290. "calloc(): %s",
  12291. strerror(ERRNO));
  12292. closesocket(sock);
  12293. return NULL;
  12294. }
  12295. #ifndef NO_SSL
  12296. #ifdef OPENSSL_API_1_1
  12297. if (use_ssl
  12298. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  12299. mg_snprintf(NULL,
  12300. NULL, /* No truncation check for ebuf */
  12301. ebuf,
  12302. ebuf_len,
  12303. "SSL_CTX_new error");
  12304. closesocket(sock);
  12305. mg_free(conn);
  12306. return NULL;
  12307. }
  12308. #else
  12309. if (use_ssl
  12310. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  12311. == NULL) {
  12312. mg_snprintf(NULL,
  12313. NULL, /* No truncation check for ebuf */
  12314. ebuf,
  12315. ebuf_len,
  12316. "SSL_CTX_new error");
  12317. closesocket(sock);
  12318. mg_free(conn);
  12319. return NULL;
  12320. }
  12321. #endif /* OPENSSL_API_1_1 */
  12322. #endif /* NO_SSL */
  12323. #ifdef USE_IPV6
  12324. socklen_t len = (sa.sa.sa_family == AF_INET)
  12325. ? sizeof(conn->client.rsa.sin)
  12326. : sizeof(conn->client.rsa.sin6);
  12327. struct sockaddr *psa = (sa.sa.sa_family == AF_INET)
  12328. ? (struct sockaddr *)&(conn->client.rsa.sin)
  12329. : (struct sockaddr *)&(conn->client.rsa.sin6);
  12330. #else
  12331. socklen_t len = sizeof(conn->client.rsa.sin);
  12332. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  12333. #endif
  12334. conn->buf_size = (int)max_req_size;
  12335. conn->buf = (char *)(conn + 1);
  12336. conn->ctx = &common_client_context;
  12337. conn->client.sock = sock;
  12338. conn->client.lsa = sa;
  12339. if (getsockname(sock, psa, &len) != 0) {
  12340. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  12341. }
  12342. conn->client.is_ssl = use_ssl ? 1 : 0;
  12343. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12344. #ifndef NO_SSL
  12345. if (use_ssl) {
  12346. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  12347. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  12348. * SSL_CTX_set_verify call is needed to switch off server
  12349. * certificate checking, which is off by default in OpenSSL and
  12350. * on in yaSSL. */
  12351. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  12352. * SSL_VERIFY_PEER, verify_ssl_server); */
  12353. if (client_options->client_cert) {
  12354. if (!ssl_use_pem_file(&common_client_context,
  12355. client_options->client_cert,
  12356. NULL)) {
  12357. mg_snprintf(NULL,
  12358. NULL, /* No truncation check for ebuf */
  12359. ebuf,
  12360. ebuf_len,
  12361. "Can not use SSL client certificate");
  12362. SSL_CTX_free(conn->client_ssl_ctx);
  12363. closesocket(sock);
  12364. mg_free(conn);
  12365. return NULL;
  12366. }
  12367. }
  12368. if (client_options->server_cert) {
  12369. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  12370. client_options->server_cert,
  12371. NULL);
  12372. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  12373. } else {
  12374. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  12375. }
  12376. if (!sslize(conn,
  12377. conn->client_ssl_ctx,
  12378. SSL_connect,
  12379. &(conn->ctx->stop_flag))) {
  12380. mg_snprintf(NULL,
  12381. NULL, /* No truncation check for ebuf */
  12382. ebuf,
  12383. ebuf_len,
  12384. "SSL connection error");
  12385. SSL_CTX_free(conn->client_ssl_ctx);
  12386. closesocket(sock);
  12387. mg_free(conn);
  12388. return NULL;
  12389. }
  12390. }
  12391. #endif
  12392. set_blocking_mode(sock, 0);
  12393. return conn;
  12394. }
  12395. CIVETWEB_API struct mg_connection *
  12396. mg_connect_client_secure(const struct mg_client_options *client_options,
  12397. char *error_buffer,
  12398. size_t error_buffer_size)
  12399. {
  12400. return mg_connect_client_impl(client_options,
  12401. 1,
  12402. error_buffer,
  12403. error_buffer_size);
  12404. }
  12405. struct mg_connection *
  12406. mg_connect_client(const char *host,
  12407. int port,
  12408. int use_ssl,
  12409. char *error_buffer,
  12410. size_t error_buffer_size)
  12411. {
  12412. struct mg_client_options opts;
  12413. memset(&opts, 0, sizeof(opts));
  12414. opts.host = host;
  12415. opts.port = port;
  12416. return mg_connect_client_impl(&opts,
  12417. use_ssl,
  12418. error_buffer,
  12419. error_buffer_size);
  12420. }
  12421. static const struct {
  12422. const char *proto;
  12423. size_t proto_len;
  12424. unsigned default_port;
  12425. } abs_uri_protocols[] = {{"http://", 7, 80},
  12426. {"https://", 8, 443},
  12427. {"ws://", 5, 80},
  12428. {"wss://", 6, 443},
  12429. {NULL, 0, 0}};
  12430. /* Check if the uri is valid.
  12431. * return 0 for invalid uri,
  12432. * return 1 for *,
  12433. * return 2 for relative uri,
  12434. * return 3 for absolute uri without port,
  12435. * return 4 for absolute uri with port */
  12436. static int
  12437. get_uri_type(const char *uri)
  12438. {
  12439. int i;
  12440. const char *hostend, *portbegin;
  12441. char *portend;
  12442. unsigned long port;
  12443. /* According to the HTTP standard
  12444. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  12445. * URI can be an asterisk (*) or should start with slash (relative uri),
  12446. * or it should start with the protocol (absolute uri). */
  12447. if ((uri[0] == '*') && (uri[1] == '\0')) {
  12448. /* asterisk */
  12449. return 1;
  12450. }
  12451. /* Valid URIs according to RFC 3986
  12452. * (https://www.ietf.org/rfc/rfc3986.txt)
  12453. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  12454. * and unreserved characters A-Z a-z 0-9 and -._~
  12455. * and % encoded symbols.
  12456. */
  12457. for (i = 0; uri[i] != 0; i++) {
  12458. if (uri[i] < 33) {
  12459. /* control characters and spaces are invalid */
  12460. return 0;
  12461. }
  12462. if (uri[i] > 126) {
  12463. /* non-ascii characters must be % encoded */
  12464. return 0;
  12465. } else {
  12466. switch (uri[i]) {
  12467. case '"': /* 34 */
  12468. case '<': /* 60 */
  12469. case '>': /* 62 */
  12470. case '\\': /* 92 */
  12471. case '^': /* 94 */
  12472. case '`': /* 96 */
  12473. case '{': /* 123 */
  12474. case '|': /* 124 */
  12475. case '}': /* 125 */
  12476. return 0;
  12477. default:
  12478. /* character is ok */
  12479. break;
  12480. }
  12481. }
  12482. }
  12483. /* A relative uri starts with a / character */
  12484. if (uri[0] == '/') {
  12485. /* relative uri */
  12486. return 2;
  12487. }
  12488. /* It could be an absolute uri: */
  12489. /* This function only checks if the uri is valid, not if it is
  12490. * addressing the current server. So civetweb can also be used
  12491. * as a proxy server. */
  12492. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  12493. if (mg_strncasecmp(uri,
  12494. abs_uri_protocols[i].proto,
  12495. abs_uri_protocols[i].proto_len) == 0) {
  12496. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  12497. if (!hostend) {
  12498. return 0;
  12499. }
  12500. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  12501. if (!portbegin) {
  12502. return 3;
  12503. }
  12504. port = strtoul(portbegin + 1, &portend, 10);
  12505. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  12506. return 0;
  12507. }
  12508. return 4;
  12509. }
  12510. }
  12511. return 0;
  12512. }
  12513. /* Return NULL or the relative uri at the current server */
  12514. static const char *
  12515. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  12516. {
  12517. const char *server_domain;
  12518. size_t server_domain_len;
  12519. size_t request_domain_len = 0;
  12520. unsigned long port = 0;
  12521. int i, auth_domain_check_enabled;
  12522. const char *hostbegin = NULL;
  12523. const char *hostend = NULL;
  12524. const char *portbegin;
  12525. char *portend;
  12526. auth_domain_check_enabled =
  12527. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  12528. if (!auth_domain_check_enabled) {
  12529. return 0;
  12530. }
  12531. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  12532. if (!server_domain) {
  12533. return 0;
  12534. }
  12535. server_domain_len = strlen(server_domain);
  12536. if (!server_domain_len) {
  12537. return 0;
  12538. }
  12539. /* DNS is case insensitive, so use case insensitive string compare here
  12540. */
  12541. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  12542. if (mg_strncasecmp(uri,
  12543. abs_uri_protocols[i].proto,
  12544. abs_uri_protocols[i].proto_len) == 0) {
  12545. hostbegin = uri + abs_uri_protocols[i].proto_len;
  12546. hostend = strchr(hostbegin, '/');
  12547. if (!hostend) {
  12548. return 0;
  12549. }
  12550. portbegin = strchr(hostbegin, ':');
  12551. if ((!portbegin) || (portbegin > hostend)) {
  12552. port = abs_uri_protocols[i].default_port;
  12553. request_domain_len = (size_t)(hostend - hostbegin);
  12554. } else {
  12555. port = strtoul(portbegin + 1, &portend, 10);
  12556. if ((portend != hostend) || (port <= 0)
  12557. || !is_valid_port(port)) {
  12558. return 0;
  12559. }
  12560. request_domain_len = (size_t)(portbegin - hostbegin);
  12561. }
  12562. /* protocol found, port set */
  12563. break;
  12564. }
  12565. }
  12566. if (!port) {
  12567. /* port remains 0 if the protocol is not found */
  12568. return 0;
  12569. }
  12570. /* Check if the request is directed to a different server. */
  12571. /* First check if the port is the same (IPv4 and IPv6). */
  12572. #if defined(USE_IPV6)
  12573. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  12574. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  12575. /* Request is directed to a different port */
  12576. return 0;
  12577. }
  12578. } else
  12579. #endif
  12580. {
  12581. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  12582. /* Request is directed to a different port */
  12583. return 0;
  12584. }
  12585. }
  12586. /* Finally check if the server corresponds to the authentication
  12587. * domain of the server (the server domain).
  12588. * Allow full matches (like http://mydomain.com/path/file.ext), and
  12589. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  12590. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  12591. * or http://mydomain.com.fake/path/file.ext).
  12592. */
  12593. if (auth_domain_check_enabled) {
  12594. if ((request_domain_len == server_domain_len)
  12595. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  12596. /* Request is directed to this server - full name match. */
  12597. } else {
  12598. if (request_domain_len < (server_domain_len + 2)) {
  12599. /* Request is directed to another server: The server name is
  12600. * longer
  12601. * than
  12602. * the request name. Drop this case here to avoid overflows in
  12603. * the
  12604. * following checks. */
  12605. return 0;
  12606. }
  12607. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  12608. /* Request is directed to another server: It could be a
  12609. * substring
  12610. * like notmyserver.com */
  12611. return 0;
  12612. }
  12613. if (0 != memcmp(server_domain,
  12614. hostbegin + request_domain_len - server_domain_len,
  12615. server_domain_len)) {
  12616. /* Request is directed to another server:
  12617. * The server name is different. */
  12618. return 0;
  12619. }
  12620. }
  12621. }
  12622. return hostend;
  12623. }
  12624. static int
  12625. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12626. {
  12627. if (ebuf_len > 0) {
  12628. ebuf[0] = '\0';
  12629. }
  12630. *err = 0;
  12631. reset_per_request_attributes(conn);
  12632. if (!conn) {
  12633. mg_snprintf(conn,
  12634. NULL, /* No truncation check for ebuf */
  12635. ebuf,
  12636. ebuf_len,
  12637. "%s",
  12638. "Internal error");
  12639. *err = 500;
  12640. return 0;
  12641. }
  12642. /* Set the time the request was received. This value should be used for
  12643. * timeouts. */
  12644. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  12645. conn->request_len =
  12646. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  12647. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  12648. */
  12649. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  12650. mg_snprintf(conn,
  12651. NULL, /* No truncation check for ebuf */
  12652. ebuf,
  12653. ebuf_len,
  12654. "%s",
  12655. "Invalid message size");
  12656. *err = 500;
  12657. return 0;
  12658. }
  12659. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  12660. mg_snprintf(conn,
  12661. NULL, /* No truncation check for ebuf */
  12662. ebuf,
  12663. ebuf_len,
  12664. "%s",
  12665. "Message too large");
  12666. *err = 413;
  12667. return 0;
  12668. }
  12669. if (conn->request_len <= 0) {
  12670. if (conn->data_len > 0) {
  12671. mg_snprintf(conn,
  12672. NULL, /* No truncation check for ebuf */
  12673. ebuf,
  12674. ebuf_len,
  12675. "%s",
  12676. "Malformed message");
  12677. *err = 400;
  12678. } else {
  12679. /* Server did not recv anything -> just close the connection */
  12680. conn->must_close = 1;
  12681. mg_snprintf(conn,
  12682. NULL, /* No truncation check for ebuf */
  12683. ebuf,
  12684. ebuf_len,
  12685. "%s",
  12686. "No data received");
  12687. *err = 0;
  12688. }
  12689. return 0;
  12690. }
  12691. return 1;
  12692. }
  12693. static int
  12694. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12695. {
  12696. const char *cl;
  12697. if (!get_message(conn, ebuf, ebuf_len, err)) {
  12698. return 0;
  12699. }
  12700. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  12701. <= 0) {
  12702. mg_snprintf(conn,
  12703. NULL, /* No truncation check for ebuf */
  12704. ebuf,
  12705. ebuf_len,
  12706. "%s",
  12707. "Bad request");
  12708. *err = 400;
  12709. return 0;
  12710. }
  12711. /* Message is a valid request */
  12712. if ((cl = get_header(conn->request_info.http_headers,
  12713. conn->request_info.num_headers,
  12714. "Content-Length")) != NULL) {
  12715. /* Request/response has content length set */
  12716. char *endptr = NULL;
  12717. conn->content_len = strtoll(cl, &endptr, 10);
  12718. if (endptr == cl) {
  12719. mg_snprintf(conn,
  12720. NULL, /* No truncation check for ebuf */
  12721. ebuf,
  12722. ebuf_len,
  12723. "%s",
  12724. "Bad request");
  12725. *err = 411;
  12726. return 0;
  12727. }
  12728. /* Publish the content length back to the request info. */
  12729. conn->request_info.content_length = conn->content_len;
  12730. } else if ((cl = get_header(conn->request_info.http_headers,
  12731. conn->request_info.num_headers,
  12732. "Transfer-Encoding")) != NULL
  12733. && !mg_strcasecmp(cl, "chunked")) {
  12734. conn->is_chunked = 1;
  12735. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  12736. || !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  12737. /* POST or PUT request without content length set */
  12738. conn->content_len = -1;
  12739. } else if (!mg_strncasecmp(conn->request_info.request_method, "HTTP/", 5)) {
  12740. /* Response without content length set */
  12741. conn->content_len = -1;
  12742. } else {
  12743. /* Other request */
  12744. conn->content_len = 0;
  12745. }
  12746. conn->connection_type = 1; /* Valid request */
  12747. return 1;
  12748. }
  12749. /* conn is assumed to be valid in this internal function */
  12750. static int
  12751. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12752. {
  12753. const char *cl;
  12754. if (!get_message(conn, ebuf, ebuf_len, err)) {
  12755. return 0;
  12756. }
  12757. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  12758. <= 0) {
  12759. mg_snprintf(conn,
  12760. NULL, /* No truncation check for ebuf */
  12761. ebuf,
  12762. ebuf_len,
  12763. "%s",
  12764. "Bad response");
  12765. *err = 400;
  12766. return 0;
  12767. }
  12768. /* Message is a valid response */
  12769. if ((cl = get_header(conn->response_info.http_headers,
  12770. conn->response_info.num_headers,
  12771. "Content-Length")) != NULL) {
  12772. /* Request/response has content length set */
  12773. char *endptr = NULL;
  12774. conn->content_len = strtoll(cl, &endptr, 10);
  12775. if (endptr == cl) {
  12776. mg_snprintf(conn,
  12777. NULL, /* No truncation check for ebuf */
  12778. ebuf,
  12779. ebuf_len,
  12780. "%s",
  12781. "Bad request");
  12782. *err = 411;
  12783. return 0;
  12784. }
  12785. /* Publish the content length back to the response info. */
  12786. conn->response_info.content_length = conn->content_len;
  12787. /* TODO: check if it is still used in response_info */
  12788. conn->request_info.content_length = conn->content_len;
  12789. } else if ((cl = get_header(conn->response_info.http_headers,
  12790. conn->response_info.num_headers,
  12791. "Transfer-Encoding")) != NULL
  12792. && !mg_strcasecmp(cl, "chunked")) {
  12793. conn->is_chunked = 1;
  12794. } else {
  12795. conn->content_len = -1;
  12796. }
  12797. conn->connection_type = 2; /* Valid response */
  12798. return 1;
  12799. }
  12800. int
  12801. mg_get_response(struct mg_connection *conn,
  12802. char *ebuf,
  12803. size_t ebuf_len,
  12804. int timeout)
  12805. {
  12806. if (ebuf_len > 0) {
  12807. ebuf[0] = '\0';
  12808. }
  12809. if (!conn) {
  12810. mg_snprintf(conn,
  12811. NULL, /* No truncation check for ebuf */
  12812. ebuf,
  12813. ebuf_len,
  12814. "%s",
  12815. "Parameter error");
  12816. return -1;
  12817. }
  12818. /* Implementation of API function for HTTP clients */
  12819. int err, ret;
  12820. struct mg_context *octx = conn->ctx;
  12821. struct mg_context rctx = *(conn->ctx);
  12822. char txt[32]; /* will not overflow */
  12823. if (timeout >= 0) {
  12824. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  12825. rctx.config[REQUEST_TIMEOUT] = txt;
  12826. /* Not required for non-blocking sockets.
  12827. set_sock_timeout(conn->client.sock, timeout);
  12828. */
  12829. } else {
  12830. rctx.config[REQUEST_TIMEOUT] = NULL;
  12831. }
  12832. conn->ctx = &rctx;
  12833. ret = get_response(conn, ebuf, ebuf_len, &err);
  12834. conn->ctx = octx;
  12835. #if defined(MG_LEGACY_INTERFACE)
  12836. /* TODO: 1) uri is deprecated;
  12837. * 2) here, ri.uri is the http response code */
  12838. conn->request_info.uri = conn->request_info.request_uri;
  12839. #endif
  12840. conn->request_info.local_uri = conn->request_info.request_uri;
  12841. /* TODO (mid): Define proper return values - maybe return length?
  12842. * For the first test use <0 for error and >0 for OK */
  12843. return (ret == 0) ? -1 : +1;
  12844. }
  12845. struct mg_connection *
  12846. mg_download(const char *host,
  12847. int port,
  12848. int use_ssl,
  12849. char *ebuf,
  12850. size_t ebuf_len,
  12851. const char *fmt,
  12852. ...)
  12853. {
  12854. struct mg_connection *conn;
  12855. va_list ap;
  12856. int i;
  12857. int reqerr;
  12858. if (ebuf_len > 0) {
  12859. ebuf[0] = '\0';
  12860. }
  12861. va_start(ap, fmt);
  12862. /* open a connection */
  12863. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  12864. if (conn != NULL) {
  12865. i = mg_vprintf(conn, fmt, ap);
  12866. if (i <= 0) {
  12867. mg_snprintf(conn,
  12868. NULL, /* No truncation check for ebuf */
  12869. ebuf,
  12870. ebuf_len,
  12871. "%s",
  12872. "Error sending request");
  12873. } else {
  12874. get_response(conn, ebuf, ebuf_len, &reqerr);
  12875. #if defined(MG_LEGACY_INTERFACE)
  12876. /* TODO: 1) uri is deprecated;
  12877. * 2) here, ri.uri is the http response code */
  12878. conn->request_info.uri = conn->request_info.request_uri;
  12879. #endif
  12880. conn->request_info.local_uri = conn->request_info.request_uri;
  12881. }
  12882. }
  12883. /* if an error occured, close the connection */
  12884. if ((ebuf[0] != '\0') && (conn != NULL)) {
  12885. mg_close_connection(conn);
  12886. conn = NULL;
  12887. }
  12888. va_end(ap);
  12889. return conn;
  12890. }
  12891. struct websocket_client_thread_data {
  12892. struct mg_connection *conn;
  12893. mg_websocket_data_handler data_handler;
  12894. mg_websocket_close_handler close_handler;
  12895. void *callback_data;
  12896. };
  12897. #if defined(USE_WEBSOCKET)
  12898. #ifdef _WIN32
  12899. static unsigned __stdcall websocket_client_thread(void *data)
  12900. #else
  12901. static void *
  12902. websocket_client_thread(void *data)
  12903. #endif
  12904. {
  12905. struct websocket_client_thread_data *cdata =
  12906. (struct websocket_client_thread_data *)data;
  12907. mg_set_thread_name("ws-clnt");
  12908. if (cdata->conn->ctx) {
  12909. if (cdata->conn->ctx->callbacks.init_thread) {
  12910. /* 3 indicates a websocket client thread */
  12911. /* TODO: check if conn->ctx can be set */
  12912. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  12913. }
  12914. }
  12915. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  12916. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  12917. if (cdata->close_handler != NULL) {
  12918. cdata->close_handler(cdata->conn, cdata->callback_data);
  12919. }
  12920. /* The websocket_client context has only this thread. If it runs out,
  12921. set the stop_flag to 2 (= "stopped"). */
  12922. cdata->conn->ctx->stop_flag = 2;
  12923. mg_free((void *)cdata);
  12924. #ifdef _WIN32
  12925. return 0;
  12926. #else
  12927. return NULL;
  12928. #endif
  12929. }
  12930. #endif
  12931. struct mg_connection *
  12932. mg_connect_websocket_client(const char *host,
  12933. int port,
  12934. int use_ssl,
  12935. char *error_buffer,
  12936. size_t error_buffer_size,
  12937. const char *path,
  12938. const char *origin,
  12939. mg_websocket_data_handler data_func,
  12940. mg_websocket_close_handler close_func,
  12941. void *user_data)
  12942. {
  12943. struct mg_connection *conn = NULL;
  12944. #if defined(USE_WEBSOCKET)
  12945. struct mg_context *newctx = NULL;
  12946. struct websocket_client_thread_data *thread_data;
  12947. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  12948. static const char *handshake_req;
  12949. if (origin != NULL) {
  12950. handshake_req = "GET %s HTTP/1.1\r\n"
  12951. "Host: %s\r\n"
  12952. "Upgrade: websocket\r\n"
  12953. "Connection: Upgrade\r\n"
  12954. "Sec-WebSocket-Key: %s\r\n"
  12955. "Sec-WebSocket-Version: 13\r\n"
  12956. "Origin: %s\r\n"
  12957. "\r\n";
  12958. } else {
  12959. handshake_req = "GET %s HTTP/1.1\r\n"
  12960. "Host: %s\r\n"
  12961. "Upgrade: websocket\r\n"
  12962. "Connection: Upgrade\r\n"
  12963. "Sec-WebSocket-Key: %s\r\n"
  12964. "Sec-WebSocket-Version: 13\r\n"
  12965. "\r\n";
  12966. }
  12967. /* Establish the client connection and request upgrade */
  12968. conn = mg_download(host,
  12969. port,
  12970. use_ssl,
  12971. error_buffer,
  12972. error_buffer_size,
  12973. handshake_req,
  12974. path,
  12975. host,
  12976. magic,
  12977. origin);
  12978. /* Connection object will be null if something goes wrong */
  12979. if (conn == NULL) {
  12980. if (!*error_buffer) {
  12981. /* There should be already an error message */
  12982. mg_snprintf(conn,
  12983. NULL, /* No truncation check for ebuf */
  12984. error_buffer,
  12985. error_buffer_size,
  12986. "Unexpected error");
  12987. }
  12988. return NULL;
  12989. }
  12990. if (conn->response_info.status_code != 101) {
  12991. /* We sent an "upgrade" request. For a correct websocket
  12992. * protocol handshake, we expect a "101 Continue" response.
  12993. * Otherwise it is a protocol violation. Maybe the HTTP
  12994. * Server does not know websockets. */
  12995. if (!*error_buffer) {
  12996. /* set an error, if not yet set */
  12997. mg_snprintf(conn,
  12998. NULL, /* No truncation check for ebuf */
  12999. error_buffer,
  13000. error_buffer_size,
  13001. "Unexpected server reply");
  13002. }
  13003. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  13004. mg_free(conn);
  13005. return conn;
  13006. }
  13007. /* For client connections, mg_context is fake. Since we need to set a
  13008. * callback function, we need to create a copy and modify it. */
  13009. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  13010. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  13011. newctx->user_data = user_data;
  13012. newctx->context_type = 2; /* ws/wss client context type */
  13013. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  13014. newctx->worker_threadids =
  13015. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  13016. sizeof(pthread_t),
  13017. newctx);
  13018. conn->ctx = newctx;
  13019. thread_data = (struct websocket_client_thread_data *)
  13020. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  13021. thread_data->conn = conn;
  13022. thread_data->data_handler = data_func;
  13023. thread_data->close_handler = close_func;
  13024. thread_data->callback_data = user_data;
  13025. /* Start a thread to read the websocket client connection
  13026. * This thread will automatically stop when mg_disconnect is
  13027. * called on the client connection */
  13028. if (mg_start_thread_with_id(websocket_client_thread,
  13029. (void *)thread_data,
  13030. newctx->worker_threadids) != 0) {
  13031. mg_free((void *)thread_data);
  13032. mg_free((void *)newctx->worker_threadids);
  13033. mg_free((void *)newctx);
  13034. mg_free((void *)conn);
  13035. conn = NULL;
  13036. DEBUG_TRACE("%s",
  13037. "Websocket client connect thread could not be started\r\n");
  13038. }
  13039. #else
  13040. /* Appease "unused parameter" warnings */
  13041. (void)host;
  13042. (void)port;
  13043. (void)use_ssl;
  13044. (void)error_buffer;
  13045. (void)error_buffer_size;
  13046. (void)path;
  13047. (void)origin;
  13048. (void)user_data;
  13049. (void)data_func;
  13050. (void)close_func;
  13051. #endif
  13052. return conn;
  13053. }
  13054. static void
  13055. process_new_connection(struct mg_connection *conn)
  13056. {
  13057. if (conn && conn->ctx) {
  13058. struct mg_request_info *ri = &conn->request_info;
  13059. int keep_alive_enabled, keep_alive, discard_len;
  13060. char ebuf[100];
  13061. const char *hostend;
  13062. int reqerr, uri_type;
  13063. #if defined(USE_SERVER_STATS)
  13064. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  13065. mg_atomic_add(&(conn->ctx->total_connections), 1);
  13066. if (mcon > (conn->ctx->max_connections)) {
  13067. /* could use atomic compare exchange, but this
  13068. * seems overkill for statistics data */
  13069. conn->ctx->max_connections = mcon;
  13070. }
  13071. #endif
  13072. keep_alive_enabled =
  13073. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  13074. /* Important: on new connection, reset the receiving buffer. Credit
  13075. * goes to crule42. */
  13076. conn->data_len = 0;
  13077. conn->handled_requests = 0;
  13078. do {
  13079. DEBUG_TRACE("calling get_request (%i times for this connection)",
  13080. conn->handled_requests + 1);
  13081. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  13082. /* The request sent by the client could not be understood by
  13083. * the server, or it was incomplete or a timeout. Send an
  13084. * error message and close the connection. */
  13085. if (reqerr > 0) {
  13086. /*assert(ebuf[0] != '\0');*/
  13087. mg_send_http_error(conn, reqerr, "%s", ebuf);
  13088. }
  13089. } else if (strcmp(ri->http_version, "1.0")
  13090. && strcmp(ri->http_version, "1.1")) {
  13091. mg_snprintf(conn,
  13092. NULL, /* No truncation check for ebuf */
  13093. ebuf,
  13094. sizeof(ebuf),
  13095. "Bad HTTP version: [%s]",
  13096. ri->http_version);
  13097. mg_send_http_error(conn, 505, "%s", ebuf);
  13098. }
  13099. if (ebuf[0] == '\0') {
  13100. uri_type = get_uri_type(conn->request_info.request_uri);
  13101. switch (uri_type) {
  13102. case 1:
  13103. /* Asterisk */
  13104. conn->request_info.local_uri = NULL;
  13105. break;
  13106. case 2:
  13107. /* relative uri */
  13108. conn->request_info.local_uri =
  13109. conn->request_info.request_uri;
  13110. break;
  13111. case 3:
  13112. case 4:
  13113. /* absolute uri (with/without port) */
  13114. hostend = get_rel_url_at_current_server(
  13115. conn->request_info.request_uri, conn);
  13116. if (hostend) {
  13117. conn->request_info.local_uri = hostend;
  13118. } else {
  13119. conn->request_info.local_uri = NULL;
  13120. }
  13121. break;
  13122. default:
  13123. mg_snprintf(conn,
  13124. NULL, /* No truncation check for ebuf */
  13125. ebuf,
  13126. sizeof(ebuf),
  13127. "Invalid URI");
  13128. mg_send_http_error(conn, 400, "%s", ebuf);
  13129. conn->request_info.local_uri = NULL;
  13130. break;
  13131. }
  13132. #if defined(MG_LEGACY_INTERFACE)
  13133. /* Legacy before split into local_uri and request_uri */
  13134. conn->request_info.uri = conn->request_info.local_uri;
  13135. #endif
  13136. }
  13137. DEBUG_TRACE("http: %s, error: %s",
  13138. (ri->http_version ? ri->http_version : "none"),
  13139. (ebuf[0] ? ebuf : "none"));
  13140. if (ebuf[0] == '\0') {
  13141. if (conn->request_info.local_uri) {
  13142. /* handle request to local server */
  13143. handle_request(conn);
  13144. DEBUG_TRACE("%s", "handle_request done");
  13145. if (conn->ctx->callbacks.end_request != NULL) {
  13146. conn->ctx->callbacks.end_request(conn,
  13147. conn->status_code);
  13148. DEBUG_TRACE("%s", "end_request callback done");
  13149. }
  13150. log_access(conn);
  13151. } else {
  13152. /* TODO: handle non-local request (PROXY) */
  13153. conn->must_close = 1;
  13154. }
  13155. } else {
  13156. conn->must_close = 1;
  13157. }
  13158. if (ri->remote_user != NULL) {
  13159. mg_free((void *)ri->remote_user);
  13160. /* Important! When having connections with and without auth
  13161. * would cause double free and then crash */
  13162. ri->remote_user = NULL;
  13163. }
  13164. /* NOTE(lsm): order is important here. should_keep_alive() call
  13165. * is
  13166. * using parsed request, which will be invalid after memmove's
  13167. * below.
  13168. * Therefore, memorize should_keep_alive() result now for later
  13169. * use
  13170. * in loop exit condition. */
  13171. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  13172. && (conn->content_len >= 0) && should_keep_alive(conn);
  13173. /* Discard all buffered data for this request */
  13174. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  13175. && ((conn->request_len + conn->content_len)
  13176. < (int64_t)conn->data_len))
  13177. ? (int)(conn->request_len + conn->content_len)
  13178. : conn->data_len;
  13179. /*assert(discard_len >= 0);*/
  13180. if (discard_len < 0) {
  13181. DEBUG_TRACE("internal error: discard_len = %li",
  13182. (long int)discard_len);
  13183. break;
  13184. }
  13185. conn->data_len -= discard_len;
  13186. if (conn->data_len > 0) {
  13187. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  13188. memmove(conn->buf,
  13189. conn->buf + discard_len,
  13190. (size_t)conn->data_len);
  13191. }
  13192. /* assert(conn->data_len >= 0); */
  13193. /* assert(conn->data_len <= conn->buf_size); */
  13194. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  13195. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  13196. (long int)conn->data_len,
  13197. (long int)conn->buf_size);
  13198. break;
  13199. }
  13200. conn->handled_requests++;
  13201. } while (keep_alive);
  13202. #if defined(USE_SERVER_STATS)
  13203. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  13204. mg_atomic_dec(&(conn->ctx->active_connections));
  13205. #endif
  13206. }
  13207. }
  13208. #if defined(ALTERNATIVE_QUEUE)
  13209. static void
  13210. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13211. {
  13212. unsigned int i;
  13213. for (;;) {
  13214. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13215. /* find a free worker slot and signal it */
  13216. if (ctx->client_socks[i].in_use == 0) {
  13217. ctx->client_socks[i] = *sp;
  13218. ctx->client_socks[i].in_use = 1;
  13219. event_signal(ctx->client_wait_events[i]);
  13220. return;
  13221. }
  13222. }
  13223. /* queue is full */
  13224. mg_sleep(1);
  13225. }
  13226. }
  13227. static int
  13228. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13229. {
  13230. DEBUG_TRACE("%s", "going idle");
  13231. ctx->client_socks[thread_index].in_use = 0;
  13232. event_wait(ctx->client_wait_events[thread_index]);
  13233. *sp = ctx->client_socks[thread_index];
  13234. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13235. return !ctx->stop_flag;
  13236. }
  13237. #else /* ALTERNATIVE_QUEUE */
  13238. /* Worker threads take accepted socket from the queue */
  13239. static int
  13240. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13241. {
  13242. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13243. (void)thread_index;
  13244. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13245. DEBUG_TRACE("%s", "going idle");
  13246. /* If the queue is empty, wait. We're idle at this point. */
  13247. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  13248. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  13249. }
  13250. /* If we're stopping, sq_head may be equal to sq_tail. */
  13251. if (ctx->sq_head > ctx->sq_tail) {
  13252. /* Copy socket from the queue and increment tail */
  13253. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  13254. ctx->sq_tail++;
  13255. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13256. /* Wrap pointers if needed */
  13257. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  13258. ctx->sq_tail -= QUEUE_SIZE(ctx);
  13259. ctx->sq_head -= QUEUE_SIZE(ctx);
  13260. }
  13261. }
  13262. (void)pthread_cond_signal(&ctx->sq_empty);
  13263. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13264. return !ctx->stop_flag;
  13265. #undef QUEUE_SIZE
  13266. }
  13267. /* Master thread adds accepted socket to a queue */
  13268. static void
  13269. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13270. {
  13271. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13272. if (!ctx) {
  13273. return;
  13274. }
  13275. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13276. /* If the queue is full, wait */
  13277. while ((ctx->stop_flag == 0)
  13278. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  13279. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  13280. }
  13281. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  13282. /* Copy socket to the queue and increment head */
  13283. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  13284. ctx->sq_head++;
  13285. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  13286. }
  13287. (void)pthread_cond_signal(&ctx->sq_full);
  13288. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13289. #undef QUEUE_SIZE
  13290. }
  13291. #endif /* ALTERNATIVE_QUEUE */
  13292. struct worker_thread_args {
  13293. struct mg_context *ctx;
  13294. int index;
  13295. };
  13296. static void *
  13297. worker_thread_run(struct worker_thread_args *thread_args)
  13298. {
  13299. struct mg_context *ctx = thread_args->ctx;
  13300. struct mg_connection *conn;
  13301. struct mg_workerTLS tls;
  13302. #if defined(MG_LEGACY_INTERFACE)
  13303. uint32_t addr;
  13304. #endif
  13305. mg_set_thread_name("worker");
  13306. tls.is_master = 0;
  13307. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13308. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13309. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13310. #endif
  13311. /* Initialize thread local storage before calling any callback */
  13312. pthread_setspecific(sTlsKey, &tls);
  13313. if (ctx->callbacks.init_thread) {
  13314. /* call init_thread for a worker thread (type 1) */
  13315. ctx->callbacks.init_thread(ctx, 1);
  13316. }
  13317. /* Connection structure has been pre-allocated */
  13318. if (((int)thread_args->index < 0)
  13319. || ((unsigned)thread_args->index
  13320. >= (unsigned)ctx->cfg_worker_threads)) {
  13321. mg_cry(fc(ctx),
  13322. "Internal error: Invalid worker index %i",
  13323. (int)thread_args->index);
  13324. return NULL;
  13325. }
  13326. conn = ctx->worker_connections + thread_args->index;
  13327. /* Request buffers are not pre-allocated. They are private to the
  13328. * request and do not contain any state information that might be
  13329. * of interest to anyone observing a server status. */
  13330. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->ctx);
  13331. if (conn->buf == NULL) {
  13332. mg_cry(fc(ctx),
  13333. "Out of memory: Cannot allocate buffer for worker %i",
  13334. (int)thread_args->index);
  13335. return NULL;
  13336. }
  13337. conn->buf_size = (int)ctx->max_request_size;
  13338. conn->ctx = ctx;
  13339. conn->thread_index = thread_args->index;
  13340. conn->request_info.user_data = ctx->user_data;
  13341. /* Allocate a mutex for this connection to allow communication both
  13342. * within the request handler and from elsewhere in the application
  13343. */
  13344. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13345. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  13346. * signal sq_empty condvar to wake up the master waiting in
  13347. * produce_socket() */
  13348. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  13349. conn->conn_birth_time = time(NULL);
  13350. /* Fill in IP, port info early so even if SSL setup below fails,
  13351. * error handler would have the corresponding info.
  13352. * Thanks to Johannes Winkelmann for the patch.
  13353. */
  13354. #if defined(USE_IPV6)
  13355. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  13356. conn->request_info.remote_port =
  13357. ntohs(conn->client.rsa.sin6.sin6_port);
  13358. } else
  13359. #endif
  13360. {
  13361. conn->request_info.remote_port =
  13362. ntohs(conn->client.rsa.sin.sin_port);
  13363. }
  13364. sockaddr_to_string(conn->request_info.remote_addr,
  13365. sizeof(conn->request_info.remote_addr),
  13366. &conn->client.rsa);
  13367. DEBUG_TRACE("Start processing connection from %s",
  13368. conn->request_info.remote_addr);
  13369. #if defined(MG_LEGACY_INTERFACE)
  13370. /* This legacy interface only works for the IPv4 case */
  13371. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  13372. memcpy(&conn->request_info.remote_ip, &addr, 4);
  13373. #endif
  13374. conn->request_info.is_ssl = conn->client.is_ssl;
  13375. if (conn->client.is_ssl) {
  13376. #ifndef NO_SSL
  13377. /* HTTPS connection */
  13378. if (sslize(conn,
  13379. conn->ctx->ssl_ctx,
  13380. SSL_accept,
  13381. &(conn->ctx->stop_flag))) {
  13382. /* Get SSL client certificate information (if set) */
  13383. ssl_get_client_cert_info(conn);
  13384. /* process HTTPS connection */
  13385. process_new_connection(conn);
  13386. /* Free client certificate info */
  13387. if (conn->request_info.client_cert) {
  13388. mg_free((void *)(conn->request_info.client_cert->subject));
  13389. mg_free((void *)(conn->request_info.client_cert->issuer));
  13390. mg_free((void *)(conn->request_info.client_cert->serial));
  13391. mg_free((void *)(conn->request_info.client_cert->finger));
  13392. conn->request_info.client_cert->subject = 0;
  13393. conn->request_info.client_cert->issuer = 0;
  13394. conn->request_info.client_cert->serial = 0;
  13395. conn->request_info.client_cert->finger = 0;
  13396. mg_free(conn->request_info.client_cert);
  13397. conn->request_info.client_cert = 0;
  13398. }
  13399. }
  13400. #endif
  13401. } else {
  13402. /* process HTTP connection */
  13403. process_new_connection(conn);
  13404. }
  13405. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  13406. conn->request_info.remote_addr,
  13407. difftime(time(NULL), conn->conn_birth_time));
  13408. close_connection(conn);
  13409. DEBUG_TRACE("%s", "Connection closed");
  13410. }
  13411. pthread_setspecific(sTlsKey, NULL);
  13412. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13413. CloseHandle(tls.pthread_cond_helper_mutex);
  13414. #endif
  13415. pthread_mutex_destroy(&conn->mutex);
  13416. /* Free the request buffer. */
  13417. conn->buf_size = 0;
  13418. mg_free(conn->buf);
  13419. conn->buf = NULL;
  13420. DEBUG_TRACE("%s", "exiting");
  13421. return NULL;
  13422. }
  13423. /* Threads have different return types on Windows and Unix. */
  13424. #ifdef _WIN32
  13425. static unsigned __stdcall worker_thread(void *thread_func_param)
  13426. {
  13427. struct worker_thread_args *pwta =
  13428. (struct worker_thread_args *)thread_func_param;
  13429. worker_thread_run(pwta);
  13430. mg_free(thread_func_param);
  13431. return 0;
  13432. }
  13433. #else
  13434. static void *
  13435. worker_thread(void *thread_func_param)
  13436. {
  13437. struct worker_thread_args *pwta =
  13438. (struct worker_thread_args *)thread_func_param;
  13439. worker_thread_run(pwta);
  13440. mg_free(thread_func_param);
  13441. return NULL;
  13442. }
  13443. #endif /* _WIN32 */
  13444. static void
  13445. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  13446. {
  13447. struct socket so;
  13448. char src_addr[IP_ADDR_STR_LEN];
  13449. socklen_t len = sizeof(so.rsa);
  13450. int on = 1;
  13451. if (!listener) {
  13452. return;
  13453. }
  13454. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  13455. == INVALID_SOCKET) {
  13456. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  13457. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  13458. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  13459. closesocket(so.sock);
  13460. } else {
  13461. /* Put so socket structure into the queue */
  13462. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  13463. set_close_on_exec(so.sock, fc(ctx));
  13464. so.is_ssl = listener->is_ssl;
  13465. so.ssl_redir = listener->ssl_redir;
  13466. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  13467. mg_cry(fc(ctx),
  13468. "%s: getsockname() failed: %s",
  13469. __func__,
  13470. strerror(ERRNO));
  13471. }
  13472. /* Set TCP keep-alive. This is needed because if HTTP-level
  13473. * keep-alive
  13474. * is enabled, and client resets the connection, server won't get
  13475. * TCP FIN or RST and will keep the connection open forever. With
  13476. * TCP keep-alive, next keep-alive handshake will figure out that
  13477. * the client is down and will close the server end.
  13478. * Thanks to Igor Klopov who suggested the patch. */
  13479. if (setsockopt(so.sock,
  13480. SOL_SOCKET,
  13481. SO_KEEPALIVE,
  13482. (SOCK_OPT_TYPE)&on,
  13483. sizeof(on)) != 0) {
  13484. mg_cry(fc(ctx),
  13485. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  13486. __func__,
  13487. strerror(ERRNO));
  13488. }
  13489. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  13490. * to effectively fill up the underlying IP packet payload and
  13491. * reduce the overhead of sending lots of small buffers. However
  13492. * this hurts the server's throughput (ie. operations per second)
  13493. * when HTTP 1.1 persistent connections are used and the responses
  13494. * are relatively small (eg. less than 1400 bytes).
  13495. */
  13496. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  13497. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  13498. if (set_tcp_nodelay(so.sock, 1) != 0) {
  13499. mg_cry(fc(ctx),
  13500. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  13501. __func__,
  13502. strerror(ERRNO));
  13503. }
  13504. }
  13505. /* We are using non-blocking sockets. Thus, the
  13506. * set_sock_timeout(so.sock, timeout);
  13507. * call is no longer required. */
  13508. set_blocking_mode(so.sock, 0);
  13509. so.in_use = 0;
  13510. produce_socket(ctx, &so);
  13511. }
  13512. }
  13513. static void
  13514. master_thread_run(void *thread_func_param)
  13515. {
  13516. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  13517. struct mg_workerTLS tls;
  13518. struct pollfd *pfd;
  13519. unsigned int i;
  13520. unsigned int workerthreadcount;
  13521. if (!ctx) {
  13522. return;
  13523. }
  13524. mg_set_thread_name("master");
  13525. /* Increase priority of the master thread */
  13526. #if defined(_WIN32)
  13527. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  13528. #elif defined(USE_MASTER_THREAD_PRIORITY)
  13529. int min_prio = sched_get_priority_min(SCHED_RR);
  13530. int max_prio = sched_get_priority_max(SCHED_RR);
  13531. if ((min_prio >= 0) && (max_prio >= 0)
  13532. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  13533. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  13534. struct sched_param sched_param = {0};
  13535. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  13536. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  13537. }
  13538. #endif
  13539. /* Initialize thread local storage */
  13540. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13541. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13542. #endif
  13543. tls.is_master = 1;
  13544. pthread_setspecific(sTlsKey, &tls);
  13545. if (ctx->callbacks.init_thread) {
  13546. /* Callback for the master thread (type 0) */
  13547. ctx->callbacks.init_thread(ctx, 0);
  13548. }
  13549. /* Server starts *now* */
  13550. ctx->start_time = time(NULL);
  13551. /* Start the server */
  13552. pfd = ctx->listening_socket_fds;
  13553. while (ctx->stop_flag == 0) {
  13554. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13555. pfd[i].fd = ctx->listening_sockets[i].sock;
  13556. pfd[i].events = POLLIN;
  13557. }
  13558. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  13559. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13560. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  13561. * successful poll, and POLLIN is defined as
  13562. * (POLLRDNORM | POLLRDBAND)
  13563. * Therefore, we're checking pfd[i].revents & POLLIN, not
  13564. * pfd[i].revents == POLLIN. */
  13565. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  13566. accept_new_connection(&ctx->listening_sockets[i], ctx);
  13567. }
  13568. }
  13569. }
  13570. }
  13571. /* Here stop_flag is 1 - Initiate shutdown. */
  13572. DEBUG_TRACE("%s", "stopping workers");
  13573. /* Stop signal received: somebody called mg_stop. Quit. */
  13574. close_all_listening_sockets(ctx);
  13575. /* Wakeup workers that are waiting for connections to handle. */
  13576. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13577. #if defined(ALTERNATIVE_QUEUE)
  13578. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13579. event_signal(ctx->client_wait_events[i]);
  13580. /* Since we know all sockets, we can shutdown the connections. */
  13581. if (ctx->client_socks[i].in_use) {
  13582. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  13583. }
  13584. }
  13585. #else
  13586. pthread_cond_broadcast(&ctx->sq_full);
  13587. #endif
  13588. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13589. /* Join all worker threads to avoid leaking threads. */
  13590. workerthreadcount = ctx->cfg_worker_threads;
  13591. for (i = 0; i < workerthreadcount; i++) {
  13592. if (ctx->worker_threadids[i] != 0) {
  13593. mg_join_thread(ctx->worker_threadids[i]);
  13594. }
  13595. }
  13596. #if defined(USE_LUA)
  13597. /* Free Lua state of lua background task */
  13598. if (ctx->lua_background_state) {
  13599. lua_close((lua_State *)ctx->lua_background_state);
  13600. ctx->lua_background_state = 0;
  13601. }
  13602. #endif
  13603. DEBUG_TRACE("%s", "exiting");
  13604. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13605. CloseHandle(tls.pthread_cond_helper_mutex);
  13606. #endif
  13607. pthread_setspecific(sTlsKey, NULL);
  13608. /* Signal mg_stop() that we're done.
  13609. * WARNING: This must be the very last thing this
  13610. * thread does, as ctx becomes invalid after this line. */
  13611. ctx->stop_flag = 2;
  13612. }
  13613. /* Threads have different return types on Windows and Unix. */
  13614. #ifdef _WIN32
  13615. static unsigned __stdcall master_thread(void *thread_func_param)
  13616. {
  13617. master_thread_run(thread_func_param);
  13618. return 0;
  13619. }
  13620. #else
  13621. static void *
  13622. master_thread(void *thread_func_param)
  13623. {
  13624. master_thread_run(thread_func_param);
  13625. return NULL;
  13626. }
  13627. #endif /* _WIN32 */
  13628. static void
  13629. free_context(struct mg_context *ctx)
  13630. {
  13631. int i;
  13632. struct mg_handler_info *tmp_rh;
  13633. if (ctx == NULL) {
  13634. return;
  13635. }
  13636. if (ctx->callbacks.exit_context) {
  13637. ctx->callbacks.exit_context(ctx);
  13638. }
  13639. /* All threads exited, no sync is needed. Destroy thread mutex and
  13640. * condvars
  13641. */
  13642. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  13643. #if defined(ALTERNATIVE_QUEUE)
  13644. mg_free(ctx->client_socks);
  13645. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13646. event_destroy(ctx->client_wait_events[i]);
  13647. }
  13648. mg_free(ctx->client_wait_events);
  13649. #else
  13650. (void)pthread_cond_destroy(&ctx->sq_empty);
  13651. (void)pthread_cond_destroy(&ctx->sq_full);
  13652. #endif
  13653. /* Destroy other context global data structures mutex */
  13654. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  13655. #if defined(USE_TIMERS)
  13656. timers_exit(ctx);
  13657. #endif
  13658. /* Deallocate config parameters */
  13659. for (i = 0; i < NUM_OPTIONS; i++) {
  13660. if (ctx->config[i] != NULL) {
  13661. #if defined(_MSC_VER)
  13662. #pragma warning(suppress : 6001)
  13663. #endif
  13664. mg_free(ctx->config[i]);
  13665. }
  13666. }
  13667. /* Deallocate request handlers */
  13668. while (ctx->handlers) {
  13669. tmp_rh = ctx->handlers;
  13670. ctx->handlers = tmp_rh->next;
  13671. mg_free(tmp_rh->uri);
  13672. mg_free(tmp_rh);
  13673. }
  13674. #ifndef NO_SSL
  13675. /* Deallocate SSL context */
  13676. if (ctx->ssl_ctx != NULL) {
  13677. SSL_CTX_free(ctx->ssl_ctx);
  13678. }
  13679. #endif /* !NO_SSL */
  13680. /* Deallocate worker thread ID array */
  13681. if (ctx->worker_threadids != NULL) {
  13682. mg_free(ctx->worker_threadids);
  13683. }
  13684. /* Deallocate worker thread ID array */
  13685. if (ctx->worker_connections != NULL) {
  13686. mg_free(ctx->worker_connections);
  13687. }
  13688. /* deallocate system name string */
  13689. mg_free(ctx->systemName);
  13690. /* Deallocate context itself */
  13691. mg_free(ctx);
  13692. }
  13693. void
  13694. mg_stop(struct mg_context *ctx)
  13695. {
  13696. pthread_t mt;
  13697. if (!ctx) {
  13698. return;
  13699. }
  13700. /* We don't use a lock here. Calling mg_stop with the same ctx from
  13701. * two threads is not allowed. */
  13702. mt = ctx->masterthreadid;
  13703. if (mt == 0) {
  13704. return;
  13705. }
  13706. ctx->masterthreadid = 0;
  13707. /* Set stop flag, so all threads know they have to exit. */
  13708. ctx->stop_flag = 1;
  13709. /* Wait until everything has stopped. */
  13710. while (ctx->stop_flag != 2) {
  13711. (void)mg_sleep(10);
  13712. }
  13713. mg_join_thread(mt);
  13714. free_context(ctx);
  13715. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13716. (void)WSACleanup();
  13717. #endif /* _WIN32 && !__SYMBIAN32__ */
  13718. }
  13719. static void
  13720. get_system_name(char **sysName)
  13721. {
  13722. #if defined(_WIN32)
  13723. #if !defined(__SYMBIAN32__)
  13724. #if defined(_WIN32_WCE)
  13725. *sysName = mg_strdup("WinCE");
  13726. #else
  13727. char name[128];
  13728. DWORD dwVersion = 0;
  13729. DWORD dwMajorVersion = 0;
  13730. DWORD dwMinorVersion = 0;
  13731. DWORD dwBuild = 0;
  13732. BOOL wowRet, isWoW = FALSE;
  13733. #ifdef _MSC_VER
  13734. #pragma warning(push)
  13735. /* GetVersion was declared deprecated */
  13736. #pragma warning(disable : 4996)
  13737. #endif
  13738. dwVersion = GetVersion();
  13739. #ifdef _MSC_VER
  13740. #pragma warning(pop)
  13741. #endif
  13742. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13743. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13744. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  13745. (void)dwBuild;
  13746. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  13747. sprintf(name,
  13748. "Windows %u.%u%s",
  13749. (unsigned)dwMajorVersion,
  13750. (unsigned)dwMinorVersion,
  13751. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  13752. *sysName = mg_strdup(name);
  13753. #endif
  13754. #else
  13755. *sysName = mg_strdup("Symbian");
  13756. #endif
  13757. #else
  13758. struct utsname name;
  13759. memset(&name, 0, sizeof(name));
  13760. uname(&name);
  13761. *sysName = mg_strdup(name.sysname);
  13762. #endif
  13763. }
  13764. struct mg_context *
  13765. mg_start(const struct mg_callbacks *callbacks,
  13766. void *user_data,
  13767. const char **options)
  13768. {
  13769. struct mg_context *ctx;
  13770. const char *name, *value, *default_value;
  13771. int idx, ok, workerthreadcount;
  13772. unsigned int i;
  13773. int itmp;
  13774. void (*exit_callback)(const struct mg_context *ctx) = 0;
  13775. struct mg_workerTLS tls;
  13776. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13777. WSADATA data;
  13778. WSAStartup(MAKEWORD(2, 2), &data);
  13779. #endif /* _WIN32 && !__SYMBIAN32__ */
  13780. /* Allocate context and initialize reasonable general case defaults. */
  13781. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  13782. return NULL;
  13783. }
  13784. /* Random number generator will initialize at the first call */
  13785. ctx->auth_nonce_mask =
  13786. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  13787. if (mg_init_library_called == 0) {
  13788. /* Legacy INIT, if mg_start is called without mg_init_library.
  13789. * Note: This may cause a memory leak */
  13790. mg_init_library(0);
  13791. }
  13792. tls.is_master = -1;
  13793. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13794. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13795. tls.pthread_cond_helper_mutex = NULL;
  13796. #endif
  13797. pthread_setspecific(sTlsKey, &tls);
  13798. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  13799. #if !defined(ALTERNATIVE_QUEUE)
  13800. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  13801. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  13802. #endif
  13803. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  13804. if (!ok) {
  13805. /* Fatal error - abort start. However, this situation should never
  13806. * occur in practice. */
  13807. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  13808. mg_free(ctx);
  13809. pthread_setspecific(sTlsKey, NULL);
  13810. return NULL;
  13811. }
  13812. if (callbacks) {
  13813. ctx->callbacks = *callbacks;
  13814. exit_callback = callbacks->exit_context;
  13815. ctx->callbacks.exit_context = 0;
  13816. }
  13817. ctx->user_data = user_data;
  13818. ctx->handlers = NULL;
  13819. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13820. ctx->shared_lua_websockets = 0;
  13821. #endif
  13822. while (options && (name = *options++) != NULL) {
  13823. if ((idx = get_option_index(name)) == -1) {
  13824. mg_cry(fc(ctx), "Invalid option: %s", name);
  13825. free_context(ctx);
  13826. pthread_setspecific(sTlsKey, NULL);
  13827. return NULL;
  13828. } else if ((value = *options++) == NULL) {
  13829. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  13830. free_context(ctx);
  13831. pthread_setspecific(sTlsKey, NULL);
  13832. return NULL;
  13833. }
  13834. if (ctx->config[idx] != NULL) {
  13835. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  13836. mg_free(ctx->config[idx]);
  13837. }
  13838. ctx->config[idx] = mg_strdup(value);
  13839. DEBUG_TRACE("[%s] -> [%s]", name, value);
  13840. }
  13841. /* Set default value if needed */
  13842. for (i = 0; config_options[i].name != NULL; i++) {
  13843. default_value = config_options[i].default_value;
  13844. if ((ctx->config[i] == NULL) && (default_value != NULL)) {
  13845. ctx->config[i] = mg_strdup(default_value);
  13846. }
  13847. }
  13848. itmp = atoi(ctx->config[MAX_REQUEST_SIZE]);
  13849. if (itmp < 1024) {
  13850. mg_cry(fc(ctx), "max_request_size too small");
  13851. free_context(ctx);
  13852. pthread_setspecific(sTlsKey, NULL);
  13853. return NULL;
  13854. }
  13855. ctx->max_request_size = (unsigned)itmp;
  13856. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  13857. if (workerthreadcount > MAX_WORKER_THREADS) {
  13858. mg_cry(fc(ctx), "Too many worker threads");
  13859. free_context(ctx);
  13860. pthread_setspecific(sTlsKey, NULL);
  13861. return NULL;
  13862. }
  13863. if (workerthreadcount <= 0) {
  13864. mg_cry(fc(ctx), "Invalid number of worker threads");
  13865. free_context(ctx);
  13866. pthread_setspecific(sTlsKey, NULL);
  13867. return NULL;
  13868. }
  13869. #if defined(NO_FILES)
  13870. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  13871. mg_cry(fc(ctx), "%s", "Document root must not be set");
  13872. free_context(ctx);
  13873. pthread_setspecific(sTlsKey, NULL);
  13874. return NULL;
  13875. }
  13876. #endif
  13877. get_system_name(&ctx->systemName);
  13878. #if defined(USE_LUA)
  13879. /* If a Lua background script has been configured, start it. */
  13880. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  13881. char ebuf[256];
  13882. void *state = (void *)mg_prepare_lua_context_script(
  13883. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  13884. if (!state) {
  13885. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  13886. free_context(ctx);
  13887. pthread_setspecific(sTlsKey, NULL);
  13888. return NULL;
  13889. }
  13890. ctx->lua_background_state = state;
  13891. } else {
  13892. ctx->lua_background_state = 0;
  13893. }
  13894. #endif
  13895. /* NOTE(lsm): order is important here. SSL certificates must
  13896. * be initialized before listening ports. UID must be set last. */
  13897. if (!set_gpass_option(ctx) ||
  13898. #if !defined(NO_SSL)
  13899. !set_ssl_option(ctx) ||
  13900. #endif
  13901. !set_ports_option(ctx) ||
  13902. #if !defined(_WIN32)
  13903. !set_uid_option(ctx) ||
  13904. #endif
  13905. !set_acl_option(ctx)) {
  13906. free_context(ctx);
  13907. pthread_setspecific(sTlsKey, NULL);
  13908. return NULL;
  13909. }
  13910. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  13911. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  13912. * won't kill the whole process. */
  13913. (void)signal(SIGPIPE, SIG_IGN);
  13914. #endif /* !_WIN32 && !__SYMBIAN32__ */
  13915. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  13916. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13917. sizeof(pthread_t),
  13918. ctx);
  13919. if (ctx->worker_threadids == NULL) {
  13920. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  13921. free_context(ctx);
  13922. pthread_setspecific(sTlsKey, NULL);
  13923. return NULL;
  13924. }
  13925. ctx->worker_connections =
  13926. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13927. sizeof(struct mg_connection),
  13928. ctx);
  13929. if (ctx->worker_connections == NULL) {
  13930. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  13931. free_context(ctx);
  13932. pthread_setspecific(sTlsKey, NULL);
  13933. return NULL;
  13934. }
  13935. #if defined(ALTERNATIVE_QUEUE)
  13936. ctx->client_wait_events = mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  13937. ctx->cfg_worker_threads,
  13938. ctx);
  13939. if (ctx->client_wait_events == NULL) {
  13940. mg_cry(fc(ctx), "Not enough memory for worker event array");
  13941. mg_free(ctx->worker_threadids);
  13942. free_context(ctx);
  13943. pthread_setspecific(sTlsKey, NULL);
  13944. return NULL;
  13945. }
  13946. ctx->client_socks = mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  13947. ctx->cfg_worker_threads,
  13948. ctx);
  13949. if (ctx->client_wait_events == NULL) {
  13950. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  13951. mg_free(ctx->client_socks);
  13952. mg_free(ctx->worker_threadids);
  13953. free_context(ctx);
  13954. pthread_setspecific(sTlsKey, NULL);
  13955. return NULL;
  13956. }
  13957. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13958. ctx->client_wait_events[i] = event_create();
  13959. if (ctx->client_wait_events[i] == 0) {
  13960. mg_cry(fc(ctx), "Error creating worker event %i", i);
  13961. while (i > 0) {
  13962. i--;
  13963. event_destroy(ctx->client_wait_events[i]);
  13964. }
  13965. mg_free(ctx->client_socks);
  13966. mg_free(ctx->worker_threadids);
  13967. free_context(ctx);
  13968. pthread_setspecific(sTlsKey, NULL);
  13969. return NULL;
  13970. }
  13971. }
  13972. #endif
  13973. #if defined(USE_TIMERS)
  13974. if (timers_init(ctx) != 0) {
  13975. mg_cry(fc(ctx), "Error creating timers");
  13976. free_context(ctx);
  13977. pthread_setspecific(sTlsKey, NULL);
  13978. return NULL;
  13979. }
  13980. #endif
  13981. /* Context has been created - init user libraries */
  13982. if (ctx->callbacks.init_context) {
  13983. ctx->callbacks.init_context(ctx);
  13984. }
  13985. ctx->callbacks.exit_context = exit_callback;
  13986. ctx->context_type = 1; /* server context */
  13987. /* Start master (listening) thread */
  13988. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  13989. /* Start worker threads */
  13990. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13991. struct worker_thread_args *wta = (struct worker_thread_args *)
  13992. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  13993. if (wta) {
  13994. wta->ctx = ctx;
  13995. wta->index = (int)i;
  13996. }
  13997. if ((wta == NULL)
  13998. || (mg_start_thread_with_id(worker_thread,
  13999. wta,
  14000. &ctx->worker_threadids[i]) != 0)) {
  14001. /* thread was not created */
  14002. if (wta != NULL) {
  14003. mg_free(wta);
  14004. }
  14005. if (i > 0) {
  14006. mg_cry(fc(ctx),
  14007. "Cannot start worker thread %i: error %ld",
  14008. i + 1,
  14009. (long)ERRNO);
  14010. } else {
  14011. mg_cry(fc(ctx),
  14012. "Cannot create threads: error %ld",
  14013. (long)ERRNO);
  14014. free_context(ctx);
  14015. pthread_setspecific(sTlsKey, NULL);
  14016. return NULL;
  14017. }
  14018. break;
  14019. }
  14020. }
  14021. pthread_setspecific(sTlsKey, NULL);
  14022. return ctx;
  14023. }
  14024. /* Feature check API function */
  14025. unsigned
  14026. mg_check_feature(unsigned feature)
  14027. {
  14028. static const unsigned feature_set = 0
  14029. /* Set bits for available features according to API documentation.
  14030. * This bit mask is created at compile time, according to the active
  14031. * preprocessor defines. It is a single const value at runtime. */
  14032. #if !defined(NO_FILES)
  14033. | 0x0001u
  14034. #endif
  14035. #if !defined(NO_SSL)
  14036. | 0x0002u
  14037. #endif
  14038. #if !defined(NO_CGI)
  14039. | 0x0004u
  14040. #endif
  14041. #if defined(USE_IPV6)
  14042. | 0x0008u
  14043. #endif
  14044. #if defined(USE_WEBSOCKET)
  14045. | 0x0010u
  14046. #endif
  14047. #if defined(USE_LUA)
  14048. | 0x0020u
  14049. #endif
  14050. #if defined(USE_DUKTAPE)
  14051. | 0x0040u
  14052. #endif
  14053. #if !defined(NO_CACHING)
  14054. | 0x0080u
  14055. #endif
  14056. #if defined(USE_SERVER_STATS)
  14057. | 0x0100u
  14058. #endif
  14059. /* Set some extra bits not defined in the API documentation.
  14060. * These bits may change without further notice. */
  14061. #if defined(MG_LEGACY_INTERFACE)
  14062. | 0x8000u
  14063. #endif
  14064. #if defined(MEMORY_DEBUGGING)
  14065. | 0x0100u
  14066. #endif
  14067. #if defined(USE_TIMERS)
  14068. | 0x0200u
  14069. #endif
  14070. #if !defined(NO_NONCE_CHECK)
  14071. | 0x0400u
  14072. #endif
  14073. #if !defined(NO_POPEN)
  14074. | 0x0800u
  14075. #endif
  14076. ;
  14077. return (feature & feature_set);
  14078. }
  14079. /* Get system information. It can be printed or stored by the caller.
  14080. * Return the size of available information. */
  14081. static int
  14082. mg_get_system_info_impl(char *buffer, int buflen)
  14083. {
  14084. char block[256];
  14085. int system_info_length = 0;
  14086. #if defined(_WIN32)
  14087. const char *eol = "\r\n";
  14088. #else
  14089. const char *eol = "\n";
  14090. #endif
  14091. if (buffer == NULL) {
  14092. /* Avoid some warning (although, if some dillweed supplies
  14093. * buffer==NULL combined with buflen>0, he deserves a crash).
  14094. */
  14095. buflen = 0;
  14096. }
  14097. /* Server version */
  14098. {
  14099. const char *version = mg_version();
  14100. mg_snprintf(NULL,
  14101. NULL,
  14102. block,
  14103. sizeof(block),
  14104. "Server Version: %s%s",
  14105. version,
  14106. eol);
  14107. system_info_length += (int)strlen(block);
  14108. if (system_info_length < buflen) {
  14109. strcat(buffer, block);
  14110. }
  14111. }
  14112. /* System info */
  14113. {
  14114. #if defined(_WIN32)
  14115. #if !defined(__SYMBIAN32__)
  14116. DWORD dwVersion = 0;
  14117. DWORD dwMajorVersion = 0;
  14118. DWORD dwMinorVersion = 0;
  14119. SYSTEM_INFO si;
  14120. GetSystemInfo(&si);
  14121. #ifdef _MSC_VER
  14122. #pragma warning(push)
  14123. /* GetVersion was declared deprecated */
  14124. #pragma warning(disable : 4996)
  14125. #endif
  14126. dwVersion = GetVersion();
  14127. #ifdef _MSC_VER
  14128. #pragma warning(pop)
  14129. #endif
  14130. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14131. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14132. mg_snprintf(NULL,
  14133. NULL,
  14134. block,
  14135. sizeof(block),
  14136. "Windows %u.%u%s",
  14137. (unsigned)dwMajorVersion,
  14138. (unsigned)dwMinorVersion,
  14139. eol);
  14140. system_info_length += (int)strlen(block);
  14141. if (system_info_length < buflen) {
  14142. strcat(buffer, block);
  14143. }
  14144. mg_snprintf(NULL,
  14145. NULL,
  14146. block,
  14147. sizeof(block),
  14148. "CPU: type %u, cores %u, mask %x%s",
  14149. (unsigned)si.wProcessorArchitecture,
  14150. (unsigned)si.dwNumberOfProcessors,
  14151. (unsigned)si.dwActiveProcessorMask,
  14152. eol);
  14153. system_info_length += (int)strlen(block);
  14154. if (system_info_length < buflen) {
  14155. strcat(buffer, block);
  14156. }
  14157. #else
  14158. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  14159. system_info_length += (int)strlen(block);
  14160. if (system_info_length < buflen) {
  14161. strcat(buffer, block);
  14162. }
  14163. #endif
  14164. #else
  14165. struct utsname name;
  14166. memset(&name, 0, sizeof(name));
  14167. uname(&name);
  14168. mg_snprintf(NULL,
  14169. NULL,
  14170. block,
  14171. sizeof(block),
  14172. "%s %s (%s) - %s%s",
  14173. name.sysname,
  14174. name.version,
  14175. name.release,
  14176. name.machine,
  14177. eol);
  14178. system_info_length += (int)strlen(block);
  14179. if (system_info_length < buflen) {
  14180. strcat(buffer, block);
  14181. }
  14182. #endif
  14183. }
  14184. /* Features */
  14185. {
  14186. mg_snprintf(NULL,
  14187. NULL,
  14188. block,
  14189. sizeof(block),
  14190. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  14191. mg_check_feature(0xFFFFFFFFu),
  14192. eol,
  14193. mg_check_feature(1) ? " Files" : "",
  14194. mg_check_feature(2) ? " HTTPS" : "",
  14195. mg_check_feature(4) ? " CGI" : "",
  14196. mg_check_feature(8) ? " IPv6" : "",
  14197. mg_check_feature(16) ? " WebSockets" : "",
  14198. mg_check_feature(32) ? " Lua" : "",
  14199. mg_check_feature(64) ? " JavaScript" : "",
  14200. mg_check_feature(128) ? " Cache" : "",
  14201. eol);
  14202. system_info_length += (int)strlen(block);
  14203. if (system_info_length < buflen) {
  14204. strcat(buffer, block);
  14205. }
  14206. #ifdef USE_LUA
  14207. mg_snprintf(NULL,
  14208. NULL,
  14209. block,
  14210. sizeof(block),
  14211. "Lua Version: %u (%s)%s",
  14212. (unsigned)LUA_VERSION_NUM,
  14213. LUA_RELEASE,
  14214. eol);
  14215. system_info_length += (int)strlen(block);
  14216. if (system_info_length < buflen) {
  14217. strcat(buffer, block);
  14218. }
  14219. #endif
  14220. #if defined(USE_DUKTAPE)
  14221. mg_snprintf(NULL,
  14222. NULL,
  14223. block,
  14224. sizeof(block),
  14225. "JavaScript: Duktape %u.%u.%u%s",
  14226. (unsigned)DUK_VERSION / 10000,
  14227. ((unsigned)DUK_VERSION / 100) % 100,
  14228. (unsigned)DUK_VERSION % 100,
  14229. eol);
  14230. system_info_length += (int)strlen(block);
  14231. if (system_info_length < buflen) {
  14232. strcat(buffer, block);
  14233. }
  14234. #endif
  14235. }
  14236. /* Build date */
  14237. {
  14238. mg_snprintf(
  14239. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  14240. system_info_length += (int)strlen(block);
  14241. if (system_info_length < buflen) {
  14242. strcat(buffer, block);
  14243. }
  14244. }
  14245. /* Compiler information */
  14246. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  14247. {
  14248. #if defined(_MSC_VER)
  14249. mg_snprintf(NULL,
  14250. NULL,
  14251. block,
  14252. sizeof(block),
  14253. "MSC: %u (%u)%s",
  14254. (unsigned)_MSC_VER,
  14255. (unsigned)_MSC_FULL_VER,
  14256. eol);
  14257. system_info_length += (int)strlen(block);
  14258. if (system_info_length < buflen) {
  14259. strcat(buffer, block);
  14260. }
  14261. #elif defined(__MINGW64__)
  14262. mg_snprintf(NULL,
  14263. NULL,
  14264. block,
  14265. sizeof(block),
  14266. "MinGW64: %u.%u%s",
  14267. (unsigned)__MINGW64_VERSION_MAJOR,
  14268. (unsigned)__MINGW64_VERSION_MINOR,
  14269. eol);
  14270. system_info_length += (int)strlen(block);
  14271. if (system_info_length < buflen) {
  14272. strcat(buffer, block);
  14273. }
  14274. mg_snprintf(NULL,
  14275. NULL,
  14276. block,
  14277. sizeof(block),
  14278. "MinGW32: %u.%u%s",
  14279. (unsigned)__MINGW32_MAJOR_VERSION,
  14280. (unsigned)__MINGW32_MINOR_VERSION,
  14281. eol);
  14282. system_info_length += (int)strlen(block);
  14283. if (system_info_length < buflen) {
  14284. strcat(buffer, block);
  14285. }
  14286. #elif defined(__MINGW32__)
  14287. mg_snprintf(NULL,
  14288. NULL,
  14289. block,
  14290. sizeof(block),
  14291. "MinGW32: %u.%u%s",
  14292. (unsigned)__MINGW32_MAJOR_VERSION,
  14293. (unsigned)__MINGW32_MINOR_VERSION,
  14294. eol);
  14295. system_info_length += (int)strlen(block);
  14296. if (system_info_length < buflen) {
  14297. strcat(buffer, block);
  14298. }
  14299. #elif defined(__clang__)
  14300. mg_snprintf(NULL,
  14301. NULL,
  14302. block,
  14303. sizeof(block),
  14304. "clang: %u.%u.%u (%s)%s",
  14305. __clang_major__,
  14306. __clang_minor__,
  14307. __clang_patchlevel__,
  14308. __clang_version__,
  14309. eol);
  14310. system_info_length += (int)strlen(block);
  14311. if (system_info_length < buflen) {
  14312. strcat(buffer, block);
  14313. }
  14314. #elif defined(__GNUC__)
  14315. mg_snprintf(NULL,
  14316. NULL,
  14317. block,
  14318. sizeof(block),
  14319. "gcc: %u.%u.%u%s",
  14320. (unsigned)__GNUC__,
  14321. (unsigned)__GNUC_MINOR__,
  14322. (unsigned)__GNUC_PATCHLEVEL__,
  14323. eol);
  14324. system_info_length += (int)strlen(block);
  14325. if (system_info_length < buflen) {
  14326. strcat(buffer, block);
  14327. }
  14328. #elif defined(__INTEL_COMPILER)
  14329. mg_snprintf(NULL,
  14330. NULL,
  14331. block,
  14332. sizeof(block),
  14333. "Intel C/C++: %u%s",
  14334. (unsigned)__INTEL_COMPILER,
  14335. eol);
  14336. system_info_length += (int)strlen(block);
  14337. if (system_info_length < buflen) {
  14338. strcat(buffer, block);
  14339. }
  14340. #elif defined(__BORLANDC__)
  14341. mg_snprintf(NULL,
  14342. NULL,
  14343. block,
  14344. sizeof(block),
  14345. "Borland C: 0x%x%s",
  14346. (unsigned)__BORLANDC__,
  14347. eol);
  14348. system_info_length += (int)strlen(block);
  14349. if (system_info_length < buflen) {
  14350. strcat(buffer, block);
  14351. }
  14352. #elif defined(__SUNPRO_C)
  14353. mg_snprintf(NULL,
  14354. NULL,
  14355. block,
  14356. sizeof(block),
  14357. "Solaris: 0x%x%s",
  14358. (unsigned)__SUNPRO_C,
  14359. eol);
  14360. system_info_length += (int)strlen(block);
  14361. if (system_info_length < buflen) {
  14362. strcat(buffer, block);
  14363. }
  14364. #else
  14365. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  14366. system_info_length += (int)strlen(block);
  14367. if (system_info_length < buflen) {
  14368. strcat(buffer, block);
  14369. }
  14370. #endif
  14371. }
  14372. /* Determine 32/64 bit data mode.
  14373. * see https://en.wikipedia.org/wiki/64-bit_computing */
  14374. {
  14375. mg_snprintf(NULL,
  14376. NULL,
  14377. block,
  14378. sizeof(block),
  14379. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  14380. "ptr:%u, size:%u, time:%u%s",
  14381. (unsigned)sizeof(short),
  14382. (unsigned)sizeof(int),
  14383. (unsigned)sizeof(long),
  14384. (unsigned)sizeof(long long),
  14385. (unsigned)sizeof(float),
  14386. (unsigned)sizeof(double),
  14387. (unsigned)sizeof(long double),
  14388. (unsigned)sizeof(char),
  14389. (unsigned)sizeof(wchar_t),
  14390. (unsigned)sizeof(void *),
  14391. (unsigned)sizeof(size_t),
  14392. (unsigned)sizeof(time_t),
  14393. eol);
  14394. system_info_length += (int)strlen(block);
  14395. if (system_info_length < buflen) {
  14396. strcat(buffer, block);
  14397. }
  14398. }
  14399. return system_info_length;
  14400. }
  14401. #if defined(USE_SERVER_STATS)
  14402. /* Get context information. It can be printed or stored by the caller.
  14403. * Return the size of available information. */
  14404. static int
  14405. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  14406. {
  14407. char block[256];
  14408. int context_info_length = 0;
  14409. #if defined(_WIN32)
  14410. const char *eol = "\r\n";
  14411. #else
  14412. const char *eol = "\n";
  14413. #endif
  14414. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  14415. const char *eoobj = "}";
  14416. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  14417. if ((buffer == NULL) || (buflen < 10)) {
  14418. buflen = 0;
  14419. }
  14420. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  14421. context_info_length += (int)strlen(block);
  14422. if (context_info_length < buflen) {
  14423. strcat(buffer, block);
  14424. }
  14425. /* Memory information */
  14426. if (ms) {
  14427. mg_snprintf(NULL,
  14428. NULL,
  14429. block,
  14430. sizeof(block),
  14431. "\"memory\" : {%s"
  14432. "\"blocks\" : %i,%s"
  14433. "\"used\" : %" INT64_FMT ",%s"
  14434. "\"maxUsed\" : %" INT64_FMT "%s"
  14435. "}%s%s",
  14436. eol,
  14437. ms->blockCount,
  14438. eol,
  14439. ms->totalMemUsed,
  14440. eol,
  14441. ms->maxMemUsed,
  14442. eol,
  14443. (ctx ? "," : ""),
  14444. eol);
  14445. context_info_length += (int)strlen(block);
  14446. if (context_info_length + reserved_len < buflen) {
  14447. strcat(buffer, block);
  14448. }
  14449. }
  14450. /* Connections information */
  14451. if (ctx) {
  14452. mg_snprintf(NULL,
  14453. NULL,
  14454. block,
  14455. sizeof(block),
  14456. "\"connections\" : {%s"
  14457. "\"active\" : %i,%s"
  14458. "\"maxActive\" : %i,%s"
  14459. "\"total\" : %" INT64_FMT "%s"
  14460. "},%s",
  14461. eol,
  14462. ctx->active_connections,
  14463. eol,
  14464. ctx->max_connections,
  14465. eol,
  14466. ctx->total_connections,
  14467. eol,
  14468. eol);
  14469. context_info_length += (int)strlen(block);
  14470. if (context_info_length + reserved_len < buflen) {
  14471. strcat(buffer, block);
  14472. }
  14473. }
  14474. /* Requests information */
  14475. if (ctx) {
  14476. mg_snprintf(NULL,
  14477. NULL,
  14478. block,
  14479. sizeof(block),
  14480. "\"requests\" : {%s"
  14481. "\"total\" : %" INT64_FMT "%s"
  14482. "}%s",
  14483. eol,
  14484. ctx->total_requests,
  14485. eol,
  14486. eol);
  14487. context_info_length += (int)strlen(block);
  14488. if (context_info_length + reserved_len < buflen) {
  14489. strcat(buffer, block);
  14490. }
  14491. }
  14492. if ((buflen > 0) && buffer && buffer[0]) {
  14493. if (context_info_length < buflen) {
  14494. strcat(buffer, eoobj);
  14495. strcat(buffer, eol);
  14496. context_info_length += reserved_len;
  14497. }
  14498. }
  14499. return context_info_length;
  14500. }
  14501. #endif
  14502. /* Get system information. It can be printed or stored by the caller.
  14503. * Return the size of available information. */
  14504. int
  14505. mg_get_system_info(char *buffer, int buflen)
  14506. {
  14507. if ((buffer == NULL) || (buflen < 1)) {
  14508. return mg_get_system_info_impl(NULL, 0);
  14509. } else {
  14510. /* Reset buffer, so we can always use strcat. */
  14511. buffer[0] = 0;
  14512. return mg_get_system_info_impl(buffer, buflen);
  14513. }
  14514. }
  14515. /* Get context information. It can be printed or stored by the caller.
  14516. * Return the size of available information. */
  14517. int
  14518. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  14519. {
  14520. #if defined(USE_SERVER_STATS)
  14521. if ((buffer == NULL) || (buflen < 1)) {
  14522. return mg_get_context_info_impl(ctx, NULL, 0);
  14523. } else {
  14524. /* Reset buffer, so we can always use strcat. */
  14525. buffer[0] = 0;
  14526. return mg_get_context_info_impl(ctx, buffer, buflen);
  14527. }
  14528. #else
  14529. (void)ctx;
  14530. if ((buffer != NULL) && (buflen > 0)) {
  14531. buffer[0] = 0;
  14532. }
  14533. return 0;
  14534. #endif
  14535. }
  14536. /* Initialize this library. This function does not need to be thread safe.
  14537. */
  14538. unsigned
  14539. mg_init_library(unsigned features)
  14540. {
  14541. #if !defined(NO_SSL)
  14542. char ebuf[128];
  14543. #endif
  14544. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  14545. unsigned features_inited = features_to_init;
  14546. if (mg_init_library_called <= 0) {
  14547. /* Not initialized yet */
  14548. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  14549. return 0;
  14550. }
  14551. }
  14552. mg_global_lock();
  14553. if (mg_init_library_called <= 0) {
  14554. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  14555. /* Fatal error - abort start. However, this situation should
  14556. * never occur in practice. */
  14557. return 0;
  14558. }
  14559. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14560. InitializeCriticalSection(&global_log_file_lock);
  14561. #endif /* _WIN32 && !__SYMBIAN32__ */
  14562. #if !defined(_WIN32)
  14563. pthread_mutexattr_init(&pthread_mutex_attr);
  14564. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  14565. #endif
  14566. #if defined(USE_LUA)
  14567. lua_init_optional_libraries();
  14568. #endif
  14569. }
  14570. #if !defined(NO_SSL)
  14571. if (features_to_init & 2) {
  14572. if (!mg_ssl_initialized) {
  14573. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  14574. mg_ssl_initialized = 1;
  14575. } else {
  14576. (void)ebuf;
  14577. /* TODO: print error */
  14578. features_inited &= ~(2u);
  14579. }
  14580. } else {
  14581. /* ssl already initialized */
  14582. }
  14583. }
  14584. #endif
  14585. /* Start WinSock for Windows */
  14586. if (mg_init_library_called <= 0) {
  14587. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14588. WSADATA data;
  14589. WSAStartup(MAKEWORD(2, 2), &data);
  14590. #endif /* _WIN32 && !__SYMBIAN32__ */
  14591. mg_init_library_called = 1;
  14592. } else {
  14593. mg_init_library_called++;
  14594. }
  14595. mg_global_unlock();
  14596. return features_inited;
  14597. }
  14598. /* Un-initialize this library. */
  14599. unsigned
  14600. mg_exit_library(void)
  14601. {
  14602. if (mg_init_library_called <= 0) {
  14603. return 0;
  14604. }
  14605. mg_global_lock();
  14606. mg_init_library_called--;
  14607. if (mg_init_library_called == 0) {
  14608. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14609. (void)WSACleanup();
  14610. #endif /* _WIN32 && !__SYMBIAN32__ */
  14611. #if !defined(NO_SSL)
  14612. if (mg_ssl_initialized) {
  14613. uninitialize_ssl();
  14614. mg_ssl_initialized = 0;
  14615. }
  14616. #endif
  14617. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14618. (void)DeleteCriticalSection(&global_log_file_lock);
  14619. #endif /* _WIN32 && !__SYMBIAN32__ */
  14620. #if !defined(_WIN32)
  14621. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  14622. #endif
  14623. (void)pthread_key_delete(sTlsKey);
  14624. #if defined(USE_LUA)
  14625. lua_exit_optional_libraries();
  14626. #endif
  14627. mg_global_unlock();
  14628. (void)pthread_mutex_destroy(&global_lock_mutex);
  14629. return 1;
  14630. }
  14631. mg_global_unlock();
  14632. return 1;
  14633. }
  14634. /* End of civetweb.c */