civetweb.c 433 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400
  1. /* Copyright (c) 2013-2017 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. #ifndef CIVETWEB_HEADER_INCLUDED
  101. /* Include the header file here, so the CivetWeb interface is defined for the
  102. * entire implementation, including the following forward definitions. */
  103. #include "civetweb.h"
  104. #endif
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __clang__
  116. /* When using -Weverything, clang does not accept it's own headers
  117. * in a release build configuration. Disable what is too much in
  118. * -Weverything. */
  119. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  120. #endif
  121. #ifdef __MACH__ /* Apple OSX section */
  122. #ifdef __clang__
  123. /* Avoid warnings for Xopen 7.00 and higher */
  124. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  125. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  126. #endif
  127. #define CLOCK_MONOTONIC (1)
  128. #define CLOCK_REALTIME (2)
  129. #include <sys/errno.h>
  130. #include <sys/time.h>
  131. #include <mach/clock.h>
  132. #include <mach/mach.h>
  133. #include <mach/mach_time.h>
  134. #include <assert.h>
  135. /* clock_gettime is not implemented on OSX prior to 10.12 */
  136. static int
  137. _civet_clock_gettime(int clk_id, struct timespec *t)
  138. {
  139. memset(t, 0, sizeof(*t));
  140. if (clk_id == CLOCK_REALTIME) {
  141. struct timeval now;
  142. int rv = gettimeofday(&now, NULL);
  143. if (rv) {
  144. return rv;
  145. }
  146. t->tv_sec = now.tv_sec;
  147. t->tv_nsec = now.tv_usec * 1000;
  148. return 0;
  149. } else if (clk_id == CLOCK_MONOTONIC) {
  150. static uint64_t clock_start_time = 0;
  151. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  152. uint64_t now = mach_absolute_time();
  153. if (clock_start_time == 0) {
  154. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  155. #if defined(DEBUG)
  156. assert(mach_status == KERN_SUCCESS);
  157. #else
  158. /* appease "unused variable" warning for release builds */
  159. (void)mach_status;
  160. #endif
  161. clock_start_time = now;
  162. }
  163. now = (uint64_t)((double)(now - clock_start_time)
  164. * (double)timebase_ifo.numer
  165. / (double)timebase_ifo.denom);
  166. t->tv_sec = now / 1000000000;
  167. t->tv_nsec = now % 1000000000;
  168. return 0;
  169. }
  170. return -1; /* EINVAL - Clock ID is unknown */
  171. }
  172. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  173. #ifdef __CLOCK_AVAILABILITY
  174. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  175. * declared but it may be NULL at runtime. So we need to check before using
  176. * it. */
  177. static int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #include <stdint.h>
  200. #ifndef INT64_MAX
  201. #define INT64_MAX (9223372036854775807)
  202. #endif
  203. #ifndef MAX_WORKER_THREADS
  204. #define MAX_WORKER_THREADS (1024 * 64)
  205. #endif
  206. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  207. #define SOCKET_TIMEOUT_QUANTUM (2000)
  208. #endif
  209. #define SHUTDOWN_RD (0)
  210. #define SHUTDOWN_WR (1)
  211. #define SHUTDOWN_BOTH (2)
  212. mg_static_assert(MAX_WORKER_THREADS >= 1,
  213. "worker threads must be a positive number");
  214. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  215. "size_t data type size check");
  216. #if defined(_WIN32) \
  217. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  218. #include <windows.h>
  219. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  220. #include <ws2tcpip.h>
  221. typedef const char *SOCK_OPT_TYPE;
  222. #if !defined(PATH_MAX)
  223. #define PATH_MAX (MAX_PATH)
  224. #endif
  225. #if !defined(PATH_MAX)
  226. #define PATH_MAX (4096)
  227. #endif
  228. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  229. #ifndef _IN_PORT_T
  230. #ifndef in_port_t
  231. #define in_port_t u_short
  232. #endif
  233. #endif
  234. #ifndef _WIN32_WCE
  235. #include <process.h>
  236. #include <direct.h>
  237. #include <io.h>
  238. #else /* _WIN32_WCE */
  239. #define NO_CGI /* WinCE has no pipes */
  240. #define NO_POPEN /* WinCE has no popen */
  241. typedef long off_t;
  242. #define errno ((int)(GetLastError()))
  243. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  244. #endif /* _WIN32_WCE */
  245. #define MAKEUQUAD(lo, hi) \
  246. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  247. #define RATE_DIFF (10000000) /* 100 nsecs */
  248. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  249. #define SYS2UNIX_TIME(lo, hi) \
  250. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  251. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  252. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  253. * Also use _strtoui64 on modern M$ compilers */
  254. #if defined(_MSC_VER)
  255. #if (_MSC_VER < 1300)
  256. #define STRX(x) #x
  257. #define STR(x) STRX(x)
  258. #define __func__ __FILE__ ":" STR(__LINE__)
  259. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  260. #define strtoll(x, y, z) (_atoi64(x))
  261. #else
  262. #define __func__ __FUNCTION__
  263. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  264. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  265. #endif
  266. #endif /* _MSC_VER */
  267. #define ERRNO ((int)(GetLastError()))
  268. #define NO_SOCKLEN_T
  269. #if defined(_WIN64) || defined(__MINGW64__)
  270. #define SSL_LIB "ssleay64.dll"
  271. #define CRYPTO_LIB "libeay64.dll"
  272. #else
  273. #define SSL_LIB "ssleay32.dll"
  274. #define CRYPTO_LIB "libeay32.dll"
  275. #endif
  276. #define O_NONBLOCK (0)
  277. #ifndef W_OK
  278. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  279. #endif
  280. #if !defined(EWOULDBLOCK)
  281. #define EWOULDBLOCK WSAEWOULDBLOCK
  282. #endif /* !EWOULDBLOCK */
  283. #define _POSIX_
  284. #define INT64_FMT "I64d"
  285. #define UINT64_FMT "I64u"
  286. #define WINCDECL __cdecl
  287. #define vsnprintf_impl _vsnprintf
  288. #define access _access
  289. #define mg_sleep(x) (Sleep(x))
  290. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  291. #ifndef popen
  292. #define popen(x, y) (_popen(x, y))
  293. #endif
  294. #ifndef pclose
  295. #define pclose(x) (_pclose(x))
  296. #endif
  297. #define close(x) (_close(x))
  298. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  299. #define RTLD_LAZY (0)
  300. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  301. #define fdopen(x, y) (_fdopen((x), (y)))
  302. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  303. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  304. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  305. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  306. #define sleep(x) (Sleep((x)*1000))
  307. #define rmdir(x) (_rmdir(x))
  308. #define timegm(x) (_mkgmtime(x))
  309. #if !defined(fileno)
  310. #define fileno(x) (_fileno(x))
  311. #endif /* !fileno MINGW #defines fileno */
  312. typedef HANDLE pthread_mutex_t;
  313. typedef DWORD pthread_key_t;
  314. typedef HANDLE pthread_t;
  315. typedef struct {
  316. CRITICAL_SECTION threadIdSec;
  317. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  318. } pthread_cond_t;
  319. #ifndef __clockid_t_defined
  320. typedef DWORD clockid_t;
  321. #endif
  322. #ifndef CLOCK_MONOTONIC
  323. #define CLOCK_MONOTONIC (1)
  324. #endif
  325. #ifndef CLOCK_REALTIME
  326. #define CLOCK_REALTIME (2)
  327. #endif
  328. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  329. #define _TIMESPEC_DEFINED
  330. #endif
  331. #ifndef _TIMESPEC_DEFINED
  332. struct timespec {
  333. time_t tv_sec; /* seconds */
  334. long tv_nsec; /* nanoseconds */
  335. };
  336. #endif
  337. #if !defined(WIN_PTHREADS_TIME_H)
  338. #define MUST_IMPLEMENT_CLOCK_GETTIME
  339. #endif
  340. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  341. #define clock_gettime mg_clock_gettime
  342. static int
  343. clock_gettime(clockid_t clk_id, struct timespec *tp)
  344. {
  345. FILETIME ft;
  346. ULARGE_INTEGER li;
  347. BOOL ok = FALSE;
  348. double d;
  349. static double perfcnt_per_sec = 0.0;
  350. if (tp) {
  351. memset(tp, 0, sizeof(*tp));
  352. if (clk_id == CLOCK_REALTIME) {
  353. GetSystemTimeAsFileTime(&ft);
  354. li.LowPart = ft.dwLowDateTime;
  355. li.HighPart = ft.dwHighDateTime;
  356. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  357. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  358. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  359. ok = TRUE;
  360. } else if (clk_id == CLOCK_MONOTONIC) {
  361. if (perfcnt_per_sec == 0.0) {
  362. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  363. perfcnt_per_sec = 1.0 / li.QuadPart;
  364. }
  365. if (perfcnt_per_sec != 0.0) {
  366. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  367. d = li.QuadPart * perfcnt_per_sec;
  368. tp->tv_sec = (time_t)d;
  369. d -= tp->tv_sec;
  370. tp->tv_nsec = (long)(d * 1.0E9);
  371. ok = TRUE;
  372. }
  373. }
  374. }
  375. return ok ? 0 : -1;
  376. }
  377. #endif
  378. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  379. static int pthread_mutex_lock(pthread_mutex_t *);
  380. static int pthread_mutex_unlock(pthread_mutex_t *);
  381. static void path_to_unicode(const struct mg_connection *conn,
  382. const char *path,
  383. wchar_t *wbuf,
  384. size_t wbuf_len);
  385. /* All file operations need to be rewritten to solve #246. */
  386. #include "file_ops.inl"
  387. struct mg_file;
  388. static const char *
  389. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  390. /* POSIX dirent interface */
  391. struct dirent {
  392. char d_name[PATH_MAX];
  393. };
  394. typedef struct DIR {
  395. HANDLE handle;
  396. WIN32_FIND_DATAW info;
  397. struct dirent result;
  398. } DIR;
  399. #if defined(_WIN32) && !defined(POLLIN)
  400. #ifndef HAVE_POLL
  401. struct pollfd {
  402. SOCKET fd;
  403. short events;
  404. short revents;
  405. };
  406. #define POLLIN (0x0300)
  407. #endif
  408. #endif
  409. /* Mark required libraries */
  410. #if defined(_MSC_VER)
  411. #pragma comment(lib, "Ws2_32.lib")
  412. #endif
  413. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. #include <sys/wait.h>
  416. #include <sys/socket.h>
  417. #include <sys/poll.h>
  418. #include <netinet/in.h>
  419. #include <arpa/inet.h>
  420. #include <sys/time.h>
  421. #include <sys/utsname.h>
  422. #include <stdint.h>
  423. #include <inttypes.h>
  424. #include <netdb.h>
  425. #include <netinet/tcp.h>
  426. typedef const void *SOCK_OPT_TYPE;
  427. #if defined(ANDROID)
  428. typedef unsigned short int in_port_t;
  429. #endif
  430. #include <pwd.h>
  431. #include <unistd.h>
  432. #include <grp.h>
  433. #include <dirent.h>
  434. #define vsnprintf_impl vsnprintf
  435. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  436. #include <dlfcn.h>
  437. #endif
  438. #include <pthread.h>
  439. #if defined(__MACH__)
  440. #define SSL_LIB "libssl.dylib"
  441. #define CRYPTO_LIB "libcrypto.dylib"
  442. #else
  443. #if !defined(SSL_LIB)
  444. #define SSL_LIB "libssl.so"
  445. #endif
  446. #if !defined(CRYPTO_LIB)
  447. #define CRYPTO_LIB "libcrypto.so"
  448. #endif
  449. #endif
  450. #ifndef O_BINARY
  451. #define O_BINARY (0)
  452. #endif /* O_BINARY */
  453. #define closesocket(a) (close(a))
  454. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  455. #define mg_remove(conn, x) (remove(x))
  456. #define mg_sleep(x) (usleep((x)*1000))
  457. #define mg_opendir(conn, x) (opendir(x))
  458. #define mg_closedir(x) (closedir(x))
  459. #define mg_readdir(x) (readdir(x))
  460. #define ERRNO (errno)
  461. #define INVALID_SOCKET (-1)
  462. #define INT64_FMT PRId64
  463. #define UINT64_FMT PRIu64
  464. typedef int SOCKET;
  465. #define WINCDECL
  466. #if defined(__hpux)
  467. /* HPUX 11 does not have monotonic, fall back to realtime */
  468. #ifndef CLOCK_MONOTONIC
  469. #define CLOCK_MONOTONIC CLOCK_REALTIME
  470. #endif
  471. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  472. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  473. * the prototypes use int* rather than socklen_t* which matches the
  474. * actual library expectation. When called with the wrong size arg
  475. * accept() returns a zero client inet addr and check_acl() always
  476. * fails. Since socklen_t is widely used below, just force replace
  477. * their typedef with int. - DTL
  478. */
  479. #define socklen_t int
  480. #endif /* hpux */
  481. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  482. WINDOWS / UNIX include block */
  483. /* va_copy should always be a macro, C99 and C++11 - DTL */
  484. #ifndef va_copy
  485. #define va_copy(x, y) ((x) = (y))
  486. #endif
  487. #ifdef _WIN32
  488. /* Create substitutes for POSIX functions in Win32. */
  489. #if defined(__MINGW32__)
  490. /* Show no warning in case system functions are not used. */
  491. #pragma GCC diagnostic push
  492. #pragma GCC diagnostic ignored "-Wunused-function"
  493. #endif
  494. static CRITICAL_SECTION global_log_file_lock;
  495. static DWORD
  496. pthread_self(void)
  497. {
  498. return GetCurrentThreadId();
  499. }
  500. static int
  501. pthread_key_create(
  502. pthread_key_t *key,
  503. void (*_ignored)(void *) /* destructor not supported for Windows */
  504. )
  505. {
  506. (void)_ignored;
  507. if ((key != 0)) {
  508. *key = TlsAlloc();
  509. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  510. }
  511. return -2;
  512. }
  513. static int
  514. pthread_key_delete(pthread_key_t key)
  515. {
  516. return TlsFree(key) ? 0 : 1;
  517. }
  518. static int
  519. pthread_setspecific(pthread_key_t key, void *value)
  520. {
  521. return TlsSetValue(key, value) ? 0 : 1;
  522. }
  523. static void *
  524. pthread_getspecific(pthread_key_t key)
  525. {
  526. return TlsGetValue(key);
  527. }
  528. #if defined(__MINGW32__)
  529. /* Enable unused function warning again */
  530. #pragma GCC diagnostic pop
  531. #endif
  532. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  533. #else
  534. static pthread_mutexattr_t pthread_mutex_attr;
  535. #endif /* _WIN32 */
  536. #define PASSWORDS_FILE_NAME ".htpasswd"
  537. #define CGI_ENVIRONMENT_SIZE (4096)
  538. #define MAX_CGI_ENVIR_VARS (256)
  539. #define MG_BUF_LEN (8192)
  540. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  541. #if defined(_WIN32_WCE)
  542. /* Create substitutes for POSIX functions in Win32. */
  543. #if defined(__MINGW32__)
  544. /* Show no warning in case system functions are not used. */
  545. #pragma GCC diagnostic push
  546. #pragma GCC diagnostic ignored "-Wunused-function"
  547. #endif
  548. static time_t
  549. time(time_t *ptime)
  550. {
  551. time_t t;
  552. SYSTEMTIME st;
  553. FILETIME ft;
  554. GetSystemTime(&st);
  555. SystemTimeToFileTime(&st, &ft);
  556. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  557. if (ptime != NULL) {
  558. *ptime = t;
  559. }
  560. return t;
  561. }
  562. static struct tm *
  563. localtime_s(const time_t *ptime, struct tm *ptm)
  564. {
  565. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  566. FILETIME ft, lft;
  567. SYSTEMTIME st;
  568. TIME_ZONE_INFORMATION tzinfo;
  569. if (ptm == NULL) {
  570. return NULL;
  571. }
  572. *(int64_t *)&ft = t;
  573. FileTimeToLocalFileTime(&ft, &lft);
  574. FileTimeToSystemTime(&lft, &st);
  575. ptm->tm_year = st.wYear - 1900;
  576. ptm->tm_mon = st.wMonth - 1;
  577. ptm->tm_wday = st.wDayOfWeek;
  578. ptm->tm_mday = st.wDay;
  579. ptm->tm_hour = st.wHour;
  580. ptm->tm_min = st.wMinute;
  581. ptm->tm_sec = st.wSecond;
  582. ptm->tm_yday = 0; /* hope nobody uses this */
  583. ptm->tm_isdst =
  584. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  585. return ptm;
  586. }
  587. static struct tm *
  588. gmtime_s(const time_t *ptime, struct tm *ptm)
  589. {
  590. /* FIXME(lsm): fix this. */
  591. return localtime_s(ptime, ptm);
  592. }
  593. static int mg_atomic_inc(volatile int *addr);
  594. static struct tm tm_array[MAX_WORKER_THREADS];
  595. static int tm_index = 0;
  596. static struct tm *
  597. localtime(const time_t *ptime)
  598. {
  599. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  600. return localtime_s(ptime, tm_array + i);
  601. }
  602. static struct tm *
  603. gmtime(const time_t *ptime)
  604. {
  605. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  606. return gmtime_s(ptime, tm_array + i);
  607. }
  608. static size_t
  609. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  610. {
  611. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  612. * for WinCE"); */
  613. return 0;
  614. }
  615. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  616. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  617. #define remove(f) mg_remove(NULL, f)
  618. static int
  619. rename(const char *a, const char *b)
  620. {
  621. wchar_t wa[PATH_MAX];
  622. wchar_t wb[PATH_MAX];
  623. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  624. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  625. return MoveFileW(wa, wb) ? 0 : -1;
  626. }
  627. struct stat {
  628. int64_t st_size;
  629. time_t st_mtime;
  630. };
  631. static int
  632. stat(const char *name, struct stat *st)
  633. {
  634. wchar_t wbuf[PATH_MAX];
  635. WIN32_FILE_ATTRIBUTE_DATA attr;
  636. time_t creation_time, write_time;
  637. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  638. memset(&attr, 0, sizeof(attr));
  639. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  640. st->st_size =
  641. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  642. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  643. attr.ftLastWriteTime.dwHighDateTime);
  644. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  645. attr.ftCreationTime.dwHighDateTime);
  646. if (creation_time > write_time) {
  647. st->st_mtime = creation_time;
  648. } else {
  649. st->st_mtime = write_time;
  650. }
  651. return 0;
  652. }
  653. #define access(x, a) 1 /* not required anyway */
  654. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  655. /* Values from errno.h in Windows SDK (Visual Studio). */
  656. #define EEXIST 17
  657. #define EACCES 13
  658. #define ENOENT 2
  659. #if defined(__MINGW32__)
  660. /* Enable unused function warning again */
  661. #pragma GCC diagnostic pop
  662. #endif
  663. #endif /* defined(_WIN32_WCE) */
  664. static int
  665. mg_atomic_inc(volatile int *addr)
  666. {
  667. int ret;
  668. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  669. /* Depending on the SDK, this function uses either
  670. * (volatile unsigned int *) or (volatile LONG *),
  671. * so whatever you use, the other SDK is likely to raise a warning. */
  672. ret = InterlockedIncrement((volatile long *)addr);
  673. #elif defined(__GNUC__) \
  674. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  675. ret = __sync_add_and_fetch(addr, 1);
  676. #else
  677. ret = (++(*addr));
  678. #endif
  679. return ret;
  680. }
  681. static int
  682. mg_atomic_dec(volatile int *addr)
  683. {
  684. int ret;
  685. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  686. /* Depending on the SDK, this function uses either
  687. * (volatile unsigned int *) or (volatile LONG *),
  688. * so whatever you use, the other SDK is likely to raise a warning. */
  689. ret = InterlockedDecrement((volatile long *)addr);
  690. #elif defined(__GNUC__) \
  691. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  692. ret = __sync_sub_and_fetch(addr, 1);
  693. #else
  694. ret = (--(*addr));
  695. #endif
  696. return ret;
  697. }
  698. #if defined(__GNUC__) || defined(__MINGW32__)
  699. /* Show no warning in case system functions are not used. */
  700. #pragma GCC diagnostic push
  701. #pragma GCC diagnostic ignored "-Wunused-function"
  702. #endif
  703. #if defined(__clang__)
  704. /* Show no warning in case system functions are not used. */
  705. #pragma clang diagnostic push
  706. #pragma clang diagnostic ignored "-Wunused-function"
  707. #endif
  708. #if defined(USE_SERVER_STATS)
  709. static int64_t
  710. mg_atomic_add(volatile int64_t *addr, int64_t value)
  711. {
  712. int64_t ret;
  713. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  714. ret = InterlockedAdd64(addr, value);
  715. #elif defined(__GNUC__) \
  716. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  717. ret = __sync_add_and_fetch(addr, value);
  718. #else
  719. ret = (++(*addr));
  720. #endif
  721. return ret;
  722. }
  723. #endif
  724. #if defined(__GNUC__)
  725. /* Show no warning in case system functions are not used. */
  726. #pragma GCC diagnostic pop
  727. #endif
  728. #if defined(__clang__)
  729. /* Show no warning in case system functions are not used. */
  730. #pragma clang diagnostic pop
  731. #endif
  732. #if defined(USE_SERVER_STATS)
  733. struct mg_memory_stat {
  734. volatile int64_t totalMemUsed;
  735. volatile int64_t maxMemUsed;
  736. volatile int blockCount;
  737. };
  738. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  739. static void *
  740. mg_malloc_ex(size_t size,
  741. struct mg_context *ctx,
  742. const char *file,
  743. unsigned line)
  744. {
  745. void *data = malloc(size + 2 * sizeof(uintptr_t));
  746. void *memory = 0;
  747. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  748. #if defined(MEMORY_DEBUGGING)
  749. char mallocStr[256];
  750. #else
  751. (void)file;
  752. (void)line;
  753. #endif
  754. if (data) {
  755. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  756. if (mmem > mstat->maxMemUsed) {
  757. /* could use atomic compare exchange, but this
  758. * seems overkill for statistics data */
  759. mstat->maxMemUsed = mmem;
  760. }
  761. mg_atomic_inc(&mstat->blockCount);
  762. ((uintptr_t *)data)[0] = size;
  763. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  764. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  765. }
  766. #if defined(MEMORY_DEBUGGING)
  767. sprintf(mallocStr,
  768. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  769. memory,
  770. (unsigned long)size,
  771. (unsigned long)mstat->totalMemUsed,
  772. (unsigned long)mstat->blockCount,
  773. file,
  774. line);
  775. #if defined(_WIN32)
  776. OutputDebugStringA(mallocStr);
  777. #else
  778. DEBUG_TRACE("%s", mallocStr);
  779. #endif
  780. #endif
  781. return memory;
  782. }
  783. static void *
  784. mg_calloc_ex(size_t count,
  785. size_t size,
  786. struct mg_context *ctx,
  787. const char *file,
  788. unsigned line)
  789. {
  790. void *data = mg_malloc_ex(size * count, ctx, file, line);
  791. if (data) {
  792. memset(data, 0, size * count);
  793. }
  794. return data;
  795. }
  796. static void
  797. mg_free_ex(void *memory, const char *file, unsigned line)
  798. {
  799. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  800. #if defined(MEMORY_DEBUGGING)
  801. char mallocStr[256];
  802. #else
  803. (void)file;
  804. (void)line;
  805. #endif
  806. if (memory) {
  807. uintptr_t size = ((uintptr_t *)data)[0];
  808. struct mg_memory_stat *mstat =
  809. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  810. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  811. mg_atomic_dec(&mstat->blockCount);
  812. #if defined(MEMORY_DEBUGGING)
  813. sprintf(mallocStr,
  814. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  815. memory,
  816. (unsigned long)size,
  817. (unsigned long)mstat->totalMemUsed,
  818. (unsigned long)mstat->blockCount,
  819. file,
  820. line);
  821. #if defined(_WIN32)
  822. OutputDebugStringA(mallocStr);
  823. #else
  824. DEBUG_TRACE("%s", mallocStr);
  825. #endif
  826. #endif
  827. free(data);
  828. }
  829. }
  830. static void *
  831. mg_realloc_ex(void *memory,
  832. size_t newsize,
  833. struct mg_context *ctx,
  834. const char *file,
  835. unsigned line)
  836. {
  837. void *data;
  838. void *_realloc;
  839. uintptr_t oldsize;
  840. #if defined(MEMORY_DEBUGGING)
  841. char mallocStr[256];
  842. #else
  843. (void)file;
  844. (void)line;
  845. #endif
  846. if (newsize) {
  847. if (memory) {
  848. /* Reallocate existing block */
  849. struct mg_memory_stat *mstat;
  850. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  851. oldsize = ((uintptr_t *)data)[0];
  852. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  853. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  854. if (_realloc) {
  855. data = _realloc;
  856. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  857. #if defined(MEMORY_DEBUGGING)
  858. sprintf(mallocStr,
  859. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  860. memory,
  861. (unsigned long)oldsize,
  862. (unsigned long)mstat->totalMemUsed,
  863. (unsigned long)mstat->blockCount,
  864. file,
  865. line);
  866. #if defined(_WIN32)
  867. OutputDebugStringA(mallocStr);
  868. #else
  869. DEBUG_TRACE("%s", mallocStr);
  870. #endif
  871. #endif
  872. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  873. #if defined(MEMORY_DEBUGGING)
  874. sprintf(mallocStr,
  875. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  876. memory,
  877. (unsigned long)newsize,
  878. (unsigned long)mstat->totalMemUsed,
  879. (unsigned long)mstat->blockCount,
  880. file,
  881. line);
  882. #if defined(_WIN32)
  883. OutputDebugStringA(mallocStr);
  884. #else
  885. DEBUG_TRACE("%s", mallocStr);
  886. #endif
  887. #endif
  888. *(uintptr_t *)data = newsize;
  889. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  890. } else {
  891. #if defined(MEMORY_DEBUGGING)
  892. #if defined(_WIN32)
  893. OutputDebugStringA("MEM: realloc failed\n");
  894. #else
  895. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  896. #endif
  897. #endif
  898. return _realloc;
  899. }
  900. } else {
  901. /* Allocate new block */
  902. data = mg_malloc_ex(newsize, ctx, file, line);
  903. }
  904. } else {
  905. /* Free existing block */
  906. data = 0;
  907. mg_free_ex(memory, file, line);
  908. }
  909. return data;
  910. }
  911. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  912. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  913. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  914. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  915. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  916. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  917. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  918. #else /* USE_SERVER_STATS */
  919. static __inline void *
  920. mg_malloc(size_t a)
  921. {
  922. return malloc(a);
  923. }
  924. static __inline void *
  925. mg_calloc(size_t a, size_t b)
  926. {
  927. return calloc(a, b);
  928. }
  929. static __inline void *
  930. mg_realloc(void *a, size_t b)
  931. {
  932. return realloc(a, b);
  933. }
  934. static __inline void
  935. mg_free(void *a)
  936. {
  937. free(a);
  938. }
  939. #define mg_malloc_ctx(a, c) mg_malloc(a)
  940. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  941. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  942. #define mg_free_ctx(a, c) mg_free(a)
  943. #endif /* USE_SERVER_STATS */
  944. static void mg_vsnprintf(const struct mg_connection *conn,
  945. int *truncated,
  946. char *buf,
  947. size_t buflen,
  948. const char *fmt,
  949. va_list ap);
  950. static void mg_snprintf(const struct mg_connection *conn,
  951. int *truncated,
  952. char *buf,
  953. size_t buflen,
  954. PRINTF_FORMAT_STRING(const char *fmt),
  955. ...) PRINTF_ARGS(5, 6);
  956. /* This following lines are just meant as a reminder to use the mg-functions
  957. * for memory management */
  958. #ifdef malloc
  959. #undef malloc
  960. #endif
  961. #ifdef calloc
  962. #undef calloc
  963. #endif
  964. #ifdef realloc
  965. #undef realloc
  966. #endif
  967. #ifdef free
  968. #undef free
  969. #endif
  970. #ifdef snprintf
  971. #undef snprintf
  972. #endif
  973. #ifdef vsnprintf
  974. #undef vsnprintf
  975. #endif
  976. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  977. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  978. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  979. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  980. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  981. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  982. * but this define only works well for Windows. */
  983. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  984. #endif
  985. static pthread_key_t sTlsKey; /* Thread local storage index */
  986. static int sTlsInit = 0;
  987. static int thread_idx_max = 0;
  988. struct mg_workerTLS {
  989. int is_master;
  990. unsigned long thread_idx;
  991. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  992. HANDLE pthread_cond_helper_mutex;
  993. struct mg_workerTLS *next_waiting_thread;
  994. #endif
  995. };
  996. #if defined(__GNUC__) || defined(__MINGW32__)
  997. /* Show no warning in case system functions are not used. */
  998. #pragma GCC diagnostic push
  999. #pragma GCC diagnostic ignored "-Wunused-function"
  1000. #endif
  1001. #if defined(__clang__)
  1002. /* Show no warning in case system functions are not used. */
  1003. #pragma clang diagnostic push
  1004. #pragma clang diagnostic ignored "-Wunused-function"
  1005. #endif
  1006. /* Get a unique thread ID as unsigned long, independent from the data type
  1007. * of thread IDs defined by the operating system API.
  1008. * If two calls to mg_current_thread_id return the same value, they calls
  1009. * are done from the same thread. If they return different values, they are
  1010. * done from different threads. (Provided this function is used in the same
  1011. * process context and threads are not repeatedly created and deleted, but
  1012. * CivetWeb does not do that).
  1013. * This function must match the signature required for SSL id callbacks:
  1014. * CRYPTO_set_id_callback
  1015. */
  1016. static unsigned long
  1017. mg_current_thread_id(void)
  1018. {
  1019. #ifdef _WIN32
  1020. return GetCurrentThreadId();
  1021. #else
  1022. #ifdef __clang__
  1023. #pragma clang diagnostic push
  1024. #pragma clang diagnostic ignored "-Wunreachable-code"
  1025. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1026. * or not, so one of the two conditions will be unreachable by construction.
  1027. * Unfortunately the C standard does not define a way to check this at
  1028. * compile time, since the #if preprocessor conditions can not use the sizeof
  1029. * operator as an argument. */
  1030. #endif
  1031. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1032. /* This is the problematic case for CRYPTO_set_id_callback:
  1033. * The OS pthread_t can not be cast to unsigned long. */
  1034. struct mg_workerTLS *tls =
  1035. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1036. if (tls == NULL) {
  1037. /* SSL called from an unknown thread: Create some thread index.
  1038. */
  1039. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1040. tls->is_master = -2; /* -2 means "3rd party thread" */
  1041. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1042. pthread_setspecific(sTlsKey, tls);
  1043. }
  1044. return tls->thread_idx;
  1045. } else {
  1046. /* pthread_t may be any data type, so a simple cast to unsigned long
  1047. * can rise a warning/error, depending on the platform.
  1048. * Here memcpy is used as an anything-to-anything cast. */
  1049. unsigned long ret = 0;
  1050. pthread_t t = pthread_self();
  1051. memcpy(&ret, &t, sizeof(pthread_t));
  1052. return ret;
  1053. }
  1054. #ifdef __clang__
  1055. #pragma clang diagnostic pop
  1056. #endif
  1057. #endif
  1058. }
  1059. static uint64_t
  1060. mg_get_current_time_ns(void)
  1061. {
  1062. struct timespec tsnow;
  1063. clock_gettime(CLOCK_REALTIME, &tsnow);
  1064. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1065. }
  1066. #if defined(__GNUC__)
  1067. /* Show no warning in case system functions are not used. */
  1068. #pragma GCC diagnostic pop
  1069. #endif
  1070. #if defined(__clang__)
  1071. /* Show no warning in case system functions are not used. */
  1072. #pragma clang diagnostic pop
  1073. #endif
  1074. #if !defined(DEBUG_TRACE)
  1075. #if defined(DEBUG)
  1076. static void DEBUG_TRACE_FUNC(const char *func,
  1077. unsigned line,
  1078. PRINTF_FORMAT_STRING(const char *fmt),
  1079. ...) PRINTF_ARGS(3, 4);
  1080. static void
  1081. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1082. {
  1083. va_list args;
  1084. uint64_t nsnow;
  1085. static uint64_t nslast;
  1086. struct timespec tsnow;
  1087. /* Get some operating system independent thread id */
  1088. unsigned long thread_id = mg_current_thread_id();
  1089. clock_gettime(CLOCK_REALTIME, &tsnow);
  1090. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1091. + ((uint64_t)tsnow.tv_nsec);
  1092. if (!nslast) {
  1093. nslast = nsnow;
  1094. }
  1095. flockfile(stdout);
  1096. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1097. (unsigned long)tsnow.tv_sec,
  1098. (unsigned long)tsnow.tv_nsec,
  1099. nsnow - nslast,
  1100. thread_id,
  1101. func,
  1102. line);
  1103. va_start(args, fmt);
  1104. vprintf(fmt, args);
  1105. va_end(args);
  1106. putchar('\n');
  1107. fflush(stdout);
  1108. funlockfile(stdout);
  1109. nslast = nsnow;
  1110. }
  1111. #define DEBUG_TRACE(fmt, ...) \
  1112. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1113. #else
  1114. #define DEBUG_TRACE(fmt, ...) \
  1115. do { \
  1116. } while (0)
  1117. #endif /* DEBUG */
  1118. #endif /* DEBUG_TRACE */
  1119. #define MD5_STATIC static
  1120. #include "md5.inl"
  1121. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1122. #ifdef NO_SOCKLEN_T
  1123. typedef int socklen_t;
  1124. #endif /* NO_SOCKLEN_T */
  1125. #define _DARWIN_UNLIMITED_SELECT
  1126. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1127. #if !defined(MSG_NOSIGNAL)
  1128. #define MSG_NOSIGNAL (0)
  1129. #endif
  1130. #if !defined(SOMAXCONN)
  1131. #define SOMAXCONN (100)
  1132. #endif
  1133. /* Size of the accepted socket queue */
  1134. #if !defined(MGSQLEN)
  1135. #define MGSQLEN (20)
  1136. #endif
  1137. #if defined(NO_SSL)
  1138. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1139. typedef struct SSL_CTX SSL_CTX;
  1140. #else
  1141. #if defined(NO_SSL_DL)
  1142. #include <openssl/ssl.h>
  1143. #include <openssl/err.h>
  1144. #include <openssl/crypto.h>
  1145. #include <openssl/x509.h>
  1146. #include <openssl/pem.h>
  1147. #include <openssl/engine.h>
  1148. #include <openssl/conf.h>
  1149. #include <openssl/dh.h>
  1150. #include <openssl/bn.h>
  1151. #include <openssl/opensslv.h>
  1152. #else
  1153. /* SSL loaded dynamically from DLL.
  1154. * I put the prototypes here to be independent from OpenSSL source
  1155. * installation. */
  1156. typedef struct ssl_st SSL;
  1157. typedef struct ssl_method_st SSL_METHOD;
  1158. typedef struct ssl_ctx_st SSL_CTX;
  1159. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1160. typedef struct x509_name X509_NAME;
  1161. typedef struct asn1_integer ASN1_INTEGER;
  1162. typedef struct bignum BIGNUM;
  1163. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1164. typedef struct evp_md EVP_MD;
  1165. typedef struct x509 X509;
  1166. #define SSL_CTRL_OPTIONS (32)
  1167. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1168. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1169. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1170. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1171. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1172. #define SSL_VERIFY_NONE (0)
  1173. #define SSL_VERIFY_PEER (1)
  1174. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1175. #define SSL_VERIFY_CLIENT_ONCE (4)
  1176. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1177. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1178. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1179. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1180. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1181. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1182. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1183. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1184. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1185. #define SSL_ERROR_NONE (0)
  1186. #define SSL_ERROR_SSL (1)
  1187. #define SSL_ERROR_WANT_READ (2)
  1188. #define SSL_ERROR_WANT_WRITE (3)
  1189. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1190. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1191. #define SSL_ERROR_ZERO_RETURN (6)
  1192. #define SSL_ERROR_WANT_CONNECT (7)
  1193. #define SSL_ERROR_WANT_ACCEPT (8)
  1194. struct ssl_func {
  1195. const char *name; /* SSL function name */
  1196. void (*ptr)(void); /* Function pointer */
  1197. };
  1198. #ifdef OPENSSL_API_1_1
  1199. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1200. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1201. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1202. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1203. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1204. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1205. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1206. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1207. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1208. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1209. #define OPENSSL_init_ssl \
  1210. (*(int (*)(uint64_t opts, \
  1211. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1212. #define SSL_CTX_use_PrivateKey_file \
  1213. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1214. #define SSL_CTX_use_certificate_file \
  1215. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1216. #define SSL_CTX_set_default_passwd_cb \
  1217. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1218. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1219. #define SSL_CTX_use_certificate_chain_file \
  1220. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1221. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1222. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1223. #define SSL_CTX_set_verify \
  1224. (*(void (*)(SSL_CTX *, \
  1225. int, \
  1226. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1227. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1228. #define SSL_CTX_load_verify_locations \
  1229. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1230. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1231. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1232. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1233. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1234. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1235. #define SSL_CIPHER_get_name \
  1236. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1237. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1238. #define SSL_CTX_set_session_id_context \
  1239. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1240. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1241. #define SSL_CTX_set_cipher_list \
  1242. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1243. #define SSL_CTX_set_options \
  1244. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1245. #define SSL_CTX_clear_options(ctx, op) \
  1246. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1247. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1248. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1249. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1250. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1251. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1252. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1253. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1254. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1255. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1256. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1257. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1258. #define X509_NAME_oneline \
  1259. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1260. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1261. #define EVP_get_digestbyname \
  1262. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1263. #define EVP_Digest \
  1264. (*(int (*)( \
  1265. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1266. crypto_sw[10].ptr)
  1267. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1268. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1269. #define ASN1_INTEGER_to_BN \
  1270. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1271. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1272. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1273. #define OPENSSL_free(a) CRYPTO_free(a)
  1274. /* set_ssl_option() function updates this array.
  1275. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1276. * of respective functions. The macros above (like SSL_connect()) are really
  1277. * just calling these functions indirectly via the pointer. */
  1278. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1279. {"SSL_accept", NULL},
  1280. {"SSL_connect", NULL},
  1281. {"SSL_read", NULL},
  1282. {"SSL_write", NULL},
  1283. {"SSL_get_error", NULL},
  1284. {"SSL_set_fd", NULL},
  1285. {"SSL_new", NULL},
  1286. {"SSL_CTX_new", NULL},
  1287. {"TLS_server_method", NULL},
  1288. {"OPENSSL_init_ssl", NULL},
  1289. {"SSL_CTX_use_PrivateKey_file", NULL},
  1290. {"SSL_CTX_use_certificate_file", NULL},
  1291. {"SSL_CTX_set_default_passwd_cb", NULL},
  1292. {"SSL_CTX_free", NULL},
  1293. {"SSL_CTX_use_certificate_chain_file", NULL},
  1294. {"TLS_client_method", NULL},
  1295. {"SSL_pending", NULL},
  1296. {"SSL_CTX_set_verify", NULL},
  1297. {"SSL_shutdown", NULL},
  1298. {"SSL_CTX_load_verify_locations", NULL},
  1299. {"SSL_CTX_set_default_verify_paths", NULL},
  1300. {"SSL_CTX_set_verify_depth", NULL},
  1301. {"SSL_get_peer_certificate", NULL},
  1302. {"SSL_get_version", NULL},
  1303. {"SSL_get_current_cipher", NULL},
  1304. {"SSL_CIPHER_get_name", NULL},
  1305. {"SSL_CTX_check_private_key", NULL},
  1306. {"SSL_CTX_set_session_id_context", NULL},
  1307. {"SSL_CTX_ctrl", NULL},
  1308. {"SSL_CTX_set_cipher_list", NULL},
  1309. {"SSL_CTX_set_options", NULL},
  1310. {NULL, NULL}};
  1311. /* Similar array as ssl_sw. These functions could be located in different
  1312. * lib. */
  1313. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1314. {"ERR_error_string", NULL},
  1315. {"ERR_remove_state", NULL},
  1316. {"CONF_modules_unload", NULL},
  1317. {"X509_free", NULL},
  1318. {"X509_get_subject_name", NULL},
  1319. {"X509_get_issuer_name", NULL},
  1320. {"X509_NAME_oneline", NULL},
  1321. {"X509_get_serialNumber", NULL},
  1322. {"EVP_get_digestbyname", NULL},
  1323. {"EVP_Digest", NULL},
  1324. {"i2d_X509", NULL},
  1325. {"BN_bn2hex", NULL},
  1326. {"ASN1_INTEGER_to_BN", NULL},
  1327. {"BN_free", NULL},
  1328. {"CRYPTO_free", NULL},
  1329. {NULL, NULL}};
  1330. #else
  1331. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1332. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1333. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1334. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1335. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1336. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1337. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1338. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1339. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1340. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1341. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1342. #define SSL_CTX_use_PrivateKey_file \
  1343. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1344. #define SSL_CTX_use_certificate_file \
  1345. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1346. #define SSL_CTX_set_default_passwd_cb \
  1347. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1348. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1349. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1350. #define SSL_CTX_use_certificate_chain_file \
  1351. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1352. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1353. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1354. #define SSL_CTX_set_verify \
  1355. (*(void (*)(SSL_CTX *, \
  1356. int, \
  1357. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1358. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1359. #define SSL_CTX_load_verify_locations \
  1360. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1361. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1362. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1363. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1364. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1365. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1366. #define SSL_CIPHER_get_name \
  1367. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1368. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1369. #define SSL_CTX_set_session_id_context \
  1370. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1371. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1372. #define SSL_CTX_set_cipher_list \
  1373. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1374. #define SSL_CTX_set_options(ctx, op) \
  1375. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1376. #define SSL_CTX_clear_options(ctx, op) \
  1377. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1378. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1379. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1380. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1381. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1382. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1383. #define CRYPTO_set_locking_callback \
  1384. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1385. #define CRYPTO_set_id_callback \
  1386. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1387. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1388. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1389. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1390. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1391. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1392. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1393. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1394. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1395. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1396. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1397. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1398. #define X509_NAME_oneline \
  1399. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1400. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1401. #define i2c_ASN1_INTEGER \
  1402. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1403. #define EVP_get_digestbyname \
  1404. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1405. #define EVP_Digest \
  1406. (*(int (*)( \
  1407. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1408. crypto_sw[18].ptr)
  1409. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1410. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1411. #define ASN1_INTEGER_to_BN \
  1412. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1413. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1414. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1415. #define OPENSSL_free(a) CRYPTO_free(a)
  1416. /* set_ssl_option() function updates this array.
  1417. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1418. * of respective functions. The macros above (like SSL_connect()) are really
  1419. * just calling these functions indirectly via the pointer. */
  1420. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1421. {"SSL_accept", NULL},
  1422. {"SSL_connect", NULL},
  1423. {"SSL_read", NULL},
  1424. {"SSL_write", NULL},
  1425. {"SSL_get_error", NULL},
  1426. {"SSL_set_fd", NULL},
  1427. {"SSL_new", NULL},
  1428. {"SSL_CTX_new", NULL},
  1429. {"SSLv23_server_method", NULL},
  1430. {"SSL_library_init", NULL},
  1431. {"SSL_CTX_use_PrivateKey_file", NULL},
  1432. {"SSL_CTX_use_certificate_file", NULL},
  1433. {"SSL_CTX_set_default_passwd_cb", NULL},
  1434. {"SSL_CTX_free", NULL},
  1435. {"SSL_load_error_strings", NULL},
  1436. {"SSL_CTX_use_certificate_chain_file", NULL},
  1437. {"SSLv23_client_method", NULL},
  1438. {"SSL_pending", NULL},
  1439. {"SSL_CTX_set_verify", NULL},
  1440. {"SSL_shutdown", NULL},
  1441. {"SSL_CTX_load_verify_locations", NULL},
  1442. {"SSL_CTX_set_default_verify_paths", NULL},
  1443. {"SSL_CTX_set_verify_depth", NULL},
  1444. {"SSL_get_peer_certificate", NULL},
  1445. {"SSL_get_version", NULL},
  1446. {"SSL_get_current_cipher", NULL},
  1447. {"SSL_CIPHER_get_name", NULL},
  1448. {"SSL_CTX_check_private_key", NULL},
  1449. {"SSL_CTX_set_session_id_context", NULL},
  1450. {"SSL_CTX_ctrl", NULL},
  1451. {"SSL_CTX_set_cipher_list", NULL},
  1452. {NULL, NULL}};
  1453. /* Similar array as ssl_sw. These functions could be located in different
  1454. * lib. */
  1455. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1456. {"CRYPTO_set_locking_callback", NULL},
  1457. {"CRYPTO_set_id_callback", NULL},
  1458. {"ERR_get_error", NULL},
  1459. {"ERR_error_string", NULL},
  1460. {"ERR_remove_state", NULL},
  1461. {"ERR_free_strings", NULL},
  1462. {"ENGINE_cleanup", NULL},
  1463. {"CONF_modules_unload", NULL},
  1464. {"CRYPTO_cleanup_all_ex_data", NULL},
  1465. {"EVP_cleanup", NULL},
  1466. {"X509_free", NULL},
  1467. {"X509_get_subject_name", NULL},
  1468. {"X509_get_issuer_name", NULL},
  1469. {"X509_NAME_oneline", NULL},
  1470. {"X509_get_serialNumber", NULL},
  1471. {"i2c_ASN1_INTEGER", NULL},
  1472. {"EVP_get_digestbyname", NULL},
  1473. {"EVP_Digest", NULL},
  1474. {"i2d_X509", NULL},
  1475. {"BN_bn2hex", NULL},
  1476. {"ASN1_INTEGER_to_BN", NULL},
  1477. {"BN_free", NULL},
  1478. {"CRYPTO_free", NULL},
  1479. {NULL, NULL}};
  1480. #endif /* OPENSSL_API_1_1 */
  1481. #endif /* NO_SSL_DL */
  1482. #endif /* NO_SSL */
  1483. #if !defined(NO_CACHING)
  1484. static const char *month_names[] = {"Jan",
  1485. "Feb",
  1486. "Mar",
  1487. "Apr",
  1488. "May",
  1489. "Jun",
  1490. "Jul",
  1491. "Aug",
  1492. "Sep",
  1493. "Oct",
  1494. "Nov",
  1495. "Dec"};
  1496. #endif /* !NO_CACHING */
  1497. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1498. * union u. */
  1499. union usa {
  1500. struct sockaddr sa;
  1501. struct sockaddr_in sin;
  1502. #if defined(USE_IPV6)
  1503. struct sockaddr_in6 sin6;
  1504. #endif
  1505. };
  1506. /* Describes a string (chunk of memory). */
  1507. struct vec {
  1508. const char *ptr;
  1509. size_t len;
  1510. };
  1511. struct mg_file_stat {
  1512. /* File properties filled by mg_stat: */
  1513. uint64_t size;
  1514. time_t last_modified;
  1515. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1516. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1517. * case we need a "Content-Eencoding: gzip" header */
  1518. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1519. };
  1520. struct mg_file_in_memory {
  1521. char *p;
  1522. uint32_t pos;
  1523. char mode;
  1524. };
  1525. struct mg_file_access {
  1526. /* File properties filled by mg_fopen: */
  1527. FILE *fp;
  1528. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1529. * support library. Use some struct mg_file_in_memory *mf; instead of
  1530. * membuf char pointer. */
  1531. const char *membuf;
  1532. };
  1533. struct mg_file {
  1534. struct mg_file_stat stat;
  1535. struct mg_file_access access;
  1536. };
  1537. #define STRUCT_FILE_INITIALIZER \
  1538. { \
  1539. { \
  1540. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1541. } \
  1542. , \
  1543. { \
  1544. (FILE *) NULL, (const char *)NULL \
  1545. } \
  1546. }
  1547. /* Describes listening socket, or socket which was accept()-ed by the master
  1548. * thread and queued for future handling by the worker thread. */
  1549. struct socket {
  1550. SOCKET sock; /* Listening socket */
  1551. union usa lsa; /* Local socket address */
  1552. union usa rsa; /* Remote socket address */
  1553. unsigned char is_ssl; /* Is port SSL-ed */
  1554. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1555. * port */
  1556. unsigned char in_use; /* Is valid */
  1557. };
  1558. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1559. enum {
  1560. CGI_EXTENSIONS,
  1561. CGI_ENVIRONMENT,
  1562. PUT_DELETE_PASSWORDS_FILE,
  1563. CGI_INTERPRETER,
  1564. PROTECT_URI,
  1565. AUTHENTICATION_DOMAIN,
  1566. ENABLE_AUTH_DOMAIN_CHECK,
  1567. SSI_EXTENSIONS,
  1568. THROTTLE,
  1569. ACCESS_LOG_FILE,
  1570. ENABLE_DIRECTORY_LISTING,
  1571. ERROR_LOG_FILE,
  1572. GLOBAL_PASSWORDS_FILE,
  1573. INDEX_FILES,
  1574. ENABLE_KEEP_ALIVE,
  1575. ACCESS_CONTROL_LIST,
  1576. EXTRA_MIME_TYPES,
  1577. LISTENING_PORTS,
  1578. DOCUMENT_ROOT,
  1579. SSL_CERTIFICATE,
  1580. SSL_CERTIFICATE_CHAIN,
  1581. NUM_THREADS,
  1582. RUN_AS_USER,
  1583. URL_REWRITE_PATTERN,
  1584. HIDE_FILES,
  1585. REQUEST_TIMEOUT,
  1586. KEEP_ALIVE_TIMEOUT,
  1587. LINGER_TIMEOUT,
  1588. SSL_DO_VERIFY_PEER,
  1589. SSL_CA_PATH,
  1590. SSL_CA_FILE,
  1591. SSL_VERIFY_DEPTH,
  1592. SSL_DEFAULT_VERIFY_PATHS,
  1593. SSL_CIPHER_LIST,
  1594. SSL_PROTOCOL_VERSION,
  1595. SSL_SHORT_TRUST,
  1596. #if defined(USE_WEBSOCKET)
  1597. WEBSOCKET_TIMEOUT,
  1598. #endif
  1599. DECODE_URL,
  1600. #if defined(USE_LUA)
  1601. LUA_PRELOAD_FILE,
  1602. LUA_SCRIPT_EXTENSIONS,
  1603. LUA_SERVER_PAGE_EXTENSIONS,
  1604. #endif
  1605. #if defined(USE_DUKTAPE)
  1606. DUKTAPE_SCRIPT_EXTENSIONS,
  1607. #endif
  1608. #if defined(USE_WEBSOCKET)
  1609. WEBSOCKET_ROOT,
  1610. #endif
  1611. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1612. LUA_WEBSOCKET_EXTENSIONS,
  1613. #endif
  1614. ACCESS_CONTROL_ALLOW_ORIGIN,
  1615. ACCESS_CONTROL_ALLOW_METHODS,
  1616. ACCESS_CONTROL_ALLOW_HEADERS,
  1617. ERROR_PAGES,
  1618. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1619. * socket option typedef TCP_NODELAY. */
  1620. #if !defined(NO_CACHING)
  1621. STATIC_FILE_MAX_AGE,
  1622. #endif
  1623. #if !defined(NO_SSL)
  1624. STRICT_HTTPS_MAX_AGE,
  1625. #endif
  1626. #if defined(__linux__)
  1627. ALLOW_SENDFILE_CALL,
  1628. #endif
  1629. #if defined(_WIN32)
  1630. CASE_SENSITIVE_FILES,
  1631. #endif
  1632. #if defined(USE_LUA)
  1633. LUA_BACKGROUND_SCRIPT,
  1634. #endif
  1635. ADDITIONAL_HEADER,
  1636. MAX_REQUEST_SIZE,
  1637. NUM_OPTIONS
  1638. };
  1639. /* Config option name, config types, default value */
  1640. static struct mg_option config_options[] = {
  1641. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1642. {"cgi_environment", CONFIG_TYPE_STRING_LIST, NULL},
  1643. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1644. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1645. {"protect_uri", CONFIG_TYPE_STRING_LIST, NULL},
  1646. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1647. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1648. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1649. {"throttle", CONFIG_TYPE_STRING_LIST, NULL},
  1650. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1651. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1652. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1653. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1654. {"index_files",
  1655. CONFIG_TYPE_STRING_LIST,
  1656. #ifdef USE_LUA
  1657. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1658. "index.shtml,index.php"},
  1659. #else
  1660. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1661. #endif
  1662. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1663. {"access_control_list", CONFIG_TYPE_STRING_LIST, NULL},
  1664. {"extra_mime_types", CONFIG_TYPE_STRING_LIST, NULL},
  1665. {"listening_ports", CONFIG_TYPE_STRING_LIST, "8080"},
  1666. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1667. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1668. {"ssl_certificate_chain", CONFIG_TYPE_FILE, NULL},
  1669. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1670. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1671. {"url_rewrite_patterns", CONFIG_TYPE_STRING_LIST, NULL},
  1672. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1673. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1674. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1675. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1676. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1677. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1678. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1679. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1680. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1681. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1682. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1683. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1684. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1685. #if defined(USE_WEBSOCKET)
  1686. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1687. #endif
  1688. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1689. #if defined(USE_LUA)
  1690. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1691. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1692. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1693. #endif
  1694. #if defined(USE_DUKTAPE)
  1695. /* The support for duktape is still in alpha version state.
  1696. * The name of this config option might change. */
  1697. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1698. #endif
  1699. #if defined(USE_WEBSOCKET)
  1700. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1701. #endif
  1702. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1703. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1704. #endif
  1705. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1706. {"access_control_allow_methods", CONFIG_TYPE_STRING, "*"},
  1707. {"access_control_allow_headers", CONFIG_TYPE_STRING, "*"},
  1708. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1709. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1710. #if !defined(NO_CACHING)
  1711. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1712. #endif
  1713. #if !defined(NO_SSL)
  1714. {"strict_transport_security_max_age", CONFIG_TYPE_NUMBER, NULL},
  1715. #endif
  1716. #if defined(__linux__)
  1717. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1718. #endif
  1719. #if defined(_WIN32)
  1720. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1721. #endif
  1722. #if defined(USE_LUA)
  1723. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1724. #endif
  1725. {"additional_header", CONFIG_TYPE_STRING_MULTILINE, NULL},
  1726. {"max_request_size", CONFIG_TYPE_NUMBER, "16384"},
  1727. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1728. /* Check if the config_options and the corresponding enum have compatible
  1729. * sizes. */
  1730. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1731. == (NUM_OPTIONS + 1),
  1732. "config_options and enum not sync");
  1733. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1734. struct mg_handler_info {
  1735. /* Name/Pattern of the URI. */
  1736. char *uri;
  1737. size_t uri_len;
  1738. /* handler type */
  1739. int handler_type;
  1740. /* Handler for http/https or authorization requests. */
  1741. mg_request_handler handler;
  1742. /* Handler for ws/wss (websocket) requests. */
  1743. mg_websocket_connect_handler connect_handler;
  1744. mg_websocket_ready_handler ready_handler;
  1745. mg_websocket_data_handler data_handler;
  1746. mg_websocket_close_handler close_handler;
  1747. /* accepted subprotocols for ws/wss requests. */
  1748. struct mg_websocket_subprotocols *subprotocols;
  1749. /* Handler for authorization requests */
  1750. mg_authorization_handler auth_handler;
  1751. /* User supplied argument for the handler function. */
  1752. void *cbdata;
  1753. /* next handler in a linked list */
  1754. struct mg_handler_info *next;
  1755. };
  1756. struct mg_context {
  1757. volatile int stop_flag; /* Should we stop event loop */
  1758. SSL_CTX *ssl_ctx; /* SSL context */
  1759. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1760. struct mg_callbacks callbacks; /* User-defined callback function */
  1761. void *user_data; /* User-defined data */
  1762. int context_type; /* 1 = server context,
  1763. * 2 = ws/wss client context,
  1764. */
  1765. struct socket *listening_sockets;
  1766. struct pollfd *listening_socket_fds;
  1767. unsigned int num_listening_sockets;
  1768. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1769. #ifdef ALTERNATIVE_QUEUE
  1770. struct socket *client_socks;
  1771. void **client_wait_events;
  1772. #else
  1773. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1774. volatile int sq_head; /* Head of the socket queue */
  1775. volatile int sq_tail; /* Tail of the socket queue */
  1776. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1777. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1778. #endif
  1779. unsigned int max_request_size; /* The max request size */
  1780. pthread_t masterthreadid; /* The master thread ID */
  1781. unsigned int
  1782. cfg_worker_threads; /* The number of configured worker threads. */
  1783. pthread_t *worker_threadids; /* The worker thread IDs */
  1784. struct mg_connection *worker_connections; /* The connection struct, pre-
  1785. * allocated for each worker */
  1786. time_t start_time; /* Server start time, used for authentication */
  1787. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1788. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1789. unsigned long nonce_count; /* Used nonces, used for authentication */
  1790. char *systemName; /* What operating system is running */
  1791. /* linked list of uri handlers */
  1792. struct mg_handler_info *handlers;
  1793. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1794. /* linked list of shared lua websockets */
  1795. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1796. #endif
  1797. #if defined(USE_TIMERS)
  1798. struct ttimers *timers;
  1799. #endif
  1800. #if defined(USE_LUA)
  1801. void *lua_background_state;
  1802. #endif
  1803. #if defined(USE_SERVER_STATS)
  1804. int active_connections;
  1805. int max_connections;
  1806. int64_t total_connections;
  1807. int64_t total_requests;
  1808. struct mg_memory_stat ctx_memory;
  1809. #endif
  1810. };
  1811. #if defined(USE_SERVER_STATS)
  1812. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  1813. static struct mg_memory_stat *
  1814. get_memory_stat(struct mg_context *ctx)
  1815. {
  1816. if (ctx) {
  1817. return &(ctx->ctx_memory);
  1818. }
  1819. return &mg_common_memory;
  1820. }
  1821. #endif
  1822. struct mg_connection {
  1823. struct mg_request_info request_info;
  1824. struct mg_context *ctx;
  1825. SSL *ssl; /* SSL descriptor */
  1826. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1827. struct socket client; /* Connected client */
  1828. time_t conn_birth_time; /* Time (wall clock) when connection was
  1829. * established */
  1830. struct timespec req_time; /* Time (since system start) when the request
  1831. * was received */
  1832. int64_t num_bytes_sent; /* Total bytes sent to client */
  1833. int64_t content_len; /* Content-Length header value */
  1834. int64_t consumed_content; /* How many bytes of content have been read */
  1835. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1836. * data available, 2: all data read */
  1837. size_t chunk_remainder; /* Unread data from the last chunk */
  1838. char *buf; /* Buffer for received data */
  1839. char *path_info; /* PATH_INFO part of the URL */
  1840. int must_close; /* 1 if connection must be closed */
  1841. int in_error_handler; /* 1 if in handler for user defined error
  1842. * pages */
  1843. int handled_requests; /* Number of requests handled by this connection */
  1844. int buf_size; /* Buffer size */
  1845. int request_len; /* Size of the request + headers in a buffer */
  1846. int data_len; /* Total size of data in a buffer */
  1847. int status_code; /* HTTP reply status code, e.g. 200 */
  1848. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1849. * throttle */
  1850. time_t last_throttle_time; /* Last time throttled data was sent */
  1851. int64_t last_throttle_bytes; /* Bytes sent this second */
  1852. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1853. * atomic transmissions for websockets */
  1854. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1855. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1856. #endif
  1857. int thread_index; /* Thread index within ctx */
  1858. };
  1859. /* Directory entry */
  1860. struct de {
  1861. struct mg_connection *conn;
  1862. char *file_name;
  1863. struct mg_file_stat file;
  1864. };
  1865. #if defined(USE_WEBSOCKET)
  1866. static int is_websocket_protocol(const struct mg_connection *conn);
  1867. #else
  1868. #define is_websocket_protocol(conn) (0)
  1869. #endif
  1870. #if !defined(NO_THREAD_NAME)
  1871. #if defined(_WIN32) && defined(_MSC_VER)
  1872. /* Set the thread name for debugging purposes in Visual Studio
  1873. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1874. */
  1875. #pragma pack(push, 8)
  1876. typedef struct tagTHREADNAME_INFO {
  1877. DWORD dwType; /* Must be 0x1000. */
  1878. LPCSTR szName; /* Pointer to name (in user addr space). */
  1879. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1880. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1881. } THREADNAME_INFO;
  1882. #pragma pack(pop)
  1883. #elif defined(__linux__)
  1884. #include <sys/prctl.h>
  1885. #include <sys/sendfile.h>
  1886. #ifdef ALTERNATIVE_QUEUE
  1887. #include <sys/eventfd.h>
  1888. #endif /* ALTERNATIVE_QUEUE */
  1889. #if defined(ALTERNATIVE_QUEUE)
  1890. static void *
  1891. event_create(void)
  1892. {
  1893. int ret = eventfd(0, EFD_CLOEXEC);
  1894. if (ret == -1) {
  1895. /* Linux uses -1 on error, Windows NULL. */
  1896. /* However, Linux does not return 0 on success either. */
  1897. return 0;
  1898. }
  1899. return (void *)ret;
  1900. }
  1901. static int
  1902. event_wait(void *eventhdl)
  1903. {
  1904. uint64_t u;
  1905. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1906. if (s != sizeof(uint64_t)) {
  1907. /* error */
  1908. return 0;
  1909. }
  1910. (void)u; /* the value is not required */
  1911. return 1;
  1912. }
  1913. static int
  1914. event_signal(void *eventhdl)
  1915. {
  1916. uint64_t u = 1;
  1917. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1918. if (s != sizeof(uint64_t)) {
  1919. /* error */
  1920. return 0;
  1921. }
  1922. return 1;
  1923. }
  1924. static void
  1925. event_destroy(void *eventhdl)
  1926. {
  1927. close((int)eventhdl);
  1928. }
  1929. #endif
  1930. #endif
  1931. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1932. struct posix_event {
  1933. pthread_mutex_t mutex;
  1934. pthread_cond_t cond;
  1935. };
  1936. static void *
  1937. event_create(void)
  1938. {
  1939. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1940. if (ret == 0) {
  1941. /* out of memory */
  1942. return 0;
  1943. }
  1944. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1945. /* pthread mutex not available */
  1946. mg_free(ret);
  1947. return 0;
  1948. }
  1949. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1950. /* pthread cond not available */
  1951. pthread_mutex_destroy(&(ret->mutex));
  1952. mg_free(ret);
  1953. return 0;
  1954. }
  1955. return (void *)ret;
  1956. }
  1957. static int
  1958. event_wait(void *eventhdl)
  1959. {
  1960. struct posix_event *ev = (struct posix_event *)eventhdl;
  1961. pthread_mutex_lock(&(ev->mutex));
  1962. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1963. pthread_mutex_unlock(&(ev->mutex));
  1964. return 1;
  1965. }
  1966. static int
  1967. event_signal(void *eventhdl)
  1968. {
  1969. struct posix_event *ev = (struct posix_event *)eventhdl;
  1970. pthread_mutex_lock(&(ev->mutex));
  1971. pthread_cond_signal(&(ev->cond));
  1972. pthread_mutex_unlock(&(ev->mutex));
  1973. return 1;
  1974. }
  1975. static void
  1976. event_destroy(void *eventhdl)
  1977. {
  1978. struct posix_event *ev = (struct posix_event *)eventhdl;
  1979. pthread_cond_destroy(&(ev->cond));
  1980. pthread_mutex_destroy(&(ev->mutex));
  1981. mg_free(ev);
  1982. }
  1983. #endif
  1984. static void
  1985. mg_set_thread_name(const char *name)
  1986. {
  1987. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1988. mg_snprintf(
  1989. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1990. #if defined(_WIN32)
  1991. #if defined(_MSC_VER)
  1992. /* Windows and Visual Studio Compiler */
  1993. __try
  1994. {
  1995. THREADNAME_INFO info;
  1996. info.dwType = 0x1000;
  1997. info.szName = threadName;
  1998. info.dwThreadID = ~0U;
  1999. info.dwFlags = 0;
  2000. RaiseException(0x406D1388,
  2001. 0,
  2002. sizeof(info) / sizeof(ULONG_PTR),
  2003. (ULONG_PTR *)&info);
  2004. }
  2005. __except(EXCEPTION_EXECUTE_HANDLER)
  2006. {
  2007. }
  2008. #elif defined(__MINGW32__)
  2009. /* No option known to set thread name for MinGW */
  2010. #endif
  2011. #elif defined(__GLIBC__) \
  2012. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2013. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2014. (void)pthread_setname_np(pthread_self(), threadName);
  2015. #elif defined(__linux__)
  2016. /* on linux we can use the old prctl function */
  2017. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2018. #endif
  2019. }
  2020. #else /* !defined(NO_THREAD_NAME) */
  2021. void
  2022. mg_set_thread_name(const char *threadName)
  2023. {
  2024. }
  2025. #endif
  2026. #if defined(MG_LEGACY_INTERFACE)
  2027. const char **
  2028. mg_get_valid_option_names(void)
  2029. {
  2030. /* This function is deprecated. Use mg_get_valid_options instead. */
  2031. static const char *
  2032. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2033. int i;
  2034. for (i = 0; config_options[i].name != NULL; i++) {
  2035. data[i * 2] = config_options[i].name;
  2036. data[i * 2 + 1] = config_options[i].default_value;
  2037. }
  2038. return data;
  2039. }
  2040. #endif
  2041. const struct mg_option *
  2042. mg_get_valid_options(void)
  2043. {
  2044. return config_options;
  2045. }
  2046. /* Do not open file (used in is_file_in_memory) */
  2047. #define MG_FOPEN_MODE_NONE (0)
  2048. /* Open file for read only access */
  2049. #define MG_FOPEN_MODE_READ (1)
  2050. /* Open file for writing, create and overwrite */
  2051. #define MG_FOPEN_MODE_WRITE (2)
  2052. /* Open file for writing, create and append */
  2053. #define MG_FOPEN_MODE_APPEND (4)
  2054. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2055. * output filep and return 1, otherwise return 0 and don't modify anything. */
  2056. static int
  2057. open_file_in_memory(const struct mg_connection *conn,
  2058. const char *path,
  2059. struct mg_file *filep,
  2060. int mode)
  2061. {
  2062. #if defined(MG_USE_OPEN_FILE)
  2063. size_t size = 0;
  2064. const char *buf = NULL;
  2065. if (!conn) {
  2066. return 0;
  2067. }
  2068. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2069. return 0;
  2070. }
  2071. if (conn->ctx->callbacks.open_file) {
  2072. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2073. if (buf != NULL) {
  2074. if (filep == NULL) {
  2075. /* This is a file in memory, but we cannot store the properties
  2076. * now.
  2077. * Called from "is_file_in_memory" function. */
  2078. return 1;
  2079. }
  2080. /* NOTE: override filep->size only on success. Otherwise, it might
  2081. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2082. filep->access.membuf = buf;
  2083. filep->access.fp = NULL;
  2084. /* Size was set by the callback */
  2085. filep->stat.size = size;
  2086. /* Assume the data may change during runtime by setting
  2087. * last_modified = now */
  2088. filep->stat.last_modified = time(NULL);
  2089. filep->stat.is_directory = 0;
  2090. filep->stat.is_gzipped = 0;
  2091. }
  2092. }
  2093. return (buf != NULL);
  2094. #else
  2095. (void)conn;
  2096. (void)path;
  2097. (void)filep;
  2098. (void)mode;
  2099. return 0;
  2100. #endif
  2101. }
  2102. static int
  2103. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2104. {
  2105. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2106. }
  2107. static int
  2108. is_file_opened(const struct mg_file_access *fileacc)
  2109. {
  2110. if (!fileacc) {
  2111. return 0;
  2112. }
  2113. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2114. }
  2115. static int mg_stat(const struct mg_connection *conn,
  2116. const char *path,
  2117. struct mg_file_stat *filep);
  2118. /* mg_fopen will open a file either in memory or on the disk.
  2119. * The input parameter path is a string in UTF-8 encoding.
  2120. * The input parameter mode is MG_FOPEN_MODE_*
  2121. * On success, either fp or membuf will be set in the output
  2122. * struct file. All status members will also be set.
  2123. * The function returns 1 on success, 0 on error. */
  2124. static int
  2125. mg_fopen(const struct mg_connection *conn,
  2126. const char *path,
  2127. int mode,
  2128. struct mg_file *filep)
  2129. {
  2130. int found;
  2131. if (!filep) {
  2132. return 0;
  2133. }
  2134. filep->access.fp = NULL;
  2135. filep->access.membuf = NULL;
  2136. if (!is_file_in_memory(conn, path)) {
  2137. /* filep is initialized in mg_stat: all fields with memset to,
  2138. * some fields like size and modification date with values */
  2139. found = mg_stat(conn, path, &(filep->stat));
  2140. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2141. /* file does not exist and will not be created */
  2142. return 0;
  2143. }
  2144. #ifdef _WIN32
  2145. {
  2146. wchar_t wbuf[PATH_MAX];
  2147. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2148. switch (mode) {
  2149. case MG_FOPEN_MODE_READ:
  2150. filep->access.fp = _wfopen(wbuf, L"rb");
  2151. break;
  2152. case MG_FOPEN_MODE_WRITE:
  2153. filep->access.fp = _wfopen(wbuf, L"wb");
  2154. break;
  2155. case MG_FOPEN_MODE_APPEND:
  2156. filep->access.fp = _wfopen(wbuf, L"ab");
  2157. break;
  2158. }
  2159. }
  2160. #else
  2161. /* Linux et al already use unicode. No need to convert. */
  2162. switch (mode) {
  2163. case MG_FOPEN_MODE_READ:
  2164. filep->access.fp = fopen(path, "r");
  2165. break;
  2166. case MG_FOPEN_MODE_WRITE:
  2167. filep->access.fp = fopen(path, "w");
  2168. break;
  2169. case MG_FOPEN_MODE_APPEND:
  2170. filep->access.fp = fopen(path, "a");
  2171. break;
  2172. }
  2173. #endif
  2174. if (!found) {
  2175. /* File did not exist before fopen was called.
  2176. * Maybe it has been created now. Get stat info
  2177. * like creation time now. */
  2178. found = mg_stat(conn, path, &(filep->stat));
  2179. (void)found;
  2180. }
  2181. /* file is on disk */
  2182. return (filep->access.fp != NULL);
  2183. } else {
  2184. /* is_file_in_memory returned true */
  2185. if (open_file_in_memory(conn, path, filep, mode)) {
  2186. /* file is in memory */
  2187. return (filep->access.membuf != NULL);
  2188. }
  2189. }
  2190. /* Open failed */
  2191. return 0;
  2192. }
  2193. /* return 0 on success, just like fclose */
  2194. static int
  2195. mg_fclose(struct mg_file_access *fileacc)
  2196. {
  2197. int ret = -1;
  2198. if (fileacc != NULL) {
  2199. if (fileacc->fp != NULL) {
  2200. ret = fclose(fileacc->fp);
  2201. } else if (fileacc->membuf != NULL) {
  2202. ret = 0;
  2203. }
  2204. /* reset all members of fileacc */
  2205. memset(fileacc, 0, sizeof(*fileacc));
  2206. }
  2207. return ret;
  2208. }
  2209. static void
  2210. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2211. {
  2212. for (; *src != '\0' && n > 1; n--) {
  2213. *dst++ = *src++;
  2214. }
  2215. *dst = '\0';
  2216. }
  2217. static int
  2218. lowercase(const char *s)
  2219. {
  2220. return tolower(*(const unsigned char *)s);
  2221. }
  2222. int
  2223. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2224. {
  2225. int diff = 0;
  2226. if (len > 0) {
  2227. do {
  2228. diff = lowercase(s1++) - lowercase(s2++);
  2229. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2230. }
  2231. return diff;
  2232. }
  2233. int
  2234. mg_strcasecmp(const char *s1, const char *s2)
  2235. {
  2236. int diff;
  2237. do {
  2238. diff = lowercase(s1++) - lowercase(s2++);
  2239. } while (diff == 0 && s1[-1] != '\0');
  2240. return diff;
  2241. }
  2242. static char *
  2243. mg_strndup(const char *ptr, size_t len)
  2244. {
  2245. char *p;
  2246. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2247. mg_strlcpy(p, ptr, len + 1);
  2248. }
  2249. return p;
  2250. }
  2251. static char *
  2252. mg_strdup(const char *str)
  2253. {
  2254. return mg_strndup(str, strlen(str));
  2255. }
  2256. static const char *
  2257. mg_strcasestr(const char *big_str, const char *small_str)
  2258. {
  2259. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2260. if (big_len >= small_len) {
  2261. for (i = 0; i <= (big_len - small_len); i++) {
  2262. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2263. return big_str + i;
  2264. }
  2265. }
  2266. }
  2267. return NULL;
  2268. }
  2269. /* Return null terminated string of given maximum length.
  2270. * Report errors if length is exceeded. */
  2271. static void
  2272. mg_vsnprintf(const struct mg_connection *conn,
  2273. int *truncated,
  2274. char *buf,
  2275. size_t buflen,
  2276. const char *fmt,
  2277. va_list ap)
  2278. {
  2279. int n, ok;
  2280. if (buflen == 0) {
  2281. if (truncated) {
  2282. *truncated = 1;
  2283. }
  2284. return;
  2285. }
  2286. #ifdef __clang__
  2287. #pragma clang diagnostic push
  2288. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2289. /* Using fmt as a non-literal is intended here, since it is mostly called
  2290. * indirectly by mg_snprintf */
  2291. #endif
  2292. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2293. ok = (n >= 0) && ((size_t)n < buflen);
  2294. #ifdef __clang__
  2295. #pragma clang diagnostic pop
  2296. #endif
  2297. if (ok) {
  2298. if (truncated) {
  2299. *truncated = 0;
  2300. }
  2301. } else {
  2302. if (truncated) {
  2303. *truncated = 1;
  2304. }
  2305. mg_cry(conn,
  2306. "truncating vsnprintf buffer: [%.*s]",
  2307. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2308. buf);
  2309. n = (int)buflen - 1;
  2310. }
  2311. buf[n] = '\0';
  2312. }
  2313. static void
  2314. mg_snprintf(const struct mg_connection *conn,
  2315. int *truncated,
  2316. char *buf,
  2317. size_t buflen,
  2318. const char *fmt,
  2319. ...)
  2320. {
  2321. va_list ap;
  2322. va_start(ap, fmt);
  2323. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2324. va_end(ap);
  2325. }
  2326. static int
  2327. get_option_index(const char *name)
  2328. {
  2329. int i;
  2330. for (i = 0; config_options[i].name != NULL; i++) {
  2331. if (strcmp(config_options[i].name, name) == 0) {
  2332. return i;
  2333. }
  2334. }
  2335. return -1;
  2336. }
  2337. const char *
  2338. mg_get_option(const struct mg_context *ctx, const char *name)
  2339. {
  2340. int i;
  2341. if ((i = get_option_index(name)) == -1) {
  2342. return NULL;
  2343. } else if (!ctx || ctx->config[i] == NULL) {
  2344. return "";
  2345. } else {
  2346. return ctx->config[i];
  2347. }
  2348. }
  2349. struct mg_context *
  2350. mg_get_context(const struct mg_connection *conn)
  2351. {
  2352. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2353. }
  2354. void *
  2355. mg_get_user_data(const struct mg_context *ctx)
  2356. {
  2357. return (ctx == NULL) ? NULL : ctx->user_data;
  2358. }
  2359. void
  2360. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2361. {
  2362. if (conn != NULL) {
  2363. conn->request_info.conn_data = data;
  2364. }
  2365. }
  2366. void *
  2367. mg_get_user_connection_data(const struct mg_connection *conn)
  2368. {
  2369. if (conn != NULL) {
  2370. return conn->request_info.conn_data;
  2371. }
  2372. return NULL;
  2373. }
  2374. #if defined(MG_LEGACY_INTERFACE)
  2375. /* Deprecated: Use mg_get_server_ports instead. */
  2376. size_t
  2377. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2378. {
  2379. size_t i;
  2380. if (!ctx) {
  2381. return 0;
  2382. }
  2383. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2384. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2385. ports[i] =
  2386. #if defined(USE_IPV6)
  2387. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2388. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2389. :
  2390. #endif
  2391. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2392. }
  2393. return i;
  2394. }
  2395. #endif
  2396. int
  2397. mg_get_server_ports(const struct mg_context *ctx,
  2398. int size,
  2399. struct mg_server_ports *ports)
  2400. {
  2401. int i, cnt = 0;
  2402. if (size <= 0) {
  2403. return -1;
  2404. }
  2405. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2406. if (!ctx) {
  2407. return -1;
  2408. }
  2409. if (!ctx->listening_sockets) {
  2410. return -1;
  2411. }
  2412. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2413. ports[cnt].port =
  2414. #if defined(USE_IPV6)
  2415. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2416. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2417. :
  2418. #endif
  2419. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2420. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2421. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2422. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2423. /* IPv4 */
  2424. ports[cnt].protocol = 1;
  2425. cnt++;
  2426. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2427. /* IPv6 */
  2428. ports[cnt].protocol = 3;
  2429. cnt++;
  2430. }
  2431. }
  2432. return cnt;
  2433. }
  2434. static void
  2435. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2436. {
  2437. buf[0] = '\0';
  2438. if (!usa) {
  2439. return;
  2440. }
  2441. if (usa->sa.sa_family == AF_INET) {
  2442. getnameinfo(&usa->sa,
  2443. sizeof(usa->sin),
  2444. buf,
  2445. (unsigned)len,
  2446. NULL,
  2447. 0,
  2448. NI_NUMERICHOST);
  2449. }
  2450. #if defined(USE_IPV6)
  2451. else if (usa->sa.sa_family == AF_INET6) {
  2452. getnameinfo(&usa->sa,
  2453. sizeof(usa->sin6),
  2454. buf,
  2455. (unsigned)len,
  2456. NULL,
  2457. 0,
  2458. NI_NUMERICHOST);
  2459. }
  2460. #endif
  2461. }
  2462. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2463. * included in all responses other than 100, 101, 5xx. */
  2464. static void
  2465. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2466. {
  2467. struct tm *tm;
  2468. tm = ((t != NULL) ? gmtime(t) : NULL);
  2469. if (tm != NULL) {
  2470. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2471. } else {
  2472. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2473. buf[buf_len - 1] = '\0';
  2474. }
  2475. }
  2476. /* difftime for struct timespec. Return value is in seconds. */
  2477. static double
  2478. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2479. {
  2480. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2481. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2482. }
  2483. /* Print error message to the opened error log stream. */
  2484. void
  2485. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2486. {
  2487. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2488. va_list ap;
  2489. struct mg_file fi;
  2490. time_t timestamp;
  2491. va_start(ap, fmt);
  2492. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2493. va_end(ap);
  2494. buf[sizeof(buf) - 1] = 0;
  2495. if (!conn) {
  2496. puts(buf);
  2497. return;
  2498. }
  2499. /* Do not lock when getting the callback value, here and below.
  2500. * I suppose this is fine, since function cannot disappear in the
  2501. * same way string option can. */
  2502. if ((conn->ctx->callbacks.log_message == NULL)
  2503. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2504. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2505. if (mg_fopen(conn,
  2506. conn->ctx->config[ERROR_LOG_FILE],
  2507. MG_FOPEN_MODE_APPEND,
  2508. &fi) == 0) {
  2509. fi.access.fp = NULL;
  2510. }
  2511. } else {
  2512. fi.access.fp = NULL;
  2513. }
  2514. if (fi.access.fp != NULL) {
  2515. flockfile(fi.access.fp);
  2516. timestamp = time(NULL);
  2517. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2518. fprintf(fi.access.fp,
  2519. "[%010lu] [error] [client %s] ",
  2520. (unsigned long)timestamp,
  2521. src_addr);
  2522. if (conn->request_info.request_method != NULL) {
  2523. fprintf(fi.access.fp,
  2524. "%s %s: ",
  2525. conn->request_info.request_method,
  2526. conn->request_info.request_uri);
  2527. }
  2528. fprintf(fi.access.fp, "%s", buf);
  2529. fputc('\n', fi.access.fp);
  2530. fflush(fi.access.fp);
  2531. funlockfile(fi.access.fp);
  2532. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2533. * mg_cry here anyway ;-) */
  2534. }
  2535. }
  2536. }
  2537. /* Return fake connection structure. Used for logging, if connection
  2538. * is not applicable at the moment of logging. */
  2539. static struct mg_connection *
  2540. fc(struct mg_context *ctx)
  2541. {
  2542. static struct mg_connection fake_connection;
  2543. fake_connection.ctx = ctx;
  2544. return &fake_connection;
  2545. }
  2546. const char *
  2547. mg_version(void)
  2548. {
  2549. return CIVETWEB_VERSION;
  2550. }
  2551. const struct mg_request_info *
  2552. mg_get_request_info(const struct mg_connection *conn)
  2553. {
  2554. if (!conn) {
  2555. return NULL;
  2556. }
  2557. return &conn->request_info;
  2558. }
  2559. int
  2560. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2561. {
  2562. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2563. return -1;
  2564. } else {
  2565. int truncated = 0;
  2566. const struct mg_request_info *ri = &conn->request_info;
  2567. #ifdef __clang__
  2568. #pragma clang diagnostic push
  2569. #pragma clang diagnostic ignored "-Wunreachable-code"
  2570. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2571. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2572. * unreachable, but splitting into four different #ifdef clauses here is more
  2573. * complicated.
  2574. */
  2575. #endif
  2576. const char *proto =
  2577. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2578. : (ri->is_ssl ? "https" : "http"));
  2579. #ifdef __clang__
  2580. #pragma clang diagnostic pop
  2581. #endif
  2582. if (ri->local_uri == NULL) {
  2583. return -1;
  2584. }
  2585. if ((ri->request_uri != NULL)
  2586. && strcmp(ri->local_uri, ri->request_uri)) {
  2587. mg_snprintf(conn,
  2588. &truncated,
  2589. buf,
  2590. buflen,
  2591. "%s://%s",
  2592. proto,
  2593. ri->request_uri);
  2594. if (truncated) {
  2595. return -1;
  2596. }
  2597. return 0;
  2598. } else {
  2599. #if defined(USE_IPV6)
  2600. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2601. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2602. : htons(conn->client.lsa.sin.sin_port);
  2603. #else
  2604. int port = htons(conn->client.lsa.sin.sin_port);
  2605. #endif
  2606. int def_port = ri->is_ssl ? 443 : 80;
  2607. int auth_domain_check_enabled =
  2608. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2609. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2610. "yes"));
  2611. const char *server_domain =
  2612. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2613. char portstr[16];
  2614. char server_ip[48];
  2615. if (port != def_port) {
  2616. sprintf(portstr, ":%u", (unsigned)port);
  2617. } else {
  2618. portstr[0] = 0;
  2619. }
  2620. if (!auth_domain_check_enabled || !server_domain) {
  2621. sockaddr_to_string(server_ip,
  2622. sizeof(server_ip),
  2623. &conn->client.lsa);
  2624. server_domain = server_ip;
  2625. }
  2626. mg_snprintf(conn,
  2627. &truncated,
  2628. buf,
  2629. buflen,
  2630. "%s://%s%s%s",
  2631. proto,
  2632. server_domain,
  2633. portstr,
  2634. ri->local_uri);
  2635. if (truncated) {
  2636. return -1;
  2637. }
  2638. return 0;
  2639. }
  2640. }
  2641. }
  2642. /* Skip the characters until one of the delimiters characters found.
  2643. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2644. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2645. * Delimiters can be quoted with quotechar. */
  2646. static char *
  2647. skip_quoted(char **buf,
  2648. const char *delimiters,
  2649. const char *whitespace,
  2650. char quotechar)
  2651. {
  2652. char *p, *begin_word, *end_word, *end_whitespace;
  2653. begin_word = *buf;
  2654. end_word = begin_word + strcspn(begin_word, delimiters);
  2655. /* Check for quotechar */
  2656. if (end_word > begin_word) {
  2657. p = end_word - 1;
  2658. while (*p == quotechar) {
  2659. /* While the delimiter is quoted, look for the next delimiter. */
  2660. /* This happens, e.g., in calls from parse_auth_header,
  2661. * if the user name contains a " character. */
  2662. /* If there is anything beyond end_word, copy it. */
  2663. if (*end_word != '\0') {
  2664. size_t end_off = strcspn(end_word + 1, delimiters);
  2665. memmove(p, end_word, end_off + 1);
  2666. p += end_off; /* p must correspond to end_word - 1 */
  2667. end_word += end_off + 1;
  2668. } else {
  2669. *p = '\0';
  2670. break;
  2671. }
  2672. }
  2673. for (p++; p < end_word; p++) {
  2674. *p = '\0';
  2675. }
  2676. }
  2677. if (*end_word == '\0') {
  2678. *buf = end_word;
  2679. } else {
  2680. #if defined(__GNUC__) || defined(__MINGW32__)
  2681. /* Disable spurious conversion warning for GCC */
  2682. #pragma GCC diagnostic push
  2683. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2684. #endif
  2685. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2686. #if defined(__GNUC__) || defined(__MINGW32__)
  2687. #pragma GCC diagnostic pop
  2688. #endif
  2689. for (p = end_word; p < end_whitespace; p++) {
  2690. *p = '\0';
  2691. }
  2692. *buf = end_whitespace;
  2693. }
  2694. return begin_word;
  2695. }
  2696. /* Simplified version of skip_quoted without quote char
  2697. * and whitespace == delimiters */
  2698. static char *
  2699. skip(char **buf, const char *delimiters)
  2700. {
  2701. return skip_quoted(buf, delimiters, delimiters, 0);
  2702. }
  2703. /* Return HTTP header value, or NULL if not found. */
  2704. static const char *
  2705. get_header(const struct mg_request_info *ri, const char *name)
  2706. {
  2707. int i;
  2708. if (ri) {
  2709. for (i = 0; i < ri->num_headers; i++) {
  2710. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2711. return ri->http_headers[i].value;
  2712. }
  2713. }
  2714. }
  2715. return NULL;
  2716. }
  2717. #if defined(USE_WEBSOCKET)
  2718. /* Retrieve requested HTTP header multiple values, and return the number of
  2719. * found occurences */
  2720. static int
  2721. get_headers(const struct mg_request_info *ri,
  2722. const char *name,
  2723. const char **output,
  2724. int output_max_size)
  2725. {
  2726. int i;
  2727. int cnt = 0;
  2728. if (ri) {
  2729. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  2730. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2731. output[cnt++] = ri->http_headers[i].value;
  2732. }
  2733. }
  2734. }
  2735. return cnt;
  2736. }
  2737. #endif
  2738. const char *
  2739. mg_get_header(const struct mg_connection *conn, const char *name)
  2740. {
  2741. if (!conn) {
  2742. return NULL;
  2743. }
  2744. return get_header(&conn->request_info, name);
  2745. }
  2746. /* A helper function for traversing a comma separated list of values.
  2747. * It returns a list pointer shifted to the next value, or NULL if the end
  2748. * of the list found.
  2749. * Value is stored in val vector. If value has form "x=y", then eq_val
  2750. * vector is initialized to point to the "y" part, and val vector length
  2751. * is adjusted to point only to "x". */
  2752. static const char *
  2753. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2754. {
  2755. int end;
  2756. reparse:
  2757. if (val == NULL || list == NULL || *list == '\0') {
  2758. /* End of the list */
  2759. list = NULL;
  2760. } else {
  2761. /* Skip over leading LWS */
  2762. while (*list == ' ' || *list == '\t')
  2763. list++;
  2764. val->ptr = list;
  2765. if ((list = strchr(val->ptr, ',')) != NULL) {
  2766. /* Comma found. Store length and shift the list ptr */
  2767. val->len = ((size_t)(list - val->ptr));
  2768. list++;
  2769. } else {
  2770. /* This value is the last one */
  2771. list = val->ptr + strlen(val->ptr);
  2772. val->len = ((size_t)(list - val->ptr));
  2773. }
  2774. /* Adjust length for trailing LWS */
  2775. end = (int)val->len - 1;
  2776. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  2777. end--;
  2778. val->len = (size_t)(end + 1);
  2779. if (val->len == 0) {
  2780. /* Ignore any empty entries. */
  2781. goto reparse;
  2782. }
  2783. if (eq_val != NULL) {
  2784. /* Value has form "x=y", adjust pointers and lengths
  2785. * so that val points to "x", and eq_val points to "y". */
  2786. eq_val->len = 0;
  2787. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2788. if (eq_val->ptr != NULL) {
  2789. eq_val->ptr++; /* Skip over '=' character */
  2790. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2791. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2792. }
  2793. }
  2794. }
  2795. return list;
  2796. }
  2797. /* A helper function for checking if a comma separated list of values contains
  2798. * the given option (case insensitvely).
  2799. * 'header' can be NULL, in which case false is returned. */
  2800. static int
  2801. header_has_option(const char *header, const char *option)
  2802. {
  2803. struct vec opt_vec;
  2804. struct vec eq_vec;
  2805. assert(option != NULL);
  2806. assert(option[0] != '\0');
  2807. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2808. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2809. return 1;
  2810. }
  2811. return 0;
  2812. }
  2813. /* Perform case-insensitive match of string against pattern */
  2814. static int
  2815. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2816. {
  2817. const char *or_str;
  2818. size_t i;
  2819. int j, len, res;
  2820. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2821. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2822. return (res > 0) ? res : match_prefix(or_str + 1,
  2823. (size_t)((pattern + pattern_len)
  2824. - (or_str + 1)),
  2825. str);
  2826. }
  2827. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  2828. if ((pattern[i] == '?') && (str[j] != '\0')) {
  2829. continue;
  2830. } else if (pattern[i] == '$') {
  2831. return (str[j] == '\0') ? j : -1;
  2832. } else if (pattern[i] == '*') {
  2833. i++;
  2834. if (pattern[i] == '*') {
  2835. i++;
  2836. len = (int)strlen(str + j);
  2837. } else {
  2838. len = (int)strcspn(str + j, "/");
  2839. }
  2840. if (i == pattern_len) {
  2841. return j + len;
  2842. }
  2843. do {
  2844. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2845. } while (res == -1 && len-- > 0);
  2846. return (res == -1) ? -1 : j + res + len;
  2847. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2848. return -1;
  2849. }
  2850. }
  2851. return j;
  2852. }
  2853. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2854. * This function must tolerate situations when connection info is not
  2855. * set up, for example if request parsing failed. */
  2856. static int
  2857. should_keep_alive(const struct mg_connection *conn)
  2858. {
  2859. if (conn != NULL) {
  2860. const char *http_version = conn->request_info.http_version;
  2861. const char *header = mg_get_header(conn, "Connection");
  2862. if (conn->must_close || (conn->status_code == 401)
  2863. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2864. || (header != NULL && !header_has_option(header, "keep-alive"))
  2865. || (header == NULL && http_version
  2866. && 0 != strcmp(http_version, "1.1"))) {
  2867. return 0;
  2868. }
  2869. return 1;
  2870. }
  2871. return 0;
  2872. }
  2873. static int
  2874. should_decode_url(const struct mg_connection *conn)
  2875. {
  2876. if (!conn || !conn->ctx) {
  2877. return 0;
  2878. }
  2879. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2880. }
  2881. static const char *
  2882. suggest_connection_header(const struct mg_connection *conn)
  2883. {
  2884. return should_keep_alive(conn) ? "keep-alive" : "close";
  2885. }
  2886. static int
  2887. send_no_cache_header(struct mg_connection *conn)
  2888. {
  2889. /* Send all current and obsolete cache opt-out directives. */
  2890. return mg_printf(conn,
  2891. "Cache-Control: no-cache, no-store, "
  2892. "must-revalidate, private, max-age=0\r\n"
  2893. "Pragma: no-cache\r\n"
  2894. "Expires: 0\r\n");
  2895. }
  2896. static int
  2897. send_static_cache_header(struct mg_connection *conn)
  2898. {
  2899. #if !defined(NO_CACHING)
  2900. /* Read the server config to check how long a file may be cached.
  2901. * The configuration is in seconds. */
  2902. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2903. if (max_age <= 0) {
  2904. /* 0 means "do not cache". All values <0 are reserved
  2905. * and may be used differently in the future. */
  2906. /* If a file should not be cached, do not only send
  2907. * max-age=0, but also pragmas and Expires headers. */
  2908. return send_no_cache_header(conn);
  2909. }
  2910. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2911. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2912. /* See also https://www.mnot.net/cache_docs/ */
  2913. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2914. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2915. * year to 31622400 seconds. For the moment, we just send whatever has
  2916. * been configured, still the behavior for >1 year should be considered
  2917. * as undefined. */
  2918. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2919. #else /* NO_CACHING */
  2920. return send_no_cache_header(conn);
  2921. #endif /* !NO_CACHING */
  2922. }
  2923. static int
  2924. send_additional_header(struct mg_connection *conn)
  2925. {
  2926. int i = 0;
  2927. const char *header = conn->ctx->config[ADDITIONAL_HEADER];
  2928. #if !defined(NO_SSL)
  2929. if (conn->ctx->config[STRICT_HTTPS_MAX_AGE]) {
  2930. int max_age = atoi(conn->ctx->config[STRICT_HTTPS_MAX_AGE]);
  2931. if (max_age >= 0) {
  2932. i += mg_printf(conn,
  2933. "Strict-Transport-Security: max-age=%u\r\n",
  2934. (unsigned)max_age);
  2935. }
  2936. }
  2937. #endif
  2938. if (header && header[0]) {
  2939. i += mg_printf(conn, "%s\r\n", header);
  2940. }
  2941. return i;
  2942. }
  2943. static void handle_file_based_request(struct mg_connection *conn,
  2944. const char *path,
  2945. struct mg_file *filep);
  2946. const char *
  2947. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  2948. {
  2949. /* See IANA HTTP status code assignment:
  2950. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2951. */
  2952. switch (response_code) {
  2953. /* RFC2616 Section 10.1 - Informational 1xx */
  2954. case 100:
  2955. return "Continue"; /* RFC2616 Section 10.1.1 */
  2956. case 101:
  2957. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2958. case 102:
  2959. return "Processing"; /* RFC2518 Section 10.1 */
  2960. /* RFC2616 Section 10.2 - Successful 2xx */
  2961. case 200:
  2962. return "OK"; /* RFC2616 Section 10.2.1 */
  2963. case 201:
  2964. return "Created"; /* RFC2616 Section 10.2.2 */
  2965. case 202:
  2966. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2967. case 203:
  2968. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2969. case 204:
  2970. return "No Content"; /* RFC2616 Section 10.2.5 */
  2971. case 205:
  2972. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2973. case 206:
  2974. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2975. case 207:
  2976. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2977. case 208:
  2978. return "Already Reported"; /* RFC5842 Section 7.1 */
  2979. case 226:
  2980. return "IM used"; /* RFC3229 Section 10.4.1 */
  2981. /* RFC2616 Section 10.3 - Redirection 3xx */
  2982. case 300:
  2983. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2984. case 301:
  2985. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2986. case 302:
  2987. return "Found"; /* RFC2616 Section 10.3.3 */
  2988. case 303:
  2989. return "See Other"; /* RFC2616 Section 10.3.4 */
  2990. case 304:
  2991. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2992. case 305:
  2993. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2994. case 307:
  2995. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2996. case 308:
  2997. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2998. /* RFC2616 Section 10.4 - Client Error 4xx */
  2999. case 400:
  3000. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3001. case 401:
  3002. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3003. case 402:
  3004. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3005. case 403:
  3006. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3007. case 404:
  3008. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3009. case 405:
  3010. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3011. case 406:
  3012. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3013. case 407:
  3014. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3015. case 408:
  3016. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3017. case 409:
  3018. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3019. case 410:
  3020. return "Gone"; /* RFC2616 Section 10.4.11 */
  3021. case 411:
  3022. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3023. case 412:
  3024. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3025. case 413:
  3026. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3027. case 414:
  3028. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3029. case 415:
  3030. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3031. case 416:
  3032. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  3033. case 417:
  3034. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3035. case 421:
  3036. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3037. case 422:
  3038. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3039. * Section 11.2 */
  3040. case 423:
  3041. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3042. case 424:
  3043. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3044. * Section 11.4 */
  3045. case 426:
  3046. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3047. case 428:
  3048. return "Precondition Required"; /* RFC 6585, Section 3 */
  3049. case 429:
  3050. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3051. case 431:
  3052. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3053. case 451:
  3054. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3055. * Section 3 */
  3056. /* RFC2616 Section 10.5 - Server Error 5xx */
  3057. case 500:
  3058. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3059. case 501:
  3060. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3061. case 502:
  3062. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3063. case 503:
  3064. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3065. case 504:
  3066. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3067. case 505:
  3068. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3069. case 506:
  3070. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3071. case 507:
  3072. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3073. * Section 11.5 */
  3074. case 508:
  3075. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3076. case 510:
  3077. return "Not Extended"; /* RFC 2774, Section 7 */
  3078. case 511:
  3079. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3080. /* Other status codes, not shown in the IANA HTTP status code assignment.
  3081. * E.g., "de facto" standards due to common use, ... */
  3082. case 418:
  3083. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3084. case 419:
  3085. return "Authentication Timeout"; /* common use */
  3086. case 420:
  3087. return "Enhance Your Calm"; /* common use */
  3088. case 440:
  3089. return "Login Timeout"; /* common use */
  3090. case 509:
  3091. return "Bandwidth Limit Exceeded"; /* common use */
  3092. default:
  3093. /* This error code is unknown. This should not happen. */
  3094. if (conn) {
  3095. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3096. }
  3097. /* Return at least a category according to RFC 2616 Section 10. */
  3098. if (response_code >= 100 && response_code < 200) {
  3099. /* Unknown informational status code */
  3100. return "Information";
  3101. }
  3102. if (response_code >= 200 && response_code < 300) {
  3103. /* Unknown success code */
  3104. return "Success";
  3105. }
  3106. if (response_code >= 300 && response_code < 400) {
  3107. /* Unknown redirection code */
  3108. return "Redirection";
  3109. }
  3110. if (response_code >= 400 && response_code < 500) {
  3111. /* Unknown request error code */
  3112. return "Client Error";
  3113. }
  3114. if (response_code >= 500 && response_code < 600) {
  3115. /* Unknown server error code */
  3116. return "Server Error";
  3117. }
  3118. /* Response code not even within reasonable range */
  3119. return "";
  3120. }
  3121. }
  3122. void
  3123. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3124. {
  3125. char buf[MG_BUF_LEN];
  3126. va_list ap;
  3127. int len, i, page_handler_found, scope, truncated, has_body;
  3128. char date[64];
  3129. time_t curtime = time(NULL);
  3130. const char *error_handler = NULL;
  3131. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3132. const char *error_page_file_ext, *tstr;
  3133. const char *status_text = mg_get_response_code_text(conn, status);
  3134. if (conn == NULL) {
  3135. return;
  3136. }
  3137. conn->status_code = status;
  3138. if (conn->in_error_handler || (conn->ctx->callbacks.http_error == NULL)
  3139. || conn->ctx->callbacks.http_error(conn, status)) {
  3140. if (!conn->in_error_handler) {
  3141. /* Send user defined error pages, if defined */
  3142. error_handler = conn->ctx->config[ERROR_PAGES];
  3143. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3144. page_handler_found = 0;
  3145. if (error_handler != NULL) {
  3146. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3147. switch (scope) {
  3148. case 1: /* Handler for specific error, e.g. 404 error */
  3149. mg_snprintf(conn,
  3150. &truncated,
  3151. buf,
  3152. sizeof(buf) - 32,
  3153. "%serror%03u.",
  3154. error_handler,
  3155. status);
  3156. break;
  3157. case 2: /* Handler for error group, e.g., 5xx error handler
  3158. * for all server errors (500-599) */
  3159. mg_snprintf(conn,
  3160. &truncated,
  3161. buf,
  3162. sizeof(buf) - 32,
  3163. "%serror%01uxx.",
  3164. error_handler,
  3165. status / 100);
  3166. break;
  3167. default: /* Handler for all errors */
  3168. mg_snprintf(conn,
  3169. &truncated,
  3170. buf,
  3171. sizeof(buf) - 32,
  3172. "%serror.",
  3173. error_handler);
  3174. break;
  3175. }
  3176. /* String truncation in buf may only occur if error_handler
  3177. * is too long. This string is from the config, not from a
  3178. * client. */
  3179. (void)truncated;
  3180. len = (int)strlen(buf);
  3181. tstr = strchr(error_page_file_ext, '.');
  3182. while (tstr) {
  3183. for (i = 1;
  3184. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3185. i++)
  3186. buf[len + i - 1] = tstr[i];
  3187. buf[len + i - 1] = 0;
  3188. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3189. page_handler_found = 1;
  3190. break;
  3191. }
  3192. tstr = strchr(tstr + i, '.');
  3193. }
  3194. }
  3195. }
  3196. if (page_handler_found) {
  3197. conn->in_error_handler = 1;
  3198. handle_file_based_request(conn, buf, &error_page_file);
  3199. conn->in_error_handler = 0;
  3200. return;
  3201. }
  3202. }
  3203. /* No custom error page. Send default error page. */
  3204. gmt_time_string(date, sizeof(date), &curtime);
  3205. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3206. has_body = ((status > 199) && (status != 204) && (status != 304));
  3207. conn->must_close = 1;
  3208. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3209. send_no_cache_header(conn);
  3210. send_additional_header(conn);
  3211. if (has_body) {
  3212. mg_printf(conn,
  3213. "%s",
  3214. "Content-Type: text/plain; charset=utf-8\r\n");
  3215. }
  3216. mg_printf(conn,
  3217. "Date: %s\r\n"
  3218. "Connection: close\r\n\r\n",
  3219. date);
  3220. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3221. if (has_body) {
  3222. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3223. if (fmt != NULL) {
  3224. va_start(ap, fmt);
  3225. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3226. va_end(ap);
  3227. mg_write(conn, buf, strlen(buf));
  3228. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3229. }
  3230. } else {
  3231. /* No body allowed. Close the connection. */
  3232. DEBUG_TRACE("Error %i", status);
  3233. }
  3234. }
  3235. }
  3236. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3237. /* Create substitutes for POSIX functions in Win32. */
  3238. #if defined(__MINGW32__)
  3239. /* Show no warning in case system functions are not used. */
  3240. #pragma GCC diagnostic push
  3241. #pragma GCC diagnostic ignored "-Wunused-function"
  3242. #endif
  3243. static int
  3244. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3245. {
  3246. (void)unused;
  3247. *mutex = CreateMutex(NULL, FALSE, NULL);
  3248. return (*mutex == NULL) ? -1 : 0;
  3249. }
  3250. static int
  3251. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3252. {
  3253. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3254. }
  3255. static int
  3256. pthread_mutex_lock(pthread_mutex_t *mutex)
  3257. {
  3258. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3259. }
  3260. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3261. static int
  3262. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3263. {
  3264. switch (WaitForSingleObject(*mutex, 0)) {
  3265. case WAIT_OBJECT_0:
  3266. return 0;
  3267. case WAIT_TIMEOUT:
  3268. return -2; /* EBUSY */
  3269. }
  3270. return -1;
  3271. }
  3272. #endif
  3273. static int
  3274. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3275. {
  3276. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3277. }
  3278. static int
  3279. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3280. {
  3281. (void)unused;
  3282. InitializeCriticalSection(&cv->threadIdSec);
  3283. cv->waiting_thread = NULL;
  3284. return 0;
  3285. }
  3286. static int
  3287. pthread_cond_timedwait(pthread_cond_t *cv,
  3288. pthread_mutex_t *mutex,
  3289. const struct timespec *abstime)
  3290. {
  3291. struct mg_workerTLS **ptls,
  3292. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3293. int ok;
  3294. int64_t nsnow, nswaitabs, nswaitrel;
  3295. DWORD mswaitrel;
  3296. EnterCriticalSection(&cv->threadIdSec);
  3297. /* Add this thread to cv's waiting list */
  3298. ptls = &cv->waiting_thread;
  3299. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3300. ;
  3301. tls->next_waiting_thread = NULL;
  3302. *ptls = tls;
  3303. LeaveCriticalSection(&cv->threadIdSec);
  3304. if (abstime) {
  3305. nsnow = mg_get_current_time_ns();
  3306. nswaitabs =
  3307. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3308. nswaitrel = nswaitabs - nsnow;
  3309. if (nswaitrel < 0) {
  3310. nswaitrel = 0;
  3311. }
  3312. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3313. } else {
  3314. mswaitrel = INFINITE;
  3315. }
  3316. pthread_mutex_unlock(mutex);
  3317. ok = (WAIT_OBJECT_0
  3318. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3319. if (!ok) {
  3320. ok = 1;
  3321. EnterCriticalSection(&cv->threadIdSec);
  3322. ptls = &cv->waiting_thread;
  3323. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3324. if (*ptls == tls) {
  3325. *ptls = tls->next_waiting_thread;
  3326. ok = 0;
  3327. break;
  3328. }
  3329. }
  3330. LeaveCriticalSection(&cv->threadIdSec);
  3331. if (ok) {
  3332. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3333. }
  3334. }
  3335. /* This thread has been removed from cv's waiting list */
  3336. pthread_mutex_lock(mutex);
  3337. return ok ? 0 : -1;
  3338. }
  3339. static int
  3340. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3341. {
  3342. return pthread_cond_timedwait(cv, mutex, NULL);
  3343. }
  3344. static int
  3345. pthread_cond_signal(pthread_cond_t *cv)
  3346. {
  3347. HANDLE wkup = NULL;
  3348. BOOL ok = FALSE;
  3349. EnterCriticalSection(&cv->threadIdSec);
  3350. if (cv->waiting_thread) {
  3351. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3352. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3353. ok = SetEvent(wkup);
  3354. assert(ok);
  3355. }
  3356. LeaveCriticalSection(&cv->threadIdSec);
  3357. return ok ? 0 : 1;
  3358. }
  3359. static int
  3360. pthread_cond_broadcast(pthread_cond_t *cv)
  3361. {
  3362. EnterCriticalSection(&cv->threadIdSec);
  3363. while (cv->waiting_thread) {
  3364. pthread_cond_signal(cv);
  3365. }
  3366. LeaveCriticalSection(&cv->threadIdSec);
  3367. return 0;
  3368. }
  3369. static int
  3370. pthread_cond_destroy(pthread_cond_t *cv)
  3371. {
  3372. EnterCriticalSection(&cv->threadIdSec);
  3373. assert(cv->waiting_thread == NULL);
  3374. LeaveCriticalSection(&cv->threadIdSec);
  3375. DeleteCriticalSection(&cv->threadIdSec);
  3376. return 0;
  3377. }
  3378. #ifdef ALTERNATIVE_QUEUE
  3379. static void *
  3380. event_create(void)
  3381. {
  3382. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3383. }
  3384. static int
  3385. event_wait(void *eventhdl)
  3386. {
  3387. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3388. return (res == WAIT_OBJECT_0);
  3389. }
  3390. static int
  3391. event_signal(void *eventhdl)
  3392. {
  3393. return (int)SetEvent((HANDLE)eventhdl);
  3394. }
  3395. static void
  3396. event_destroy(void *eventhdl)
  3397. {
  3398. CloseHandle((HANDLE)eventhdl);
  3399. }
  3400. #endif
  3401. #if defined(__MINGW32__)
  3402. /* Enable unused function warning again */
  3403. #pragma GCC diagnostic pop
  3404. #endif
  3405. /* For Windows, change all slashes to backslashes in path names. */
  3406. static void
  3407. change_slashes_to_backslashes(char *path)
  3408. {
  3409. int i;
  3410. for (i = 0; path[i] != '\0'; i++) {
  3411. if (path[i] == '/') {
  3412. path[i] = '\\';
  3413. }
  3414. /* remove double backslash (check i > 0 to preserve UNC paths,
  3415. * like \\server\file.txt) */
  3416. if ((path[i] == '\\') && (i > 0)) {
  3417. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3418. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3419. }
  3420. }
  3421. }
  3422. }
  3423. static int
  3424. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3425. {
  3426. int diff;
  3427. do {
  3428. diff = tolower(*s1) - tolower(*s2);
  3429. s1++;
  3430. s2++;
  3431. } while ((diff == 0) && (s1[-1] != '\0'));
  3432. return diff;
  3433. }
  3434. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3435. * wbuf and wbuf_len is a target buffer and its length. */
  3436. static void
  3437. path_to_unicode(const struct mg_connection *conn,
  3438. const char *path,
  3439. wchar_t *wbuf,
  3440. size_t wbuf_len)
  3441. {
  3442. char buf[PATH_MAX], buf2[PATH_MAX];
  3443. wchar_t wbuf2[MAX_PATH + 1];
  3444. DWORD long_len, err;
  3445. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3446. mg_strlcpy(buf, path, sizeof(buf));
  3447. change_slashes_to_backslashes(buf);
  3448. /* Convert to Unicode and back. If doubly-converted string does not
  3449. * match the original, something is fishy, reject. */
  3450. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3451. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3452. WideCharToMultiByte(
  3453. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3454. if (strcmp(buf, buf2) != 0) {
  3455. wbuf[0] = L'\0';
  3456. }
  3457. /* Windows file systems are not case sensitive, but you can still use
  3458. * uppercase and lowercase letters (on all modern file systems).
  3459. * The server can check if the URI uses the same upper/lowercase
  3460. * letters an the file system, effectively making Windows servers
  3461. * case sensitive (like Linux servers are). It is still not possible
  3462. * to use two files with the same name in different cases on Windows
  3463. * (like /a and /A) - this would be possible in Linux.
  3464. * As a default, Windows is not case sensitive, but the case sensitive
  3465. * file name check can be activated by an additional configuration. */
  3466. if (conn) {
  3467. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3468. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3469. /* Use case sensitive compare function */
  3470. fcompare = wcscmp;
  3471. }
  3472. }
  3473. (void)conn; /* conn is currently unused */
  3474. #if !defined(_WIN32_WCE)
  3475. /* Only accept a full file path, not a Windows short (8.3) path. */
  3476. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3477. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3478. if (long_len == 0) {
  3479. err = GetLastError();
  3480. if (err == ERROR_FILE_NOT_FOUND) {
  3481. /* File does not exist. This is not always a problem here. */
  3482. return;
  3483. }
  3484. }
  3485. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3486. /* Short name is used. */
  3487. wbuf[0] = L'\0';
  3488. }
  3489. #else
  3490. (void)long_len;
  3491. (void)wbuf2;
  3492. (void)err;
  3493. if (strchr(path, '~')) {
  3494. wbuf[0] = L'\0';
  3495. }
  3496. #endif
  3497. }
  3498. /* Windows happily opens files with some garbage at the end of file name.
  3499. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3500. * "a.cgi", despite one would expect an error back.
  3501. * This function returns non-0 if path ends with some garbage. */
  3502. static int
  3503. path_cannot_disclose_cgi(const char *path)
  3504. {
  3505. static const char *allowed_last_characters = "_-";
  3506. int last = path[strlen(path) - 1];
  3507. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3508. }
  3509. static int
  3510. mg_stat(const struct mg_connection *conn,
  3511. const char *path,
  3512. struct mg_file_stat *filep)
  3513. {
  3514. wchar_t wbuf[PATH_MAX];
  3515. WIN32_FILE_ATTRIBUTE_DATA info;
  3516. time_t creation_time;
  3517. if (!filep) {
  3518. return 0;
  3519. }
  3520. memset(filep, 0, sizeof(*filep));
  3521. if (conn && is_file_in_memory(conn, path)) {
  3522. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3523. * memset */
  3524. /* Quick fix (for 1.9.x): */
  3525. /* mg_stat must fill all fields, also for files in memory */
  3526. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3527. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3528. filep->size = tmp_file.stat.size;
  3529. filep->location = 2;
  3530. /* TODO: for 1.10: restructure how files in memory are handled */
  3531. /* The "file in memory" feature is a candidate for deletion.
  3532. * Please join the discussion at
  3533. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3534. */
  3535. filep->last_modified = time(NULL); /* TODO */
  3536. /* last_modified = now ... assumes the file may change during runtime,
  3537. * so every mg_fopen call may return different data */
  3538. /* last_modified = conn->ctx.start_time;
  3539. * May be used it the data does not change during runtime. This allows
  3540. * browser caching. Since we do not know, we have to assume the file
  3541. * in memory may change. */
  3542. return 1;
  3543. }
  3544. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3545. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3546. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3547. filep->last_modified =
  3548. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3549. info.ftLastWriteTime.dwHighDateTime);
  3550. /* On Windows, the file creation time can be higher than the
  3551. * modification time, e.g. when a file is copied.
  3552. * Since the Last-Modified timestamp is used for caching
  3553. * it should be based on the most recent timestamp. */
  3554. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3555. info.ftCreationTime.dwHighDateTime);
  3556. if (creation_time > filep->last_modified) {
  3557. filep->last_modified = creation_time;
  3558. }
  3559. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3560. /* If file name is fishy, reset the file structure and return
  3561. * error.
  3562. * Note it is important to reset, not just return the error, cause
  3563. * functions like is_file_opened() check the struct. */
  3564. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3565. memset(filep, 0, sizeof(*filep));
  3566. return 0;
  3567. }
  3568. return 1;
  3569. }
  3570. return 0;
  3571. }
  3572. static int
  3573. mg_remove(const struct mg_connection *conn, const char *path)
  3574. {
  3575. wchar_t wbuf[PATH_MAX];
  3576. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3577. return DeleteFileW(wbuf) ? 0 : -1;
  3578. }
  3579. static int
  3580. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3581. {
  3582. wchar_t wbuf[PATH_MAX];
  3583. (void)mode;
  3584. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3585. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3586. }
  3587. /* Create substitutes for POSIX functions in Win32. */
  3588. #if defined(__MINGW32__)
  3589. /* Show no warning in case system functions are not used. */
  3590. #pragma GCC diagnostic push
  3591. #pragma GCC diagnostic ignored "-Wunused-function"
  3592. #endif
  3593. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3594. static DIR *
  3595. mg_opendir(const struct mg_connection *conn, const char *name)
  3596. {
  3597. DIR *dir = NULL;
  3598. wchar_t wpath[PATH_MAX];
  3599. DWORD attrs;
  3600. if (name == NULL) {
  3601. SetLastError(ERROR_BAD_ARGUMENTS);
  3602. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3603. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3604. } else {
  3605. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3606. attrs = GetFileAttributesW(wpath);
  3607. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3608. == FILE_ATTRIBUTE_DIRECTORY)) {
  3609. (void)wcscat(wpath, L"\\*");
  3610. dir->handle = FindFirstFileW(wpath, &dir->info);
  3611. dir->result.d_name[0] = '\0';
  3612. } else {
  3613. mg_free(dir);
  3614. dir = NULL;
  3615. }
  3616. }
  3617. return dir;
  3618. }
  3619. static int
  3620. mg_closedir(DIR *dir)
  3621. {
  3622. int result = 0;
  3623. if (dir != NULL) {
  3624. if (dir->handle != INVALID_HANDLE_VALUE)
  3625. result = FindClose(dir->handle) ? 0 : -1;
  3626. mg_free(dir);
  3627. } else {
  3628. result = -1;
  3629. SetLastError(ERROR_BAD_ARGUMENTS);
  3630. }
  3631. return result;
  3632. }
  3633. static struct dirent *
  3634. mg_readdir(DIR *dir)
  3635. {
  3636. struct dirent *result = 0;
  3637. if (dir) {
  3638. if (dir->handle != INVALID_HANDLE_VALUE) {
  3639. result = &dir->result;
  3640. (void)WideCharToMultiByte(CP_UTF8,
  3641. 0,
  3642. dir->info.cFileName,
  3643. -1,
  3644. result->d_name,
  3645. sizeof(result->d_name),
  3646. NULL,
  3647. NULL);
  3648. if (!FindNextFileW(dir->handle, &dir->info)) {
  3649. (void)FindClose(dir->handle);
  3650. dir->handle = INVALID_HANDLE_VALUE;
  3651. }
  3652. } else {
  3653. SetLastError(ERROR_FILE_NOT_FOUND);
  3654. }
  3655. } else {
  3656. SetLastError(ERROR_BAD_ARGUMENTS);
  3657. }
  3658. return result;
  3659. }
  3660. #ifndef HAVE_POLL
  3661. static int
  3662. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3663. {
  3664. struct timeval tv;
  3665. fd_set set;
  3666. unsigned int i;
  3667. int result;
  3668. SOCKET maxfd = 0;
  3669. memset(&tv, 0, sizeof(tv));
  3670. tv.tv_sec = milliseconds / 1000;
  3671. tv.tv_usec = (milliseconds % 1000) * 1000;
  3672. FD_ZERO(&set);
  3673. for (i = 0; i < n; i++) {
  3674. FD_SET((SOCKET)pfd[i].fd, &set);
  3675. pfd[i].revents = 0;
  3676. if (pfd[i].fd > maxfd) {
  3677. maxfd = pfd[i].fd;
  3678. }
  3679. }
  3680. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3681. for (i = 0; i < n; i++) {
  3682. if (FD_ISSET(pfd[i].fd, &set)) {
  3683. pfd[i].revents = POLLIN;
  3684. }
  3685. }
  3686. }
  3687. /* We should subtract the time used in select from remaining
  3688. * "milliseconds", in particular if called from mg_poll with a
  3689. * timeout quantum.
  3690. * Unfortunately, the remaining time is not stored in "tv" in all
  3691. * implementations, so the result in "tv" must be considered undefined.
  3692. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3693. return result;
  3694. }
  3695. #endif /* HAVE_POLL */
  3696. #if defined(__MINGW32__)
  3697. /* Enable unused function warning again */
  3698. #pragma GCC diagnostic pop
  3699. #endif
  3700. static void
  3701. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3702. {
  3703. (void)conn; /* Unused. */
  3704. #if defined(_WIN32_WCE)
  3705. (void)sock;
  3706. #else
  3707. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3708. #endif
  3709. }
  3710. int
  3711. mg_start_thread(mg_thread_func_t f, void *p)
  3712. {
  3713. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3714. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3715. */
  3716. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3717. == ((uintptr_t)(-1L)))
  3718. ? -1
  3719. : 0);
  3720. #else
  3721. return (
  3722. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3723. ? -1
  3724. : 0);
  3725. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3726. }
  3727. /* Start a thread storing the thread context. */
  3728. static int
  3729. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3730. void *p,
  3731. pthread_t *threadidptr)
  3732. {
  3733. uintptr_t uip;
  3734. HANDLE threadhandle;
  3735. int result = -1;
  3736. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3737. threadhandle = (HANDLE)uip;
  3738. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3739. *threadidptr = threadhandle;
  3740. result = 0;
  3741. }
  3742. return result;
  3743. }
  3744. /* Wait for a thread to finish. */
  3745. static int
  3746. mg_join_thread(pthread_t threadid)
  3747. {
  3748. int result;
  3749. DWORD dwevent;
  3750. result = -1;
  3751. dwevent = WaitForSingleObject(threadid, INFINITE);
  3752. if (dwevent == WAIT_FAILED) {
  3753. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3754. } else {
  3755. if (dwevent == WAIT_OBJECT_0) {
  3756. CloseHandle(threadid);
  3757. result = 0;
  3758. }
  3759. }
  3760. return result;
  3761. }
  3762. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3763. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3764. /* Create substitutes for POSIX functions in Win32. */
  3765. #if defined(__MINGW32__)
  3766. /* Show no warning in case system functions are not used. */
  3767. #pragma GCC diagnostic push
  3768. #pragma GCC diagnostic ignored "-Wunused-function"
  3769. #endif
  3770. static HANDLE
  3771. dlopen(const char *dll_name, int flags)
  3772. {
  3773. wchar_t wbuf[PATH_MAX];
  3774. (void)flags;
  3775. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3776. return LoadLibraryW(wbuf);
  3777. }
  3778. static int
  3779. dlclose(void *handle)
  3780. {
  3781. int result;
  3782. if (FreeLibrary((HMODULE)handle) != 0) {
  3783. result = 0;
  3784. } else {
  3785. result = -1;
  3786. }
  3787. return result;
  3788. }
  3789. #if defined(__MINGW32__)
  3790. /* Enable unused function warning again */
  3791. #pragma GCC diagnostic pop
  3792. #endif
  3793. #endif
  3794. #if !defined(NO_CGI)
  3795. #define SIGKILL (0)
  3796. static int
  3797. kill(pid_t pid, int sig_num)
  3798. {
  3799. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3800. (void)CloseHandle((HANDLE)pid);
  3801. return 0;
  3802. }
  3803. static void
  3804. trim_trailing_whitespaces(char *s)
  3805. {
  3806. char *e = s + strlen(s) - 1;
  3807. while ((e > s) && isspace(*(unsigned char *)e)) {
  3808. *e-- = '\0';
  3809. }
  3810. }
  3811. static pid_t
  3812. spawn_process(struct mg_connection *conn,
  3813. const char *prog,
  3814. char *envblk,
  3815. char *envp[],
  3816. int fdin[2],
  3817. int fdout[2],
  3818. int fderr[2],
  3819. const char *dir)
  3820. {
  3821. HANDLE me;
  3822. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3823. cmdline[PATH_MAX], buf[PATH_MAX];
  3824. int truncated;
  3825. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3826. STARTUPINFOA si;
  3827. PROCESS_INFORMATION pi = {0};
  3828. (void)envp;
  3829. memset(&si, 0, sizeof(si));
  3830. si.cb = sizeof(si);
  3831. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3832. si.wShowWindow = SW_HIDE;
  3833. me = GetCurrentProcess();
  3834. DuplicateHandle(me,
  3835. (HANDLE)_get_osfhandle(fdin[0]),
  3836. me,
  3837. &si.hStdInput,
  3838. 0,
  3839. TRUE,
  3840. DUPLICATE_SAME_ACCESS);
  3841. DuplicateHandle(me,
  3842. (HANDLE)_get_osfhandle(fdout[1]),
  3843. me,
  3844. &si.hStdOutput,
  3845. 0,
  3846. TRUE,
  3847. DUPLICATE_SAME_ACCESS);
  3848. DuplicateHandle(me,
  3849. (HANDLE)_get_osfhandle(fderr[1]),
  3850. me,
  3851. &si.hStdError,
  3852. 0,
  3853. TRUE,
  3854. DUPLICATE_SAME_ACCESS);
  3855. /* Mark handles that should not be inherited. See
  3856. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3857. */
  3858. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3859. HANDLE_FLAG_INHERIT,
  3860. 0);
  3861. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3862. HANDLE_FLAG_INHERIT,
  3863. 0);
  3864. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3865. HANDLE_FLAG_INHERIT,
  3866. 0);
  3867. /* If CGI file is a script, try to read the interpreter line */
  3868. interp = conn->ctx->config[CGI_INTERPRETER];
  3869. if (interp == NULL) {
  3870. buf[0] = buf[1] = '\0';
  3871. /* Read the first line of the script into the buffer */
  3872. mg_snprintf(
  3873. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3874. if (truncated) {
  3875. pi.hProcess = (pid_t)-1;
  3876. goto spawn_cleanup;
  3877. }
  3878. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3879. p = (char *)file.access.membuf;
  3880. mg_fgets(buf, sizeof(buf), &file, &p);
  3881. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3882. buf[sizeof(buf) - 1] = '\0';
  3883. }
  3884. if ((buf[0] == '#') && (buf[1] == '!')) {
  3885. trim_trailing_whitespaces(buf + 2);
  3886. } else {
  3887. buf[2] = '\0';
  3888. }
  3889. interp = buf + 2;
  3890. }
  3891. if (interp[0] != '\0') {
  3892. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3893. interp = full_interp;
  3894. }
  3895. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3896. if (interp[0] != '\0') {
  3897. mg_snprintf(conn,
  3898. &truncated,
  3899. cmdline,
  3900. sizeof(cmdline),
  3901. "\"%s\" \"%s\\%s\"",
  3902. interp,
  3903. full_dir,
  3904. prog);
  3905. } else {
  3906. mg_snprintf(conn,
  3907. &truncated,
  3908. cmdline,
  3909. sizeof(cmdline),
  3910. "\"%s\\%s\"",
  3911. full_dir,
  3912. prog);
  3913. }
  3914. if (truncated) {
  3915. pi.hProcess = (pid_t)-1;
  3916. goto spawn_cleanup;
  3917. }
  3918. DEBUG_TRACE("Running [%s]", cmdline);
  3919. if (CreateProcessA(NULL,
  3920. cmdline,
  3921. NULL,
  3922. NULL,
  3923. TRUE,
  3924. CREATE_NEW_PROCESS_GROUP,
  3925. envblk,
  3926. NULL,
  3927. &si,
  3928. &pi) == 0) {
  3929. mg_cry(
  3930. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3931. pi.hProcess = (pid_t)-1;
  3932. /* goto spawn_cleanup; */
  3933. }
  3934. spawn_cleanup:
  3935. (void)CloseHandle(si.hStdOutput);
  3936. (void)CloseHandle(si.hStdError);
  3937. (void)CloseHandle(si.hStdInput);
  3938. if (pi.hThread != NULL) {
  3939. (void)CloseHandle(pi.hThread);
  3940. }
  3941. return (pid_t)pi.hProcess;
  3942. }
  3943. #endif /* !NO_CGI */
  3944. static int
  3945. set_blocking_mode(SOCKET sock, int blocking)
  3946. {
  3947. unsigned long non_blocking = !blocking;
  3948. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3949. }
  3950. #else
  3951. static int
  3952. mg_stat(const struct mg_connection *conn,
  3953. const char *path,
  3954. struct mg_file_stat *filep)
  3955. {
  3956. struct stat st;
  3957. if (!filep) {
  3958. return 0;
  3959. }
  3960. memset(filep, 0, sizeof(*filep));
  3961. if (conn && is_file_in_memory(conn, path)) {
  3962. /* Quick fix (for 1.9.x): */
  3963. /* mg_stat must fill all fields, also for files in memory */
  3964. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3965. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3966. filep->size = tmp_file.stat.size;
  3967. filep->last_modified = time(NULL);
  3968. filep->location = 2;
  3969. /* TODO: for 1.10: restructure how files in memory are handled */
  3970. return 1;
  3971. }
  3972. if (0 == stat(path, &st)) {
  3973. filep->size = (uint64_t)(st.st_size);
  3974. filep->last_modified = st.st_mtime;
  3975. filep->is_directory = S_ISDIR(st.st_mode);
  3976. return 1;
  3977. }
  3978. return 0;
  3979. }
  3980. static void
  3981. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3982. {
  3983. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3984. if (conn) {
  3985. mg_cry(conn,
  3986. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3987. __func__,
  3988. strerror(ERRNO));
  3989. }
  3990. }
  3991. }
  3992. int
  3993. mg_start_thread(mg_thread_func_t func, void *param)
  3994. {
  3995. pthread_t thread_id;
  3996. pthread_attr_t attr;
  3997. int result;
  3998. (void)pthread_attr_init(&attr);
  3999. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4000. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4001. /* Compile-time option to control stack size,
  4002. * e.g. -DUSE_STACK_SIZE=16384 */
  4003. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4004. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4005. result = pthread_create(&thread_id, &attr, func, param);
  4006. pthread_attr_destroy(&attr);
  4007. return result;
  4008. }
  4009. /* Start a thread storing the thread context. */
  4010. static int
  4011. mg_start_thread_with_id(mg_thread_func_t func,
  4012. void *param,
  4013. pthread_t *threadidptr)
  4014. {
  4015. pthread_t thread_id;
  4016. pthread_attr_t attr;
  4017. int result;
  4018. (void)pthread_attr_init(&attr);
  4019. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4020. /* Compile-time option to control stack size,
  4021. * e.g. -DUSE_STACK_SIZE=16384 */
  4022. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4023. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4024. result = pthread_create(&thread_id, &attr, func, param);
  4025. pthread_attr_destroy(&attr);
  4026. if ((result == 0) && (threadidptr != NULL)) {
  4027. *threadidptr = thread_id;
  4028. }
  4029. return result;
  4030. }
  4031. /* Wait for a thread to finish. */
  4032. static int
  4033. mg_join_thread(pthread_t threadid)
  4034. {
  4035. int result;
  4036. result = pthread_join(threadid, NULL);
  4037. return result;
  4038. }
  4039. #ifndef NO_CGI
  4040. static pid_t
  4041. spawn_process(struct mg_connection *conn,
  4042. const char *prog,
  4043. char *envblk,
  4044. char *envp[],
  4045. int fdin[2],
  4046. int fdout[2],
  4047. int fderr[2],
  4048. const char *dir)
  4049. {
  4050. pid_t pid;
  4051. const char *interp;
  4052. (void)envblk;
  4053. if (conn == NULL) {
  4054. return 0;
  4055. }
  4056. if ((pid = fork()) == -1) {
  4057. /* Parent */
  4058. mg_send_http_error(conn,
  4059. 500,
  4060. "Error: Creating CGI process\nfork(): %s",
  4061. strerror(ERRNO));
  4062. } else if (pid == 0) {
  4063. /* Child */
  4064. if (chdir(dir) != 0) {
  4065. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4066. } else if (dup2(fdin[0], 0) == -1) {
  4067. mg_cry(conn,
  4068. "%s: dup2(%d, 0): %s",
  4069. __func__,
  4070. fdin[0],
  4071. strerror(ERRNO));
  4072. } else if (dup2(fdout[1], 1) == -1) {
  4073. mg_cry(conn,
  4074. "%s: dup2(%d, 1): %s",
  4075. __func__,
  4076. fdout[1],
  4077. strerror(ERRNO));
  4078. } else if (dup2(fderr[1], 2) == -1) {
  4079. mg_cry(conn,
  4080. "%s: dup2(%d, 2): %s",
  4081. __func__,
  4082. fderr[1],
  4083. strerror(ERRNO));
  4084. } else {
  4085. /* Keep stderr and stdout in two different pipes.
  4086. * Stdout will be sent back to the client,
  4087. * stderr should go into a server error log. */
  4088. (void)close(fdin[0]);
  4089. (void)close(fdout[1]);
  4090. (void)close(fderr[1]);
  4091. /* Close write end fdin and read end fdout and fderr */
  4092. (void)close(fdin[1]);
  4093. (void)close(fdout[0]);
  4094. (void)close(fderr[0]);
  4095. /* After exec, all signal handlers are restored to their default
  4096. * values, with one exception of SIGCHLD. According to
  4097. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4098. * leave unchanged after exec if it was set to be ignored. Restore
  4099. * it to default action. */
  4100. signal(SIGCHLD, SIG_DFL);
  4101. interp = conn->ctx->config[CGI_INTERPRETER];
  4102. if (interp == NULL) {
  4103. (void)execle(prog, prog, NULL, envp);
  4104. mg_cry(conn,
  4105. "%s: execle(%s): %s",
  4106. __func__,
  4107. prog,
  4108. strerror(ERRNO));
  4109. } else {
  4110. (void)execle(interp, interp, prog, NULL, envp);
  4111. mg_cry(conn,
  4112. "%s: execle(%s %s): %s",
  4113. __func__,
  4114. interp,
  4115. prog,
  4116. strerror(ERRNO));
  4117. }
  4118. }
  4119. exit(EXIT_FAILURE);
  4120. }
  4121. return pid;
  4122. }
  4123. #endif /* !NO_CGI */
  4124. static int
  4125. set_blocking_mode(SOCKET sock, int blocking)
  4126. {
  4127. int flags;
  4128. flags = fcntl(sock, F_GETFL, 0);
  4129. if (blocking) {
  4130. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  4131. } else {
  4132. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  4133. }
  4134. return 0;
  4135. }
  4136. #endif /* _WIN32 */
  4137. /* End of initial operating system specific define block. */
  4138. /* Get a random number (independent of C rand function) */
  4139. static uint64_t
  4140. get_random(void)
  4141. {
  4142. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4143. static uint64_t lcg = 0; /* Linear congruential generator */
  4144. uint64_t now = mg_get_current_time_ns();
  4145. if (lfsr == 0) {
  4146. /* lfsr will be only 0 if has not been initialized,
  4147. * so this code is called only once. */
  4148. lfsr = mg_get_current_time_ns();
  4149. lcg = mg_get_current_time_ns();
  4150. } else {
  4151. /* Get the next step of both random number generators. */
  4152. lfsr = (lfsr >> 1)
  4153. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4154. << 63);
  4155. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  4156. }
  4157. /* Combining two pseudo-random number generators and a high resolution part
  4158. * of the current server time will make it hard (impossible?) to guess the
  4159. * next number. */
  4160. return (lfsr ^ lcg ^ now);
  4161. }
  4162. static int
  4163. mg_poll(struct pollfd *pfd,
  4164. unsigned int n,
  4165. int milliseconds,
  4166. volatile int *stop_server)
  4167. {
  4168. int ms_now, result;
  4169. /* Call poll, but only for a maximum time of a few seconds.
  4170. * This will allow to stop the server after some seconds, instead
  4171. * of having to wait for a long socket timeout. */
  4172. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4173. do {
  4174. if (*stop_server) {
  4175. /* Shut down signal */
  4176. return -2;
  4177. }
  4178. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4179. ms_now = milliseconds;
  4180. }
  4181. result = poll(pfd, n, ms_now);
  4182. if (result != 0) {
  4183. /* Poll returned either success (1) or error (-1).
  4184. * Forward both to the caller. */
  4185. return result;
  4186. }
  4187. /* Poll returned timeout (0). */
  4188. if (milliseconds > 0) {
  4189. milliseconds -= ms_now;
  4190. }
  4191. } while (milliseconds != 0);
  4192. return result;
  4193. }
  4194. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4195. * descriptor.
  4196. * Return value:
  4197. * >=0 .. number of bytes successfully written
  4198. * -1 .. timeout
  4199. * -2 .. error
  4200. */
  4201. static int
  4202. push_inner(struct mg_context *ctx,
  4203. FILE *fp,
  4204. SOCKET sock,
  4205. SSL *ssl,
  4206. const char *buf,
  4207. int len,
  4208. double timeout)
  4209. {
  4210. uint64_t start = 0, now = 0, timeout_ns = 0;
  4211. int n, err;
  4212. int ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4213. #ifdef _WIN32
  4214. typedef int len_t;
  4215. #else
  4216. typedef size_t len_t;
  4217. #endif
  4218. if (timeout > 0) {
  4219. start = mg_get_current_time_ns();
  4220. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4221. }
  4222. if (ctx == NULL) {
  4223. return -2;
  4224. }
  4225. #ifdef NO_SSL
  4226. if (ssl) {
  4227. return -2;
  4228. }
  4229. #endif
  4230. do {
  4231. #ifndef NO_SSL
  4232. if (ssl != NULL) {
  4233. n = SSL_write(ssl, buf, len);
  4234. if (n <= 0) {
  4235. err = SSL_get_error(ssl, n);
  4236. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4237. err = ERRNO;
  4238. } else if ((err == SSL_ERROR_WANT_READ)
  4239. || (err == SSL_ERROR_WANT_WRITE)) {
  4240. n = 0;
  4241. } else {
  4242. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4243. return -2;
  4244. }
  4245. } else {
  4246. err = 0;
  4247. }
  4248. } else
  4249. #endif
  4250. if (fp != NULL) {
  4251. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4252. if (ferror(fp)) {
  4253. n = -1;
  4254. err = ERRNO;
  4255. } else {
  4256. err = 0;
  4257. }
  4258. } else {
  4259. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4260. err = (n < 0) ? ERRNO : 0;
  4261. #ifdef _WIN32
  4262. if (err == WSAEWOULDBLOCK) {
  4263. err = 0;
  4264. n = 0;
  4265. }
  4266. #else
  4267. if (err == EWOULDBLOCK) {
  4268. err = 0;
  4269. n = 0;
  4270. }
  4271. #endif
  4272. if (n < 0) {
  4273. /* shutdown of the socket at client side */
  4274. return -2;
  4275. }
  4276. }
  4277. if (ctx->stop_flag) {
  4278. return -2;
  4279. }
  4280. if ((n > 0) || ((n == 0) && (len == 0))) {
  4281. /* some data has been read, or no data was requested */
  4282. return n;
  4283. }
  4284. if (n < 0) {
  4285. /* socket error - check errno */
  4286. DEBUG_TRACE("send() failed, error %d", err);
  4287. /* TODO (mid): error handling depending on the error code.
  4288. * These codes are different between Windows and Linux.
  4289. * Currently there is no problem with failing send calls,
  4290. * if there is a reproducible situation, it should be
  4291. * investigated in detail.
  4292. */
  4293. return -2;
  4294. }
  4295. /* Only in case n=0 (timeout), repeat calling the write function */
  4296. /* Quick fix for #474 - TODO: use select to wait for send socket */
  4297. (void)ms_wait;
  4298. mg_sleep(1);
  4299. if (timeout >= 0) {
  4300. now = mg_get_current_time_ns();
  4301. }
  4302. } while ((timeout <= 0) || ((now - start) <= timeout_ns));
  4303. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4304. used */
  4305. return -1;
  4306. }
  4307. static int64_t
  4308. push_all(struct mg_context *ctx,
  4309. FILE *fp,
  4310. SOCKET sock,
  4311. SSL *ssl,
  4312. const char *buf,
  4313. int64_t len)
  4314. {
  4315. double timeout = -1.0;
  4316. int64_t n, nwritten = 0;
  4317. if (ctx == NULL) {
  4318. return -1;
  4319. }
  4320. if (ctx->config[REQUEST_TIMEOUT]) {
  4321. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4322. }
  4323. while ((len > 0) && (ctx->stop_flag == 0)) {
  4324. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4325. if (n < 0) {
  4326. if (nwritten == 0) {
  4327. nwritten = n; /* Propagate the error */
  4328. }
  4329. break;
  4330. } else if (n == 0) {
  4331. break; /* No more data to write */
  4332. } else {
  4333. nwritten += n;
  4334. len -= n;
  4335. }
  4336. }
  4337. return nwritten;
  4338. }
  4339. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4340. * Return value:
  4341. * >=0 .. number of bytes successfully read
  4342. * -1 .. timeout
  4343. * -2 .. error
  4344. */
  4345. static int
  4346. pull_inner(FILE *fp,
  4347. struct mg_connection *conn,
  4348. char *buf,
  4349. int len,
  4350. double timeout)
  4351. {
  4352. int nread, err = 0;
  4353. #ifdef _WIN32
  4354. typedef int len_t;
  4355. #else
  4356. typedef size_t len_t;
  4357. #endif
  4358. #ifndef NO_SSL
  4359. int ssl_pending;
  4360. #endif
  4361. /* We need an additional wait loop around this, because in some cases
  4362. * with TLSwe may get data from the socket but not from SSL_read.
  4363. * In this case we need to repeat at least once.
  4364. */
  4365. if (fp != NULL) {
  4366. #if !defined(_WIN32_WCE)
  4367. /* Use read() instead of fread(), because if we're reading from the
  4368. * CGI pipe, fread() may block until IO buffer is filled up. We
  4369. * cannot afford to block and must pass all read bytes immediately
  4370. * to the client. */
  4371. nread = (int)read(fileno(fp), buf, (size_t)len);
  4372. #else
  4373. /* WinCE does not support CGI pipes */
  4374. nread = (int)fread(buf, 1, (size_t)len, fp);
  4375. #endif
  4376. err = (nread < 0) ? ERRNO : 0;
  4377. #ifndef NO_SSL
  4378. } else if ((conn->ssl != NULL)
  4379. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4380. /* We already know there is no more data buffered in conn->buf
  4381. * but there is more available in the SSL layer. So don't poll
  4382. * conn->client.sock yet. */
  4383. if (ssl_pending > len) {
  4384. ssl_pending = len;
  4385. }
  4386. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4387. if (nread <= 0) {
  4388. err = SSL_get_error(conn->ssl, nread);
  4389. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4390. err = ERRNO;
  4391. } else if ((err == SSL_ERROR_WANT_READ)
  4392. || (err == SSL_ERROR_WANT_WRITE)) {
  4393. nread = 0;
  4394. } else {
  4395. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4396. return -1;
  4397. }
  4398. } else {
  4399. err = 0;
  4400. }
  4401. } else if (conn->ssl != NULL) {
  4402. struct pollfd pfd[1];
  4403. int pollres;
  4404. pfd[0].fd = conn->client.sock;
  4405. pfd[0].events = POLLIN;
  4406. pollres =
  4407. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4408. if (conn->ctx->stop_flag) {
  4409. return -2;
  4410. }
  4411. if (pollres > 0) {
  4412. nread = SSL_read(conn->ssl, buf, len);
  4413. if (nread <= 0) {
  4414. err = SSL_get_error(conn->ssl, nread);
  4415. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4416. err = ERRNO;
  4417. } else if ((err == SSL_ERROR_WANT_READ)
  4418. || (err == SSL_ERROR_WANT_WRITE)) {
  4419. nread = 0;
  4420. } else {
  4421. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4422. return -2;
  4423. }
  4424. } else {
  4425. err = 0;
  4426. }
  4427. } else if (pollres < 0) {
  4428. /* Error */
  4429. return -2;
  4430. } else {
  4431. /* pollres = 0 means timeout */
  4432. nread = 0;
  4433. }
  4434. #endif
  4435. } else {
  4436. struct pollfd pfd[1];
  4437. int pollres;
  4438. pfd[0].fd = conn->client.sock;
  4439. pfd[0].events = POLLIN;
  4440. pollres =
  4441. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4442. if (conn->ctx->stop_flag) {
  4443. return -2;
  4444. }
  4445. if (pollres > 0) {
  4446. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4447. err = (nread < 0) ? ERRNO : 0;
  4448. if (nread <= 0) {
  4449. /* shutdown of the socket at client side */
  4450. return -2;
  4451. }
  4452. } else if (pollres < 0) {
  4453. /* error callint poll */
  4454. return -2;
  4455. } else {
  4456. /* pollres = 0 means timeout */
  4457. nread = 0;
  4458. }
  4459. }
  4460. if (conn->ctx->stop_flag) {
  4461. return -2;
  4462. }
  4463. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  4464. /* some data has been read, or no data was requested */
  4465. return nread;
  4466. }
  4467. if (nread < 0) {
  4468. /* socket error - check errno */
  4469. #ifdef _WIN32
  4470. if (err == WSAEWOULDBLOCK) {
  4471. /* TODO (low): check if this is still required */
  4472. /* standard case if called from close_socket_gracefully */
  4473. return -2;
  4474. } else if (err == WSAETIMEDOUT) {
  4475. /* TODO (low): check if this is still required */
  4476. /* timeout is handled by the while loop */
  4477. return 0;
  4478. } else if (err == WSAECONNABORTED) {
  4479. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4480. return -2;
  4481. } else {
  4482. DEBUG_TRACE("recv() failed, error %d", err);
  4483. return -2;
  4484. }
  4485. #else
  4486. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4487. * if the timeout is reached and if the socket was set to non-
  4488. * blocking in close_socket_gracefully, so we can not distinguish
  4489. * here. We have to wait for the timeout in both cases for now.
  4490. */
  4491. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  4492. /* TODO (low): check if this is still required */
  4493. /* EAGAIN/EWOULDBLOCK:
  4494. * standard case if called from close_socket_gracefully
  4495. * => should return -1 */
  4496. /* or timeout occured
  4497. * => the code must stay in the while loop */
  4498. /* EINTR can be generated on a socket with a timeout set even
  4499. * when SA_RESTART is effective for all relevant signals
  4500. * (see signal(7)).
  4501. * => stay in the while loop */
  4502. } else {
  4503. DEBUG_TRACE("recv() failed, error %d", err);
  4504. return -2;
  4505. }
  4506. #endif
  4507. }
  4508. /* Timeout occured, but no data available. */
  4509. return -1;
  4510. }
  4511. static int
  4512. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4513. {
  4514. int n, nread = 0;
  4515. double timeout = -1.0;
  4516. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4517. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4518. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4519. }
  4520. if (timeout >= 0.0) {
  4521. start_time = mg_get_current_time_ns();
  4522. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4523. }
  4524. while ((len > 0) && (conn->ctx->stop_flag == 0)) {
  4525. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4526. if (n == -2) {
  4527. if (nread == 0) {
  4528. nread = -1; /* Propagate the error */
  4529. }
  4530. break;
  4531. } else if (n == -1) {
  4532. /* timeout */
  4533. if (timeout >= 0.0) {
  4534. now = mg_get_current_time_ns();
  4535. if ((now - start_time) <= timeout_ns) {
  4536. continue;
  4537. }
  4538. }
  4539. break;
  4540. } else if (n == 0) {
  4541. break; /* No more data to read */
  4542. } else {
  4543. conn->consumed_content += n;
  4544. nread += n;
  4545. len -= n;
  4546. }
  4547. }
  4548. return nread;
  4549. }
  4550. static void
  4551. discard_unread_request_data(struct mg_connection *conn)
  4552. {
  4553. char buf[MG_BUF_LEN];
  4554. size_t to_read;
  4555. int nread;
  4556. if (conn == NULL) {
  4557. return;
  4558. }
  4559. to_read = sizeof(buf);
  4560. if (conn->is_chunked) {
  4561. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4562. * completely */
  4563. while (conn->is_chunked == 1) {
  4564. nread = mg_read(conn, buf, to_read);
  4565. if (nread <= 0) {
  4566. break;
  4567. }
  4568. }
  4569. } else {
  4570. /* Not chunked: content length is known */
  4571. while (conn->consumed_content < conn->content_len) {
  4572. if (to_read
  4573. > (size_t)(conn->content_len - conn->consumed_content)) {
  4574. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4575. }
  4576. nread = mg_read(conn, buf, to_read);
  4577. if (nread <= 0) {
  4578. break;
  4579. }
  4580. }
  4581. }
  4582. }
  4583. static int
  4584. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4585. {
  4586. int64_t n, buffered_len, nread;
  4587. int64_t len64 =
  4588. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4589. * int, we may not read more
  4590. * bytes */
  4591. const char *body;
  4592. if (conn == NULL) {
  4593. return 0;
  4594. }
  4595. /* If Content-Length is not set for a PUT or POST request, read until
  4596. * socket is closed */
  4597. if ((conn->consumed_content) == 0 && (conn->content_len == -1)) {
  4598. conn->content_len = INT64_MAX;
  4599. conn->must_close = 1;
  4600. }
  4601. nread = 0;
  4602. if (conn->consumed_content < conn->content_len) {
  4603. /* Adjust number of bytes to read. */
  4604. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4605. if (left_to_read < len64) {
  4606. /* Do not read more than the total content length of the request.
  4607. */
  4608. len64 = left_to_read;
  4609. }
  4610. /* Return buffered data */
  4611. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4612. - conn->consumed_content;
  4613. if (buffered_len > 0) {
  4614. if (len64 < buffered_len) {
  4615. buffered_len = len64;
  4616. }
  4617. body = conn->buf + conn->request_len + conn->consumed_content;
  4618. memcpy(buf, body, (size_t)buffered_len);
  4619. len64 -= buffered_len;
  4620. conn->consumed_content += buffered_len;
  4621. nread += buffered_len;
  4622. buf = (char *)buf + buffered_len;
  4623. }
  4624. /* We have returned all buffered data. Read new data from the remote
  4625. * socket.
  4626. */
  4627. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4628. nread += n;
  4629. } else {
  4630. nread = ((nread > 0) ? nread : n);
  4631. }
  4632. }
  4633. return (int)nread;
  4634. }
  4635. static char
  4636. mg_getc(struct mg_connection *conn)
  4637. {
  4638. char c;
  4639. if (conn == NULL) {
  4640. return 0;
  4641. }
  4642. conn->content_len++;
  4643. if (mg_read_inner(conn, &c, 1) <= 0) {
  4644. return (char)0;
  4645. }
  4646. return c;
  4647. }
  4648. int
  4649. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4650. {
  4651. if (len > INT_MAX) {
  4652. len = INT_MAX;
  4653. }
  4654. if (conn == NULL) {
  4655. return 0;
  4656. }
  4657. if (conn->is_chunked) {
  4658. size_t all_read = 0;
  4659. while (len > 0) {
  4660. if (conn->is_chunked == 2) {
  4661. /* No more data left to read */
  4662. return 0;
  4663. }
  4664. if (conn->chunk_remainder) {
  4665. /* copy from the remainder of the last received chunk */
  4666. long read_ret;
  4667. size_t read_now =
  4668. ((conn->chunk_remainder > len) ? (len)
  4669. : (conn->chunk_remainder));
  4670. conn->content_len += (int)read_now;
  4671. read_ret =
  4672. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4673. if (read_ret < 1) {
  4674. /* read error */
  4675. return -1;
  4676. }
  4677. all_read += (size_t)read_ret;
  4678. conn->chunk_remainder -= (size_t)read_ret;
  4679. len -= (size_t)read_ret;
  4680. if (conn->chunk_remainder == 0) {
  4681. /* Add data bytes in the current chunk have been read,
  4682. * so we are expecting \r\n now. */
  4683. char x1 = mg_getc(conn);
  4684. char x2 = mg_getc(conn);
  4685. if ((x1 != '\r') || (x2 != '\n')) {
  4686. /* Protocol violation */
  4687. return -1;
  4688. }
  4689. }
  4690. } else {
  4691. /* fetch a new chunk */
  4692. int i = 0;
  4693. char lenbuf[64];
  4694. char *end = 0;
  4695. unsigned long chunkSize = 0;
  4696. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4697. lenbuf[i] = mg_getc(conn);
  4698. if ((i > 0) && (lenbuf[i] == '\r')
  4699. && (lenbuf[i - 1] != '\r')) {
  4700. continue;
  4701. }
  4702. if ((i > 1) && (lenbuf[i] == '\n')
  4703. && (lenbuf[i - 1] == '\r')) {
  4704. lenbuf[i + 1] = 0;
  4705. chunkSize = strtoul(lenbuf, &end, 16);
  4706. if (chunkSize == 0) {
  4707. /* regular end of content */
  4708. conn->is_chunked = 2;
  4709. }
  4710. break;
  4711. }
  4712. if (!isxdigit(lenbuf[i])) {
  4713. /* illegal character for chunk length */
  4714. return -1;
  4715. }
  4716. }
  4717. if ((end == NULL) || (*end != '\r')) {
  4718. /* chunksize not set correctly */
  4719. return -1;
  4720. }
  4721. if (chunkSize == 0) {
  4722. break;
  4723. }
  4724. conn->chunk_remainder = chunkSize;
  4725. }
  4726. }
  4727. return (int)all_read;
  4728. }
  4729. return mg_read_inner(conn, buf, len);
  4730. }
  4731. int
  4732. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4733. {
  4734. time_t now;
  4735. int64_t n, total, allowed;
  4736. if (conn == NULL) {
  4737. return 0;
  4738. }
  4739. if (conn->throttle > 0) {
  4740. if ((now = time(NULL)) != conn->last_throttle_time) {
  4741. conn->last_throttle_time = now;
  4742. conn->last_throttle_bytes = 0;
  4743. }
  4744. allowed = conn->throttle - conn->last_throttle_bytes;
  4745. if (allowed > (int64_t)len) {
  4746. allowed = (int64_t)len;
  4747. }
  4748. if ((total = push_all(conn->ctx,
  4749. NULL,
  4750. conn->client.sock,
  4751. conn->ssl,
  4752. (const char *)buf,
  4753. (int64_t)allowed)) == allowed) {
  4754. buf = (const char *)buf + total;
  4755. conn->last_throttle_bytes += total;
  4756. while ((total < (int64_t)len) && (conn->ctx->stop_flag == 0)) {
  4757. allowed = (conn->throttle > ((int64_t)len - total))
  4758. ? (int64_t)len - total
  4759. : conn->throttle;
  4760. if ((n = push_all(conn->ctx,
  4761. NULL,
  4762. conn->client.sock,
  4763. conn->ssl,
  4764. (const char *)buf,
  4765. (int64_t)allowed)) != allowed) {
  4766. break;
  4767. }
  4768. sleep(1);
  4769. conn->last_throttle_bytes = allowed;
  4770. conn->last_throttle_time = time(NULL);
  4771. buf = (const char *)buf + n;
  4772. total += n;
  4773. }
  4774. }
  4775. } else {
  4776. total = push_all(conn->ctx,
  4777. NULL,
  4778. conn->client.sock,
  4779. conn->ssl,
  4780. (const char *)buf,
  4781. (int64_t)len);
  4782. }
  4783. if (total > 0) {
  4784. conn->num_bytes_sent += total;
  4785. }
  4786. return (int)total;
  4787. }
  4788. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  4789. int
  4790. mg_send_chunk(struct mg_connection *conn,
  4791. const char *chunk,
  4792. unsigned int chunk_len)
  4793. {
  4794. char lenbuf[16];
  4795. size_t lenbuf_len;
  4796. int ret;
  4797. int t;
  4798. /* First store the length information in a text buffer. */
  4799. sprintf(lenbuf, "%x\r\n", chunk_len);
  4800. lenbuf_len = strlen(lenbuf);
  4801. /* Then send length information, chunk and terminating \r\n. */
  4802. ret = mg_write(conn, lenbuf, lenbuf_len);
  4803. if (ret != (int)lenbuf_len) {
  4804. return -1;
  4805. }
  4806. t = ret;
  4807. ret = mg_write(conn, chunk, chunk_len);
  4808. if (ret != (int)chunk_len) {
  4809. return -1;
  4810. }
  4811. t += ret;
  4812. ret = mg_write(conn, "\r\n", 2);
  4813. if (ret != 2) {
  4814. return -1;
  4815. }
  4816. t += ret;
  4817. return t;
  4818. }
  4819. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4820. static int
  4821. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4822. {
  4823. va_list ap_copy;
  4824. size_t size = MG_BUF_LEN / 4;
  4825. int len = -1;
  4826. *buf = NULL;
  4827. while (len < 0) {
  4828. if (*buf) {
  4829. mg_free(*buf);
  4830. }
  4831. size *= 4;
  4832. *buf = (char *)mg_malloc(size);
  4833. if (!*buf) {
  4834. break;
  4835. }
  4836. va_copy(ap_copy, ap);
  4837. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4838. va_end(ap_copy);
  4839. (*buf)[size - 1] = 0;
  4840. }
  4841. return len;
  4842. }
  4843. /* Print message to buffer. If buffer is large enough to hold the message,
  4844. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4845. * and return allocated buffer. */
  4846. static int
  4847. alloc_vprintf(char **out_buf,
  4848. char *prealloc_buf,
  4849. size_t prealloc_size,
  4850. const char *fmt,
  4851. va_list ap)
  4852. {
  4853. va_list ap_copy;
  4854. int len;
  4855. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4856. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4857. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4858. * Therefore, we make two passes: on first pass, get required message
  4859. * length.
  4860. * On second pass, actually print the message. */
  4861. va_copy(ap_copy, ap);
  4862. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4863. va_end(ap_copy);
  4864. if (len < 0) {
  4865. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4866. * Switch to alternative code path that uses incremental allocations.
  4867. */
  4868. va_copy(ap_copy, ap);
  4869. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4870. va_end(ap_copy);
  4871. } else if ((size_t)(len) >= prealloc_size) {
  4872. /* The pre-allocated buffer not large enough. */
  4873. /* Allocate a new buffer. */
  4874. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4875. if (!*out_buf) {
  4876. /* Allocation failed. Return -1 as "out of memory" error. */
  4877. return -1;
  4878. }
  4879. /* Buffer allocation successful. Store the string there. */
  4880. va_copy(ap_copy, ap);
  4881. IGNORE_UNUSED_RESULT(
  4882. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4883. va_end(ap_copy);
  4884. } else {
  4885. /* The pre-allocated buffer is large enough.
  4886. * Use it to store the string and return the address. */
  4887. va_copy(ap_copy, ap);
  4888. IGNORE_UNUSED_RESULT(
  4889. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4890. va_end(ap_copy);
  4891. *out_buf = prealloc_buf;
  4892. }
  4893. return len;
  4894. }
  4895. static int
  4896. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4897. {
  4898. char mem[MG_BUF_LEN];
  4899. char *buf = NULL;
  4900. int len;
  4901. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4902. len = mg_write(conn, buf, (size_t)len);
  4903. }
  4904. if ((buf != mem) && (buf != NULL)) {
  4905. mg_free(buf);
  4906. }
  4907. return len;
  4908. }
  4909. int
  4910. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4911. {
  4912. va_list ap;
  4913. int result;
  4914. va_start(ap, fmt);
  4915. result = mg_vprintf(conn, fmt, ap);
  4916. va_end(ap);
  4917. return result;
  4918. }
  4919. int
  4920. mg_url_decode(const char *src,
  4921. int src_len,
  4922. char *dst,
  4923. int dst_len,
  4924. int is_form_url_encoded)
  4925. {
  4926. int i, j, a, b;
  4927. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4928. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4929. if ((i < src_len - 2) && (src[i] == '%')
  4930. && isxdigit(*(const unsigned char *)(src + i + 1))
  4931. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4932. a = tolower(*(const unsigned char *)(src + i + 1));
  4933. b = tolower(*(const unsigned char *)(src + i + 2));
  4934. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4935. i += 2;
  4936. } else if (is_form_url_encoded && (src[i] == '+')) {
  4937. dst[j] = ' ';
  4938. } else {
  4939. dst[j] = src[i];
  4940. }
  4941. }
  4942. dst[j] = '\0'; /* Null-terminate the destination */
  4943. return (i >= src_len) ? j : -1;
  4944. }
  4945. int
  4946. mg_get_var(const char *data,
  4947. size_t data_len,
  4948. const char *name,
  4949. char *dst,
  4950. size_t dst_len)
  4951. {
  4952. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4953. }
  4954. int
  4955. mg_get_var2(const char *data,
  4956. size_t data_len,
  4957. const char *name,
  4958. char *dst,
  4959. size_t dst_len,
  4960. size_t occurrence)
  4961. {
  4962. const char *p, *e, *s;
  4963. size_t name_len;
  4964. int len;
  4965. if ((dst == NULL) || (dst_len == 0)) {
  4966. len = -2;
  4967. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  4968. len = -1;
  4969. dst[0] = '\0';
  4970. } else {
  4971. name_len = strlen(name);
  4972. e = data + data_len;
  4973. len = -1;
  4974. dst[0] = '\0';
  4975. /* data is "var1=val1&var2=val2...". Find variable first */
  4976. for (p = data; p + name_len < e; p++) {
  4977. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  4978. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4979. /* Point p to variable value */
  4980. p += name_len + 1;
  4981. /* Point s to the end of the value */
  4982. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4983. if (s == NULL) {
  4984. s = e;
  4985. }
  4986. /* assert(s >= p); */
  4987. if (s < p) {
  4988. return -3;
  4989. }
  4990. /* Decode variable into destination buffer */
  4991. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4992. /* Redirect error code from -1 to -2 (destination buffer too
  4993. * small). */
  4994. if (len == -1) {
  4995. len = -2;
  4996. }
  4997. break;
  4998. }
  4999. }
  5000. }
  5001. return len;
  5002. }
  5003. /* HCP24: some changes to compare hole var_name */
  5004. int
  5005. mg_get_cookie(const char *cookie_header,
  5006. const char *var_name,
  5007. char *dst,
  5008. size_t dst_size)
  5009. {
  5010. const char *s, *p, *end;
  5011. int name_len, len = -1;
  5012. if ((dst == NULL) || (dst_size == 0)) {
  5013. return -2;
  5014. }
  5015. dst[0] = '\0';
  5016. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5017. return -1;
  5018. }
  5019. name_len = (int)strlen(var_name);
  5020. end = s + strlen(s);
  5021. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5022. if (s[name_len] == '=') {
  5023. /* HCP24: now check is it a substring or a full cookie name */
  5024. if ((s == cookie_header) || (s[-1] == ' ')) {
  5025. s += name_len + 1;
  5026. if ((p = strchr(s, ' ')) == NULL) {
  5027. p = end;
  5028. }
  5029. if (p[-1] == ';') {
  5030. p--;
  5031. }
  5032. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5033. s++;
  5034. p--;
  5035. }
  5036. if ((size_t)(p - s) < dst_size) {
  5037. len = (int)(p - s);
  5038. mg_strlcpy(dst, s, (size_t)len + 1);
  5039. } else {
  5040. len = -3;
  5041. }
  5042. break;
  5043. }
  5044. }
  5045. }
  5046. return len;
  5047. }
  5048. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5049. static void
  5050. base64_encode(const unsigned char *src, int src_len, char *dst)
  5051. {
  5052. static const char *b64 =
  5053. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5054. int i, j, a, b, c;
  5055. for (i = j = 0; i < src_len; i += 3) {
  5056. a = src[i];
  5057. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5058. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5059. dst[j++] = b64[a >> 2];
  5060. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5061. if (i + 1 < src_len) {
  5062. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5063. }
  5064. if (i + 2 < src_len) {
  5065. dst[j++] = b64[c & 63];
  5066. }
  5067. }
  5068. while (j % 4 != 0) {
  5069. dst[j++] = '=';
  5070. }
  5071. dst[j++] = '\0';
  5072. }
  5073. #endif
  5074. #if defined(USE_LUA)
  5075. static unsigned char
  5076. b64reverse(char letter)
  5077. {
  5078. if ((letter >= 'A') && (letter <= 'Z')) {
  5079. return letter - 'A';
  5080. }
  5081. if ((letter >= 'a') && (letter <= 'z')) {
  5082. return letter - 'a' + 26;
  5083. }
  5084. if ((letter >= '0') && (letter <= '9')) {
  5085. return letter - '0' + 52;
  5086. }
  5087. if (letter == '+') {
  5088. return 62;
  5089. }
  5090. if (letter == '/') {
  5091. return 63;
  5092. }
  5093. if (letter == '=') {
  5094. return 255; /* normal end */
  5095. }
  5096. return 254; /* error */
  5097. }
  5098. static int
  5099. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5100. {
  5101. int i;
  5102. unsigned char a, b, c, d;
  5103. *dst_len = 0;
  5104. for (i = 0; i < src_len; i += 4) {
  5105. a = b64reverse(src[i]);
  5106. if (a >= 254) {
  5107. return i;
  5108. }
  5109. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5110. if (b >= 254) {
  5111. return i + 1;
  5112. }
  5113. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5114. if (c == 254) {
  5115. return i + 2;
  5116. }
  5117. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5118. if (d == 254) {
  5119. return i + 3;
  5120. }
  5121. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5122. if (c != 255) {
  5123. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5124. if (d != 255) {
  5125. dst[(*dst_len)++] = (c << 6) + d;
  5126. }
  5127. }
  5128. }
  5129. return -1;
  5130. }
  5131. #endif
  5132. static int
  5133. is_put_or_delete_method(const struct mg_connection *conn)
  5134. {
  5135. if (conn) {
  5136. const char *s = conn->request_info.request_method;
  5137. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5138. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5139. }
  5140. return 0;
  5141. }
  5142. #if !defined(NO_FILES)
  5143. static int
  5144. extention_matches_script(
  5145. struct mg_connection *conn, /* in: request (must be valid) */
  5146. const char *filename /* in: filename (must be valid) */
  5147. )
  5148. {
  5149. #if !defined(NO_CGI)
  5150. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5151. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5152. filename) > 0) {
  5153. return 1;
  5154. }
  5155. #endif
  5156. #if defined(USE_LUA)
  5157. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5158. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5159. filename) > 0) {
  5160. return 1;
  5161. }
  5162. #endif
  5163. #if defined(USE_DUKTAPE)
  5164. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5165. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5166. filename) > 0) {
  5167. return 1;
  5168. }
  5169. #endif
  5170. /* filename and conn could be unused, if all preocessor conditions
  5171. * are false (no script language supported). */
  5172. (void)filename;
  5173. (void)conn;
  5174. return 0;
  5175. }
  5176. /* For given directory path, substitute it to valid index file.
  5177. * Return 1 if index file has been found, 0 if not found.
  5178. * If the file is found, it's stats is returned in stp. */
  5179. static int
  5180. substitute_index_file(struct mg_connection *conn,
  5181. char *path,
  5182. size_t path_len,
  5183. struct mg_file_stat *filestat)
  5184. {
  5185. const char *list = conn->ctx->config[INDEX_FILES];
  5186. struct vec filename_vec;
  5187. size_t n = strlen(path);
  5188. int found = 0;
  5189. /* The 'path' given to us points to the directory. Remove all trailing
  5190. * directory separator characters from the end of the path, and
  5191. * then append single directory separator character. */
  5192. while ((n > 0) && (path[n - 1] == '/')) {
  5193. n--;
  5194. }
  5195. path[n] = '/';
  5196. /* Traverse index files list. For each entry, append it to the given
  5197. * path and see if the file exists. If it exists, break the loop */
  5198. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5199. /* Ignore too long entries that may overflow path buffer */
  5200. if (filename_vec.len > (path_len - (n + 2))) {
  5201. continue;
  5202. }
  5203. /* Prepare full path to the index file */
  5204. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5205. /* Does it exist? */
  5206. if (mg_stat(conn, path, filestat)) {
  5207. /* Yes it does, break the loop */
  5208. found = 1;
  5209. break;
  5210. }
  5211. }
  5212. /* If no index file exists, restore directory path */
  5213. if (!found) {
  5214. path[n] = '\0';
  5215. }
  5216. return found;
  5217. }
  5218. #endif
  5219. static void
  5220. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5221. char *filename, /* out: filename */
  5222. size_t filename_buf_len, /* in: size of filename buffer */
  5223. struct mg_file_stat *filestat, /* out: file status structure */
  5224. int *is_found, /* out: file found (directly) */
  5225. int *is_script_resource, /* out: handled by a script? */
  5226. int *is_websocket_request, /* out: websocket connetion? */
  5227. int *is_put_or_delete_request /* out: put/delete a file? */
  5228. )
  5229. {
  5230. #if !defined(NO_FILES)
  5231. const char *uri = conn->request_info.local_uri;
  5232. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5233. const char *rewrite;
  5234. struct vec a, b;
  5235. int match_len;
  5236. char gz_path[PATH_MAX];
  5237. char const *accept_encoding;
  5238. int truncated;
  5239. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5240. char *tmp_str;
  5241. size_t tmp_str_len, sep_pos;
  5242. #endif
  5243. #else
  5244. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5245. #endif
  5246. /* Step 1: Set all initially unknown outputs to zero */
  5247. memset(filestat, 0, sizeof(*filestat));
  5248. *filename = 0;
  5249. *is_found = 0;
  5250. *is_script_resource = 0;
  5251. /* Step 2: Check if the request attempts to modify the file system */
  5252. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5253. /* Step 3: Check if it is a websocket request, and modify the document
  5254. * root if required */
  5255. #if defined(USE_WEBSOCKET)
  5256. *is_websocket_request = is_websocket_protocol(conn);
  5257. #if !defined(NO_FILES)
  5258. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5259. root = conn->ctx->config[WEBSOCKET_ROOT];
  5260. }
  5261. #endif /* !NO_FILES */
  5262. #else /* USE_WEBSOCKET */
  5263. *is_websocket_request = 0;
  5264. #endif /* USE_WEBSOCKET */
  5265. #if !defined(NO_FILES)
  5266. /* Step 4: If there is no root directory, don't look for files. */
  5267. /* Note that root == NULL is a regular use case here. This occurs,
  5268. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5269. * config is not required. */
  5270. if (root == NULL) {
  5271. /* all file related outputs have already been set to 0, just return
  5272. */
  5273. return;
  5274. }
  5275. /* Step 5: Determine the local file path from the root path and the
  5276. * request uri. */
  5277. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5278. * part of the path one byte on the right. */
  5279. mg_snprintf(
  5280. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5281. if (truncated) {
  5282. goto interpret_cleanup;
  5283. }
  5284. /* Step 6: URI rewriting */
  5285. rewrite = conn->ctx->config[URL_REWRITE_PATTERN];
  5286. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5287. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5288. mg_snprintf(conn,
  5289. &truncated,
  5290. filename,
  5291. filename_buf_len - 1,
  5292. "%.*s%s",
  5293. (int)b.len,
  5294. b.ptr,
  5295. uri + match_len);
  5296. break;
  5297. }
  5298. }
  5299. if (truncated) {
  5300. goto interpret_cleanup;
  5301. }
  5302. /* Step 7: Check if the file exists at the server */
  5303. /* Local file path and name, corresponding to requested URI
  5304. * is now stored in "filename" variable. */
  5305. if (mg_stat(conn, filename, filestat)) {
  5306. /* 7.1: File exists. */
  5307. *is_found = 1;
  5308. /* 7.2: Check if it is a script type. */
  5309. if (extention_matches_script(conn, filename)) {
  5310. /* The request addresses a CGI resource, Lua script or
  5311. * server-side javascript.
  5312. * The URI corresponds to the script itself (like
  5313. * /path/script.cgi), and there is no additional resource
  5314. * path (like /path/script.cgi/something).
  5315. * Requests that modify (replace or delete) a resource, like
  5316. * PUT and DELETE requests, should replace/delete the script
  5317. * file.
  5318. * Requests that read or write from/to a resource, like GET and
  5319. * POST requests, should call the script and return the
  5320. * generated response. */
  5321. *is_script_resource = (!*is_put_or_delete_request);
  5322. }
  5323. /* 7.3: If the request target is a directory, there could be
  5324. * a substitute file (index.html, index.cgi, ...). */
  5325. if (filestat->is_directory) {
  5326. /* Use a local copy here, since substitute_index_file will
  5327. * change the content of the file status */
  5328. struct mg_file_stat tmp_filestat;
  5329. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5330. if (substitute_index_file(
  5331. conn, filename, filename_buf_len, &tmp_filestat)) {
  5332. /* Substitute file found. Copy stat to the output, then
  5333. * check if the file is a script file */
  5334. *filestat = tmp_filestat;
  5335. if (extention_matches_script(conn, filename)) {
  5336. /* Substitute file is a script file */
  5337. *is_script_resource = 1;
  5338. } else {
  5339. /* Substitute file is a regular file */
  5340. *is_script_resource = 0;
  5341. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5342. }
  5343. }
  5344. /* If there is no substitute file, the server could return
  5345. * a directory listing in a later step */
  5346. }
  5347. return;
  5348. }
  5349. /* Step 8: Check for zipped files: */
  5350. /* If we can't find the actual file, look for the file
  5351. * with the same name but a .gz extension. If we find it,
  5352. * use that and set the gzipped flag in the file struct
  5353. * to indicate that the response need to have the content-
  5354. * encoding: gzip header.
  5355. * We can only do this if the browser declares support. */
  5356. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5357. if (strstr(accept_encoding, "gzip") != NULL) {
  5358. mg_snprintf(
  5359. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5360. if (truncated) {
  5361. goto interpret_cleanup;
  5362. }
  5363. if (mg_stat(conn, gz_path, filestat)) {
  5364. if (filestat) {
  5365. filestat->is_gzipped = 1;
  5366. *is_found = 1;
  5367. }
  5368. /* Currently gz files can not be scripts. */
  5369. return;
  5370. }
  5371. }
  5372. }
  5373. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5374. /* Step 9: Script resources may handle sub-resources */
  5375. /* Support PATH_INFO for CGI scripts. */
  5376. tmp_str_len = strlen(filename);
  5377. tmp_str = mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->ctx);
  5378. if (!tmp_str) {
  5379. /* Out of memory */
  5380. goto interpret_cleanup;
  5381. }
  5382. memcpy(tmp_str, filename, tmp_str_len + 1);
  5383. sep_pos = tmp_str_len;
  5384. while (sep_pos > 0) {
  5385. sep_pos--;
  5386. if (tmp_str[sep_pos] == '/') {
  5387. int is_script = 0, does_exist = 0;
  5388. tmp_str[sep_pos] = 0;
  5389. if (tmp_str[0]) {
  5390. is_script = extention_matches_script(conn, tmp_str);
  5391. does_exist = mg_stat(conn, tmp_str, filestat);
  5392. }
  5393. if (does_exist && is_script) {
  5394. filename[sep_pos] = 0;
  5395. memmove(filename + sep_pos + 2,
  5396. filename + sep_pos + 1,
  5397. strlen(filename + sep_pos + 1) + 1);
  5398. conn->path_info = filename + sep_pos + 1;
  5399. filename[sep_pos + 1] = '/';
  5400. *is_script_resource = 1;
  5401. *is_found = 1;
  5402. break;
  5403. }
  5404. if (substitute_index_file(
  5405. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5406. /* some intermediate directory has an index file */
  5407. if (extention_matches_script(conn, tmp_str)) {
  5408. /* this index file is a script */
  5409. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5410. mg_snprintf(conn,
  5411. &truncated,
  5412. filename,
  5413. filename_buf_len,
  5414. "%s//%s",
  5415. tmp_str,
  5416. tmp_str2);
  5417. mg_free(tmp_str2);
  5418. if (truncated) {
  5419. mg_free(tmp_str);
  5420. goto interpret_cleanup;
  5421. }
  5422. sep_pos = strlen(tmp_str);
  5423. filename[sep_pos] = 0;
  5424. conn->path_info = filename + sep_pos + 1;
  5425. *is_script_resource = 1;
  5426. *is_found = 1;
  5427. break;
  5428. } else {
  5429. /* non-script files will not have sub-resources */
  5430. filename[sep_pos] = 0;
  5431. conn->path_info = 0;
  5432. *is_script_resource = 0;
  5433. *is_found = 0;
  5434. break;
  5435. }
  5436. }
  5437. tmp_str[sep_pos] = '/';
  5438. }
  5439. }
  5440. mg_free(tmp_str);
  5441. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5442. #endif /* !defined(NO_FILES) */
  5443. return;
  5444. #if !defined(NO_FILES)
  5445. /* Reset all outputs */
  5446. interpret_cleanup:
  5447. memset(filestat, 0, sizeof(*filestat));
  5448. *filename = 0;
  5449. *is_found = 0;
  5450. *is_script_resource = 0;
  5451. *is_websocket_request = 0;
  5452. *is_put_or_delete_request = 0;
  5453. #endif /* !defined(NO_FILES) */
  5454. }
  5455. /* Check whether full request is buffered. Return:
  5456. * -1 if request is malformed
  5457. * 0 if request is not yet fully buffered
  5458. * >0 actual request length, including last \r\n\r\n */
  5459. static int
  5460. get_request_len(const char *buf, int buflen)
  5461. {
  5462. const char *s, *e;
  5463. int len = 0;
  5464. for (s = buf, e = s + buflen - 1; (len <= 0) && (s < e); s++)
  5465. /* Control characters are not allowed but >=128 is. */
  5466. if (!isprint(*(const unsigned char *)s) && (*s != '\r') && (*s != '\n')
  5467. && (*(const unsigned char *)s < 128)) {
  5468. len = -1;
  5469. break; /* [i_a] abort scan as soon as one malformed character is
  5470. * found; */
  5471. /* don't let subsequent \r\n\r\n win us over anyhow */
  5472. } else if ((s[0] == '\n') && (s[1] == '\n')) {
  5473. len = (int)(s - buf) + 2;
  5474. } else if ((s[0] == '\n') && (&s[1] < e) && (s[1] == '\r')
  5475. && (s[2] == '\n')) {
  5476. len = (int)(s - buf) + 3;
  5477. }
  5478. return len;
  5479. }
  5480. #if !defined(NO_CACHING)
  5481. /* Convert month to the month number. Return -1 on error, or month number */
  5482. static int
  5483. get_month_index(const char *s)
  5484. {
  5485. size_t i;
  5486. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5487. if (!strcmp(s, month_names[i])) {
  5488. return (int)i;
  5489. }
  5490. }
  5491. return -1;
  5492. }
  5493. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5494. static time_t
  5495. parse_date_string(const char *datetime)
  5496. {
  5497. char month_str[32] = {0};
  5498. int second, minute, hour, day, month, year;
  5499. time_t result = (time_t)0;
  5500. struct tm tm;
  5501. if ((sscanf(datetime,
  5502. "%d/%3s/%d %d:%d:%d",
  5503. &day,
  5504. month_str,
  5505. &year,
  5506. &hour,
  5507. &minute,
  5508. &second) == 6) || (sscanf(datetime,
  5509. "%d %3s %d %d:%d:%d",
  5510. &day,
  5511. month_str,
  5512. &year,
  5513. &hour,
  5514. &minute,
  5515. &second) == 6)
  5516. || (sscanf(datetime,
  5517. "%*3s, %d %3s %d %d:%d:%d",
  5518. &day,
  5519. month_str,
  5520. &year,
  5521. &hour,
  5522. &minute,
  5523. &second) == 6) || (sscanf(datetime,
  5524. "%d-%3s-%d %d:%d:%d",
  5525. &day,
  5526. month_str,
  5527. &year,
  5528. &hour,
  5529. &minute,
  5530. &second) == 6)) {
  5531. month = get_month_index(month_str);
  5532. if ((month >= 0) && (year >= 1970)) {
  5533. memset(&tm, 0, sizeof(tm));
  5534. tm.tm_year = year - 1900;
  5535. tm.tm_mon = month;
  5536. tm.tm_mday = day;
  5537. tm.tm_hour = hour;
  5538. tm.tm_min = minute;
  5539. tm.tm_sec = second;
  5540. result = timegm(&tm);
  5541. }
  5542. }
  5543. return result;
  5544. }
  5545. #endif /* !NO_CACHING */
  5546. /* Protect against directory disclosure attack by removing '..',
  5547. * excessive '/' and '\' characters */
  5548. static void
  5549. remove_double_dots_and_double_slashes(char *s)
  5550. {
  5551. char *p = s;
  5552. while ((s[0] == '.') && (s[1] == '.')) {
  5553. s++;
  5554. }
  5555. while (*s != '\0') {
  5556. *p++ = *s++;
  5557. if ((s[-1] == '/') || (s[-1] == '\\')) {
  5558. /* Skip all following slashes, backslashes and double-dots */
  5559. while (s[0] != '\0') {
  5560. if ((s[0] == '/') || (s[0] == '\\')) {
  5561. s++;
  5562. } else if ((s[0] == '.') && (s[1] == '.')) {
  5563. s += 2;
  5564. } else {
  5565. break;
  5566. }
  5567. }
  5568. }
  5569. }
  5570. *p = '\0';
  5571. }
  5572. static const struct {
  5573. const char *extension;
  5574. size_t ext_len;
  5575. const char *mime_type;
  5576. } builtin_mime_types[] = {
  5577. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5578. * application types */
  5579. {".doc", 4, "application/msword"},
  5580. {".eps", 4, "application/postscript"},
  5581. {".exe", 4, "application/octet-stream"},
  5582. {".js", 3, "application/javascript"},
  5583. {".json", 5, "application/json"},
  5584. {".pdf", 4, "application/pdf"},
  5585. {".ps", 3, "application/postscript"},
  5586. {".rtf", 4, "application/rtf"},
  5587. {".xhtml", 6, "application/xhtml+xml"},
  5588. {".xsl", 4, "application/xml"},
  5589. {".xslt", 5, "application/xml"},
  5590. /* fonts */
  5591. {".ttf", 4, "application/font-sfnt"},
  5592. {".cff", 4, "application/font-sfnt"},
  5593. {".otf", 4, "application/font-sfnt"},
  5594. {".aat", 4, "application/font-sfnt"},
  5595. {".sil", 4, "application/font-sfnt"},
  5596. {".pfr", 4, "application/font-tdpfr"},
  5597. {".woff", 5, "application/font-woff"},
  5598. /* audio */
  5599. {".mp3", 4, "audio/mpeg"},
  5600. {".oga", 4, "audio/ogg"},
  5601. {".ogg", 4, "audio/ogg"},
  5602. /* image */
  5603. {".gif", 4, "image/gif"},
  5604. {".ief", 4, "image/ief"},
  5605. {".jpeg", 5, "image/jpeg"},
  5606. {".jpg", 4, "image/jpeg"},
  5607. {".jpm", 4, "image/jpm"},
  5608. {".jpx", 4, "image/jpx"},
  5609. {".png", 4, "image/png"},
  5610. {".svg", 4, "image/svg+xml"},
  5611. {".tif", 4, "image/tiff"},
  5612. {".tiff", 5, "image/tiff"},
  5613. /* model */
  5614. {".wrl", 4, "model/vrml"},
  5615. /* text */
  5616. {".css", 4, "text/css"},
  5617. {".csv", 4, "text/csv"},
  5618. {".htm", 4, "text/html"},
  5619. {".html", 5, "text/html"},
  5620. {".sgm", 4, "text/sgml"},
  5621. {".shtm", 5, "text/html"},
  5622. {".shtml", 6, "text/html"},
  5623. {".txt", 4, "text/plain"},
  5624. {".xml", 4, "text/xml"},
  5625. /* video */
  5626. {".mov", 4, "video/quicktime"},
  5627. {".mp4", 4, "video/mp4"},
  5628. {".mpeg", 5, "video/mpeg"},
  5629. {".mpg", 4, "video/mpeg"},
  5630. {".ogv", 4, "video/ogg"},
  5631. {".qt", 3, "video/quicktime"},
  5632. /* not registered types
  5633. * (http://reference.sitepoint.com/html/mime-types-full,
  5634. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5635. {".arj", 4, "application/x-arj-compressed"},
  5636. {".gz", 3, "application/x-gunzip"},
  5637. {".rar", 4, "application/x-arj-compressed"},
  5638. {".swf", 4, "application/x-shockwave-flash"},
  5639. {".tar", 4, "application/x-tar"},
  5640. {".tgz", 4, "application/x-tar-gz"},
  5641. {".torrent", 8, "application/x-bittorrent"},
  5642. {".ppt", 4, "application/x-mspowerpoint"},
  5643. {".xls", 4, "application/x-msexcel"},
  5644. {".zip", 4, "application/x-zip-compressed"},
  5645. {".aac",
  5646. 4,
  5647. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5648. {".aif", 4, "audio/x-aif"},
  5649. {".m3u", 4, "audio/x-mpegurl"},
  5650. {".mid", 4, "audio/x-midi"},
  5651. {".ra", 3, "audio/x-pn-realaudio"},
  5652. {".ram", 4, "audio/x-pn-realaudio"},
  5653. {".wav", 4, "audio/x-wav"},
  5654. {".bmp", 4, "image/bmp"},
  5655. {".ico", 4, "image/x-icon"},
  5656. {".pct", 4, "image/x-pct"},
  5657. {".pict", 5, "image/pict"},
  5658. {".rgb", 4, "image/x-rgb"},
  5659. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5660. {".asf", 4, "video/x-ms-asf"},
  5661. {".avi", 4, "video/x-msvideo"},
  5662. {".m4v", 4, "video/x-m4v"},
  5663. {NULL, 0, NULL}};
  5664. const char *
  5665. mg_get_builtin_mime_type(const char *path)
  5666. {
  5667. const char *ext;
  5668. size_t i, path_len;
  5669. path_len = strlen(path);
  5670. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5671. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5672. if ((path_len > builtin_mime_types[i].ext_len)
  5673. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  5674. return builtin_mime_types[i].mime_type;
  5675. }
  5676. }
  5677. return "text/plain";
  5678. }
  5679. /* Look at the "path" extension and figure what mime type it has.
  5680. * Store mime type in the vector. */
  5681. static void
  5682. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5683. {
  5684. struct vec ext_vec, mime_vec;
  5685. const char *list, *ext;
  5686. size_t path_len;
  5687. path_len = strlen(path);
  5688. if ((ctx == NULL) || (vec == NULL)) {
  5689. if (vec != NULL) {
  5690. memset(vec, '\0', sizeof(struct vec));
  5691. }
  5692. return;
  5693. }
  5694. /* Scan user-defined mime types first, in case user wants to
  5695. * override default mime types. */
  5696. list = ctx->config[EXTRA_MIME_TYPES];
  5697. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5698. /* ext now points to the path suffix */
  5699. ext = path + path_len - ext_vec.len;
  5700. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5701. *vec = mime_vec;
  5702. return;
  5703. }
  5704. }
  5705. vec->ptr = mg_get_builtin_mime_type(path);
  5706. vec->len = strlen(vec->ptr);
  5707. }
  5708. /* Stringify binary data. Output buffer must be twice as big as input,
  5709. * because each byte takes 2 bytes in string representation */
  5710. static void
  5711. bin2str(char *to, const unsigned char *p, size_t len)
  5712. {
  5713. static const char *hex = "0123456789abcdef";
  5714. for (; len--; p++) {
  5715. *to++ = hex[p[0] >> 4];
  5716. *to++ = hex[p[0] & 0x0f];
  5717. }
  5718. *to = '\0';
  5719. }
  5720. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5721. char *
  5722. mg_md5(char buf[33], ...)
  5723. {
  5724. md5_byte_t hash[16];
  5725. const char *p;
  5726. va_list ap;
  5727. md5_state_t ctx;
  5728. md5_init(&ctx);
  5729. va_start(ap, buf);
  5730. while ((p = va_arg(ap, const char *)) != NULL) {
  5731. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5732. }
  5733. va_end(ap);
  5734. md5_finish(&ctx, hash);
  5735. bin2str(buf, hash, sizeof(hash));
  5736. return buf;
  5737. }
  5738. /* Check the user's password, return 1 if OK */
  5739. static int
  5740. check_password(const char *method,
  5741. const char *ha1,
  5742. const char *uri,
  5743. const char *nonce,
  5744. const char *nc,
  5745. const char *cnonce,
  5746. const char *qop,
  5747. const char *response)
  5748. {
  5749. char ha2[32 + 1], expected_response[32 + 1];
  5750. /* Some of the parameters may be NULL */
  5751. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  5752. || (qop == NULL) || (response == NULL)) {
  5753. return 0;
  5754. }
  5755. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5756. if (strlen(response) != 32) {
  5757. return 0;
  5758. }
  5759. mg_md5(ha2, method, ":", uri, NULL);
  5760. mg_md5(expected_response,
  5761. ha1,
  5762. ":",
  5763. nonce,
  5764. ":",
  5765. nc,
  5766. ":",
  5767. cnonce,
  5768. ":",
  5769. qop,
  5770. ":",
  5771. ha2,
  5772. NULL);
  5773. return mg_strcasecmp(response, expected_response) == 0;
  5774. }
  5775. /* Use the global passwords file, if specified by auth_gpass option,
  5776. * or search for .htpasswd in the requested directory. */
  5777. static void
  5778. open_auth_file(struct mg_connection *conn,
  5779. const char *path,
  5780. struct mg_file *filep)
  5781. {
  5782. if ((conn != NULL) && (conn->ctx != NULL)) {
  5783. char name[PATH_MAX];
  5784. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5785. int truncated;
  5786. if (gpass != NULL) {
  5787. /* Use global passwords file */
  5788. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5789. #ifdef DEBUG
  5790. /* Use mg_cry here, since gpass has been configured. */
  5791. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5792. #endif
  5793. }
  5794. /* Important: using local struct mg_file to test path for
  5795. * is_directory flag. If filep is used, mg_stat() makes it
  5796. * appear as if auth file was opened.
  5797. * TODO(mid): Check if this is still required after rewriting
  5798. * mg_stat */
  5799. } else if (mg_stat(conn, path, &filep->stat)
  5800. && filep->stat.is_directory) {
  5801. mg_snprintf(conn,
  5802. &truncated,
  5803. name,
  5804. sizeof(name),
  5805. "%s/%s",
  5806. path,
  5807. PASSWORDS_FILE_NAME);
  5808. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5809. #ifdef DEBUG
  5810. /* Don't use mg_cry here, but only a trace, since this is
  5811. * a typical case. It will occur for every directory
  5812. * without a password file. */
  5813. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5814. #endif
  5815. }
  5816. } else {
  5817. /* Try to find .htpasswd in requested directory. */
  5818. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5819. if (e[0] == '/') {
  5820. break;
  5821. }
  5822. }
  5823. mg_snprintf(conn,
  5824. &truncated,
  5825. name,
  5826. sizeof(name),
  5827. "%.*s/%s",
  5828. (int)(e - p),
  5829. p,
  5830. PASSWORDS_FILE_NAME);
  5831. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5832. #ifdef DEBUG
  5833. /* Don't use mg_cry here, but only a trace, since this is
  5834. * a typical case. It will occur for every directory
  5835. * without a password file. */
  5836. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5837. #endif
  5838. }
  5839. }
  5840. }
  5841. }
  5842. /* Parsed Authorization header */
  5843. struct ah {
  5844. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5845. };
  5846. /* Return 1 on success. Always initializes the ah structure. */
  5847. static int
  5848. parse_auth_header(struct mg_connection *conn,
  5849. char *buf,
  5850. size_t buf_size,
  5851. struct ah *ah)
  5852. {
  5853. char *name, *value, *s;
  5854. const char *auth_header;
  5855. uint64_t nonce;
  5856. if (!ah || !conn) {
  5857. return 0;
  5858. }
  5859. (void)memset(ah, 0, sizeof(*ah));
  5860. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  5861. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5862. return 0;
  5863. }
  5864. /* Make modifiable copy of the auth header */
  5865. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5866. s = buf;
  5867. /* Parse authorization header */
  5868. for (;;) {
  5869. /* Gobble initial spaces */
  5870. while (isspace(*(unsigned char *)s)) {
  5871. s++;
  5872. }
  5873. name = skip_quoted(&s, "=", " ", 0);
  5874. /* Value is either quote-delimited, or ends at first comma or space. */
  5875. if (s[0] == '\"') {
  5876. s++;
  5877. value = skip_quoted(&s, "\"", " ", '\\');
  5878. if (s[0] == ',') {
  5879. s++;
  5880. }
  5881. } else {
  5882. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5883. * spaces */
  5884. }
  5885. if (*name == '\0') {
  5886. break;
  5887. }
  5888. if (!strcmp(name, "username")) {
  5889. ah->user = value;
  5890. } else if (!strcmp(name, "cnonce")) {
  5891. ah->cnonce = value;
  5892. } else if (!strcmp(name, "response")) {
  5893. ah->response = value;
  5894. } else if (!strcmp(name, "uri")) {
  5895. ah->uri = value;
  5896. } else if (!strcmp(name, "qop")) {
  5897. ah->qop = value;
  5898. } else if (!strcmp(name, "nc")) {
  5899. ah->nc = value;
  5900. } else if (!strcmp(name, "nonce")) {
  5901. ah->nonce = value;
  5902. }
  5903. }
  5904. #ifndef NO_NONCE_CHECK
  5905. /* Read the nonce from the response. */
  5906. if (ah->nonce == NULL) {
  5907. return 0;
  5908. }
  5909. s = NULL;
  5910. nonce = strtoull(ah->nonce, &s, 10);
  5911. if ((s == NULL) || (*s != 0)) {
  5912. return 0;
  5913. }
  5914. /* Convert the nonce from the client to a number. */
  5915. nonce ^= conn->ctx->auth_nonce_mask;
  5916. /* The converted number corresponds to the time the nounce has been
  5917. * created. This should not be earlier than the server start. */
  5918. /* Server side nonce check is valuable in all situations but one:
  5919. * if the server restarts frequently, but the client should not see
  5920. * that, so the server should accept nonces from previous starts. */
  5921. /* However, the reasonable default is to not accept a nonce from a
  5922. * previous start, so if anyone changed the access rights between
  5923. * two restarts, a new login is required. */
  5924. if (nonce < (uint64_t)conn->ctx->start_time) {
  5925. /* nonce is from a previous start of the server and no longer valid
  5926. * (replay attack?) */
  5927. return 0;
  5928. }
  5929. /* Check if the nonce is too high, so it has not (yet) been used by the
  5930. * server. */
  5931. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5932. return 0;
  5933. }
  5934. #else
  5935. (void)nonce;
  5936. #endif
  5937. /* CGI needs it as REMOTE_USER */
  5938. if (ah->user != NULL) {
  5939. conn->request_info.remote_user = mg_strdup(ah->user);
  5940. } else {
  5941. return 0;
  5942. }
  5943. return 1;
  5944. }
  5945. static const char *
  5946. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5947. {
  5948. const char *eof;
  5949. size_t len;
  5950. const char *memend;
  5951. if (!filep) {
  5952. return NULL;
  5953. }
  5954. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  5955. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5956. /* Search for \n from p till the end of stream */
  5957. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5958. if (eof != NULL) {
  5959. eof += 1; /* Include \n */
  5960. } else {
  5961. eof = memend; /* Copy remaining data */
  5962. }
  5963. len =
  5964. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5965. memcpy(buf, *p, len);
  5966. buf[len] = '\0';
  5967. *p += len;
  5968. return len ? eof : NULL;
  5969. } else if (filep->access.fp != NULL) {
  5970. return fgets(buf, (int)size, filep->access.fp);
  5971. } else {
  5972. return NULL;
  5973. }
  5974. }
  5975. /* Define the initial recursion depth for procesesing htpasswd files that
  5976. * include other htpasswd
  5977. * (or even the same) files. It is not difficult to provide a file or files
  5978. * s.t. they force civetweb
  5979. * to infinitely recurse and then crash.
  5980. */
  5981. #define INITIAL_DEPTH 9
  5982. #if INITIAL_DEPTH <= 0
  5983. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5984. #endif
  5985. struct read_auth_file_struct {
  5986. struct mg_connection *conn;
  5987. struct ah ah;
  5988. char *domain;
  5989. char buf[256 + 256 + 40];
  5990. char *f_user;
  5991. char *f_domain;
  5992. char *f_ha1;
  5993. };
  5994. static int
  5995. read_auth_file(struct mg_file *filep,
  5996. struct read_auth_file_struct *workdata,
  5997. int depth)
  5998. {
  5999. char *p;
  6000. int is_authorized = 0;
  6001. struct mg_file fp;
  6002. size_t l;
  6003. if (!filep || !workdata || (0 == depth)) {
  6004. return 0;
  6005. }
  6006. /* Loop over passwords file */
  6007. p = (char *)filep->access.membuf;
  6008. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6009. l = strlen(workdata->buf);
  6010. while (l > 0) {
  6011. if (isspace(workdata->buf[l - 1])
  6012. || iscntrl(workdata->buf[l - 1])) {
  6013. l--;
  6014. workdata->buf[l] = 0;
  6015. } else
  6016. break;
  6017. }
  6018. if (l < 1) {
  6019. continue;
  6020. }
  6021. workdata->f_user = workdata->buf;
  6022. if (workdata->f_user[0] == ':') {
  6023. /* user names may not contain a ':' and may not be empty,
  6024. * so lines starting with ':' may be used for a special purpose */
  6025. if (workdata->f_user[1] == '#') {
  6026. /* :# is a comment */
  6027. continue;
  6028. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6029. if (mg_fopen(workdata->conn,
  6030. workdata->f_user + 9,
  6031. MG_FOPEN_MODE_READ,
  6032. &fp)) {
  6033. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6034. (void)mg_fclose(
  6035. &fp.access); /* ignore error on read only file */
  6036. /* No need to continue processing files once we have a
  6037. * match, since nothing will reset it back
  6038. * to 0.
  6039. */
  6040. if (is_authorized) {
  6041. return is_authorized;
  6042. }
  6043. } else {
  6044. mg_cry(workdata->conn,
  6045. "%s: cannot open authorization file: %s",
  6046. __func__,
  6047. workdata->buf);
  6048. }
  6049. continue;
  6050. }
  6051. /* everything is invalid for the moment (might change in the
  6052. * future) */
  6053. mg_cry(workdata->conn,
  6054. "%s: syntax error in authorization file: %s",
  6055. __func__,
  6056. workdata->buf);
  6057. continue;
  6058. }
  6059. workdata->f_domain = strchr(workdata->f_user, ':');
  6060. if (workdata->f_domain == NULL) {
  6061. mg_cry(workdata->conn,
  6062. "%s: syntax error in authorization file: %s",
  6063. __func__,
  6064. workdata->buf);
  6065. continue;
  6066. }
  6067. *(workdata->f_domain) = 0;
  6068. (workdata->f_domain)++;
  6069. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6070. if (workdata->f_ha1 == NULL) {
  6071. mg_cry(workdata->conn,
  6072. "%s: syntax error in authorization file: %s",
  6073. __func__,
  6074. workdata->buf);
  6075. continue;
  6076. }
  6077. *(workdata->f_ha1) = 0;
  6078. (workdata->f_ha1)++;
  6079. if (!strcmp(workdata->ah.user, workdata->f_user)
  6080. && !strcmp(workdata->domain, workdata->f_domain)) {
  6081. return check_password(workdata->conn->request_info.request_method,
  6082. workdata->f_ha1,
  6083. workdata->ah.uri,
  6084. workdata->ah.nonce,
  6085. workdata->ah.nc,
  6086. workdata->ah.cnonce,
  6087. workdata->ah.qop,
  6088. workdata->ah.response);
  6089. }
  6090. }
  6091. return is_authorized;
  6092. }
  6093. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6094. static int
  6095. authorize(struct mg_connection *conn, struct mg_file *filep)
  6096. {
  6097. struct read_auth_file_struct workdata;
  6098. char buf[MG_BUF_LEN];
  6099. if (!conn || !conn->ctx) {
  6100. return 0;
  6101. }
  6102. memset(&workdata, 0, sizeof(workdata));
  6103. workdata.conn = conn;
  6104. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6105. return 0;
  6106. }
  6107. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6108. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6109. }
  6110. /* Return 1 if request is authorised, 0 otherwise. */
  6111. static int
  6112. check_authorization(struct mg_connection *conn, const char *path)
  6113. {
  6114. char fname[PATH_MAX];
  6115. struct vec uri_vec, filename_vec;
  6116. const char *list;
  6117. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6118. int authorized = 1, truncated;
  6119. if (!conn || !conn->ctx) {
  6120. return 0;
  6121. }
  6122. list = conn->ctx->config[PROTECT_URI];
  6123. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6124. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6125. mg_snprintf(conn,
  6126. &truncated,
  6127. fname,
  6128. sizeof(fname),
  6129. "%.*s",
  6130. (int)filename_vec.len,
  6131. filename_vec.ptr);
  6132. if (truncated
  6133. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6134. mg_cry(conn,
  6135. "%s: cannot open %s: %s",
  6136. __func__,
  6137. fname,
  6138. strerror(errno));
  6139. }
  6140. break;
  6141. }
  6142. }
  6143. if (!is_file_opened(&file.access)) {
  6144. open_auth_file(conn, path, &file);
  6145. }
  6146. if (is_file_opened(&file.access)) {
  6147. authorized = authorize(conn, &file);
  6148. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6149. }
  6150. return authorized;
  6151. }
  6152. static void
  6153. send_authorization_request(struct mg_connection *conn)
  6154. {
  6155. char date[64];
  6156. time_t curtime = time(NULL);
  6157. if (conn && conn->ctx) {
  6158. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6159. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6160. nonce += conn->ctx->nonce_count;
  6161. ++conn->ctx->nonce_count;
  6162. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6163. nonce ^= conn->ctx->auth_nonce_mask;
  6164. conn->status_code = 401;
  6165. conn->must_close = 1;
  6166. gmt_time_string(date, sizeof(date), &curtime);
  6167. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6168. send_no_cache_header(conn);
  6169. send_additional_header(conn);
  6170. mg_printf(conn,
  6171. "Date: %s\r\n"
  6172. "Connection: %s\r\n"
  6173. "Content-Length: 0\r\n"
  6174. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6175. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6176. date,
  6177. suggest_connection_header(conn),
  6178. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6179. nonce);
  6180. }
  6181. }
  6182. #if !defined(NO_FILES)
  6183. static int
  6184. is_authorized_for_put(struct mg_connection *conn)
  6185. {
  6186. if (conn) {
  6187. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6188. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6189. int ret = 0;
  6190. if (passfile != NULL
  6191. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6192. ret = authorize(conn, &file);
  6193. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6194. }
  6195. return ret;
  6196. }
  6197. return 0;
  6198. }
  6199. #endif
  6200. int
  6201. mg_modify_passwords_file(const char *fname,
  6202. const char *domain,
  6203. const char *user,
  6204. const char *pass)
  6205. {
  6206. int found, i;
  6207. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6208. FILE *fp, *fp2;
  6209. found = 0;
  6210. fp = fp2 = NULL;
  6211. /* Regard empty password as no password - remove user record. */
  6212. if ((pass != NULL) && (pass[0] == '\0')) {
  6213. pass = NULL;
  6214. }
  6215. /* Other arguments must not be empty */
  6216. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6217. return 0;
  6218. }
  6219. /* Using the given file format, user name and domain must not contain ':'
  6220. */
  6221. if (strchr(user, ':') != NULL) {
  6222. return 0;
  6223. }
  6224. if (strchr(domain, ':') != NULL) {
  6225. return 0;
  6226. }
  6227. /* Do not allow control characters like newline in user name and domain.
  6228. * Do not allow excessively long names either. */
  6229. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6230. if (iscntrl(user[i])) {
  6231. return 0;
  6232. }
  6233. }
  6234. if (user[i]) {
  6235. return 0;
  6236. }
  6237. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6238. if (iscntrl(domain[i])) {
  6239. return 0;
  6240. }
  6241. }
  6242. if (domain[i]) {
  6243. return 0;
  6244. }
  6245. /* The maximum length of the path to the password file is limited */
  6246. if ((strlen(fname) + 4) >= PATH_MAX) {
  6247. return 0;
  6248. }
  6249. /* Create a temporary file name. Length has been checked before. */
  6250. strcpy(tmp, fname);
  6251. strcat(tmp, ".tmp");
  6252. /* Create the file if does not exist */
  6253. /* Use of fopen here is OK, since fname is only ASCII */
  6254. if ((fp = fopen(fname, "a+")) != NULL) {
  6255. (void)fclose(fp);
  6256. }
  6257. /* Open the given file and temporary file */
  6258. if ((fp = fopen(fname, "r")) == NULL) {
  6259. return 0;
  6260. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6261. fclose(fp);
  6262. return 0;
  6263. }
  6264. /* Copy the stuff to temporary file */
  6265. while (fgets(line, sizeof(line), fp) != NULL) {
  6266. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6267. continue;
  6268. }
  6269. u[255] = 0;
  6270. d[255] = 0;
  6271. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6272. found++;
  6273. if (pass != NULL) {
  6274. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6275. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6276. }
  6277. } else {
  6278. fprintf(fp2, "%s", line);
  6279. }
  6280. }
  6281. /* If new user, just add it */
  6282. if (!found && (pass != NULL)) {
  6283. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6284. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6285. }
  6286. /* Close files */
  6287. fclose(fp);
  6288. fclose(fp2);
  6289. /* Put the temp file in place of real file */
  6290. IGNORE_UNUSED_RESULT(remove(fname));
  6291. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6292. return 1;
  6293. }
  6294. static int
  6295. is_valid_port(unsigned long port)
  6296. {
  6297. return (port <= 0xffff);
  6298. }
  6299. static int
  6300. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6301. {
  6302. struct addrinfo hints, *res, *ressave;
  6303. int func_ret = 0;
  6304. int gai_ret;
  6305. memset(&hints, 0, sizeof(struct addrinfo));
  6306. hints.ai_family = af;
  6307. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6308. if (gai_ret != 0) {
  6309. /* gai_strerror could be used to convert gai_ret to a string */
  6310. /* POSIX return values: see
  6311. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6312. */
  6313. /* Windows return values: see
  6314. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6315. */
  6316. return 0;
  6317. }
  6318. ressave = res;
  6319. while (res) {
  6320. if (dstlen >= (size_t)res->ai_addrlen) {
  6321. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6322. func_ret = 1;
  6323. }
  6324. res = res->ai_next;
  6325. }
  6326. freeaddrinfo(ressave);
  6327. return func_ret;
  6328. }
  6329. static int
  6330. connect_socket(struct mg_context *ctx /* may be NULL */,
  6331. const char *host,
  6332. int port,
  6333. int use_ssl,
  6334. char *ebuf,
  6335. size_t ebuf_len,
  6336. SOCKET *sock /* output: socket, must not be NULL */,
  6337. union usa *sa /* output: socket address, must not be NULL */
  6338. )
  6339. {
  6340. int ip_ver = 0;
  6341. *sock = INVALID_SOCKET;
  6342. memset(sa, 0, sizeof(*sa));
  6343. if (ebuf_len > 0) {
  6344. *ebuf = 0;
  6345. }
  6346. if (host == NULL) {
  6347. mg_snprintf(NULL,
  6348. NULL, /* No truncation check for ebuf */
  6349. ebuf,
  6350. ebuf_len,
  6351. "%s",
  6352. "NULL host");
  6353. return 0;
  6354. }
  6355. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  6356. mg_snprintf(NULL,
  6357. NULL, /* No truncation check for ebuf */
  6358. ebuf,
  6359. ebuf_len,
  6360. "%s",
  6361. "invalid port");
  6362. return 0;
  6363. }
  6364. #if !defined(NO_SSL)
  6365. #if !defined(NO_SSL_DL)
  6366. #ifdef OPENSSL_API_1_1
  6367. if (use_ssl && (TLS_client_method == NULL)) {
  6368. mg_snprintf(NULL,
  6369. NULL, /* No truncation check for ebuf */
  6370. ebuf,
  6371. ebuf_len,
  6372. "%s",
  6373. "SSL is not initialized");
  6374. return 0;
  6375. }
  6376. #else
  6377. if (use_ssl && (SSLv23_client_method == NULL)) {
  6378. mg_snprintf(NULL,
  6379. NULL, /* No truncation check for ebuf */
  6380. ebuf,
  6381. ebuf_len,
  6382. "%s",
  6383. "SSL is not initialized");
  6384. return 0;
  6385. }
  6386. #endif /* OPENSSL_API_1_1 */
  6387. #else
  6388. (void)use_ssl;
  6389. #endif /* NO_SSL_DL */
  6390. #else
  6391. (void)use_ssl;
  6392. #endif /* !defined(NO_SSL) */
  6393. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6394. sa->sin.sin_family = AF_INET;
  6395. sa->sin.sin_port = htons((uint16_t)port);
  6396. ip_ver = 4;
  6397. #ifdef USE_IPV6
  6398. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6399. sa->sin6.sin6_family = AF_INET6;
  6400. sa->sin6.sin6_port = htons((uint16_t)port);
  6401. ip_ver = 6;
  6402. } else if (host[0] == '[') {
  6403. /* While getaddrinfo on Windows will work with [::1],
  6404. * getaddrinfo on Linux only works with ::1 (without []). */
  6405. size_t l = strlen(host + 1);
  6406. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6407. if (h) {
  6408. h[l - 1] = 0;
  6409. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6410. sa->sin6.sin6_family = AF_INET6;
  6411. sa->sin6.sin6_port = htons((uint16_t)port);
  6412. ip_ver = 6;
  6413. }
  6414. mg_free(h);
  6415. }
  6416. #endif
  6417. }
  6418. if (ip_ver == 0) {
  6419. mg_snprintf(NULL,
  6420. NULL, /* No truncation check for ebuf */
  6421. ebuf,
  6422. ebuf_len,
  6423. "%s",
  6424. "host not found");
  6425. return 0;
  6426. }
  6427. if (ip_ver == 4) {
  6428. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6429. }
  6430. #ifdef USE_IPV6
  6431. else if (ip_ver == 6) {
  6432. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6433. }
  6434. #endif
  6435. if (*sock == INVALID_SOCKET) {
  6436. mg_snprintf(NULL,
  6437. NULL, /* No truncation check for ebuf */
  6438. ebuf,
  6439. ebuf_len,
  6440. "socket(): %s",
  6441. strerror(ERRNO));
  6442. return 0;
  6443. }
  6444. set_close_on_exec(*sock, fc(ctx));
  6445. if ((ip_ver == 4)
  6446. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6447. == 0)) {
  6448. /* connected with IPv4 */
  6449. set_blocking_mode(*sock, 0);
  6450. return 1;
  6451. }
  6452. #ifdef USE_IPV6
  6453. if ((ip_ver == 6)
  6454. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6455. == 0)) {
  6456. /* connected with IPv6 */
  6457. set_blocking_mode(*sock, 0);
  6458. return 1;
  6459. }
  6460. #endif
  6461. /* Not connected */
  6462. mg_snprintf(NULL,
  6463. NULL, /* No truncation check for ebuf */
  6464. ebuf,
  6465. ebuf_len,
  6466. "connect(%s:%d): %s",
  6467. host,
  6468. port,
  6469. strerror(ERRNO));
  6470. closesocket(*sock);
  6471. *sock = INVALID_SOCKET;
  6472. return 0;
  6473. }
  6474. int
  6475. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6476. {
  6477. static const char *dont_escape = "._-$,;~()";
  6478. static const char *hex = "0123456789abcdef";
  6479. char *pos = dst;
  6480. const char *end = dst + dst_len - 1;
  6481. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  6482. if (isalnum(*(const unsigned char *)src)
  6483. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  6484. *pos = *src;
  6485. } else if (pos + 2 < end) {
  6486. pos[0] = '%';
  6487. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6488. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6489. pos += 2;
  6490. } else {
  6491. break;
  6492. }
  6493. }
  6494. *pos = '\0';
  6495. return (*src == '\0') ? (int)(pos - dst) : -1;
  6496. }
  6497. /* Return 0 on success, non-zero if an error occurs. */
  6498. static int
  6499. print_dir_entry(struct de *de)
  6500. {
  6501. size_t hrefsize;
  6502. char *href;
  6503. char size[64], mod[64];
  6504. struct tm *tm;
  6505. hrefsize = PATH_MAX * 3; /* worst case */
  6506. href = mg_malloc(hrefsize);
  6507. if (href == NULL) {
  6508. return -1;
  6509. }
  6510. if (de->file.is_directory) {
  6511. mg_snprintf(de->conn,
  6512. NULL, /* Buffer is big enough */
  6513. size,
  6514. sizeof(size),
  6515. "%s",
  6516. "[DIRECTORY]");
  6517. } else {
  6518. /* We use (signed) cast below because MSVC 6 compiler cannot
  6519. * convert unsigned __int64 to double. Sigh. */
  6520. if (de->file.size < 1024) {
  6521. mg_snprintf(de->conn,
  6522. NULL, /* Buffer is big enough */
  6523. size,
  6524. sizeof(size),
  6525. "%d",
  6526. (int)de->file.size);
  6527. } else if (de->file.size < 0x100000) {
  6528. mg_snprintf(de->conn,
  6529. NULL, /* Buffer is big enough */
  6530. size,
  6531. sizeof(size),
  6532. "%.1fk",
  6533. (double)de->file.size / 1024.0);
  6534. } else if (de->file.size < 0x40000000) {
  6535. mg_snprintf(de->conn,
  6536. NULL, /* Buffer is big enough */
  6537. size,
  6538. sizeof(size),
  6539. "%.1fM",
  6540. (double)de->file.size / 1048576);
  6541. } else {
  6542. mg_snprintf(de->conn,
  6543. NULL, /* Buffer is big enough */
  6544. size,
  6545. sizeof(size),
  6546. "%.1fG",
  6547. (double)de->file.size / 1073741824);
  6548. }
  6549. }
  6550. /* Note: mg_snprintf will not cause a buffer overflow above.
  6551. * So, string truncation checks are not required here. */
  6552. tm = localtime(&de->file.last_modified);
  6553. if (tm != NULL) {
  6554. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6555. } else {
  6556. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6557. mod[sizeof(mod) - 1] = '\0';
  6558. }
  6559. mg_url_encode(de->file_name, href, hrefsize);
  6560. mg_printf(de->conn,
  6561. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6562. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6563. de->conn->request_info.local_uri,
  6564. href,
  6565. de->file.is_directory ? "/" : "",
  6566. de->file_name,
  6567. de->file.is_directory ? "/" : "",
  6568. mod,
  6569. size);
  6570. mg_free(href);
  6571. return 0;
  6572. }
  6573. /* This function is called from send_directory() and used for
  6574. * sorting directory entries by size, or name, or modification time.
  6575. * On windows, __cdecl specification is needed in case if project is built
  6576. * with __stdcall convention. qsort always requires __cdels callback. */
  6577. static int WINCDECL
  6578. compare_dir_entries(const void *p1, const void *p2)
  6579. {
  6580. if (p1 && p2) {
  6581. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6582. const char *query_string = a->conn->request_info.query_string;
  6583. int cmp_result = 0;
  6584. if (query_string == NULL) {
  6585. query_string = "na";
  6586. }
  6587. if (a->file.is_directory && !b->file.is_directory) {
  6588. return -1; /* Always put directories on top */
  6589. } else if (!a->file.is_directory && b->file.is_directory) {
  6590. return 1; /* Always put directories on top */
  6591. } else if (*query_string == 'n') {
  6592. cmp_result = strcmp(a->file_name, b->file_name);
  6593. } else if (*query_string == 's') {
  6594. cmp_result = (a->file.size == b->file.size)
  6595. ? 0
  6596. : ((a->file.size > b->file.size) ? 1 : -1);
  6597. } else if (*query_string == 'd') {
  6598. cmp_result =
  6599. (a->file.last_modified == b->file.last_modified)
  6600. ? 0
  6601. : ((a->file.last_modified > b->file.last_modified) ? 1
  6602. : -1);
  6603. }
  6604. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6605. }
  6606. return 0;
  6607. }
  6608. static int
  6609. must_hide_file(struct mg_connection *conn, const char *path)
  6610. {
  6611. if (conn && conn->ctx) {
  6612. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6613. const char *pattern = conn->ctx->config[HIDE_FILES];
  6614. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  6615. || ((pattern != NULL)
  6616. && (match_prefix(pattern, strlen(pattern), path) > 0));
  6617. }
  6618. return 0;
  6619. }
  6620. static int
  6621. scan_directory(struct mg_connection *conn,
  6622. const char *dir,
  6623. void *data,
  6624. int (*cb)(struct de *, void *))
  6625. {
  6626. char path[PATH_MAX];
  6627. struct dirent *dp;
  6628. DIR *dirp;
  6629. struct de de;
  6630. int truncated;
  6631. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6632. return 0;
  6633. } else {
  6634. de.conn = conn;
  6635. while ((dp = mg_readdir(dirp)) != NULL) {
  6636. /* Do not show current dir and hidden files */
  6637. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6638. || must_hide_file(conn, dp->d_name)) {
  6639. continue;
  6640. }
  6641. mg_snprintf(
  6642. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6643. /* If we don't memset stat structure to zero, mtime will have
  6644. * garbage and strftime() will segfault later on in
  6645. * print_dir_entry(). memset is required only if mg_stat()
  6646. * fails. For more details, see
  6647. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6648. memset(&de.file, 0, sizeof(de.file));
  6649. if (truncated) {
  6650. /* If the path is not complete, skip processing. */
  6651. continue;
  6652. }
  6653. if (!mg_stat(conn, path, &de.file)) {
  6654. mg_cry(conn,
  6655. "%s: mg_stat(%s) failed: %s",
  6656. __func__,
  6657. path,
  6658. strerror(ERRNO));
  6659. }
  6660. de.file_name = dp->d_name;
  6661. cb(&de, data);
  6662. }
  6663. (void)mg_closedir(dirp);
  6664. }
  6665. return 1;
  6666. }
  6667. #if !defined(NO_FILES)
  6668. static int
  6669. remove_directory(struct mg_connection *conn, const char *dir)
  6670. {
  6671. char path[PATH_MAX];
  6672. struct dirent *dp;
  6673. DIR *dirp;
  6674. struct de de;
  6675. int truncated;
  6676. int ok = 1;
  6677. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6678. return 0;
  6679. } else {
  6680. de.conn = conn;
  6681. while ((dp = mg_readdir(dirp)) != NULL) {
  6682. /* Do not show current dir (but show hidden files as they will
  6683. * also be removed) */
  6684. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6685. continue;
  6686. }
  6687. mg_snprintf(
  6688. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6689. /* If we don't memset stat structure to zero, mtime will have
  6690. * garbage and strftime() will segfault later on in
  6691. * print_dir_entry(). memset is required only if mg_stat()
  6692. * fails. For more details, see
  6693. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6694. memset(&de.file, 0, sizeof(de.file));
  6695. if (truncated) {
  6696. /* Do not delete anything shorter */
  6697. ok = 0;
  6698. continue;
  6699. }
  6700. if (!mg_stat(conn, path, &de.file)) {
  6701. mg_cry(conn,
  6702. "%s: mg_stat(%s) failed: %s",
  6703. __func__,
  6704. path,
  6705. strerror(ERRNO));
  6706. ok = 0;
  6707. }
  6708. if (de.file.is_directory) {
  6709. if (remove_directory(conn, path) == 0) {
  6710. ok = 0;
  6711. }
  6712. } else {
  6713. /* This will fail file is the file is in memory */
  6714. if (mg_remove(conn, path) == 0) {
  6715. ok = 0;
  6716. }
  6717. }
  6718. }
  6719. (void)mg_closedir(dirp);
  6720. IGNORE_UNUSED_RESULT(rmdir(dir));
  6721. }
  6722. return ok;
  6723. }
  6724. #endif
  6725. struct dir_scan_data {
  6726. struct de *entries;
  6727. unsigned int num_entries;
  6728. unsigned int arr_size;
  6729. };
  6730. /* Behaves like realloc(), but frees original pointer on failure */
  6731. static void *
  6732. realloc2(void *ptr, size_t size)
  6733. {
  6734. void *new_ptr = mg_realloc(ptr, size);
  6735. if (new_ptr == NULL) {
  6736. mg_free(ptr);
  6737. }
  6738. return new_ptr;
  6739. }
  6740. static int
  6741. dir_scan_callback(struct de *de, void *data)
  6742. {
  6743. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6744. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  6745. dsd->arr_size *= 2;
  6746. dsd->entries =
  6747. (struct de *)realloc2(dsd->entries,
  6748. dsd->arr_size * sizeof(dsd->entries[0]));
  6749. }
  6750. if (dsd->entries == NULL) {
  6751. /* TODO(lsm, low): propagate an error to the caller */
  6752. dsd->num_entries = 0;
  6753. } else {
  6754. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6755. dsd->entries[dsd->num_entries].file = de->file;
  6756. dsd->entries[dsd->num_entries].conn = de->conn;
  6757. dsd->num_entries++;
  6758. }
  6759. return 0;
  6760. }
  6761. static void
  6762. handle_directory_request(struct mg_connection *conn, const char *dir)
  6763. {
  6764. unsigned int i;
  6765. int sort_direction;
  6766. struct dir_scan_data data = {NULL, 0, 128};
  6767. char date[64];
  6768. time_t curtime = time(NULL);
  6769. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6770. mg_send_http_error(conn,
  6771. 500,
  6772. "Error: Cannot open directory\nopendir(%s): %s",
  6773. dir,
  6774. strerror(ERRNO));
  6775. return;
  6776. }
  6777. gmt_time_string(date, sizeof(date), &curtime);
  6778. if (!conn) {
  6779. return;
  6780. }
  6781. sort_direction = ((conn->request_info.query_string != NULL)
  6782. && (conn->request_info.query_string[1] == 'd'))
  6783. ? 'a'
  6784. : 'd';
  6785. conn->must_close = 1;
  6786. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6787. send_static_cache_header(conn);
  6788. send_additional_header(conn);
  6789. mg_printf(conn,
  6790. "Date: %s\r\n"
  6791. "Connection: close\r\n"
  6792. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6793. date);
  6794. mg_printf(conn,
  6795. "<html><head><title>Index of %s</title>"
  6796. "<style>th {text-align: left;}</style></head>"
  6797. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6798. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6799. "<th><a href=\"?d%c\">Modified</a></th>"
  6800. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6801. "<tr><td colspan=\"3\"><hr></td></tr>",
  6802. conn->request_info.local_uri,
  6803. conn->request_info.local_uri,
  6804. sort_direction,
  6805. sort_direction,
  6806. sort_direction);
  6807. /* Print first entry - link to a parent directory */
  6808. mg_printf(conn,
  6809. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6810. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6811. conn->request_info.local_uri,
  6812. "..",
  6813. "Parent directory",
  6814. "-",
  6815. "-");
  6816. /* Sort and print directory entries */
  6817. if (data.entries != NULL) {
  6818. qsort(data.entries,
  6819. (size_t)data.num_entries,
  6820. sizeof(data.entries[0]),
  6821. compare_dir_entries);
  6822. for (i = 0; i < data.num_entries; i++) {
  6823. print_dir_entry(&data.entries[i]);
  6824. mg_free(data.entries[i].file_name);
  6825. }
  6826. mg_free(data.entries);
  6827. }
  6828. mg_printf(conn, "%s", "</table></body></html>");
  6829. conn->status_code = 200;
  6830. }
  6831. /* Send len bytes from the opened file to the client. */
  6832. static void
  6833. send_file_data(struct mg_connection *conn,
  6834. struct mg_file *filep,
  6835. int64_t offset,
  6836. int64_t len)
  6837. {
  6838. char buf[MG_BUF_LEN];
  6839. int to_read, num_read, num_written;
  6840. int64_t size;
  6841. if (!filep || !conn) {
  6842. return;
  6843. }
  6844. /* Sanity check the offset */
  6845. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6846. : (int64_t)(filep->stat.size);
  6847. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6848. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6849. /* file stored in memory */
  6850. if (len > size - offset) {
  6851. len = size - offset;
  6852. }
  6853. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6854. } else if (len > 0 && filep->access.fp != NULL) {
  6855. /* file stored on disk */
  6856. #if defined(__linux__)
  6857. /* sendfile is only available for Linux */
  6858. if ((conn->ssl == 0) && (conn->throttle == 0)
  6859. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6860. "yes"))) {
  6861. off_t sf_offs = (off_t)offset;
  6862. ssize_t sf_sent;
  6863. int sf_file = fileno(filep->access.fp);
  6864. int loop_cnt = 0;
  6865. do {
  6866. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6867. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6868. size_t sf_tosend =
  6869. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6870. sf_sent =
  6871. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6872. if (sf_sent > 0) {
  6873. len -= sf_sent;
  6874. offset += sf_sent;
  6875. } else if (loop_cnt == 0) {
  6876. /* This file can not be sent using sendfile.
  6877. * This might be the case for pseudo-files in the
  6878. * /sys/ and /proc/ file system.
  6879. * Use the regular user mode copy code instead. */
  6880. break;
  6881. } else if (sf_sent == 0) {
  6882. /* No error, but 0 bytes sent. May be EOF? */
  6883. return;
  6884. }
  6885. loop_cnt++;
  6886. } while ((len > 0) && (sf_sent >= 0));
  6887. if (sf_sent > 0) {
  6888. return; /* OK */
  6889. }
  6890. /* sf_sent<0 means error, thus fall back to the classic way */
  6891. /* This is always the case, if sf_file is not a "normal" file,
  6892. * e.g., for sending data from the output of a CGI process. */
  6893. offset = (int64_t)sf_offs;
  6894. }
  6895. #endif
  6896. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6897. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6898. mg_send_http_error(
  6899. conn,
  6900. 500,
  6901. "%s",
  6902. "Error: Unable to access file at requested position.");
  6903. } else {
  6904. while (len > 0) {
  6905. /* Calculate how much to read from the file in the buffer */
  6906. to_read = sizeof(buf);
  6907. if ((int64_t)to_read > len) {
  6908. to_read = (int)len;
  6909. }
  6910. /* Read from file, exit the loop on error */
  6911. if ((num_read =
  6912. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6913. <= 0) {
  6914. break;
  6915. }
  6916. /* Send read bytes to the client, exit the loop on error */
  6917. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6918. != num_read) {
  6919. break;
  6920. }
  6921. /* Both read and were successful, adjust counters */
  6922. len -= num_written;
  6923. }
  6924. }
  6925. }
  6926. }
  6927. static int
  6928. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6929. {
  6930. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6931. }
  6932. static void
  6933. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6934. {
  6935. if ((filestat != NULL) && (buf != NULL)) {
  6936. mg_snprintf(NULL,
  6937. NULL, /* All calls to construct_etag use 64 byte buffer */
  6938. buf,
  6939. buf_len,
  6940. "\"%lx.%" INT64_FMT "\"",
  6941. (unsigned long)filestat->last_modified,
  6942. filestat->size);
  6943. }
  6944. }
  6945. static void
  6946. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6947. {
  6948. if (filep != NULL && filep->fp != NULL) {
  6949. #ifdef _WIN32
  6950. (void)conn; /* Unused. */
  6951. #else
  6952. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6953. mg_cry(conn,
  6954. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6955. __func__,
  6956. strerror(ERRNO));
  6957. }
  6958. #endif
  6959. }
  6960. }
  6961. static void
  6962. handle_static_file_request(struct mg_connection *conn,
  6963. const char *path,
  6964. struct mg_file *filep,
  6965. const char *mime_type,
  6966. const char *additional_headers)
  6967. {
  6968. char date[64], lm[64], etag[64];
  6969. char range[128]; /* large enough, so there will be no overflow */
  6970. const char *msg = "OK", *hdr;
  6971. time_t curtime = time(NULL);
  6972. int64_t cl, r1, r2;
  6973. struct vec mime_vec;
  6974. int n, truncated;
  6975. char gz_path[PATH_MAX];
  6976. const char *encoding = "";
  6977. const char *cors1, *cors2, *cors3;
  6978. if ((conn == NULL) || (conn->ctx == NULL) || (filep == NULL)) {
  6979. return;
  6980. }
  6981. if (mime_type == NULL) {
  6982. get_mime_type(conn->ctx, path, &mime_vec);
  6983. } else {
  6984. mime_vec.ptr = mime_type;
  6985. mime_vec.len = strlen(mime_type);
  6986. }
  6987. if (filep->stat.size > INT64_MAX) {
  6988. mg_send_http_error(conn,
  6989. 500,
  6990. "Error: File size is too large to send\n%" INT64_FMT,
  6991. filep->stat.size);
  6992. return;
  6993. }
  6994. cl = (int64_t)filep->stat.size;
  6995. conn->status_code = 200;
  6996. range[0] = '\0';
  6997. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6998. * it's important to rewrite the filename after resolving
  6999. * the mime type from it, to preserve the actual file's type */
  7000. if (filep->stat.is_gzipped) {
  7001. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7002. if (truncated) {
  7003. mg_send_http_error(conn,
  7004. 500,
  7005. "Error: Path of zipped file too long (%s)",
  7006. path);
  7007. return;
  7008. }
  7009. path = gz_path;
  7010. encoding = "Content-Encoding: gzip\r\n";
  7011. }
  7012. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7013. mg_send_http_error(conn,
  7014. 500,
  7015. "Error: Cannot open file\nfopen(%s): %s",
  7016. path,
  7017. strerror(ERRNO));
  7018. return;
  7019. }
  7020. fclose_on_exec(&filep->access, conn);
  7021. /* If Range: header specified, act accordingly */
  7022. r1 = r2 = 0;
  7023. hdr = mg_get_header(conn, "Range");
  7024. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7025. && (r1 >= 0) && (r2 >= 0)) {
  7026. /* actually, range requests don't play well with a pre-gzipped
  7027. * file (since the range is specified in the uncompressed space) */
  7028. if (filep->stat.is_gzipped) {
  7029. mg_send_http_error(
  7030. conn,
  7031. 416, /* 416 = Range Not Satisfiable */
  7032. "%s",
  7033. "Error: Range requests in gzipped files are not supported");
  7034. (void)mg_fclose(
  7035. &filep->access); /* ignore error on read only file */
  7036. return;
  7037. }
  7038. conn->status_code = 206;
  7039. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7040. mg_snprintf(conn,
  7041. NULL, /* range buffer is big enough */
  7042. range,
  7043. sizeof(range),
  7044. "Content-Range: bytes "
  7045. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7046. r1,
  7047. r1 + cl - 1,
  7048. filep->stat.size);
  7049. msg = "Partial Content";
  7050. }
  7051. hdr = mg_get_header(conn, "Origin");
  7052. if (hdr) {
  7053. /* Cross-origin resource sharing (CORS), see
  7054. * http://www.html5rocks.com/en/tutorials/cors/,
  7055. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  7056. * preflight is not supported for files. */
  7057. cors1 = "Access-Control-Allow-Origin: ";
  7058. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7059. cors3 = "\r\n";
  7060. } else {
  7061. cors1 = cors2 = cors3 = "";
  7062. }
  7063. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  7064. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7065. gmt_time_string(date, sizeof(date), &curtime);
  7066. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7067. construct_etag(etag, sizeof(etag), &filep->stat);
  7068. (void)mg_printf(conn,
  7069. "HTTP/1.1 %d %s\r\n"
  7070. "%s%s%s"
  7071. "Date: %s\r\n",
  7072. conn->status_code,
  7073. msg,
  7074. cors1,
  7075. cors2,
  7076. cors3,
  7077. date);
  7078. send_static_cache_header(conn);
  7079. send_additional_header(conn);
  7080. (void)mg_printf(conn,
  7081. "Last-Modified: %s\r\n"
  7082. "Etag: %s\r\n"
  7083. "Content-Type: %.*s\r\n"
  7084. "Content-Length: %" INT64_FMT "\r\n"
  7085. "Connection: %s\r\n"
  7086. "Accept-Ranges: bytes\r\n"
  7087. "%s%s",
  7088. lm,
  7089. etag,
  7090. (int)mime_vec.len,
  7091. mime_vec.ptr,
  7092. cl,
  7093. suggest_connection_header(conn),
  7094. range,
  7095. encoding);
  7096. /* The previous code must not add any header starting with X- to make
  7097. * sure no one of the additional_headers is included twice */
  7098. if (additional_headers != NULL) {
  7099. (void)mg_printf(conn,
  7100. "%.*s\r\n\r\n",
  7101. (int)strlen(additional_headers),
  7102. additional_headers);
  7103. } else {
  7104. (void)mg_printf(conn, "\r\n");
  7105. }
  7106. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7107. send_file_data(conn, filep, r1, cl);
  7108. }
  7109. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7110. }
  7111. #if !defined(NO_CACHING)
  7112. static void
  7113. handle_not_modified_static_file_request(struct mg_connection *conn,
  7114. struct mg_file *filep)
  7115. {
  7116. char date[64], lm[64], etag[64];
  7117. time_t curtime = time(NULL);
  7118. if ((conn == NULL) || (filep == NULL)) {
  7119. return;
  7120. }
  7121. conn->status_code = 304;
  7122. gmt_time_string(date, sizeof(date), &curtime);
  7123. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7124. construct_etag(etag, sizeof(etag), &filep->stat);
  7125. (void)mg_printf(conn,
  7126. "HTTP/1.1 %d %s\r\n"
  7127. "Date: %s\r\n",
  7128. conn->status_code,
  7129. mg_get_response_code_text(conn, conn->status_code),
  7130. date);
  7131. send_static_cache_header(conn);
  7132. send_additional_header(conn);
  7133. (void)mg_printf(conn,
  7134. "Last-Modified: %s\r\n"
  7135. "Etag: %s\r\n"
  7136. "Connection: %s\r\n"
  7137. "\r\n",
  7138. lm,
  7139. etag,
  7140. suggest_connection_header(conn));
  7141. }
  7142. #endif
  7143. void
  7144. mg_send_file(struct mg_connection *conn, const char *path)
  7145. {
  7146. mg_send_mime_file(conn, path, NULL);
  7147. }
  7148. void
  7149. mg_send_mime_file(struct mg_connection *conn,
  7150. const char *path,
  7151. const char *mime_type)
  7152. {
  7153. mg_send_mime_file2(conn, path, mime_type, NULL);
  7154. }
  7155. void
  7156. mg_send_mime_file2(struct mg_connection *conn,
  7157. const char *path,
  7158. const char *mime_type,
  7159. const char *additional_headers)
  7160. {
  7161. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7162. if (mg_stat(conn, path, &file.stat)) {
  7163. if (file.stat.is_directory) {
  7164. if (!conn) {
  7165. return;
  7166. }
  7167. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7168. "yes")) {
  7169. handle_directory_request(conn, path);
  7170. } else {
  7171. mg_send_http_error(conn,
  7172. 403,
  7173. "%s",
  7174. "Error: Directory listing denied");
  7175. }
  7176. } else {
  7177. handle_static_file_request(
  7178. conn, path, &file, mime_type, additional_headers);
  7179. }
  7180. } else {
  7181. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7182. }
  7183. }
  7184. /* For a given PUT path, create all intermediate subdirectories.
  7185. * Return 0 if the path itself is a directory.
  7186. * Return 1 if the path leads to a file.
  7187. * Return -1 for if the path is too long.
  7188. * Return -2 if path can not be created.
  7189. */
  7190. static int
  7191. put_dir(struct mg_connection *conn, const char *path)
  7192. {
  7193. char buf[PATH_MAX];
  7194. const char *s, *p;
  7195. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7196. size_t len;
  7197. int res = 1;
  7198. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7199. len = (size_t)(p - path);
  7200. if (len >= sizeof(buf)) {
  7201. /* path too long */
  7202. res = -1;
  7203. break;
  7204. }
  7205. memcpy(buf, path, len);
  7206. buf[len] = '\0';
  7207. /* Try to create intermediate directory */
  7208. DEBUG_TRACE("mkdir(%s)", buf);
  7209. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7210. /* path does not exixt and can not be created */
  7211. res = -2;
  7212. break;
  7213. }
  7214. /* Is path itself a directory? */
  7215. if (p[1] == '\0') {
  7216. res = 0;
  7217. }
  7218. }
  7219. return res;
  7220. }
  7221. static void
  7222. remove_bad_file(const struct mg_connection *conn, const char *path)
  7223. {
  7224. int r = mg_remove(conn, path);
  7225. if (r != 0) {
  7226. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7227. }
  7228. }
  7229. long long
  7230. mg_store_body(struct mg_connection *conn, const char *path)
  7231. {
  7232. char buf[MG_BUF_LEN];
  7233. long long len = 0;
  7234. int ret, n;
  7235. struct mg_file fi;
  7236. if (conn->consumed_content != 0) {
  7237. mg_cry(conn, "%s: Contents already consumed", __func__);
  7238. return -11;
  7239. }
  7240. ret = put_dir(conn, path);
  7241. if (ret < 0) {
  7242. /* -1 for path too long,
  7243. * -2 for path can not be created. */
  7244. return ret;
  7245. }
  7246. if (ret != 1) {
  7247. /* Return 0 means, path itself is a directory. */
  7248. return 0;
  7249. }
  7250. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7251. return -12;
  7252. }
  7253. ret = mg_read(conn, buf, sizeof(buf));
  7254. while (ret > 0) {
  7255. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7256. if (n != ret) {
  7257. (void)mg_fclose(
  7258. &fi.access); /* File is bad and will be removed anyway. */
  7259. remove_bad_file(conn, path);
  7260. return -13;
  7261. }
  7262. len += ret;
  7263. ret = mg_read(conn, buf, sizeof(buf));
  7264. }
  7265. /* File is open for writing. If fclose fails, there was probably an
  7266. * error flushing the buffer to disk, so the file on disk might be
  7267. * broken. Delete it and return an error to the caller. */
  7268. if (mg_fclose(&fi.access) != 0) {
  7269. remove_bad_file(conn, path);
  7270. return -14;
  7271. }
  7272. return len;
  7273. }
  7274. /* Parse HTTP headers from the given buffer, advance buf pointer
  7275. * to the point where parsing stopped.
  7276. * All parameters must be valid pointers (not NULL).
  7277. * Return <0 on error. */
  7278. static int
  7279. parse_http_headers(char **buf, struct mg_request_info *ri)
  7280. {
  7281. int i;
  7282. ri->num_headers = 0;
  7283. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  7284. char *dp = *buf;
  7285. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7286. dp++;
  7287. }
  7288. if (dp == *buf) {
  7289. /* End of headers reached. */
  7290. break;
  7291. }
  7292. if (*dp != ':') {
  7293. /* This is not a valid field. */
  7294. return -1;
  7295. }
  7296. /* End of header key (*dp == ':') */
  7297. /* Truncate here and set the key name */
  7298. *dp = 0;
  7299. ri->http_headers[i].name = *buf;
  7300. do {
  7301. dp++;
  7302. } while (*dp == ' ');
  7303. /* The rest of the line is the value */
  7304. ri->http_headers[i].value = dp;
  7305. *buf = dp + strcspn(dp, "\r\n");
  7306. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7307. *buf = NULL;
  7308. }
  7309. ri->num_headers = i + 1;
  7310. if (*buf) {
  7311. (*buf)[0] = 0;
  7312. (*buf)[1] = 0;
  7313. *buf += 2;
  7314. } else {
  7315. *buf = dp;
  7316. break;
  7317. }
  7318. if ((*buf)[0] == '\r') {
  7319. /* This is the end of the header */
  7320. break;
  7321. }
  7322. }
  7323. return ri->num_headers;
  7324. }
  7325. static int
  7326. is_valid_http_method(const char *method)
  7327. {
  7328. /* Check if the method is known to the server. The list of all known
  7329. * HTTP methods can be found here at
  7330. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7331. */
  7332. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7333. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7334. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7335. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7336. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7337. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7338. /* TRACE method (RFC 2616) is not supported for security reasons */
  7339. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7340. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7341. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7342. /* Unsupported WEBDAV Methods: */
  7343. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7344. /* + 11 methods from RFC 3253 */
  7345. /* ORDERPATCH (RFC 3648) */
  7346. /* ACL (RFC 3744) */
  7347. /* SEARCH (RFC 5323) */
  7348. /* + MicroSoft extensions
  7349. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7350. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7351. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7352. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7353. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7354. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7355. * to be useful for REST in case a "GET request with body" is
  7356. * required. */
  7357. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7358. ;
  7359. }
  7360. /* Parse HTTP request, fill in mg_request_info structure.
  7361. * This function modifies the buffer by NUL-terminating
  7362. * HTTP request components, header names and header values.
  7363. * Parameters:
  7364. * buf (in/out): pointer to the HTTP header to parse and split
  7365. * len (in): length of HTTP header buffer
  7366. * re (out): parsed header as mg_request_info
  7367. * buf and ri must be valid pointers (not NULL), len>0.
  7368. * Returns <0 on error. */
  7369. static int
  7370. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  7371. {
  7372. int is_request, request_length;
  7373. char *start_line;
  7374. request_length = get_request_len(buf, len);
  7375. if (request_length > 0) {
  7376. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7377. * remote_port */
  7378. ri->remote_user = ri->request_method = ri->request_uri =
  7379. ri->http_version = NULL;
  7380. ri->num_headers = 0;
  7381. buf[request_length - 1] = '\0';
  7382. /* RFC says that all initial whitespaces should be ingored */
  7383. while ((*buf != '\0') && isspace(*(unsigned char *)buf)) {
  7384. buf++;
  7385. }
  7386. /* Separate first line from the following lines.
  7387. * "buf" will point to the next line afterwards and the \r\n at
  7388. * the end of the line will be replaced by 0 */
  7389. start_line = skip(&buf, "\r\n");
  7390. /* Separate the first word in the first line from the rest.
  7391. * For a HTTP request, this is the method (e.g. "GET").
  7392. * The string will be terminated after the method by
  7393. * replacing the space by a 0 character. */
  7394. ri->request_method = skip(&start_line, " ");
  7395. /* The second element in the first line is the URI,
  7396. * again terminated by a space. */
  7397. ri->request_uri = skip(&start_line, " ");
  7398. /* Last element of the first line of a HTTP request
  7399. * is the version string (e.g. "HTTP/1.0"). */
  7400. ri->http_version = start_line;
  7401. /* HTTP message could be either HTTP request:
  7402. * "GET / HTTP/1.0 ..."
  7403. * or a HTTP response:
  7404. * "HTTP/1.0 200 OK ..."
  7405. * otherwise it is invalid.
  7406. */
  7407. is_request = is_valid_http_method(ri->request_method);
  7408. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  7409. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  7410. /* Not a valid request or response: invalid */
  7411. return -1;
  7412. }
  7413. if (is_request) {
  7414. ri->http_version += 5;
  7415. }
  7416. if (parse_http_headers(&buf, ri) < 0) {
  7417. /* Error while parsing headers */
  7418. return -1;
  7419. }
  7420. }
  7421. return request_length;
  7422. }
  7423. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7424. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7425. * buffer (which marks the end of HTTP request). Buffer buf may already
  7426. * have some data. The length of the data is stored in nread.
  7427. * Upon every read operation, increase nread by the number of bytes read. */
  7428. static int
  7429. read_request(FILE *fp,
  7430. struct mg_connection *conn,
  7431. char *buf,
  7432. int bufsiz,
  7433. int *nread)
  7434. {
  7435. int request_len, n = 0;
  7436. struct timespec last_action_time;
  7437. double request_timeout;
  7438. if (!conn) {
  7439. return 0;
  7440. }
  7441. memset(&last_action_time, 0, sizeof(last_action_time));
  7442. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7443. /* value of request_timeout is in seconds, config in milliseconds */
  7444. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7445. } else {
  7446. request_timeout = -1.0;
  7447. }
  7448. if (conn->handled_requests > 0) {
  7449. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7450. request_timeout =
  7451. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7452. }
  7453. }
  7454. request_len = get_request_len(buf, *nread);
  7455. /* first time reading from this connection */
  7456. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7457. while (request_len == 0) {
  7458. /* Full request not yet received */
  7459. if (conn->ctx->stop_flag != 0) {
  7460. /* Server is to be stopped. */
  7461. return -1;
  7462. }
  7463. if (*nread >= bufsiz) {
  7464. /* Request too long */
  7465. return -2;
  7466. }
  7467. n = pull_inner(
  7468. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7469. if (n == -2) {
  7470. /* Receive error */
  7471. return -1;
  7472. }
  7473. if (n > 0) {
  7474. *nread += n;
  7475. request_len = get_request_len(buf, *nread);
  7476. } else {
  7477. request_len = 0;
  7478. }
  7479. if ((request_len == 0) && (request_timeout >= 0)) {
  7480. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7481. > request_timeout) {
  7482. /* Timeout */
  7483. return -1;
  7484. }
  7485. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7486. }
  7487. }
  7488. return request_len;
  7489. }
  7490. #if !defined(NO_CACHING)
  7491. /* Return True if we should reply 304 Not Modified. */
  7492. static int
  7493. is_not_modified(const struct mg_connection *conn,
  7494. const struct mg_file_stat *filestat)
  7495. {
  7496. char etag[64];
  7497. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7498. const char *inm = mg_get_header(conn, "If-None-Match");
  7499. construct_etag(etag, sizeof(etag), filestat);
  7500. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  7501. || ((ims != NULL)
  7502. && (filestat->last_modified <= parse_date_string(ims)));
  7503. }
  7504. #endif /* !NO_CACHING */
  7505. #if !defined(NO_CGI) || !defined(NO_FILES)
  7506. static int
  7507. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7508. {
  7509. const char *expect, *body;
  7510. char buf[MG_BUF_LEN];
  7511. int to_read, nread, success = 0;
  7512. int64_t buffered_len;
  7513. double timeout = -1.0;
  7514. if (!conn) {
  7515. return 0;
  7516. }
  7517. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7518. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7519. }
  7520. expect = mg_get_header(conn, "Expect");
  7521. /* assert(fp != NULL); */
  7522. if (!fp) {
  7523. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  7524. return 0;
  7525. }
  7526. if ((conn->content_len == -1) && !conn->is_chunked) {
  7527. /* Content length is not specified by the client. */
  7528. mg_send_http_error(conn,
  7529. 411,
  7530. "%s",
  7531. "Error: Client did not specify content length");
  7532. } else if ((expect != NULL)
  7533. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7534. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7535. mg_send_http_error(conn,
  7536. 417,
  7537. "Error: Can not fulfill expectation %s",
  7538. expect);
  7539. } else {
  7540. if (expect != NULL) {
  7541. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7542. conn->status_code = 100;
  7543. } else {
  7544. conn->status_code = 200;
  7545. }
  7546. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7547. - conn->consumed_content;
  7548. /* assert(buffered_len >= 0); */
  7549. /* assert(conn->consumed_content == 0); */
  7550. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7551. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7552. return 0;
  7553. }
  7554. if (buffered_len > 0) {
  7555. if ((int64_t)buffered_len > conn->content_len) {
  7556. buffered_len = (int)conn->content_len;
  7557. }
  7558. body = conn->buf + conn->request_len + conn->consumed_content;
  7559. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7560. conn->consumed_content += buffered_len;
  7561. }
  7562. nread = 0;
  7563. while (conn->consumed_content < conn->content_len) {
  7564. to_read = sizeof(buf);
  7565. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7566. to_read = (int)(conn->content_len - conn->consumed_content);
  7567. }
  7568. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7569. if (nread == -2) {
  7570. /* error */
  7571. break;
  7572. }
  7573. if (nread > 0) {
  7574. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7575. break;
  7576. }
  7577. }
  7578. conn->consumed_content += nread;
  7579. }
  7580. if (conn->consumed_content == conn->content_len) {
  7581. success = (nread >= 0);
  7582. }
  7583. /* Each error code path in this function must send an error */
  7584. if (!success) {
  7585. /* NOTE: Maybe some data has already been sent. */
  7586. /* TODO (low): If some data has been sent, a correct error
  7587. * reply can no longer be sent, so just close the connection */
  7588. mg_send_http_error(conn, 500, "%s", "");
  7589. }
  7590. }
  7591. return success;
  7592. }
  7593. #endif
  7594. #if !defined(NO_CGI)
  7595. /* This structure helps to create an environment for the spawned CGI program.
  7596. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7597. * last element must be NULL.
  7598. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7599. * strings must reside in a contiguous buffer. The end of the buffer is
  7600. * marked by two '\0' characters.
  7601. * We satisfy both worlds: we create an envp array (which is vars), all
  7602. * entries are actually pointers inside buf. */
  7603. struct cgi_environment {
  7604. struct mg_connection *conn;
  7605. /* Data block */
  7606. char *buf; /* Environment buffer */
  7607. size_t buflen; /* Space available in buf */
  7608. size_t bufused; /* Space taken in buf */
  7609. /* Index block */
  7610. char **var; /* char **envp */
  7611. size_t varlen; /* Number of variables available in var */
  7612. size_t varused; /* Number of variables stored in var */
  7613. };
  7614. static void addenv(struct cgi_environment *env,
  7615. PRINTF_FORMAT_STRING(const char *fmt),
  7616. ...) PRINTF_ARGS(2, 3);
  7617. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7618. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7619. static void
  7620. addenv(struct cgi_environment *env, const char *fmt, ...)
  7621. {
  7622. size_t n, space;
  7623. int truncated = 0;
  7624. char *added;
  7625. va_list ap;
  7626. /* Calculate how much space is left in the buffer */
  7627. space = (env->buflen - env->bufused);
  7628. /* Calculate an estimate for the required space */
  7629. n = strlen(fmt) + 2 + 128;
  7630. do {
  7631. if (space <= n) {
  7632. /* Allocate new buffer */
  7633. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7634. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  7635. if (!added) {
  7636. /* Out of memory */
  7637. mg_cry(env->conn,
  7638. "%s: Cannot allocate memory for CGI variable [%s]",
  7639. __func__,
  7640. fmt);
  7641. return;
  7642. }
  7643. env->buf = added;
  7644. env->buflen = n;
  7645. space = (env->buflen - env->bufused);
  7646. }
  7647. /* Make a pointer to the free space int the buffer */
  7648. added = env->buf + env->bufused;
  7649. /* Copy VARIABLE=VALUE\0 string into the free space */
  7650. va_start(ap, fmt);
  7651. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7652. va_end(ap);
  7653. /* Do not add truncated strings to the environment */
  7654. if (truncated) {
  7655. /* Reallocate the buffer */
  7656. space = 0;
  7657. n = 1;
  7658. }
  7659. } while (truncated);
  7660. /* Calculate number of bytes added to the environment */
  7661. n = strlen(added) + 1;
  7662. env->bufused += n;
  7663. /* Now update the variable index */
  7664. space = (env->varlen - env->varused);
  7665. if (space < 2) {
  7666. mg_cry(env->conn,
  7667. "%s: Cannot register CGI variable [%s]",
  7668. __func__,
  7669. fmt);
  7670. return;
  7671. }
  7672. /* Append a pointer to the added string into the envp array */
  7673. env->var[env->varused] = added;
  7674. env->varused++;
  7675. }
  7676. /* Return 0 on success, non-zero if an error occurs. */
  7677. static int
  7678. prepare_cgi_environment(struct mg_connection *conn,
  7679. const char *prog,
  7680. struct cgi_environment *env)
  7681. {
  7682. const char *s;
  7683. struct vec var_vec;
  7684. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7685. int i, truncated, uri_len;
  7686. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  7687. return -1;
  7688. }
  7689. env->conn = conn;
  7690. env->buflen = CGI_ENVIRONMENT_SIZE;
  7691. env->bufused = 0;
  7692. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  7693. if (env->buf == NULL) {
  7694. mg_cry(conn,
  7695. "%s: Not enough memory for environmental buffer",
  7696. __func__);
  7697. return -1;
  7698. }
  7699. env->varlen = MAX_CGI_ENVIR_VARS;
  7700. env->varused = 0;
  7701. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  7702. if (env->var == NULL) {
  7703. mg_cry(conn,
  7704. "%s: Not enough memory for environmental variables",
  7705. __func__);
  7706. mg_free(env->buf);
  7707. return -1;
  7708. }
  7709. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7710. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7711. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7712. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7713. /* Prepare the environment block */
  7714. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7715. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7716. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7717. #if defined(USE_IPV6)
  7718. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7719. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7720. } else
  7721. #endif
  7722. {
  7723. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7724. }
  7725. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7726. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7727. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7728. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7729. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7730. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7731. /* SCRIPT_NAME */
  7732. uri_len = (int)strlen(conn->request_info.local_uri);
  7733. if (conn->path_info == NULL) {
  7734. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7735. /* URI: /path_to_script/script.cgi */
  7736. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7737. } else {
  7738. /* URI: /path_to_script/ ... using index.cgi */
  7739. const char *index_file = strrchr(prog, '/');
  7740. if (index_file) {
  7741. addenv(env,
  7742. "SCRIPT_NAME=%s%s",
  7743. conn->request_info.local_uri,
  7744. index_file + 1);
  7745. }
  7746. }
  7747. } else {
  7748. /* URI: /path_to_script/script.cgi/path_info */
  7749. addenv(env,
  7750. "SCRIPT_NAME=%.*s",
  7751. uri_len - (int)strlen(conn->path_info),
  7752. conn->request_info.local_uri);
  7753. }
  7754. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7755. if (conn->path_info == NULL) {
  7756. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7757. } else {
  7758. addenv(env,
  7759. "PATH_TRANSLATED=%s%s",
  7760. conn->ctx->config[DOCUMENT_ROOT],
  7761. conn->path_info);
  7762. }
  7763. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7764. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7765. addenv(env, "CONTENT_TYPE=%s", s);
  7766. }
  7767. if (conn->request_info.query_string != NULL) {
  7768. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7769. }
  7770. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7771. addenv(env, "CONTENT_LENGTH=%s", s);
  7772. }
  7773. if ((s = getenv("PATH")) != NULL) {
  7774. addenv(env, "PATH=%s", s);
  7775. }
  7776. if (conn->path_info != NULL) {
  7777. addenv(env, "PATH_INFO=%s", conn->path_info);
  7778. }
  7779. if (conn->status_code > 0) {
  7780. /* CGI error handler should show the status code */
  7781. addenv(env, "STATUS=%d", conn->status_code);
  7782. }
  7783. #if defined(_WIN32)
  7784. if ((s = getenv("COMSPEC")) != NULL) {
  7785. addenv(env, "COMSPEC=%s", s);
  7786. }
  7787. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7788. addenv(env, "SYSTEMROOT=%s", s);
  7789. }
  7790. if ((s = getenv("SystemDrive")) != NULL) {
  7791. addenv(env, "SystemDrive=%s", s);
  7792. }
  7793. if ((s = getenv("ProgramFiles")) != NULL) {
  7794. addenv(env, "ProgramFiles=%s", s);
  7795. }
  7796. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7797. addenv(env, "ProgramFiles(x86)=%s", s);
  7798. }
  7799. #else
  7800. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7801. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7802. }
  7803. #endif /* _WIN32 */
  7804. if ((s = getenv("PERLLIB")) != NULL) {
  7805. addenv(env, "PERLLIB=%s", s);
  7806. }
  7807. if (conn->request_info.remote_user != NULL) {
  7808. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7809. addenv(env, "%s", "AUTH_TYPE=Digest");
  7810. }
  7811. /* Add all headers as HTTP_* variables */
  7812. for (i = 0; i < conn->request_info.num_headers; i++) {
  7813. (void)mg_snprintf(conn,
  7814. &truncated,
  7815. http_var_name,
  7816. sizeof(http_var_name),
  7817. "HTTP_%s",
  7818. conn->request_info.http_headers[i].name);
  7819. if (truncated) {
  7820. mg_cry(conn,
  7821. "%s: HTTP header variable too long [%s]",
  7822. __func__,
  7823. conn->request_info.http_headers[i].name);
  7824. continue;
  7825. }
  7826. /* Convert variable name into uppercase, and change - to _ */
  7827. for (p = http_var_name; *p != '\0'; p++) {
  7828. if (*p == '-') {
  7829. *p = '_';
  7830. }
  7831. *p = (char)toupper(*(unsigned char *)p);
  7832. }
  7833. addenv(env,
  7834. "%s=%s",
  7835. http_var_name,
  7836. conn->request_info.http_headers[i].value);
  7837. }
  7838. /* Add user-specified variables */
  7839. s = conn->ctx->config[CGI_ENVIRONMENT];
  7840. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7841. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7842. }
  7843. env->var[env->varused] = NULL;
  7844. env->buf[env->bufused] = '\0';
  7845. return 0;
  7846. }
  7847. static void
  7848. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7849. {
  7850. char *buf;
  7851. size_t buflen;
  7852. int headers_len, data_len, i, truncated;
  7853. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7854. const char *status, *status_text, *connection_state;
  7855. char *pbuf, dir[PATH_MAX], *p;
  7856. struct mg_request_info ri;
  7857. struct cgi_environment blk;
  7858. FILE *in = NULL, *out = NULL, *err = NULL;
  7859. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7860. pid_t pid = (pid_t)-1;
  7861. if (conn == NULL) {
  7862. return;
  7863. }
  7864. buf = NULL;
  7865. buflen = 16384;
  7866. i = prepare_cgi_environment(conn, prog, &blk);
  7867. if (i != 0) {
  7868. blk.buf = NULL;
  7869. blk.var = NULL;
  7870. goto done;
  7871. }
  7872. /* CGI must be executed in its own directory. 'dir' must point to the
  7873. * directory containing executable program, 'p' must point to the
  7874. * executable program name relative to 'dir'. */
  7875. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7876. if (truncated) {
  7877. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7878. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7879. goto done;
  7880. }
  7881. if ((p = strrchr(dir, '/')) != NULL) {
  7882. *p++ = '\0';
  7883. } else {
  7884. dir[0] = '.', dir[1] = '\0';
  7885. p = (char *)prog;
  7886. }
  7887. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  7888. status = strerror(ERRNO);
  7889. mg_cry(conn,
  7890. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7891. prog,
  7892. status);
  7893. mg_send_http_error(conn,
  7894. 500,
  7895. "Error: Cannot create CGI pipe: %s",
  7896. status);
  7897. goto done;
  7898. }
  7899. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7900. if (pid == (pid_t)-1) {
  7901. status = strerror(ERRNO);
  7902. mg_cry(conn,
  7903. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7904. prog,
  7905. status);
  7906. mg_send_http_error(conn,
  7907. 500,
  7908. "Error: Cannot spawn CGI process [%s]: %s",
  7909. prog,
  7910. status);
  7911. goto done;
  7912. }
  7913. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7914. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7915. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7916. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7917. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7918. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7919. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7920. /* Parent closes only one side of the pipes.
  7921. * If we don't mark them as closed, close() attempt before
  7922. * return from this function throws an exception on Windows.
  7923. * Windows does not like when closed descriptor is closed again. */
  7924. (void)close(fdin[0]);
  7925. (void)close(fdout[1]);
  7926. (void)close(fderr[1]);
  7927. fdin[0] = fdout[1] = fderr[1] = -1;
  7928. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7929. status = strerror(ERRNO);
  7930. mg_cry(conn,
  7931. "Error: CGI program \"%s\": Can not open stdin: %s",
  7932. prog,
  7933. status);
  7934. mg_send_http_error(conn,
  7935. 500,
  7936. "Error: CGI can not open fdin\nfopen: %s",
  7937. status);
  7938. goto done;
  7939. }
  7940. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7941. status = strerror(ERRNO);
  7942. mg_cry(conn,
  7943. "Error: CGI program \"%s\": Can not open stdout: %s",
  7944. prog,
  7945. status);
  7946. mg_send_http_error(conn,
  7947. 500,
  7948. "Error: CGI can not open fdout\nfopen: %s",
  7949. status);
  7950. goto done;
  7951. }
  7952. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7953. status = strerror(ERRNO);
  7954. mg_cry(conn,
  7955. "Error: CGI program \"%s\": Can not open stderr: %s",
  7956. prog,
  7957. status);
  7958. mg_send_http_error(conn,
  7959. 500,
  7960. "Error: CGI can not open fdout\nfopen: %s",
  7961. status);
  7962. goto done;
  7963. }
  7964. setbuf(in, NULL);
  7965. setbuf(out, NULL);
  7966. setbuf(err, NULL);
  7967. fout.access.fp = out;
  7968. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7969. /* This is a POST/PUT request, or another request with body data. */
  7970. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7971. /* Error sending the body data */
  7972. mg_cry(conn,
  7973. "Error: CGI program \"%s\": Forward body data failed",
  7974. prog);
  7975. goto done;
  7976. }
  7977. }
  7978. /* Close so child gets an EOF. */
  7979. fclose(in);
  7980. in = NULL;
  7981. fdin[1] = -1;
  7982. /* Now read CGI reply into a buffer. We need to set correct
  7983. * status code, thus we need to see all HTTP headers first.
  7984. * Do not send anything back to client, until we buffer in all
  7985. * HTTP headers. */
  7986. data_len = 0;
  7987. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  7988. if (buf == NULL) {
  7989. mg_send_http_error(conn,
  7990. 500,
  7991. "Error: Not enough memory for CGI buffer (%u bytes)",
  7992. (unsigned int)buflen);
  7993. mg_cry(conn,
  7994. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7995. "bytes)",
  7996. prog,
  7997. (unsigned int)buflen);
  7998. goto done;
  7999. }
  8000. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  8001. if (headers_len <= 0) {
  8002. /* Could not parse the CGI response. Check if some error message on
  8003. * stderr. */
  8004. i = pull_all(err, conn, buf, (int)buflen);
  8005. if (i > 0) {
  8006. mg_cry(conn,
  8007. "Error: CGI program \"%s\" sent error "
  8008. "message: [%.*s]",
  8009. prog,
  8010. i,
  8011. buf);
  8012. mg_send_http_error(conn,
  8013. 500,
  8014. "Error: CGI program \"%s\" sent error "
  8015. "message: [%.*s]",
  8016. prog,
  8017. i,
  8018. buf);
  8019. } else {
  8020. mg_cry(conn,
  8021. "Error: CGI program sent malformed or too big "
  8022. "(>%u bytes) HTTP headers: [%.*s]",
  8023. (unsigned)buflen,
  8024. data_len,
  8025. buf);
  8026. mg_send_http_error(conn,
  8027. 500,
  8028. "Error: CGI program sent malformed or too big "
  8029. "(>%u bytes) HTTP headers: [%.*s]",
  8030. (unsigned)buflen,
  8031. data_len,
  8032. buf);
  8033. }
  8034. goto done;
  8035. }
  8036. pbuf = buf;
  8037. buf[headers_len - 1] = '\0';
  8038. parse_http_headers(&pbuf, &ri);
  8039. /* Make up and send the status line */
  8040. status_text = "OK";
  8041. if ((status = get_header(&ri, "Status")) != NULL) {
  8042. conn->status_code = atoi(status);
  8043. status_text = status;
  8044. while (isdigit(*(const unsigned char *)status_text)
  8045. || *status_text == ' ') {
  8046. status_text++;
  8047. }
  8048. } else if (get_header(&ri, "Location") != NULL) {
  8049. conn->status_code = 302;
  8050. } else {
  8051. conn->status_code = 200;
  8052. }
  8053. connection_state = get_header(&ri, "Connection");
  8054. if (!header_has_option(connection_state, "keep-alive")) {
  8055. conn->must_close = 1;
  8056. }
  8057. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  8058. /* Send headers */
  8059. for (i = 0; i < ri.num_headers; i++) {
  8060. mg_printf(conn,
  8061. "%s: %s\r\n",
  8062. ri.http_headers[i].name,
  8063. ri.http_headers[i].value);
  8064. }
  8065. mg_write(conn, "\r\n", 2);
  8066. /* Send chunk of data that may have been read after the headers */
  8067. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  8068. /* Read the rest of CGI output and send to the client */
  8069. send_file_data(conn, &fout, 0, INT64_MAX);
  8070. done:
  8071. mg_free(blk.var);
  8072. mg_free(blk.buf);
  8073. if (pid != (pid_t)-1) {
  8074. kill(pid, SIGKILL);
  8075. #if !defined(_WIN32)
  8076. {
  8077. int st;
  8078. while (waitpid(pid, &st, 0) != -1)
  8079. ; /* clean zombies */
  8080. }
  8081. #endif
  8082. }
  8083. if (fdin[0] != -1) {
  8084. close(fdin[0]);
  8085. }
  8086. if (fdout[1] != -1) {
  8087. close(fdout[1]);
  8088. }
  8089. if (in != NULL) {
  8090. fclose(in);
  8091. } else if (fdin[1] != -1) {
  8092. close(fdin[1]);
  8093. }
  8094. if (out != NULL) {
  8095. fclose(out);
  8096. } else if (fdout[0] != -1) {
  8097. close(fdout[0]);
  8098. }
  8099. if (err != NULL) {
  8100. fclose(err);
  8101. } else if (fderr[0] != -1) {
  8102. close(fderr[0]);
  8103. }
  8104. if (buf != NULL) {
  8105. mg_free(buf);
  8106. }
  8107. }
  8108. #endif /* !NO_CGI */
  8109. #if !defined(NO_FILES)
  8110. static void
  8111. mkcol(struct mg_connection *conn, const char *path)
  8112. {
  8113. int rc, body_len;
  8114. struct de de;
  8115. char date[64];
  8116. time_t curtime = time(NULL);
  8117. if (conn == NULL) {
  8118. return;
  8119. }
  8120. /* TODO (mid): Check the mg_send_http_error situations in this function */
  8121. memset(&de.file, 0, sizeof(de.file));
  8122. if (!mg_stat(conn, path, &de.file)) {
  8123. mg_cry(conn,
  8124. "%s: mg_stat(%s) failed: %s",
  8125. __func__,
  8126. path,
  8127. strerror(ERRNO));
  8128. }
  8129. if (de.file.last_modified) {
  8130. /* TODO (mid): This check does not seem to make any sense ! */
  8131. /* TODO (mid): Add a webdav unit test first, before changing
  8132. * anything here. */
  8133. mg_send_http_error(
  8134. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8135. return;
  8136. }
  8137. body_len = conn->data_len - conn->request_len;
  8138. if (body_len > 0) {
  8139. mg_send_http_error(
  8140. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8141. return;
  8142. }
  8143. rc = mg_mkdir(conn, path, 0755);
  8144. if (rc == 0) {
  8145. conn->status_code = 201;
  8146. gmt_time_string(date, sizeof(date), &curtime);
  8147. mg_printf(conn,
  8148. "HTTP/1.1 %d Created\r\n"
  8149. "Date: %s\r\n",
  8150. conn->status_code,
  8151. date);
  8152. send_static_cache_header(conn);
  8153. send_additional_header(conn);
  8154. mg_printf(conn,
  8155. "Content-Length: 0\r\n"
  8156. "Connection: %s\r\n\r\n",
  8157. suggest_connection_header(conn));
  8158. } else if (rc == -1) {
  8159. if (errno == EEXIST) {
  8160. mg_send_http_error(
  8161. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8162. } else if (errno == EACCES) {
  8163. mg_send_http_error(
  8164. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8165. } else if (errno == ENOENT) {
  8166. mg_send_http_error(
  8167. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8168. } else {
  8169. mg_send_http_error(
  8170. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8171. }
  8172. }
  8173. }
  8174. static void
  8175. put_file(struct mg_connection *conn, const char *path)
  8176. {
  8177. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8178. const char *range;
  8179. int64_t r1, r2;
  8180. int rc;
  8181. char date[64];
  8182. time_t curtime = time(NULL);
  8183. if (conn == NULL) {
  8184. return;
  8185. }
  8186. if (mg_stat(conn, path, &file.stat)) {
  8187. /* File already exists */
  8188. conn->status_code = 200;
  8189. if (file.stat.is_directory) {
  8190. /* This is an already existing directory,
  8191. * so there is nothing to do for the server. */
  8192. rc = 0;
  8193. } else {
  8194. /* File exists and is not a directory. */
  8195. /* Can it be replaced? */
  8196. if (file.access.membuf != NULL) {
  8197. /* This is an "in-memory" file, that can not be replaced */
  8198. mg_send_http_error(
  8199. conn,
  8200. 405,
  8201. "Error: Put not possible\nReplacing %s is not supported",
  8202. path);
  8203. return;
  8204. }
  8205. /* Check if the server may write this file */
  8206. if (access(path, W_OK) == 0) {
  8207. /* Access granted */
  8208. conn->status_code = 200;
  8209. rc = 1;
  8210. } else {
  8211. mg_send_http_error(
  8212. conn,
  8213. 403,
  8214. "Error: Put not possible\nReplacing %s is not allowed",
  8215. path);
  8216. return;
  8217. }
  8218. }
  8219. } else {
  8220. /* File should be created */
  8221. conn->status_code = 201;
  8222. rc = put_dir(conn, path);
  8223. }
  8224. if (rc == 0) {
  8225. /* put_dir returns 0 if path is a directory */
  8226. gmt_time_string(date, sizeof(date), &curtime);
  8227. mg_printf(conn,
  8228. "HTTP/1.1 %d %s\r\n",
  8229. conn->status_code,
  8230. mg_get_response_code_text(NULL, conn->status_code));
  8231. send_no_cache_header(conn);
  8232. send_additional_header(conn);
  8233. mg_printf(conn,
  8234. "Date: %s\r\n"
  8235. "Content-Length: 0\r\n"
  8236. "Connection: %s\r\n\r\n",
  8237. date,
  8238. suggest_connection_header(conn));
  8239. /* Request to create a directory has been fulfilled successfully.
  8240. * No need to put a file. */
  8241. return;
  8242. }
  8243. if (rc == -1) {
  8244. /* put_dir returns -1 if the path is too long */
  8245. mg_send_http_error(conn,
  8246. 414,
  8247. "Error: Path too long\nput_dir(%s): %s",
  8248. path,
  8249. strerror(ERRNO));
  8250. return;
  8251. }
  8252. if (rc == -2) {
  8253. /* put_dir returns -2 if the directory can not be created */
  8254. mg_send_http_error(conn,
  8255. 500,
  8256. "Error: Can not create directory\nput_dir(%s): %s",
  8257. path,
  8258. strerror(ERRNO));
  8259. return;
  8260. }
  8261. /* A file should be created or overwritten. */
  8262. /* Currently CivetWeb does not nead read+write access. */
  8263. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8264. || file.access.fp == NULL) {
  8265. (void)mg_fclose(&file.access);
  8266. mg_send_http_error(conn,
  8267. 500,
  8268. "Error: Can not create file\nfopen(%s): %s",
  8269. path,
  8270. strerror(ERRNO));
  8271. return;
  8272. }
  8273. fclose_on_exec(&file.access, conn);
  8274. range = mg_get_header(conn, "Content-Range");
  8275. r1 = r2 = 0;
  8276. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  8277. conn->status_code = 206; /* Partial content */
  8278. fseeko(file.access.fp, r1, SEEK_SET);
  8279. }
  8280. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8281. /* forward_body_data failed.
  8282. * The error code has already been sent to the client,
  8283. * and conn->status_code is already set. */
  8284. (void)mg_fclose(&file.access);
  8285. return;
  8286. }
  8287. if (mg_fclose(&file.access) != 0) {
  8288. /* fclose failed. This might have different reasons, but a likely
  8289. * one is "no space on disk", http 507. */
  8290. conn->status_code = 507;
  8291. }
  8292. gmt_time_string(date, sizeof(date), &curtime);
  8293. mg_printf(conn,
  8294. "HTTP/1.1 %d %s\r\n",
  8295. conn->status_code,
  8296. mg_get_response_code_text(NULL, conn->status_code));
  8297. send_no_cache_header(conn);
  8298. send_additional_header(conn);
  8299. mg_printf(conn,
  8300. "Date: %s\r\n"
  8301. "Content-Length: 0\r\n"
  8302. "Connection: %s\r\n\r\n",
  8303. date,
  8304. suggest_connection_header(conn));
  8305. }
  8306. static void
  8307. delete_file(struct mg_connection *conn, const char *path)
  8308. {
  8309. struct de de;
  8310. memset(&de.file, 0, sizeof(de.file));
  8311. if (!mg_stat(conn, path, &de.file)) {
  8312. /* mg_stat returns 0 if the file does not exist */
  8313. mg_send_http_error(conn,
  8314. 404,
  8315. "Error: Cannot delete file\nFile %s not found",
  8316. path);
  8317. return;
  8318. }
  8319. #if 0 /* Ignore if a file in memory is inside a folder */
  8320. if (de.access.membuf != NULL) {
  8321. /* the file is cached in memory */
  8322. mg_send_http_error(
  8323. conn,
  8324. 405,
  8325. "Error: Delete not possible\nDeleting %s is not supported",
  8326. path);
  8327. return;
  8328. }
  8329. #endif
  8330. if (de.file.is_directory) {
  8331. if (remove_directory(conn, path)) {
  8332. /* Delete is successful: Return 204 without content. */
  8333. mg_send_http_error(conn, 204, "%s", "");
  8334. } else {
  8335. /* Delete is not successful: Return 500 (Server error). */
  8336. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8337. }
  8338. return;
  8339. }
  8340. /* This is an existing file (not a directory).
  8341. * Check if write permission is granted. */
  8342. if (access(path, W_OK) != 0) {
  8343. /* File is read only */
  8344. mg_send_http_error(
  8345. conn,
  8346. 403,
  8347. "Error: Delete not possible\nDeleting %s is not allowed",
  8348. path);
  8349. return;
  8350. }
  8351. /* Try to delete it. */
  8352. if (mg_remove(conn, path) == 0) {
  8353. /* Delete was successful: Return 204 without content. */
  8354. mg_send_http_error(conn, 204, "%s", "");
  8355. } else {
  8356. /* Delete not successful (file locked). */
  8357. mg_send_http_error(conn,
  8358. 423,
  8359. "Error: Cannot delete file\nremove(%s): %s",
  8360. path,
  8361. strerror(ERRNO));
  8362. }
  8363. }
  8364. #endif /* !NO_FILES */
  8365. static void
  8366. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8367. static void
  8368. do_ssi_include(struct mg_connection *conn,
  8369. const char *ssi,
  8370. char *tag,
  8371. int include_level)
  8372. {
  8373. char file_name[MG_BUF_LEN], path[512], *p;
  8374. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8375. size_t len;
  8376. int truncated = 0;
  8377. if (conn == NULL) {
  8378. return;
  8379. }
  8380. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8381. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8382. * always < MG_BUF_LEN. */
  8383. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8384. /* File name is relative to the webserver root */
  8385. file_name[511] = 0;
  8386. (void)mg_snprintf(conn,
  8387. &truncated,
  8388. path,
  8389. sizeof(path),
  8390. "%s/%s",
  8391. conn->ctx->config[DOCUMENT_ROOT],
  8392. file_name);
  8393. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8394. /* File name is relative to the webserver working directory
  8395. * or it is absolute system path */
  8396. file_name[511] = 0;
  8397. (void)
  8398. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8399. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  8400. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  8401. /* File name is relative to the currect document */
  8402. file_name[511] = 0;
  8403. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8404. if (!truncated) {
  8405. if ((p = strrchr(path, '/')) != NULL) {
  8406. p[1] = '\0';
  8407. }
  8408. len = strlen(path);
  8409. (void)mg_snprintf(conn,
  8410. &truncated,
  8411. path + len,
  8412. sizeof(path) - len,
  8413. "%s",
  8414. file_name);
  8415. }
  8416. } else {
  8417. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8418. return;
  8419. }
  8420. if (truncated) {
  8421. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8422. return;
  8423. }
  8424. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8425. mg_cry(conn,
  8426. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8427. tag,
  8428. path,
  8429. strerror(ERRNO));
  8430. } else {
  8431. fclose_on_exec(&file.access, conn);
  8432. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8433. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8434. path) > 0) {
  8435. send_ssi_file(conn, path, &file, include_level + 1);
  8436. } else {
  8437. send_file_data(conn, &file, 0, INT64_MAX);
  8438. }
  8439. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8440. }
  8441. }
  8442. #if !defined(NO_POPEN)
  8443. static void
  8444. do_ssi_exec(struct mg_connection *conn, char *tag)
  8445. {
  8446. char cmd[1024] = "";
  8447. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8448. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8449. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8450. } else {
  8451. cmd[1023] = 0;
  8452. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8453. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8454. } else {
  8455. send_file_data(conn, &file, 0, INT64_MAX);
  8456. pclose(file.access.fp);
  8457. }
  8458. }
  8459. }
  8460. #endif /* !NO_POPEN */
  8461. static int
  8462. mg_fgetc(struct mg_file *filep, int offset)
  8463. {
  8464. if (filep == NULL) {
  8465. return EOF;
  8466. }
  8467. if ((filep->access.membuf != NULL) && (offset >= 0)
  8468. && (((unsigned int)(offset)) < filep->stat.size)) {
  8469. return ((const unsigned char *)filep->access.membuf)[offset];
  8470. } else if (filep->access.fp != NULL) {
  8471. return fgetc(filep->access.fp);
  8472. } else {
  8473. return EOF;
  8474. }
  8475. }
  8476. static void
  8477. send_ssi_file(struct mg_connection *conn,
  8478. const char *path,
  8479. struct mg_file *filep,
  8480. int include_level)
  8481. {
  8482. char buf[MG_BUF_LEN];
  8483. int ch, offset, len, in_tag, in_ssi_tag;
  8484. if (include_level > 10) {
  8485. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8486. return;
  8487. }
  8488. in_tag = in_ssi_tag = len = offset = 0;
  8489. /* Read file, byte by byte, and look for SSI include tags */
  8490. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  8491. if (in_tag) {
  8492. /* We are in a tag, either SSI tag or html tag */
  8493. if (ch == '>') {
  8494. /* Tag is closing */
  8495. buf[len++] = '>';
  8496. if (in_ssi_tag) {
  8497. /* Handle SSI tag */
  8498. buf[len] = 0;
  8499. if (!memcmp(buf + 5, "include", 7)) {
  8500. do_ssi_include(conn, path, buf + 12, include_level + 1);
  8501. #if !defined(NO_POPEN)
  8502. } else if (!memcmp(buf + 5, "exec", 4)) {
  8503. do_ssi_exec(conn, buf + 9);
  8504. #endif /* !NO_POPEN */
  8505. } else {
  8506. mg_cry(conn,
  8507. "%s: unknown SSI "
  8508. "command: \"%s\"",
  8509. path,
  8510. buf);
  8511. }
  8512. len = 0;
  8513. in_ssi_tag = in_tag = 0;
  8514. } else {
  8515. /* Not an SSI tag */
  8516. /* Flush buffer */
  8517. (void)mg_write(conn, buf, (size_t)len);
  8518. len = 0;
  8519. in_tag = 0;
  8520. }
  8521. } else {
  8522. /* Tag is still open */
  8523. buf[len++] = (char)(ch & 0xff);
  8524. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  8525. /* All SSI tags start with <!--# */
  8526. in_ssi_tag = 1;
  8527. }
  8528. if ((len + 2) > (int)sizeof(buf)) {
  8529. /* Tag to long for buffer */
  8530. mg_cry(conn, "%s: tag is too large", path);
  8531. len = 0;
  8532. return;
  8533. }
  8534. }
  8535. } else {
  8536. /* We are not in a tag yet. */
  8537. if (ch == '<') {
  8538. /* Tag is opening */
  8539. in_tag = 1;
  8540. /* Flush current buffer */
  8541. (void)mg_write(conn, buf, (size_t)len);
  8542. /* Store the < */
  8543. len = 1;
  8544. buf[0] = '<';
  8545. } else {
  8546. /* No Tag */
  8547. /* Add data to buffer */
  8548. buf[len++] = (char)(ch & 0xff);
  8549. /* Flush if buffer is full */
  8550. if (len == (int)sizeof(buf)) {
  8551. mg_write(conn, buf, (size_t)len);
  8552. len = 0;
  8553. }
  8554. }
  8555. }
  8556. }
  8557. /* Send the rest of buffered data */
  8558. if (len > 0) {
  8559. mg_write(conn, buf, (size_t)len);
  8560. }
  8561. }
  8562. static void
  8563. handle_ssi_file_request(struct mg_connection *conn,
  8564. const char *path,
  8565. struct mg_file *filep)
  8566. {
  8567. char date[64];
  8568. time_t curtime = time(NULL);
  8569. const char *cors1, *cors2, *cors3;
  8570. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  8571. return;
  8572. }
  8573. if (mg_get_header(conn, "Origin")) {
  8574. /* Cross-origin resource sharing (CORS). */
  8575. cors1 = "Access-Control-Allow-Origin: ";
  8576. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8577. cors3 = "\r\n";
  8578. } else {
  8579. cors1 = cors2 = cors3 = "";
  8580. }
  8581. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8582. /* File exists (precondition for calling this function),
  8583. * but can not be opened by the server. */
  8584. mg_send_http_error(conn,
  8585. 500,
  8586. "Error: Cannot read file\nfopen(%s): %s",
  8587. path,
  8588. strerror(ERRNO));
  8589. } else {
  8590. conn->must_close = 1;
  8591. gmt_time_string(date, sizeof(date), &curtime);
  8592. fclose_on_exec(&filep->access, conn);
  8593. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8594. send_no_cache_header(conn);
  8595. send_additional_header(conn);
  8596. mg_printf(conn,
  8597. "%s%s%s"
  8598. "Date: %s\r\n"
  8599. "Content-Type: text/html\r\n"
  8600. "Connection: %s\r\n\r\n",
  8601. cors1,
  8602. cors2,
  8603. cors3,
  8604. date,
  8605. suggest_connection_header(conn));
  8606. send_ssi_file(conn, path, filep, 0);
  8607. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8608. }
  8609. }
  8610. #if !defined(NO_FILES)
  8611. static void
  8612. send_options(struct mg_connection *conn)
  8613. {
  8614. char date[64];
  8615. time_t curtime = time(NULL);
  8616. if (!conn) {
  8617. return;
  8618. }
  8619. conn->status_code = 200;
  8620. conn->must_close = 1;
  8621. gmt_time_string(date, sizeof(date), &curtime);
  8622. /* We do not set a "Cache-Control" header here, but leave the default.
  8623. * Since browsers do not send an OPTIONS request, we can not test the
  8624. * effect anyway. */
  8625. mg_printf(conn,
  8626. "HTTP/1.1 200 OK\r\n"
  8627. "Date: %s\r\n"
  8628. "Connection: %s\r\n"
  8629. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8630. "PROPFIND, MKCOL\r\n"
  8631. "DAV: 1\r\n",
  8632. date,
  8633. suggest_connection_header(conn));
  8634. send_additional_header(conn);
  8635. mg_printf(conn, "\r\n");
  8636. }
  8637. /* Writes PROPFIND properties for a collection element */
  8638. static void
  8639. print_props(struct mg_connection *conn,
  8640. const char *uri,
  8641. struct mg_file_stat *filep)
  8642. {
  8643. char mtime[64];
  8644. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  8645. return;
  8646. }
  8647. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8648. mg_printf(conn,
  8649. "<d:response>"
  8650. "<d:href>%s</d:href>"
  8651. "<d:propstat>"
  8652. "<d:prop>"
  8653. "<d:resourcetype>%s</d:resourcetype>"
  8654. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8655. "<d:getlastmodified>%s</d:getlastmodified>"
  8656. "</d:prop>"
  8657. "<d:status>HTTP/1.1 200 OK</d:status>"
  8658. "</d:propstat>"
  8659. "</d:response>\n",
  8660. uri,
  8661. filep->is_directory ? "<d:collection/>" : "",
  8662. filep->size,
  8663. mtime);
  8664. }
  8665. static int
  8666. print_dav_dir_entry(struct de *de, void *data)
  8667. {
  8668. char href[PATH_MAX];
  8669. int truncated;
  8670. struct mg_connection *conn = (struct mg_connection *)data;
  8671. if (!de || !conn) {
  8672. return -1;
  8673. }
  8674. mg_snprintf(conn,
  8675. &truncated,
  8676. href,
  8677. sizeof(href),
  8678. "%s%s",
  8679. conn->request_info.local_uri,
  8680. de->file_name);
  8681. if (!truncated) {
  8682. size_t href_encoded_size;
  8683. char *href_encoded;
  8684. href_encoded_size = PATH_MAX * 3; /* worst case */
  8685. href_encoded = mg_malloc(href_encoded_size);
  8686. if (href_encoded == NULL) {
  8687. return -1;
  8688. }
  8689. mg_url_encode(href, href_encoded, href_encoded_size);
  8690. print_props(conn, href_encoded, &de->file);
  8691. mg_free(href_encoded);
  8692. }
  8693. return 0;
  8694. }
  8695. static void
  8696. handle_propfind(struct mg_connection *conn,
  8697. const char *path,
  8698. struct mg_file_stat *filep)
  8699. {
  8700. const char *depth = mg_get_header(conn, "Depth");
  8701. char date[64];
  8702. time_t curtime = time(NULL);
  8703. gmt_time_string(date, sizeof(date), &curtime);
  8704. if (!conn || !path || !filep || !conn->ctx) {
  8705. return;
  8706. }
  8707. conn->must_close = 1;
  8708. conn->status_code = 207;
  8709. mg_printf(conn,
  8710. "HTTP/1.1 207 Multi-Status\r\n"
  8711. "Date: %s\r\n",
  8712. date);
  8713. send_static_cache_header(conn);
  8714. send_additional_header(conn);
  8715. mg_printf(conn,
  8716. "Connection: %s\r\n"
  8717. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8718. suggest_connection_header(conn));
  8719. mg_printf(conn,
  8720. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8721. "<d:multistatus xmlns:d='DAV:'>\n");
  8722. /* Print properties for the requested resource itself */
  8723. print_props(conn, conn->request_info.local_uri, filep);
  8724. /* If it is a directory, print directory entries too if Depth is not 0 */
  8725. if (filep && filep->is_directory
  8726. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8727. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  8728. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8729. }
  8730. mg_printf(conn, "%s\n", "</d:multistatus>");
  8731. }
  8732. #endif
  8733. void
  8734. mg_lock_connection(struct mg_connection *conn)
  8735. {
  8736. if (conn) {
  8737. (void)pthread_mutex_lock(&conn->mutex);
  8738. }
  8739. }
  8740. void
  8741. mg_unlock_connection(struct mg_connection *conn)
  8742. {
  8743. if (conn) {
  8744. (void)pthread_mutex_unlock(&conn->mutex);
  8745. }
  8746. }
  8747. void
  8748. mg_lock_context(struct mg_context *ctx)
  8749. {
  8750. if (ctx) {
  8751. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8752. }
  8753. }
  8754. void
  8755. mg_unlock_context(struct mg_context *ctx)
  8756. {
  8757. if (ctx) {
  8758. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8759. }
  8760. }
  8761. #if defined(USE_TIMERS)
  8762. #define TIMER_API static
  8763. #include "timer.inl"
  8764. #endif /* USE_TIMERS */
  8765. #ifdef USE_LUA
  8766. #include "mod_lua.inl"
  8767. #endif /* USE_LUA */
  8768. #ifdef USE_DUKTAPE
  8769. #include "mod_duktape.inl"
  8770. #endif /* USE_DUKTAPE */
  8771. #if defined(USE_WEBSOCKET)
  8772. #if !defined(NO_SSL_DL)
  8773. #define SHA_API static
  8774. #include "sha1.inl"
  8775. #endif
  8776. static int
  8777. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8778. {
  8779. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8780. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8781. SHA_CTX sha_ctx;
  8782. int truncated;
  8783. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8784. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8785. if (truncated) {
  8786. conn->must_close = 1;
  8787. return 0;
  8788. }
  8789. SHA1_Init(&sha_ctx);
  8790. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8791. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8792. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8793. mg_printf(conn,
  8794. "HTTP/1.1 101 Switching Protocols\r\n"
  8795. "Upgrade: websocket\r\n"
  8796. "Connection: Upgrade\r\n"
  8797. "Sec-WebSocket-Accept: %s\r\n",
  8798. b64_sha);
  8799. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8800. mg_printf(conn,
  8801. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8802. conn->request_info.acceptedWebSocketSubprotocol);
  8803. } else {
  8804. mg_printf(conn, "%s", "\r\n");
  8805. }
  8806. return 1;
  8807. }
  8808. static void
  8809. read_websocket(struct mg_connection *conn,
  8810. mg_websocket_data_handler ws_data_handler,
  8811. void *callback_data)
  8812. {
  8813. /* Pointer to the beginning of the portion of the incoming websocket
  8814. * message queue.
  8815. * The original websocket upgrade request is never removed, so the queue
  8816. * begins after it. */
  8817. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8818. int n, error, exit_by_callback;
  8819. /* body_len is the length of the entire queue in bytes
  8820. * len is the length of the current message
  8821. * data_len is the length of the current message's data payload
  8822. * header_len is the length of the current message's header */
  8823. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8824. /* "The masking key is a 32-bit value chosen at random by the client."
  8825. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8826. */
  8827. unsigned char mask[4];
  8828. /* data points to the place where the message is stored when passed to
  8829. * the
  8830. * websocket_data callback. This is either mem on the stack, or a
  8831. * dynamically allocated buffer if it is too large. */
  8832. unsigned char mem[4096];
  8833. unsigned char *data = mem;
  8834. unsigned char mop; /* mask flag and opcode */
  8835. double timeout = -1.0;
  8836. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8837. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8838. }
  8839. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8840. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8841. }
  8842. mg_set_thread_name("wsock");
  8843. /* Loop continuously, reading messages from the socket, invoking the
  8844. * callback, and waiting repeatedly until an error occurs. */
  8845. while (!conn->ctx->stop_flag) {
  8846. header_len = 0;
  8847. assert(conn->data_len >= conn->request_len);
  8848. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8849. len = buf[1] & 127;
  8850. mask_len = (buf[1] & 128) ? 4 : 0;
  8851. if ((len < 126) && (body_len >= mask_len)) {
  8852. /* inline 7-bit length field */
  8853. data_len = len;
  8854. header_len = 2 + mask_len;
  8855. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8856. /* 16-bit length field */
  8857. header_len = 4 + mask_len;
  8858. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8859. } else if (body_len >= (10 + mask_len)) {
  8860. /* 64-bit length field */
  8861. uint32_t l1, l2;
  8862. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  8863. memcpy(&l2, &buf[6], 4);
  8864. header_len = 10 + mask_len;
  8865. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  8866. }
  8867. }
  8868. if ((header_len > 0) && (body_len >= header_len)) {
  8869. /* Allocate space to hold websocket payload */
  8870. data = mem;
  8871. if (data_len > sizeof(mem)) {
  8872. data = (unsigned char *)mg_malloc_ctx(data_len, conn->ctx);
  8873. if (data == NULL) {
  8874. /* Allocation failed, exit the loop and then close the
  8875. * connection */
  8876. mg_cry(conn, "websocket out of memory; closing connection");
  8877. break;
  8878. }
  8879. }
  8880. /* Copy the mask before we shift the queue and destroy it */
  8881. if (mask_len > 0) {
  8882. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8883. } else {
  8884. memset(mask, 0, sizeof(mask));
  8885. }
  8886. /* Read frame payload from the first message in the queue into
  8887. * data and advance the queue by moving the memory in place. */
  8888. assert(body_len >= header_len);
  8889. if (data_len + header_len > body_len) {
  8890. mop = buf[0]; /* current mask and opcode */
  8891. /* Overflow case */
  8892. len = body_len - header_len;
  8893. memcpy(data, buf + header_len, len);
  8894. error = 0;
  8895. while (len < data_len) {
  8896. n = pull_inner(NULL,
  8897. conn,
  8898. (char *)(data + len),
  8899. (int)(data_len - len),
  8900. timeout);
  8901. if (n <= -2) {
  8902. error = 1;
  8903. break;
  8904. } else if (n > 0) {
  8905. len += (size_t)n;
  8906. } else {
  8907. /* Timeout: should retry */
  8908. /* TODO: retry condition */
  8909. }
  8910. }
  8911. if (error) {
  8912. mg_cry(conn, "Websocket pull failed; closing connection");
  8913. break;
  8914. }
  8915. conn->data_len = conn->request_len;
  8916. } else {
  8917. mop = buf[0]; /* current mask and opcode, overwritten by
  8918. * memmove() */
  8919. /* Length of the message being read at the front of the
  8920. * queue */
  8921. len = data_len + header_len;
  8922. /* Copy the data payload into the data pointer for the
  8923. * callback */
  8924. memcpy(data, buf + header_len, data_len);
  8925. /* Move the queue forward len bytes */
  8926. memmove(buf, buf + len, body_len - len);
  8927. /* Mark the queue as advanced */
  8928. conn->data_len -= (int)len;
  8929. }
  8930. /* Apply mask if necessary */
  8931. if (mask_len > 0) {
  8932. for (i = 0; i < data_len; ++i) {
  8933. data[i] ^= mask[i & 3];
  8934. }
  8935. }
  8936. /* Exit the loop if callback signals to exit (server side),
  8937. * or "connection close" opcode received (client side). */
  8938. exit_by_callback = 0;
  8939. if ((ws_data_handler != NULL)
  8940. && !ws_data_handler(
  8941. conn, mop, (char *)data, data_len, callback_data)) {
  8942. exit_by_callback = 1;
  8943. }
  8944. if (data != mem) {
  8945. mg_free(data);
  8946. }
  8947. if (exit_by_callback
  8948. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8949. /* Opcode == 8, connection close */
  8950. break;
  8951. }
  8952. /* Not breaking the loop, process next websocket frame. */
  8953. } else {
  8954. /* Read from the socket into the next available location in the
  8955. * message queue. */
  8956. n = pull_inner(NULL,
  8957. conn,
  8958. conn->buf + conn->data_len,
  8959. conn->buf_size - conn->data_len,
  8960. timeout);
  8961. if (n <= -2) {
  8962. /* Error, no bytes read */
  8963. break;
  8964. }
  8965. if (n > 0) {
  8966. conn->data_len += n;
  8967. } else {
  8968. /* Timeout: should retry */
  8969. /* TODO: get timeout def */
  8970. }
  8971. }
  8972. }
  8973. mg_set_thread_name("worker");
  8974. }
  8975. static int
  8976. mg_websocket_write_exec(struct mg_connection *conn,
  8977. int opcode,
  8978. const char *data,
  8979. size_t dataLen,
  8980. uint32_t masking_key)
  8981. {
  8982. unsigned char header[14];
  8983. size_t headerLen = 1;
  8984. int retval = -1;
  8985. #if defined(__GNUC__) || defined(__MINGW32__)
  8986. /* Disable spurious conversion warning for GCC */
  8987. #pragma GCC diagnostic push
  8988. #pragma GCC diagnostic ignored "-Wconversion"
  8989. #endif
  8990. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8991. #if defined(__GNUC__) || defined(__MINGW32__)
  8992. #pragma GCC diagnostic pop
  8993. #endif
  8994. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8995. if (dataLen < 126) {
  8996. /* inline 7-bit length field */
  8997. header[1] = (unsigned char)dataLen;
  8998. headerLen = 2;
  8999. } else if (dataLen <= 0xFFFF) {
  9000. /* 16-bit length field */
  9001. uint16_t len = htons((uint16_t)dataLen);
  9002. header[1] = 126;
  9003. memcpy(header + 2, &len, 2);
  9004. headerLen = 4;
  9005. } else {
  9006. /* 64-bit length field */
  9007. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  9008. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  9009. header[1] = 127;
  9010. memcpy(header + 2, &len1, 4);
  9011. memcpy(header + 6, &len2, 4);
  9012. headerLen = 10;
  9013. }
  9014. if (masking_key) {
  9015. /* add mask */
  9016. header[1] |= 0x80;
  9017. memcpy(header + headerLen, &masking_key, 4);
  9018. headerLen += 4;
  9019. }
  9020. /* Note that POSIX/Winsock's send() is threadsafe
  9021. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  9022. * but mongoose's mg_printf/mg_write is not (because of the loop in
  9023. * push(), although that is only a problem if the packet is large or
  9024. * outgoing buffer is full). */
  9025. /* TODO: Check if this lock should be moved to user land.
  9026. * Currently the server sets this lock for websockets, but
  9027. * not for any other connection. It must be set for every
  9028. * conn read/written by more than one thread, no matter if
  9029. * it is a websocket or regular connection. */
  9030. (void)mg_lock_connection(conn);
  9031. retval = mg_write(conn, header, headerLen);
  9032. if (dataLen > 0) {
  9033. retval = mg_write(conn, data, dataLen);
  9034. }
  9035. /* TODO: Remove this unlock as well, when lock is moved. */
  9036. mg_unlock_connection(conn);
  9037. return retval;
  9038. }
  9039. int
  9040. mg_websocket_write(struct mg_connection *conn,
  9041. int opcode,
  9042. const char *data,
  9043. size_t dataLen)
  9044. {
  9045. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  9046. }
  9047. static void
  9048. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  9049. {
  9050. size_t i = 0;
  9051. i = 0;
  9052. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  9053. /* Convert in 32 bit words, if data is 4 byte aligned */
  9054. while (i < (in_len - 3)) {
  9055. *(uint32_t *)(void *)(out + i) =
  9056. *(uint32_t *)(void *)(in + i) ^ masking_key;
  9057. i += 4;
  9058. }
  9059. }
  9060. if (i != in_len) {
  9061. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  9062. while (i < in_len) {
  9063. *(uint8_t *)(void *)(out + i) =
  9064. *(uint8_t *)(void *)(in + i)
  9065. ^ *(((uint8_t *)&masking_key) + (i % 4));
  9066. i++;
  9067. }
  9068. }
  9069. }
  9070. int
  9071. mg_websocket_client_write(struct mg_connection *conn,
  9072. int opcode,
  9073. const char *data,
  9074. size_t dataLen)
  9075. {
  9076. int retval = -1;
  9077. char *masked_data =
  9078. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  9079. uint32_t masking_key = (uint32_t)get_random();
  9080. if (masked_data == NULL) {
  9081. /* Return -1 in an error case */
  9082. mg_cry(conn,
  9083. "Cannot allocate buffer for masked websocket response: "
  9084. "Out of memory");
  9085. return -1;
  9086. }
  9087. mask_data(data, dataLen, masking_key, masked_data);
  9088. retval = mg_websocket_write_exec(
  9089. conn, opcode, masked_data, dataLen, masking_key);
  9090. mg_free(masked_data);
  9091. return retval;
  9092. }
  9093. static void
  9094. handle_websocket_request(struct mg_connection *conn,
  9095. const char *path,
  9096. int is_callback_resource,
  9097. struct mg_websocket_subprotocols *subprotocols,
  9098. mg_websocket_connect_handler ws_connect_handler,
  9099. mg_websocket_ready_handler ws_ready_handler,
  9100. mg_websocket_data_handler ws_data_handler,
  9101. mg_websocket_close_handler ws_close_handler,
  9102. void *cbData)
  9103. {
  9104. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  9105. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  9106. int lua_websock = 0;
  9107. #if !defined(USE_LUA)
  9108. (void)path;
  9109. #endif
  9110. /* Step 1: Check websocket protocol version. */
  9111. /* Step 1.1: Check Sec-WebSocket-Key. */
  9112. if (!websock_key) {
  9113. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  9114. * requires a Sec-WebSocket-Key header.
  9115. */
  9116. /* It could be the hixie draft version
  9117. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  9118. */
  9119. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  9120. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  9121. char key3[8];
  9122. if ((key1 != NULL) && (key2 != NULL)) {
  9123. /* This version uses 8 byte body data in a GET request */
  9124. conn->content_len = 8;
  9125. if (8 == mg_read(conn, key3, 8)) {
  9126. /* This is the hixie version */
  9127. mg_send_http_error(conn,
  9128. 426,
  9129. "%s",
  9130. "Protocol upgrade to RFC 6455 required");
  9131. return;
  9132. }
  9133. }
  9134. /* This is an unknown version */
  9135. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  9136. return;
  9137. }
  9138. /* Step 1.2: Check websocket protocol version. */
  9139. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  9140. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  9141. /* Reject wrong versions */
  9142. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  9143. return;
  9144. }
  9145. /* Step 1.3: Could check for "Host", but we do not really nead this
  9146. * value for anything, so just ignore it. */
  9147. /* Step 2: If a callback is responsible, call it. */
  9148. if (is_callback_resource) {
  9149. /* Step 2.1 check and select subprotocol */
  9150. const char *protocols[64]; // max 64 headers
  9151. int nbSubprotocolHeader = get_headers(&conn->request_info,
  9152. "Sec-WebSocket-Protocol",
  9153. protocols,
  9154. 64);
  9155. if ((nbSubprotocolHeader > 0) && subprotocols) {
  9156. int cnt = 0;
  9157. int idx;
  9158. unsigned long len;
  9159. const char *sep, *curSubProtocol,
  9160. *acceptedWebSocketSubprotocol = NULL;
  9161. /* look for matching subprotocol */
  9162. do {
  9163. const char *protocol = protocols[cnt];
  9164. do {
  9165. sep = strchr(protocol, ',');
  9166. curSubProtocol = protocol;
  9167. len = sep ? (unsigned long)(sep - protocol)
  9168. : (unsigned long)strlen(protocol);
  9169. while (sep && isspace(*++sep))
  9170. ; // ignore leading whitespaces
  9171. protocol = sep;
  9172. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  9173. if ((strlen(subprotocols->subprotocols[idx]) == len)
  9174. && (strncmp(curSubProtocol,
  9175. subprotocols->subprotocols[idx],
  9176. len) == 0)) {
  9177. acceptedWebSocketSubprotocol =
  9178. subprotocols->subprotocols[idx];
  9179. break;
  9180. }
  9181. }
  9182. } while (sep && !acceptedWebSocketSubprotocol);
  9183. } while (++cnt < nbSubprotocolHeader
  9184. && !acceptedWebSocketSubprotocol);
  9185. conn->request_info.acceptedWebSocketSubprotocol =
  9186. acceptedWebSocketSubprotocol;
  9187. } else if (nbSubprotocolHeader > 0) {
  9188. /* keep legacy behavior */
  9189. const char *protocol = protocols[0];
  9190. /* The protocol is a comma separated list of names. */
  9191. /* The server must only return one value from this list. */
  9192. /* First check if it is a list or just a single value. */
  9193. const char *sep = strrchr(protocol, ',');
  9194. if (sep == NULL) {
  9195. /* Just a single protocol -> accept it. */
  9196. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  9197. } else {
  9198. /* Multiple protocols -> accept the last one. */
  9199. /* This is just a quick fix if the client offers multiple
  9200. * protocols. The handler should have a list of accepted
  9201. * protocols on his own
  9202. * and use it to select one protocol among those the client has
  9203. * offered.
  9204. */
  9205. while (isspace(*++sep)) {
  9206. ; /* ignore leading whitespaces */
  9207. }
  9208. conn->request_info.acceptedWebSocketSubprotocol = sep;
  9209. }
  9210. }
  9211. if ((ws_connect_handler != NULL)
  9212. && (ws_connect_handler(conn, cbData) != 0)) {
  9213. /* C callback has returned non-zero, do not proceed with
  9214. * handshake.
  9215. */
  9216. /* Note that C callbacks are no longer called when Lua is
  9217. * responsible, so C can no longer filter callbacks for Lua. */
  9218. return;
  9219. }
  9220. }
  9221. #if defined(USE_LUA)
  9222. /* Step 3: No callback. Check if Lua is responsible. */
  9223. else {
  9224. /* Step 3.1: Check if Lua is responsible. */
  9225. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  9226. lua_websock =
  9227. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  9228. strlen(
  9229. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  9230. path);
  9231. }
  9232. if (lua_websock) {
  9233. /* Step 3.2: Lua is responsible: call it. */
  9234. conn->lua_websocket_state = lua_websocket_new(path, conn);
  9235. if (!conn->lua_websocket_state) {
  9236. /* Lua rejected the new client */
  9237. return;
  9238. }
  9239. }
  9240. }
  9241. #endif
  9242. /* Step 4: Check if there is a responsible websocket handler. */
  9243. if (!is_callback_resource && !lua_websock) {
  9244. /* There is no callback, and Lua is not responsible either. */
  9245. /* Reply with a 404 Not Found. We are still at a standard
  9246. * HTTP request here, before the websocket handshake, so
  9247. * we can still send standard HTTP error replies. */
  9248. mg_send_http_error(conn, 404, "%s", "Not found");
  9249. return;
  9250. }
  9251. /* Step 5: The websocket connection has been accepted */
  9252. if (!send_websocket_handshake(conn, websock_key)) {
  9253. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  9254. return;
  9255. }
  9256. /* Step 6: Call the ready handler */
  9257. if (is_callback_resource) {
  9258. if (ws_ready_handler != NULL) {
  9259. ws_ready_handler(conn, cbData);
  9260. }
  9261. #if defined(USE_LUA)
  9262. } else if (lua_websock) {
  9263. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9264. /* the ready handler returned false */
  9265. return;
  9266. }
  9267. #endif
  9268. }
  9269. /* Step 7: Enter the read loop */
  9270. if (is_callback_resource) {
  9271. read_websocket(conn, ws_data_handler, cbData);
  9272. #if defined(USE_LUA)
  9273. } else if (lua_websock) {
  9274. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9275. #endif
  9276. }
  9277. /* Step 8: Call the close handler */
  9278. if (ws_close_handler) {
  9279. ws_close_handler(conn, cbData);
  9280. }
  9281. }
  9282. static int
  9283. is_websocket_protocol(const struct mg_connection *conn)
  9284. {
  9285. const char *upgrade, *connection;
  9286. /* A websocket protocoll has the following HTTP headers:
  9287. *
  9288. * Connection: Upgrade
  9289. * Upgrade: Websocket
  9290. */
  9291. upgrade = mg_get_header(conn, "Upgrade");
  9292. if (upgrade == NULL) {
  9293. return 0; /* fail early, don't waste time checking other header
  9294. * fields
  9295. */
  9296. }
  9297. if (!mg_strcasestr(upgrade, "websocket")) {
  9298. return 0;
  9299. }
  9300. connection = mg_get_header(conn, "Connection");
  9301. if (connection == NULL) {
  9302. return 0;
  9303. }
  9304. if (!mg_strcasestr(connection, "upgrade")) {
  9305. return 0;
  9306. }
  9307. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9308. * "Sec-WebSocket-Version" are also required.
  9309. * Don't check them here, since even an unsupported websocket protocol
  9310. * request still IS a websocket request (in contrast to a standard HTTP
  9311. * request). It will fail later in handle_websocket_request.
  9312. */
  9313. return 1;
  9314. }
  9315. #endif /* !USE_WEBSOCKET */
  9316. static int
  9317. isbyte(int n)
  9318. {
  9319. return (n >= 0) && (n <= 255);
  9320. }
  9321. static int
  9322. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9323. {
  9324. int n, a, b, c, d, slash = 32, len = 0;
  9325. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  9326. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  9327. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  9328. && (slash < 33)) {
  9329. len = n;
  9330. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9331. | (uint32_t)d;
  9332. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9333. }
  9334. return len;
  9335. }
  9336. static int
  9337. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9338. {
  9339. int throttle = 0;
  9340. struct vec vec, val;
  9341. uint32_t net, mask;
  9342. char mult;
  9343. double v;
  9344. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9345. mult = ',';
  9346. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9347. || (v < 0) || ((lowercase(&mult) != 'k')
  9348. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9349. continue;
  9350. }
  9351. v *= (lowercase(&mult) == 'k')
  9352. ? 1024
  9353. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9354. if (vec.len == 1 && vec.ptr[0] == '*') {
  9355. throttle = (int)v;
  9356. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9357. if ((remote_ip & mask) == net) {
  9358. throttle = (int)v;
  9359. }
  9360. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9361. throttle = (int)v;
  9362. }
  9363. }
  9364. return throttle;
  9365. }
  9366. static uint32_t
  9367. get_remote_ip(const struct mg_connection *conn)
  9368. {
  9369. if (!conn) {
  9370. return 0;
  9371. }
  9372. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9373. }
  9374. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9375. #include "handle_form.inl"
  9376. #if defined(MG_LEGACY_INTERFACE)
  9377. /* Implement the deprecated mg_upload function by calling the new
  9378. * mg_handle_form_request function. While mg_upload could only handle
  9379. * HTML forms sent as POST request in multipart/form-data format
  9380. * containing only file input elements, mg_handle_form_request can
  9381. * handle all form input elements and all standard request methods. */
  9382. struct mg_upload_user_data {
  9383. struct mg_connection *conn;
  9384. const char *destination_dir;
  9385. int num_uploaded_files;
  9386. };
  9387. /* Helper function for deprecated mg_upload. */
  9388. static int
  9389. mg_upload_field_found(const char *key,
  9390. const char *filename,
  9391. char *path,
  9392. size_t pathlen,
  9393. void *user_data)
  9394. {
  9395. int truncated = 0;
  9396. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9397. (void)key;
  9398. if (!filename) {
  9399. mg_cry(fud->conn, "%s: No filename set", __func__);
  9400. return FORM_FIELD_STORAGE_ABORT;
  9401. }
  9402. mg_snprintf(fud->conn,
  9403. &truncated,
  9404. path,
  9405. pathlen - 1,
  9406. "%s/%s",
  9407. fud->destination_dir,
  9408. filename);
  9409. if (!truncated) {
  9410. mg_cry(fud->conn, "%s: File path too long", __func__);
  9411. return FORM_FIELD_STORAGE_ABORT;
  9412. }
  9413. return FORM_FIELD_STORAGE_STORE;
  9414. }
  9415. /* Helper function for deprecated mg_upload. */
  9416. static int
  9417. mg_upload_field_get(const char *key,
  9418. const char *value,
  9419. size_t value_size,
  9420. void *user_data)
  9421. {
  9422. /* Function should never be called */
  9423. (void)key;
  9424. (void)value;
  9425. (void)value_size;
  9426. (void)user_data;
  9427. return 0;
  9428. }
  9429. /* Helper function for deprecated mg_upload. */
  9430. static int
  9431. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9432. {
  9433. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9434. (void)file_size;
  9435. fud->num_uploaded_files++;
  9436. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9437. return 0;
  9438. }
  9439. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9440. int
  9441. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9442. {
  9443. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9444. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9445. mg_upload_field_get,
  9446. mg_upload_field_stored,
  9447. 0};
  9448. int ret;
  9449. fdh.user_data = (void *)&fud;
  9450. ret = mg_handle_form_request(conn, &fdh);
  9451. if (ret < 0) {
  9452. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9453. }
  9454. return fud.num_uploaded_files;
  9455. }
  9456. #endif
  9457. static int
  9458. get_first_ssl_listener_index(const struct mg_context *ctx)
  9459. {
  9460. unsigned int i;
  9461. int idx = -1;
  9462. if (ctx) {
  9463. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  9464. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9465. }
  9466. }
  9467. return idx;
  9468. }
  9469. static void
  9470. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9471. {
  9472. char host[1025];
  9473. const char *host_header;
  9474. size_t hostlen;
  9475. host_header = mg_get_header(conn, "Host");
  9476. hostlen = sizeof(host);
  9477. if (host_header != NULL) {
  9478. char *pos;
  9479. mg_strlcpy(host, host_header, hostlen);
  9480. host[hostlen - 1] = '\0';
  9481. pos = strchr(host, ':');
  9482. if (pos != NULL) {
  9483. *pos = '\0';
  9484. }
  9485. } else {
  9486. /* Cannot get host from the Host: header.
  9487. * Fallback to our IP address. */
  9488. if (conn) {
  9489. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9490. }
  9491. }
  9492. /* Send host, port, uri and (if it exists) ?query_string */
  9493. if (conn) {
  9494. mg_printf(conn,
  9495. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9496. host,
  9497. #if defined(USE_IPV6)
  9498. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9499. == AF_INET6)
  9500. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9501. .lsa.sin6.sin6_port)
  9502. :
  9503. #endif
  9504. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9505. .lsa.sin.sin_port),
  9506. conn->request_info.local_uri,
  9507. (conn->request_info.query_string == NULL) ? "" : "?",
  9508. (conn->request_info.query_string == NULL)
  9509. ? ""
  9510. : conn->request_info.query_string);
  9511. }
  9512. }
  9513. static void
  9514. mg_set_handler_type(struct mg_context *ctx,
  9515. const char *uri,
  9516. int handler_type,
  9517. int is_delete_request,
  9518. mg_request_handler handler,
  9519. struct mg_websocket_subprotocols *subprotocols,
  9520. mg_websocket_connect_handler connect_handler,
  9521. mg_websocket_ready_handler ready_handler,
  9522. mg_websocket_data_handler data_handler,
  9523. mg_websocket_close_handler close_handler,
  9524. mg_authorization_handler auth_handler,
  9525. void *cbdata)
  9526. {
  9527. struct mg_handler_info *tmp_rh, **lastref;
  9528. size_t urilen = strlen(uri);
  9529. if (handler_type == WEBSOCKET_HANDLER) {
  9530. /* assert(handler == NULL); */
  9531. /* assert(is_delete_request || connect_handler!=NULL ||
  9532. * ready_handler!=NULL || data_handler!=NULL ||
  9533. * close_handler!=NULL);
  9534. */
  9535. /* assert(auth_handler == NULL); */
  9536. if (handler != NULL) {
  9537. return;
  9538. }
  9539. if (!is_delete_request && (connect_handler == NULL)
  9540. && (ready_handler == NULL) && (data_handler == NULL)
  9541. && (close_handler == NULL)) {
  9542. return;
  9543. }
  9544. if (auth_handler != NULL) {
  9545. return;
  9546. }
  9547. } else if (handler_type == REQUEST_HANDLER) {
  9548. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9549. * data_handler==NULL && close_handler==NULL); */
  9550. /* assert(is_delete_request || (handler!=NULL));
  9551. */
  9552. /* assert(auth_handler == NULL); */
  9553. if ((connect_handler != NULL) || (ready_handler != NULL)
  9554. || (data_handler != NULL) || (close_handler != NULL)) {
  9555. return;
  9556. }
  9557. if (!is_delete_request && (handler == NULL)) {
  9558. return;
  9559. }
  9560. if (auth_handler != NULL) {
  9561. return;
  9562. }
  9563. } else { /* AUTH_HANDLER */
  9564. /* assert(handler == NULL); */
  9565. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9566. * data_handler==NULL && close_handler==NULL); */
  9567. /* assert(auth_handler != NULL); */
  9568. if (handler != NULL) {
  9569. return;
  9570. }
  9571. if ((connect_handler != NULL) || (ready_handler != NULL)
  9572. || (data_handler != NULL) || (close_handler != NULL)) {
  9573. return;
  9574. }
  9575. if (!is_delete_request && (auth_handler == NULL)) {
  9576. return;
  9577. }
  9578. }
  9579. if (!ctx) {
  9580. return;
  9581. }
  9582. mg_lock_context(ctx);
  9583. /* first try to find an existing handler */
  9584. lastref = &(ctx->handlers);
  9585. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9586. if (tmp_rh->handler_type == handler_type) {
  9587. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  9588. if (!is_delete_request) {
  9589. /* update existing handler */
  9590. if (handler_type == REQUEST_HANDLER) {
  9591. tmp_rh->handler = handler;
  9592. } else if (handler_type == WEBSOCKET_HANDLER) {
  9593. tmp_rh->subprotocols = subprotocols;
  9594. tmp_rh->connect_handler = connect_handler;
  9595. tmp_rh->ready_handler = ready_handler;
  9596. tmp_rh->data_handler = data_handler;
  9597. tmp_rh->close_handler = close_handler;
  9598. } else { /* AUTH_HANDLER */
  9599. tmp_rh->auth_handler = auth_handler;
  9600. }
  9601. tmp_rh->cbdata = cbdata;
  9602. } else {
  9603. /* remove existing handler */
  9604. *lastref = tmp_rh->next;
  9605. mg_free(tmp_rh->uri);
  9606. mg_free(tmp_rh);
  9607. }
  9608. mg_unlock_context(ctx);
  9609. return;
  9610. }
  9611. }
  9612. lastref = &(tmp_rh->next);
  9613. }
  9614. if (is_delete_request) {
  9615. /* no handler to set, this was a remove request to a non-existing
  9616. * handler */
  9617. mg_unlock_context(ctx);
  9618. return;
  9619. }
  9620. tmp_rh =
  9621. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  9622. 1,
  9623. ctx);
  9624. if (tmp_rh == NULL) {
  9625. mg_unlock_context(ctx);
  9626. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9627. return;
  9628. }
  9629. tmp_rh->uri = mg_strdup(uri);
  9630. if (!tmp_rh->uri) {
  9631. mg_unlock_context(ctx);
  9632. mg_free(tmp_rh);
  9633. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9634. return;
  9635. }
  9636. tmp_rh->uri_len = urilen;
  9637. if (handler_type == REQUEST_HANDLER) {
  9638. tmp_rh->handler = handler;
  9639. } else if (handler_type == WEBSOCKET_HANDLER) {
  9640. tmp_rh->subprotocols = subprotocols;
  9641. tmp_rh->connect_handler = connect_handler;
  9642. tmp_rh->ready_handler = ready_handler;
  9643. tmp_rh->data_handler = data_handler;
  9644. tmp_rh->close_handler = close_handler;
  9645. } else { /* AUTH_HANDLER */
  9646. tmp_rh->auth_handler = auth_handler;
  9647. }
  9648. tmp_rh->cbdata = cbdata;
  9649. tmp_rh->handler_type = handler_type;
  9650. tmp_rh->next = NULL;
  9651. *lastref = tmp_rh;
  9652. mg_unlock_context(ctx);
  9653. }
  9654. void
  9655. mg_set_request_handler(struct mg_context *ctx,
  9656. const char *uri,
  9657. mg_request_handler handler,
  9658. void *cbdata)
  9659. {
  9660. mg_set_handler_type(ctx,
  9661. uri,
  9662. REQUEST_HANDLER,
  9663. handler == NULL,
  9664. handler,
  9665. NULL,
  9666. NULL,
  9667. NULL,
  9668. NULL,
  9669. NULL,
  9670. NULL,
  9671. cbdata);
  9672. }
  9673. void
  9674. mg_set_websocket_handler(struct mg_context *ctx,
  9675. const char *uri,
  9676. mg_websocket_connect_handler connect_handler,
  9677. mg_websocket_ready_handler ready_handler,
  9678. mg_websocket_data_handler data_handler,
  9679. mg_websocket_close_handler close_handler,
  9680. void *cbdata)
  9681. {
  9682. mg_set_websocket_handler_with_subprotocols(ctx,
  9683. uri,
  9684. NULL,
  9685. connect_handler,
  9686. ready_handler,
  9687. data_handler,
  9688. close_handler,
  9689. cbdata);
  9690. }
  9691. void
  9692. mg_set_websocket_handler_with_subprotocols(
  9693. struct mg_context *ctx,
  9694. const char *uri,
  9695. struct mg_websocket_subprotocols *subprotocols,
  9696. mg_websocket_connect_handler connect_handler,
  9697. mg_websocket_ready_handler ready_handler,
  9698. mg_websocket_data_handler data_handler,
  9699. mg_websocket_close_handler close_handler,
  9700. void *cbdata)
  9701. {
  9702. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9703. && (data_handler == NULL)
  9704. && (close_handler == NULL);
  9705. mg_set_handler_type(ctx,
  9706. uri,
  9707. WEBSOCKET_HANDLER,
  9708. is_delete_request,
  9709. NULL,
  9710. subprotocols,
  9711. connect_handler,
  9712. ready_handler,
  9713. data_handler,
  9714. close_handler,
  9715. NULL,
  9716. cbdata);
  9717. }
  9718. void
  9719. mg_set_auth_handler(struct mg_context *ctx,
  9720. const char *uri,
  9721. mg_request_handler handler,
  9722. void *cbdata)
  9723. {
  9724. mg_set_handler_type(ctx,
  9725. uri,
  9726. AUTH_HANDLER,
  9727. handler == NULL,
  9728. NULL,
  9729. NULL,
  9730. NULL,
  9731. NULL,
  9732. NULL,
  9733. NULL,
  9734. handler,
  9735. cbdata);
  9736. }
  9737. static int
  9738. get_request_handler(struct mg_connection *conn,
  9739. int handler_type,
  9740. mg_request_handler *handler,
  9741. struct mg_websocket_subprotocols **subprotocols,
  9742. mg_websocket_connect_handler *connect_handler,
  9743. mg_websocket_ready_handler *ready_handler,
  9744. mg_websocket_data_handler *data_handler,
  9745. mg_websocket_close_handler *close_handler,
  9746. mg_authorization_handler *auth_handler,
  9747. void **cbdata)
  9748. {
  9749. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9750. if (request_info) {
  9751. const char *uri = request_info->local_uri;
  9752. size_t urilen = strlen(uri);
  9753. struct mg_handler_info *tmp_rh;
  9754. if (!conn || !conn->ctx) {
  9755. return 0;
  9756. }
  9757. mg_lock_context(conn->ctx);
  9758. /* first try for an exact match */
  9759. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9760. tmp_rh = tmp_rh->next) {
  9761. if (tmp_rh->handler_type == handler_type) {
  9762. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  9763. if (handler_type == WEBSOCKET_HANDLER) {
  9764. *subprotocols = tmp_rh->subprotocols;
  9765. *connect_handler = tmp_rh->connect_handler;
  9766. *ready_handler = tmp_rh->ready_handler;
  9767. *data_handler = tmp_rh->data_handler;
  9768. *close_handler = tmp_rh->close_handler;
  9769. } else if (handler_type == REQUEST_HANDLER) {
  9770. *handler = tmp_rh->handler;
  9771. } else { /* AUTH_HANDLER */
  9772. *auth_handler = tmp_rh->auth_handler;
  9773. }
  9774. *cbdata = tmp_rh->cbdata;
  9775. mg_unlock_context(conn->ctx);
  9776. return 1;
  9777. }
  9778. }
  9779. }
  9780. /* next try for a partial match, we will accept uri/something */
  9781. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9782. tmp_rh = tmp_rh->next) {
  9783. if (tmp_rh->handler_type == handler_type) {
  9784. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  9785. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  9786. if (handler_type == WEBSOCKET_HANDLER) {
  9787. *subprotocols = tmp_rh->subprotocols;
  9788. *connect_handler = tmp_rh->connect_handler;
  9789. *ready_handler = tmp_rh->ready_handler;
  9790. *data_handler = tmp_rh->data_handler;
  9791. *close_handler = tmp_rh->close_handler;
  9792. } else if (handler_type == REQUEST_HANDLER) {
  9793. *handler = tmp_rh->handler;
  9794. } else { /* AUTH_HANDLER */
  9795. *auth_handler = tmp_rh->auth_handler;
  9796. }
  9797. *cbdata = tmp_rh->cbdata;
  9798. mg_unlock_context(conn->ctx);
  9799. return 1;
  9800. }
  9801. }
  9802. }
  9803. /* finally try for pattern match */
  9804. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9805. tmp_rh = tmp_rh->next) {
  9806. if (tmp_rh->handler_type == handler_type) {
  9807. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9808. if (handler_type == WEBSOCKET_HANDLER) {
  9809. *subprotocols = tmp_rh->subprotocols;
  9810. *connect_handler = tmp_rh->connect_handler;
  9811. *ready_handler = tmp_rh->ready_handler;
  9812. *data_handler = tmp_rh->data_handler;
  9813. *close_handler = tmp_rh->close_handler;
  9814. } else if (handler_type == REQUEST_HANDLER) {
  9815. *handler = tmp_rh->handler;
  9816. } else { /* AUTH_HANDLER */
  9817. *auth_handler = tmp_rh->auth_handler;
  9818. }
  9819. *cbdata = tmp_rh->cbdata;
  9820. mg_unlock_context(conn->ctx);
  9821. return 1;
  9822. }
  9823. }
  9824. }
  9825. mg_unlock_context(conn->ctx);
  9826. }
  9827. return 0; /* none found */
  9828. }
  9829. /* Check if the script file is in a path, allowed for script files.
  9830. * This can be used if uploading files is possible not only for the server
  9831. * admin, and the upload mechanism does not check the file extension.
  9832. */
  9833. static int
  9834. is_in_script_path(const struct mg_connection *conn, const char *path)
  9835. {
  9836. /* TODO (Feature): Add config value for allowed script path.
  9837. * Default: All allowed. */
  9838. (void)conn;
  9839. (void)path;
  9840. return 1;
  9841. }
  9842. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9843. static int
  9844. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9845. void *cbdata)
  9846. {
  9847. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9848. if (pcallbacks->websocket_connect) {
  9849. return pcallbacks->websocket_connect(conn);
  9850. }
  9851. /* No handler set - assume "OK" */
  9852. return 0;
  9853. }
  9854. static void
  9855. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9856. {
  9857. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9858. if (pcallbacks->websocket_ready) {
  9859. pcallbacks->websocket_ready(conn);
  9860. }
  9861. }
  9862. static int
  9863. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9864. int bits,
  9865. char *data,
  9866. size_t len,
  9867. void *cbdata)
  9868. {
  9869. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9870. if (pcallbacks->websocket_data) {
  9871. return pcallbacks->websocket_data(conn, bits, data, len);
  9872. }
  9873. /* No handler set - assume "OK" */
  9874. return 1;
  9875. }
  9876. #endif
  9877. /* This is the heart of the Civetweb's logic.
  9878. * This function is called when the request is read, parsed and validated,
  9879. * and Civetweb must decide what action to take: serve a file, or
  9880. * a directory, or call embedded function, etcetera. */
  9881. static void
  9882. handle_request(struct mg_connection *conn)
  9883. {
  9884. struct mg_request_info *ri = &conn->request_info;
  9885. char path[PATH_MAX];
  9886. int uri_len, ssl_index;
  9887. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9888. is_put_or_delete_request = 0, is_callback_resource = 0;
  9889. int i;
  9890. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9891. mg_request_handler callback_handler = NULL;
  9892. struct mg_websocket_subprotocols *subprotocols;
  9893. mg_websocket_connect_handler ws_connect_handler = NULL;
  9894. mg_websocket_ready_handler ws_ready_handler = NULL;
  9895. mg_websocket_data_handler ws_data_handler = NULL;
  9896. mg_websocket_close_handler ws_close_handler = NULL;
  9897. void *callback_data = NULL;
  9898. mg_authorization_handler auth_handler = NULL;
  9899. void *auth_callback_data = NULL;
  9900. int handler_type;
  9901. time_t curtime = time(NULL);
  9902. char date[64];
  9903. path[0] = 0;
  9904. /* 1. get the request url */
  9905. /* 1.1. split into url and query string */
  9906. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9907. != NULL) {
  9908. *((char *)conn->request_info.query_string++) = '\0';
  9909. }
  9910. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9911. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9912. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9913. if (ssl_index >= 0) {
  9914. redirect_to_https_port(conn, ssl_index);
  9915. } else {
  9916. /* A http to https forward port has been specified,
  9917. * but no https port to forward to. */
  9918. mg_send_http_error(conn,
  9919. 503,
  9920. "%s",
  9921. "Error: SSL forward not configured properly");
  9922. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9923. }
  9924. return;
  9925. }
  9926. uri_len = (int)strlen(ri->local_uri);
  9927. /* 1.3. decode url (if config says so) */
  9928. if (should_decode_url(conn)) {
  9929. mg_url_decode(
  9930. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9931. }
  9932. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9933. * not possible */
  9934. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9935. /* step 1. completed, the url is known now */
  9936. uri_len = (int)strlen(ri->local_uri);
  9937. DEBUG_TRACE("URL: %s", ri->local_uri);
  9938. /* 2. if this ip has limited speed, set it for this connection */
  9939. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9940. get_remote_ip(conn),
  9941. ri->local_uri);
  9942. /* 3. call a "handle everything" callback, if registered */
  9943. if (conn->ctx->callbacks.begin_request != NULL) {
  9944. /* Note that since V1.7 the "begin_request" function is called
  9945. * before an authorization check. If an authorization check is
  9946. * required, use a request_handler instead. */
  9947. i = conn->ctx->callbacks.begin_request(conn);
  9948. if (i > 0) {
  9949. /* callback already processed the request. Store the
  9950. return value as a status code for the access log. */
  9951. conn->status_code = i;
  9952. discard_unread_request_data(conn);
  9953. return;
  9954. } else if (i == 0) {
  9955. /* civetweb should process the request */
  9956. } else {
  9957. /* unspecified - may change with the next version */
  9958. return;
  9959. }
  9960. }
  9961. /* request not yet handled by a handler or redirect, so the request
  9962. * is processed here */
  9963. /* 4. Check for CORS preflight requests and handle them (if configured).
  9964. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  9965. */
  9966. if (!strcmp(ri->request_method, "OPTIONS")) {
  9967. /* Send a response to CORS preflights only if
  9968. * access_control_allow_methods is not NULL and not an empty string.
  9969. * In this case, scripts can still handle CORS. */
  9970. const char *cors_meth_cfg =
  9971. conn->ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  9972. const char *cors_orig_cfg =
  9973. conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9974. const char *cors_origin = get_header(ri, "Origin");
  9975. const char *cors_acrm = get_header(ri, "Access-Control-Request-Method");
  9976. /* Todo: check if cors_origin is in cors_orig_cfg.
  9977. * Or, let the client check this. */
  9978. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  9979. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  9980. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  9981. /* This is a valid CORS preflight, and the server is configured to
  9982. * handle it automatically. */
  9983. const char *cors_acrh =
  9984. get_header(ri, "Access-Control-Request-Headers");
  9985. gmt_time_string(date, sizeof(date), &curtime);
  9986. mg_printf(conn,
  9987. "HTTP/1.1 200 OK\r\n"
  9988. "Date: %s\r\n"
  9989. "Access-Control-Allow-Origin: %s\r\n"
  9990. "Access-Control-Allow-Methods: %s\r\n"
  9991. "Content-Length: 0\r\n"
  9992. "Connection: %s\r\n",
  9993. date,
  9994. cors_orig_cfg,
  9995. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  9996. suggest_connection_header(conn));
  9997. if (cors_acrh != NULL) {
  9998. /* CORS request is asking for additional headers */
  9999. const char *cors_hdr_cfg =
  10000. conn->ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  10001. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  10002. /* Allow only if access_control_allow_headers is
  10003. * not NULL and not an empty string. If this
  10004. * configuration is set to *, allow everything.
  10005. * Otherwise this configuration must be a list
  10006. * of allowed HTTP header names. */
  10007. mg_printf(conn,
  10008. "Access-Control-Allow-Headers: %s\r\n",
  10009. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  10010. : cors_hdr_cfg));
  10011. }
  10012. }
  10013. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  10014. mg_printf(conn, "\r\n");
  10015. return;
  10016. }
  10017. }
  10018. /* 5. interpret the url to find out how the request must be handled
  10019. */
  10020. /* 5.1. first test, if the request targets the regular http(s)://
  10021. * protocol namespace or the websocket ws(s):// protocol namespace.
  10022. */
  10023. is_websocket_request = is_websocket_protocol(conn);
  10024. #if defined(USE_WEBSOCKET)
  10025. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  10026. #else
  10027. handler_type = REQUEST_HANDLER;
  10028. #endif /* defined(USE_WEBSOCKET) */
  10029. /* 5.2. check if the request will be handled by a callback */
  10030. if (get_request_handler(conn,
  10031. handler_type,
  10032. &callback_handler,
  10033. &subprotocols,
  10034. &ws_connect_handler,
  10035. &ws_ready_handler,
  10036. &ws_data_handler,
  10037. &ws_close_handler,
  10038. NULL,
  10039. &callback_data)) {
  10040. /* 5.2.1. A callback will handle this request. All requests
  10041. * handled
  10042. * by a callback have to be considered as requests to a script
  10043. * resource. */
  10044. is_callback_resource = 1;
  10045. is_script_resource = 1;
  10046. is_put_or_delete_request = is_put_or_delete_method(conn);
  10047. } else {
  10048. no_callback_resource:
  10049. /* 5.2.2. No callback is responsible for this request. The URI
  10050. * addresses a file based resource (static content or Lua/cgi
  10051. * scripts in the file system). */
  10052. is_callback_resource = 0;
  10053. interpret_uri(conn,
  10054. path,
  10055. sizeof(path),
  10056. &file.stat,
  10057. &is_found,
  10058. &is_script_resource,
  10059. &is_websocket_request,
  10060. &is_put_or_delete_request);
  10061. }
  10062. /* 6. authorization check */
  10063. /* 6.1. a custom authorization handler is installed */
  10064. if (get_request_handler(conn,
  10065. AUTH_HANDLER,
  10066. NULL,
  10067. NULL,
  10068. NULL,
  10069. NULL,
  10070. NULL,
  10071. NULL,
  10072. &auth_handler,
  10073. &auth_callback_data)) {
  10074. if (!auth_handler(conn, auth_callback_data)) {
  10075. return;
  10076. }
  10077. } else if (is_put_or_delete_request && !is_script_resource
  10078. && !is_callback_resource) {
  10079. /* 6.2. this request is a PUT/DELETE to a real file */
  10080. /* 6.2.1. thus, the server must have real files */
  10081. #if defined(NO_FILES)
  10082. if (1) {
  10083. #else
  10084. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10085. #endif
  10086. /* This server does not have any real files, thus the
  10087. * PUT/DELETE methods are not valid. */
  10088. mg_send_http_error(conn,
  10089. 405,
  10090. "%s method not allowed",
  10091. conn->request_info.request_method);
  10092. return;
  10093. }
  10094. #if !defined(NO_FILES)
  10095. /* 6.2.2. Check if put authorization for static files is
  10096. * available.
  10097. */
  10098. if (!is_authorized_for_put(conn)) {
  10099. send_authorization_request(conn);
  10100. return;
  10101. }
  10102. #endif
  10103. } else {
  10104. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  10105. * or it is a PUT or DELETE request to a resource that does not
  10106. * correspond to a file. Check authorization. */
  10107. if (!check_authorization(conn, path)) {
  10108. send_authorization_request(conn);
  10109. return;
  10110. }
  10111. }
  10112. /* request is authorized or does not need authorization */
  10113. /* 7. check if there are request handlers for this uri */
  10114. if (is_callback_resource) {
  10115. if (!is_websocket_request) {
  10116. i = callback_handler(conn, callback_data);
  10117. if (i > 0) {
  10118. /* Do nothing, callback has served the request. Store
  10119. * then return value as status code for the log and discard
  10120. * all data from the client not used by the callback. */
  10121. conn->status_code = i;
  10122. discard_unread_request_data(conn);
  10123. } else {
  10124. /* The handler did NOT handle the request. */
  10125. /* Some proper reactions would be:
  10126. * a) close the connections without sending anything
  10127. * b) send a 404 not found
  10128. * c) try if there is a file matching the URI
  10129. * It would be possible to do a, b or c in the callback
  10130. * implementation, and return 1 - we cannot do anything
  10131. * here, that is not possible in the callback.
  10132. *
  10133. * TODO: What would be the best reaction here?
  10134. * (Note: The reaction may change, if there is a better idea.)
  10135. */
  10136. /* For the moment, use option c: We look for a proper file,
  10137. * but since a file request is not always a script resource,
  10138. * the authorization check might be different. */
  10139. interpret_uri(conn,
  10140. path,
  10141. sizeof(path),
  10142. &file.stat,
  10143. &is_found,
  10144. &is_script_resource,
  10145. &is_websocket_request,
  10146. &is_put_or_delete_request);
  10147. callback_handler = NULL;
  10148. /* Here we are at a dead end:
  10149. * According to URI matching, a callback should be
  10150. * responsible for handling the request,
  10151. * we called it, but the callback declared itself
  10152. * not responsible.
  10153. * We use a goto here, to get out of this dead end,
  10154. * and continue with the default handling.
  10155. * A goto here is simpler and better to understand
  10156. * than some curious loop. */
  10157. goto no_callback_resource;
  10158. }
  10159. } else {
  10160. #if defined(USE_WEBSOCKET)
  10161. handle_websocket_request(conn,
  10162. path,
  10163. is_callback_resource,
  10164. subprotocols,
  10165. ws_connect_handler,
  10166. ws_ready_handler,
  10167. ws_data_handler,
  10168. ws_close_handler,
  10169. callback_data);
  10170. #endif
  10171. }
  10172. return;
  10173. }
  10174. /* 8. handle websocket requests */
  10175. #if defined(USE_WEBSOCKET)
  10176. if (is_websocket_request) {
  10177. if (is_script_resource) {
  10178. if (is_in_script_path(conn, path)) {
  10179. /* Websocket Lua script */
  10180. handle_websocket_request(conn,
  10181. path,
  10182. 0 /* Lua Script */,
  10183. NULL,
  10184. NULL,
  10185. NULL,
  10186. NULL,
  10187. NULL,
  10188. &conn->ctx->callbacks);
  10189. } else {
  10190. /* Script was in an illegal path */
  10191. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10192. }
  10193. } else {
  10194. #if defined(MG_LEGACY_INTERFACE)
  10195. handle_websocket_request(
  10196. conn,
  10197. path,
  10198. !is_script_resource /* could be deprecated global callback */,
  10199. NULL,
  10200. deprecated_websocket_connect_wrapper,
  10201. deprecated_websocket_ready_wrapper,
  10202. deprecated_websocket_data_wrapper,
  10203. NULL,
  10204. &conn->ctx->callbacks);
  10205. #else
  10206. mg_send_http_error(conn, 404, "%s", "Not found");
  10207. #endif
  10208. }
  10209. return;
  10210. } else
  10211. #endif
  10212. #if defined(NO_FILES)
  10213. /* 9a. In case the server uses only callbacks, this uri is
  10214. * unknown.
  10215. * Then, all request handling ends here. */
  10216. mg_send_http_error(conn, 404, "%s", "Not Found");
  10217. #else
  10218. /* 9b. This request is either for a static file or resource handled
  10219. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  10220. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10221. mg_send_http_error(conn, 404, "%s", "Not Found");
  10222. return;
  10223. }
  10224. /* 10. Request is handled by a script */
  10225. if (is_script_resource) {
  10226. handle_file_based_request(conn, path, &file);
  10227. return;
  10228. }
  10229. /* 11. Handle put/delete/mkcol requests */
  10230. if (is_put_or_delete_request) {
  10231. /* 11.1. PUT method */
  10232. if (!strcmp(ri->request_method, "PUT")) {
  10233. put_file(conn, path);
  10234. return;
  10235. }
  10236. /* 11.2. DELETE method */
  10237. if (!strcmp(ri->request_method, "DELETE")) {
  10238. delete_file(conn, path);
  10239. return;
  10240. }
  10241. /* 11.3. MKCOL method */
  10242. if (!strcmp(ri->request_method, "MKCOL")) {
  10243. mkcol(conn, path);
  10244. return;
  10245. }
  10246. /* 11.4. PATCH method
  10247. * This method is not supported for static resources,
  10248. * only for scripts (Lua, CGI) and callbacks. */
  10249. mg_send_http_error(conn,
  10250. 405,
  10251. "%s method not allowed",
  10252. conn->request_info.request_method);
  10253. return;
  10254. }
  10255. /* 11. File does not exist, or it was configured that it should be
  10256. * hidden */
  10257. if (!is_found || (must_hide_file(conn, path))) {
  10258. mg_send_http_error(conn, 404, "%s", "Not found");
  10259. return;
  10260. }
  10261. /* 12. Directory uris should end with a slash */
  10262. if (file.stat.is_directory && (uri_len > 0)
  10263. && (ri->local_uri[uri_len - 1] != '/')) {
  10264. gmt_time_string(date, sizeof(date), &curtime);
  10265. mg_printf(conn,
  10266. "HTTP/1.1 301 Moved Permanently\r\n"
  10267. "Location: %s/\r\n"
  10268. "Date: %s\r\n"
  10269. /* "Cache-Control: private\r\n" (= default) */
  10270. "Content-Length: 0\r\n"
  10271. "Connection: %s\r\n",
  10272. ri->request_uri,
  10273. date,
  10274. suggest_connection_header(conn));
  10275. send_additional_header(conn);
  10276. mg_printf(conn, "\r\n");
  10277. return;
  10278. }
  10279. /* 13. Handle other methods than GET/HEAD */
  10280. /* 13.1. Handle PROPFIND */
  10281. if (!strcmp(ri->request_method, "PROPFIND")) {
  10282. handle_propfind(conn, path, &file.stat);
  10283. return;
  10284. }
  10285. /* 13.2. Handle OPTIONS for files */
  10286. if (!strcmp(ri->request_method, "OPTIONS")) {
  10287. /* This standard handler is only used for real files.
  10288. * Scripts should support the OPTIONS method themselves, to allow a
  10289. * maximum flexibility.
  10290. * Lua and CGI scripts may fully support CORS this way (including
  10291. * preflights). */
  10292. send_options(conn);
  10293. return;
  10294. }
  10295. /* 13.3. everything but GET and HEAD (e.g. POST) */
  10296. if ((0 != strcmp(ri->request_method, "GET"))
  10297. && (0 != strcmp(ri->request_method, "HEAD"))) {
  10298. mg_send_http_error(conn,
  10299. 405,
  10300. "%s method not allowed",
  10301. conn->request_info.request_method);
  10302. return;
  10303. }
  10304. /* 14. directories */
  10305. if (file.stat.is_directory) {
  10306. /* Substitute files have already been handled above. */
  10307. /* Here we can either generate and send a directory listing,
  10308. * or send an "access denied" error. */
  10309. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  10310. "yes")) {
  10311. handle_directory_request(conn, path);
  10312. } else {
  10313. mg_send_http_error(conn,
  10314. 403,
  10315. "%s",
  10316. "Error: Directory listing denied");
  10317. }
  10318. return;
  10319. }
  10320. handle_file_based_request(conn, path, &file);
  10321. #endif /* !defined(NO_FILES) */
  10322. #if 0
  10323. /* Perform redirect and auth checks before calling begin_request()
  10324. * handler.
  10325. * Otherwise, begin_request() would need to perform auth checks and
  10326. * redirects. */
  10327. #endif
  10328. }
  10329. static void
  10330. handle_file_based_request(struct mg_connection *conn,
  10331. const char *path,
  10332. struct mg_file *file)
  10333. {
  10334. if (!conn || !conn->ctx) {
  10335. return;
  10336. }
  10337. if (0) {
  10338. #ifdef USE_LUA
  10339. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10340. strlen(
  10341. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10342. path) > 0) {
  10343. if (is_in_script_path(conn, path)) {
  10344. /* Lua server page: an SSI like page containing mostly plain html
  10345. * code
  10346. * plus some tags with server generated contents. */
  10347. handle_lsp_request(conn, path, file, NULL);
  10348. } else {
  10349. /* Script was in an illegal path */
  10350. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10351. }
  10352. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10353. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10354. path) > 0) {
  10355. if (is_in_script_path(conn, path)) {
  10356. /* Lua in-server module script: a CGI like script used to generate
  10357. * the
  10358. * entire reply. */
  10359. mg_exec_lua_script(conn, path, NULL);
  10360. } else {
  10361. /* Script was in an illegal path */
  10362. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10363. }
  10364. #endif
  10365. #if defined(USE_DUKTAPE)
  10366. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10367. strlen(
  10368. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10369. path) > 0) {
  10370. if (is_in_script_path(conn, path)) {
  10371. /* Call duktape to generate the page */
  10372. mg_exec_duktape_script(conn, path);
  10373. } else {
  10374. /* Script was in an illegal path */
  10375. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10376. }
  10377. #endif
  10378. #if !defined(NO_CGI)
  10379. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10380. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10381. path) > 0) {
  10382. if (is_in_script_path(conn, path)) {
  10383. /* CGI scripts may support all HTTP methods */
  10384. handle_cgi_request(conn, path);
  10385. } else {
  10386. /* Script was in an illegal path */
  10387. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10388. }
  10389. #endif /* !NO_CGI */
  10390. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10391. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10392. path) > 0) {
  10393. if (is_in_script_path(conn, path)) {
  10394. handle_ssi_file_request(conn, path, file);
  10395. } else {
  10396. /* Script was in an illegal path */
  10397. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10398. }
  10399. #if !defined(NO_CACHING)
  10400. } else if ((!conn->in_error_handler)
  10401. && is_not_modified(conn, &file->stat)) {
  10402. /* Send 304 "Not Modified" - this must not send any body data */
  10403. handle_not_modified_static_file_request(conn, file);
  10404. #endif /* !NO_CACHING */
  10405. } else {
  10406. handle_static_file_request(conn, path, file, NULL, NULL);
  10407. }
  10408. }
  10409. static void
  10410. close_all_listening_sockets(struct mg_context *ctx)
  10411. {
  10412. unsigned int i;
  10413. if (!ctx) {
  10414. return;
  10415. }
  10416. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10417. closesocket(ctx->listening_sockets[i].sock);
  10418. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10419. }
  10420. mg_free(ctx->listening_sockets);
  10421. ctx->listening_sockets = NULL;
  10422. mg_free(ctx->listening_socket_fds);
  10423. ctx->listening_socket_fds = NULL;
  10424. }
  10425. /* Valid listening port specification is: [ip_address:]port[s]
  10426. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10427. * Examples for IPv6: [::]:80, [::1]:80,
  10428. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10429. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10430. * In order to bind to both, IPv4 and IPv6, you can either add
  10431. * both ports using 8080,[::]:8080, or the short form +8080.
  10432. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10433. * one only accepting IPv4 the other only IPv6. +8080 creates
  10434. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10435. * environment, they might work differently, or might not work
  10436. * at all - it must be tested what options work best in the
  10437. * relevant network environment.
  10438. */
  10439. static int
  10440. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10441. {
  10442. unsigned int a, b, c, d, port;
  10443. int ch, len;
  10444. char *cb;
  10445. #if defined(USE_IPV6)
  10446. char buf[100] = {0};
  10447. #endif
  10448. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10449. * Also, all-zeroes in the socket address means binding to all addresses
  10450. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10451. memset(so, 0, sizeof(*so));
  10452. so->lsa.sin.sin_family = AF_INET;
  10453. *ip_version = 0;
  10454. /* Initialize port and len as invalid. */
  10455. port = 0;
  10456. len = 0;
  10457. /* Test for different ways to format this string */
  10458. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10459. == 5) {
  10460. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10461. so->lsa.sin.sin_addr.s_addr =
  10462. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10463. so->lsa.sin.sin_port = htons((uint16_t)port);
  10464. *ip_version = 4;
  10465. #if defined(USE_IPV6)
  10466. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10467. && mg_inet_pton(
  10468. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10469. /* IPv6 address, examples: see above */
  10470. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10471. */
  10472. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10473. *ip_version = 6;
  10474. #endif
  10475. } else if ((vec->ptr[0] == '+')
  10476. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10477. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10478. /* Add 1 to len for the + character we skipped before */
  10479. len++;
  10480. #if defined(USE_IPV6)
  10481. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10482. so->lsa.sin6.sin6_family = AF_INET6;
  10483. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10484. *ip_version = 4 + 6;
  10485. #else
  10486. /* Bind to IPv4 only, since IPv6 is not built in. */
  10487. so->lsa.sin.sin_port = htons((uint16_t)port);
  10488. *ip_version = 4;
  10489. #endif
  10490. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10491. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10492. so->lsa.sin.sin_port = htons((uint16_t)port);
  10493. *ip_version = 4;
  10494. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  10495. /* Could be a hostname */
  10496. /* Will only work for RFC 952 compliant hostnames,
  10497. * starting with a letter, containing only letters,
  10498. * digits and hyphen ('-'). Newer specs may allow
  10499. * more, but this is not guaranteed here, since it
  10500. * may interfere with rules for port option lists. */
  10501. *cb = 0;
  10502. if (mg_inet_pton(
  10503. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  10504. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  10505. *ip_version = 4;
  10506. so->lsa.sin.sin_family = AF_INET;
  10507. so->lsa.sin.sin_port = htons((uint16_t)port);
  10508. len += (int)(cb - vec->ptr) + 1;
  10509. } else {
  10510. port = 0;
  10511. len = 0;
  10512. }
  10513. #if defined(USE_IPV6)
  10514. } else if (mg_inet_pton(AF_INET6,
  10515. vec->ptr,
  10516. &so->lsa.sin6,
  10517. sizeof(so->lsa.sin6))) {
  10518. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  10519. *ip_version = 6;
  10520. so->lsa.sin6.sin6_family = AF_INET6;
  10521. so->lsa.sin.sin_port = htons((uint16_t)port);
  10522. len += (int)(cb - vec->ptr) + 1;
  10523. } else {
  10524. port = 0;
  10525. len = 0;
  10526. }
  10527. #endif
  10528. }
  10529. *cb = ':';
  10530. } else {
  10531. /* Parsing failure. */
  10532. }
  10533. /* sscanf and the option splitting code ensure the following condition
  10534. */
  10535. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  10536. *ip_version = 0;
  10537. return 0;
  10538. }
  10539. ch = vec->ptr[len]; /* Next character after the port number */
  10540. so->is_ssl = (ch == 's');
  10541. so->ssl_redir = (ch == 'r');
  10542. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  10543. if (is_valid_port(port)
  10544. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  10545. return 1;
  10546. }
  10547. /* Reset ip_version to 0 of there is an error */
  10548. *ip_version = 0;
  10549. return 0;
  10550. }
  10551. static int
  10552. set_ports_option(struct mg_context *ctx)
  10553. {
  10554. const char *list;
  10555. int on = 1;
  10556. #if defined(USE_IPV6)
  10557. int off = 0;
  10558. #endif
  10559. struct vec vec;
  10560. struct socket so, *ptr;
  10561. struct pollfd *pfd;
  10562. union usa usa;
  10563. socklen_t len;
  10564. int ip_version;
  10565. int portsTotal = 0;
  10566. int portsOk = 0;
  10567. if (!ctx) {
  10568. return 0;
  10569. }
  10570. memset(&so, 0, sizeof(so));
  10571. memset(&usa, 0, sizeof(usa));
  10572. len = sizeof(usa);
  10573. list = ctx->config[LISTENING_PORTS];
  10574. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10575. portsTotal++;
  10576. if (!parse_port_string(&vec, &so, &ip_version)) {
  10577. mg_cry(fc(ctx),
  10578. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  10579. (int)vec.len,
  10580. vec.ptr,
  10581. portsTotal,
  10582. "[IP_ADDRESS:]PORT[s|r]");
  10583. continue;
  10584. }
  10585. #if !defined(NO_SSL)
  10586. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10587. mg_cry(fc(ctx),
  10588. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10589. "option set?",
  10590. portsTotal);
  10591. continue;
  10592. }
  10593. #endif
  10594. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10595. == INVALID_SOCKET) {
  10596. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10597. continue;
  10598. }
  10599. #ifdef _WIN32
  10600. /* Windows SO_REUSEADDR lets many procs binds to a
  10601. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10602. * if someone already has the socket -- DTL */
  10603. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10604. * Windows might need a few seconds before
  10605. * the same port can be used again in the
  10606. * same process, so a short Sleep may be
  10607. * required between mg_stop and mg_start.
  10608. */
  10609. if (setsockopt(so.sock,
  10610. SOL_SOCKET,
  10611. SO_EXCLUSIVEADDRUSE,
  10612. (SOCK_OPT_TYPE)&on,
  10613. sizeof(on)) != 0) {
  10614. /* Set reuse option, but don't abort on errors. */
  10615. mg_cry(fc(ctx),
  10616. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10617. portsTotal);
  10618. }
  10619. #else
  10620. if (setsockopt(so.sock,
  10621. SOL_SOCKET,
  10622. SO_REUSEADDR,
  10623. (SOCK_OPT_TYPE)&on,
  10624. sizeof(on)) != 0) {
  10625. /* Set reuse option, but don't abort on errors. */
  10626. mg_cry(fc(ctx),
  10627. "cannot set socket option SO_REUSEADDR (entry %i)",
  10628. portsTotal);
  10629. }
  10630. #endif
  10631. if (ip_version > 4) {
  10632. #if defined(USE_IPV6)
  10633. if (ip_version == 6) {
  10634. if (so.lsa.sa.sa_family == AF_INET6
  10635. && setsockopt(so.sock,
  10636. IPPROTO_IPV6,
  10637. IPV6_V6ONLY,
  10638. (void *)&off,
  10639. sizeof(off)) != 0) {
  10640. /* Set IPv6 only option, but don't abort on errors. */
  10641. mg_cry(fc(ctx),
  10642. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10643. portsTotal);
  10644. }
  10645. }
  10646. #else
  10647. mg_cry(fc(ctx), "IPv6 not available");
  10648. closesocket(so.sock);
  10649. so.sock = INVALID_SOCKET;
  10650. continue;
  10651. #endif
  10652. }
  10653. if (so.lsa.sa.sa_family == AF_INET) {
  10654. len = sizeof(so.lsa.sin);
  10655. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10656. mg_cry(fc(ctx),
  10657. "cannot bind to %.*s: %d (%s)",
  10658. (int)vec.len,
  10659. vec.ptr,
  10660. (int)ERRNO,
  10661. strerror(errno));
  10662. closesocket(so.sock);
  10663. so.sock = INVALID_SOCKET;
  10664. continue;
  10665. }
  10666. }
  10667. #if defined(USE_IPV6)
  10668. else if (so.lsa.sa.sa_family == AF_INET6) {
  10669. len = sizeof(so.lsa.sin6);
  10670. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10671. mg_cry(fc(ctx),
  10672. "cannot bind to IPv6 %.*s: %d (%s)",
  10673. (int)vec.len,
  10674. vec.ptr,
  10675. (int)ERRNO,
  10676. strerror(errno));
  10677. closesocket(so.sock);
  10678. so.sock = INVALID_SOCKET;
  10679. continue;
  10680. }
  10681. }
  10682. #endif
  10683. else {
  10684. mg_cry(fc(ctx),
  10685. "cannot bind: address family not supported (entry %i)",
  10686. portsTotal);
  10687. closesocket(so.sock);
  10688. so.sock = INVALID_SOCKET;
  10689. continue;
  10690. }
  10691. if (listen(so.sock, SOMAXCONN) != 0) {
  10692. mg_cry(fc(ctx),
  10693. "cannot listen to %.*s: %d (%s)",
  10694. (int)vec.len,
  10695. vec.ptr,
  10696. (int)ERRNO,
  10697. strerror(errno));
  10698. closesocket(so.sock);
  10699. so.sock = INVALID_SOCKET;
  10700. continue;
  10701. }
  10702. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  10703. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  10704. int err = (int)ERRNO;
  10705. mg_cry(fc(ctx),
  10706. "call to getsockname failed %.*s: %d (%s)",
  10707. (int)vec.len,
  10708. vec.ptr,
  10709. err,
  10710. strerror(errno));
  10711. closesocket(so.sock);
  10712. so.sock = INVALID_SOCKET;
  10713. continue;
  10714. }
  10715. /* Update lsa port in case of random free ports */
  10716. #if defined(USE_IPV6)
  10717. if (so.lsa.sa.sa_family == AF_INET6) {
  10718. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10719. } else
  10720. #endif
  10721. {
  10722. so.lsa.sin.sin_port = usa.sin.sin_port;
  10723. }
  10724. if ((ptr = (struct socket *)
  10725. mg_realloc_ctx(ctx->listening_sockets,
  10726. (ctx->num_listening_sockets + 1)
  10727. * sizeof(ctx->listening_sockets[0]),
  10728. ctx)) == NULL) {
  10729. mg_cry(fc(ctx), "%s", "Out of memory");
  10730. closesocket(so.sock);
  10731. so.sock = INVALID_SOCKET;
  10732. continue;
  10733. }
  10734. if ((pfd = (struct pollfd *)
  10735. mg_realloc_ctx(ctx->listening_socket_fds,
  10736. (ctx->num_listening_sockets + 1)
  10737. * sizeof(ctx->listening_socket_fds[0]),
  10738. ctx)) == NULL) {
  10739. mg_cry(fc(ctx), "%s", "Out of memory");
  10740. closesocket(so.sock);
  10741. so.sock = INVALID_SOCKET;
  10742. mg_free(ptr);
  10743. continue;
  10744. }
  10745. set_close_on_exec(so.sock, fc(ctx));
  10746. ctx->listening_sockets = ptr;
  10747. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10748. ctx->listening_socket_fds = pfd;
  10749. ctx->num_listening_sockets++;
  10750. portsOk++;
  10751. }
  10752. if (portsOk != portsTotal) {
  10753. close_all_listening_sockets(ctx);
  10754. portsOk = 0;
  10755. }
  10756. return portsOk;
  10757. }
  10758. static const char *
  10759. header_val(const struct mg_connection *conn, const char *header)
  10760. {
  10761. const char *header_value;
  10762. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10763. return "-";
  10764. } else {
  10765. return header_value;
  10766. }
  10767. }
  10768. static void
  10769. log_access(const struct mg_connection *conn)
  10770. {
  10771. const struct mg_request_info *ri;
  10772. struct mg_file fi;
  10773. char date[64], src_addr[IP_ADDR_STR_LEN];
  10774. struct tm *tm;
  10775. const char *referer;
  10776. const char *user_agent;
  10777. char buf[4096];
  10778. if (!conn || !conn->ctx) {
  10779. return;
  10780. }
  10781. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10782. if (mg_fopen(conn,
  10783. conn->ctx->config[ACCESS_LOG_FILE],
  10784. MG_FOPEN_MODE_APPEND,
  10785. &fi) == 0) {
  10786. fi.access.fp = NULL;
  10787. }
  10788. } else {
  10789. fi.access.fp = NULL;
  10790. }
  10791. /* Log is written to a file and/or a callback. If both are not set,
  10792. * executing the rest of the function is pointless. */
  10793. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10794. return;
  10795. }
  10796. tm = localtime(&conn->conn_birth_time);
  10797. if (tm != NULL) {
  10798. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10799. } else {
  10800. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10801. date[sizeof(date) - 1] = '\0';
  10802. }
  10803. ri = &conn->request_info;
  10804. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10805. referer = header_val(conn, "Referer");
  10806. user_agent = header_val(conn, "User-Agent");
  10807. mg_snprintf(conn,
  10808. NULL, /* Ignore truncation in access log */
  10809. buf,
  10810. sizeof(buf),
  10811. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10812. src_addr,
  10813. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10814. date,
  10815. ri->request_method ? ri->request_method : "-",
  10816. ri->request_uri ? ri->request_uri : "-",
  10817. ri->query_string ? "?" : "",
  10818. ri->query_string ? ri->query_string : "",
  10819. ri->http_version,
  10820. conn->status_code,
  10821. conn->num_bytes_sent,
  10822. referer,
  10823. user_agent);
  10824. if (conn->ctx->callbacks.log_access) {
  10825. conn->ctx->callbacks.log_access(conn, buf);
  10826. }
  10827. if (fi.access.fp) {
  10828. int ok = 1;
  10829. flockfile(fi.access.fp);
  10830. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10831. ok = 0;
  10832. }
  10833. if (fflush(fi.access.fp) != 0) {
  10834. ok = 0;
  10835. }
  10836. funlockfile(fi.access.fp);
  10837. if (mg_fclose(&fi.access) != 0) {
  10838. ok = 0;
  10839. }
  10840. if (!ok) {
  10841. mg_cry(conn,
  10842. "Error writing log file %s",
  10843. conn->ctx->config[ACCESS_LOG_FILE]);
  10844. }
  10845. }
  10846. }
  10847. /* Verify given socket address against the ACL.
  10848. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10849. */
  10850. static int
  10851. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10852. {
  10853. int allowed, flag;
  10854. uint32_t net, mask;
  10855. struct vec vec;
  10856. if (ctx) {
  10857. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10858. /* If any ACL is set, deny by default */
  10859. allowed = (list == NULL) ? '+' : '-';
  10860. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10861. flag = vec.ptr[0];
  10862. if ((flag != '+' && flag != '-')
  10863. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  10864. mg_cry(fc(ctx),
  10865. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10866. __func__);
  10867. return -1;
  10868. }
  10869. if (net == (remote_ip & mask)) {
  10870. allowed = flag;
  10871. }
  10872. }
  10873. return allowed == '+';
  10874. }
  10875. return -1;
  10876. }
  10877. #if !defined(_WIN32)
  10878. static int
  10879. set_uid_option(struct mg_context *ctx)
  10880. {
  10881. struct passwd *pw;
  10882. if (ctx) {
  10883. const char *uid = ctx->config[RUN_AS_USER];
  10884. int success = 0;
  10885. if (uid == NULL) {
  10886. success = 1;
  10887. } else {
  10888. if ((pw = getpwnam(uid)) == NULL) {
  10889. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10890. } else if (setgid(pw->pw_gid) == -1) {
  10891. mg_cry(fc(ctx),
  10892. "%s: setgid(%s): %s",
  10893. __func__,
  10894. uid,
  10895. strerror(errno));
  10896. } else if (setgroups(0, NULL)) {
  10897. mg_cry(fc(ctx),
  10898. "%s: setgroups(): %s",
  10899. __func__,
  10900. strerror(errno));
  10901. } else if (setuid(pw->pw_uid) == -1) {
  10902. mg_cry(fc(ctx),
  10903. "%s: setuid(%s): %s",
  10904. __func__,
  10905. uid,
  10906. strerror(errno));
  10907. } else {
  10908. success = 1;
  10909. }
  10910. }
  10911. return success;
  10912. }
  10913. return 0;
  10914. }
  10915. #endif /* !_WIN32 */
  10916. static void
  10917. tls_dtor(void *key)
  10918. {
  10919. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10920. /* key == pthread_getspecific(sTlsKey); */
  10921. if (tls) {
  10922. if (tls->is_master == 2) {
  10923. tls->is_master = -3; /* Mark memory as dead */
  10924. mg_free(tls);
  10925. }
  10926. }
  10927. pthread_setspecific(sTlsKey, NULL);
  10928. }
  10929. #if !defined(NO_SSL)
  10930. static int
  10931. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  10932. static const char *ssl_error(void);
  10933. static int
  10934. refresh_trust(struct mg_connection *conn)
  10935. {
  10936. static int reload_lock = 0;
  10937. static long int data_check = 0;
  10938. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10939. struct stat cert_buf;
  10940. long int t;
  10941. const char *pem;
  10942. const char *chain;
  10943. int should_verify_peer;
  10944. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10945. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10946. * refresh_trust still can not work. */
  10947. return 0;
  10948. }
  10949. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  10950. if (chain == NULL) {
  10951. chain = pem;
  10952. }
  10953. if ((chain != NULL) && (*chain == 0)) {
  10954. chain = NULL;
  10955. }
  10956. t = data_check;
  10957. if (stat(pem, &cert_buf) != -1) {
  10958. t = (long int)cert_buf.st_mtime;
  10959. }
  10960. if (data_check != t) {
  10961. data_check = t;
  10962. should_verify_peer = 0;
  10963. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  10964. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10965. == 0) {
  10966. should_verify_peer = 1;
  10967. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  10968. "optional") == 0) {
  10969. should_verify_peer = 1;
  10970. }
  10971. }
  10972. if (should_verify_peer) {
  10973. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10974. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10975. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10976. ca_file,
  10977. ca_path) != 1) {
  10978. mg_cry(fc(conn->ctx),
  10979. "SSL_CTX_load_verify_locations error: %s "
  10980. "ssl_verify_peer requires setting "
  10981. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10982. "present in "
  10983. "the .conf file?",
  10984. ssl_error());
  10985. return 0;
  10986. }
  10987. }
  10988. if (1 == mg_atomic_inc(p_reload_lock)) {
  10989. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  10990. return 0;
  10991. }
  10992. *p_reload_lock = 0;
  10993. }
  10994. }
  10995. /* lock while cert is reloading */
  10996. while (*p_reload_lock) {
  10997. sleep(1);
  10998. }
  10999. return 1;
  11000. }
  11001. #ifdef OPENSSL_API_1_1
  11002. #else
  11003. static pthread_mutex_t *ssl_mutexes;
  11004. #endif /* OPENSSL_API_1_1 */
  11005. static int
  11006. sslize(struct mg_connection *conn,
  11007. SSL_CTX *s,
  11008. int (*func)(SSL *),
  11009. volatile int *stop_server)
  11010. {
  11011. int ret, err;
  11012. int short_trust;
  11013. unsigned i;
  11014. if (!conn) {
  11015. return 0;
  11016. }
  11017. short_trust =
  11018. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  11019. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  11020. if (short_trust) {
  11021. int trust_ret = refresh_trust(conn);
  11022. if (!trust_ret) {
  11023. return trust_ret;
  11024. }
  11025. }
  11026. conn->ssl = SSL_new(s);
  11027. if (conn->ssl == NULL) {
  11028. return 0;
  11029. }
  11030. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  11031. if (ret != 1) {
  11032. err = SSL_get_error(conn->ssl, ret);
  11033. (void)err; /* TODO: set some error message */
  11034. SSL_free(conn->ssl);
  11035. conn->ssl = NULL;
  11036. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11037. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11038. #ifndef OPENSSL_API_1_1
  11039. ERR_remove_state(0);
  11040. #endif
  11041. return 0;
  11042. }
  11043. /* SSL functions may fail and require to be called again:
  11044. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  11045. * Here "func" could be SSL_connect or SSL_accept. */
  11046. for (i = 16; i <= 1024; i *= 2) {
  11047. ret = func(conn->ssl);
  11048. if (ret != 1) {
  11049. err = SSL_get_error(conn->ssl, ret);
  11050. if ((err == SSL_ERROR_WANT_CONNECT)
  11051. || (err == SSL_ERROR_WANT_ACCEPT)
  11052. || (err == SSL_ERROR_WANT_READ)
  11053. || (err == SSL_ERROR_WANT_WRITE)) {
  11054. /* Need to retry the function call "later".
  11055. * See https://linux.die.net/man/3/ssl_get_error
  11056. * This is typical for non-blocking sockets. */
  11057. if (*stop_server) {
  11058. /* Don't wait if the server is going to be stopped. */
  11059. break;
  11060. }
  11061. mg_sleep(i);
  11062. } else if (err == SSL_ERROR_SYSCALL) {
  11063. /* This is an IO error. Look at errno. */
  11064. err = errno;
  11065. /* TODO: set some error message */
  11066. (void)err;
  11067. break;
  11068. } else {
  11069. /* This is an SSL specific error */
  11070. /* TODO: set some error message */
  11071. break;
  11072. }
  11073. } else {
  11074. /* success */
  11075. break;
  11076. }
  11077. }
  11078. if (ret != 1) {
  11079. SSL_free(conn->ssl);
  11080. conn->ssl = NULL;
  11081. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11082. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11083. #ifndef OPENSSL_API_1_1
  11084. ERR_remove_state(0);
  11085. #endif
  11086. return 0;
  11087. }
  11088. return 1;
  11089. }
  11090. /* Return OpenSSL error message (from CRYPTO lib) */
  11091. static const char *
  11092. ssl_error(void)
  11093. {
  11094. unsigned long err;
  11095. err = ERR_get_error();
  11096. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  11097. }
  11098. static int
  11099. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  11100. {
  11101. int i;
  11102. const char hexdigit[] = "0123456789abcdef";
  11103. if ((memlen <= 0) || (buflen <= 0)) {
  11104. return 0;
  11105. }
  11106. if (buflen < (3 * memlen)) {
  11107. return 0;
  11108. }
  11109. for (i = 0; i < memlen; i++) {
  11110. if (i > 0) {
  11111. buf[3 * i - 1] = ' ';
  11112. }
  11113. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  11114. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  11115. }
  11116. buf[3 * memlen - 1] = 0;
  11117. return 1;
  11118. }
  11119. static void
  11120. ssl_get_client_cert_info(struct mg_connection *conn)
  11121. {
  11122. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  11123. if (cert) {
  11124. char str_subject[1024];
  11125. char str_issuer[1024];
  11126. char str_finger[1024];
  11127. unsigned char buf[256];
  11128. char *str_serial = NULL;
  11129. unsigned int ulen;
  11130. int ilen;
  11131. unsigned char *tmp_buf;
  11132. unsigned char *tmp_p;
  11133. /* Handle to algorithm used for fingerprint */
  11134. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  11135. /* Get Subject and issuer */
  11136. X509_NAME *subj = X509_get_subject_name(cert);
  11137. X509_NAME *iss = X509_get_issuer_name(cert);
  11138. /* Get serial number */
  11139. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  11140. /* Translate serial number to a hex string */
  11141. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  11142. str_serial = BN_bn2hex(serial_bn);
  11143. BN_free(serial_bn);
  11144. /* Translate subject and issuer to a string */
  11145. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  11146. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  11147. /* Calculate SHA1 fingerprint and store as a hex string */
  11148. ulen = 0;
  11149. /* ASN1_digest is deprecated. Do the calculation manually,
  11150. * using EVP_Digest. */
  11151. ilen = i2d_X509((void *)cert, NULL);
  11152. tmp_buf =
  11153. (ilen > 0)
  11154. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  11155. : NULL;
  11156. if (tmp_buf) {
  11157. tmp_p = tmp_buf;
  11158. (void)i2d_X509((void *)cert, &tmp_p);
  11159. if (!EVP_Digest(
  11160. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  11161. ulen = 0;
  11162. }
  11163. mg_free(tmp_buf);
  11164. }
  11165. if (!hexdump2string(
  11166. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  11167. *str_finger = 0;
  11168. }
  11169. conn->request_info.client_cert =
  11170. (struct client_cert *)mg_malloc_ctx(sizeof(struct client_cert),
  11171. conn->ctx);
  11172. if (conn->request_info.client_cert) {
  11173. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  11174. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  11175. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  11176. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  11177. } else {
  11178. /* TODO: write some OOM message */
  11179. }
  11180. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  11181. * see https://linux.die.net/man/3/bn_bn2hex */
  11182. OPENSSL_free(str_serial);
  11183. /* Free certificate memory */
  11184. X509_free(cert);
  11185. }
  11186. }
  11187. #ifdef OPENSSL_API_1_1
  11188. #else
  11189. static void
  11190. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  11191. {
  11192. (void)line;
  11193. (void)file;
  11194. if (mode & 1) {
  11195. /* 1 is CRYPTO_LOCK */
  11196. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  11197. } else {
  11198. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  11199. }
  11200. }
  11201. #endif /* OPENSSL_API_1_1 */
  11202. #if !defined(NO_SSL_DL)
  11203. static void *
  11204. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  11205. {
  11206. union {
  11207. void *p;
  11208. void (*fp)(void);
  11209. } u;
  11210. void *dll_handle;
  11211. struct ssl_func *fp;
  11212. int ok;
  11213. int truncated = 0;
  11214. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  11215. mg_snprintf(NULL,
  11216. NULL, /* No truncation check for ebuf */
  11217. ebuf,
  11218. ebuf_len,
  11219. "%s: cannot load %s",
  11220. __func__,
  11221. dll_name);
  11222. return NULL;
  11223. }
  11224. ok = 1;
  11225. for (fp = sw; fp->name != NULL; fp++) {
  11226. #ifdef _WIN32
  11227. /* GetProcAddress() returns pointer to function */
  11228. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  11229. #else
  11230. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  11231. * pointers to function pointers. We need to use a union to make a
  11232. * cast. */
  11233. u.p = dlsym(dll_handle, fp->name);
  11234. #endif /* _WIN32 */
  11235. if (u.fp == NULL) {
  11236. if (ok) {
  11237. mg_snprintf(NULL,
  11238. &truncated,
  11239. ebuf,
  11240. ebuf_len,
  11241. "%s: %s: cannot find %s",
  11242. __func__,
  11243. dll_name,
  11244. fp->name);
  11245. ok = 0;
  11246. } else {
  11247. size_t cur_len = strlen(ebuf);
  11248. if (!truncated) {
  11249. mg_snprintf(NULL,
  11250. &truncated,
  11251. ebuf + cur_len,
  11252. ebuf_len - cur_len - 3,
  11253. ", %s",
  11254. fp->name);
  11255. if (truncated) {
  11256. /* If truncated, add "..." */
  11257. strcat(ebuf, "...");
  11258. }
  11259. }
  11260. }
  11261. /* Debug:
  11262. * printf("Missing function: %s\n", fp->name); */
  11263. } else {
  11264. fp->ptr = u.fp;
  11265. }
  11266. }
  11267. if (!ok) {
  11268. (void)dlclose(dll_handle);
  11269. return NULL;
  11270. }
  11271. return dll_handle;
  11272. }
  11273. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  11274. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  11275. #endif /* NO_SSL_DL */
  11276. #if defined(SSL_ALREADY_INITIALIZED)
  11277. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  11278. #else
  11279. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  11280. #endif
  11281. static int
  11282. initialize_ssl(char *ebuf, size_t ebuf_len)
  11283. {
  11284. #ifdef OPENSSL_API_1_1
  11285. if (ebuf_len > 0) {
  11286. ebuf[0] = 0;
  11287. }
  11288. #if !defined(NO_SSL_DL)
  11289. if (!cryptolib_dll_handle) {
  11290. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11291. if (!cryptolib_dll_handle) {
  11292. return 0;
  11293. }
  11294. }
  11295. #endif /* NO_SSL_DL */
  11296. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11297. return 1;
  11298. }
  11299. #else /* not OPENSSL_API_1_1 */
  11300. int i;
  11301. size_t size;
  11302. if (ebuf_len > 0) {
  11303. ebuf[0] = 0;
  11304. }
  11305. #if !defined(NO_SSL_DL)
  11306. if (!cryptolib_dll_handle) {
  11307. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11308. if (!cryptolib_dll_handle) {
  11309. return 0;
  11310. }
  11311. }
  11312. #endif /* NO_SSL_DL */
  11313. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11314. return 1;
  11315. }
  11316. /* Initialize locking callbacks, needed for thread safety.
  11317. * http://www.openssl.org/support/faq.html#PROG1
  11318. */
  11319. i = CRYPTO_num_locks();
  11320. if (i < 0) {
  11321. i = 0;
  11322. }
  11323. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  11324. if (size == 0) {
  11325. ssl_mutexes = NULL;
  11326. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  11327. mg_snprintf(NULL,
  11328. NULL, /* No truncation check for ebuf */
  11329. ebuf,
  11330. ebuf_len,
  11331. "%s: cannot allocate mutexes: %s",
  11332. __func__,
  11333. ssl_error());
  11334. return 0;
  11335. }
  11336. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11337. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  11338. }
  11339. CRYPTO_set_locking_callback(&ssl_locking_callback);
  11340. CRYPTO_set_id_callback(&mg_current_thread_id);
  11341. #endif /* OPENSSL_API_1_1 */
  11342. return 1;
  11343. }
  11344. static int
  11345. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  11346. {
  11347. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  11348. mg_cry(fc(ctx),
  11349. "%s: cannot open certificate file %s: %s",
  11350. __func__,
  11351. pem,
  11352. ssl_error());
  11353. return 0;
  11354. }
  11355. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  11356. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  11357. mg_cry(fc(ctx),
  11358. "%s: cannot open private key file %s: %s",
  11359. __func__,
  11360. pem,
  11361. ssl_error());
  11362. return 0;
  11363. }
  11364. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  11365. mg_cry(fc(ctx),
  11366. "%s: certificate and private key do not match: %s",
  11367. __func__,
  11368. pem);
  11369. return 0;
  11370. }
  11371. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11372. * chain files that contain private keys and certificates in
  11373. * SSL_CTX_use_certificate_chain_file.
  11374. * The CivetWeb-Server used pem-Files that contained both information.
  11375. * In order to make wolfSSL work, it is split in two files.
  11376. * One file that contains key and certificate used by the server and
  11377. * an optional chain file for the ssl stack.
  11378. */
  11379. if (chain) {
  11380. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11381. mg_cry(fc(ctx),
  11382. "%s: cannot use certificate chain file %s: %s",
  11383. __func__,
  11384. pem,
  11385. ssl_error());
  11386. return 0;
  11387. }
  11388. }
  11389. return 1;
  11390. }
  11391. #ifdef OPENSSL_API_1_1
  11392. static unsigned long
  11393. ssl_get_protocol(int version_id)
  11394. {
  11395. long unsigned ret = SSL_OP_ALL;
  11396. if (version_id > 0)
  11397. ret |= SSL_OP_NO_SSLv2;
  11398. if (version_id > 1)
  11399. ret |= SSL_OP_NO_SSLv3;
  11400. if (version_id > 2)
  11401. ret |= SSL_OP_NO_TLSv1;
  11402. if (version_id > 3)
  11403. ret |= SSL_OP_NO_TLSv1_1;
  11404. return ret;
  11405. }
  11406. #else
  11407. static long
  11408. ssl_get_protocol(int version_id)
  11409. {
  11410. long ret = SSL_OP_ALL;
  11411. if (version_id > 0)
  11412. ret |= SSL_OP_NO_SSLv2;
  11413. if (version_id > 1)
  11414. ret |= SSL_OP_NO_SSLv3;
  11415. if (version_id > 2)
  11416. ret |= SSL_OP_NO_TLSv1;
  11417. if (version_id > 3)
  11418. ret |= SSL_OP_NO_TLSv1_1;
  11419. return ret;
  11420. }
  11421. #endif /* OPENSSL_API_1_1 */
  11422. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11423. static int
  11424. set_ssl_option(struct mg_context *ctx)
  11425. {
  11426. const char *pem;
  11427. const char *chain;
  11428. int callback_ret;
  11429. int should_verify_peer;
  11430. int peer_certificate_optional;
  11431. const char *ca_path;
  11432. const char *ca_file;
  11433. int use_default_verify_paths;
  11434. int verify_depth;
  11435. time_t now_rt = time(NULL);
  11436. struct timespec now_mt;
  11437. md5_byte_t ssl_context_id[16];
  11438. md5_state_t md5state;
  11439. int protocol_ver;
  11440. char ebuf[128];
  11441. /* If PEM file is not specified and the init_ssl callback
  11442. * is not specified, skip SSL initialization. */
  11443. if (!ctx) {
  11444. return 0;
  11445. }
  11446. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11447. && ctx->callbacks.init_ssl == NULL) {
  11448. return 1;
  11449. }
  11450. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11451. if (chain == NULL) {
  11452. chain = pem;
  11453. }
  11454. if ((chain != NULL) && (*chain == 0)) {
  11455. chain = NULL;
  11456. }
  11457. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11458. mg_cry(fc(ctx), "%s", ebuf);
  11459. return 0;
  11460. }
  11461. #if !defined(NO_SSL_DL)
  11462. if (!ssllib_dll_handle) {
  11463. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11464. if (!ssllib_dll_handle) {
  11465. mg_cry(fc(ctx), "%s", ebuf);
  11466. return 0;
  11467. }
  11468. }
  11469. #endif /* NO_SSL_DL */
  11470. #ifdef OPENSSL_API_1_1
  11471. /* Initialize SSL library */
  11472. OPENSSL_init_ssl(0, NULL);
  11473. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11474. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11475. NULL);
  11476. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11477. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11478. return 0;
  11479. }
  11480. #else
  11481. /* Initialize SSL library */
  11482. SSL_library_init();
  11483. SSL_load_error_strings();
  11484. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11485. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11486. return 0;
  11487. }
  11488. #endif /* OPENSSL_API_1_1 */
  11489. SSL_CTX_clear_options(ctx->ssl_ctx,
  11490. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11491. | SSL_OP_NO_TLSv1_1);
  11492. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11493. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11494. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11495. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11496. #if !defined(NO_SSL_DL)
  11497. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11498. #endif /* NO_SSL_DL */
  11499. /* If a callback has been specified, call it. */
  11500. callback_ret =
  11501. (ctx->callbacks.init_ssl == NULL)
  11502. ? 0
  11503. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11504. /* If callback returns 0, civetweb sets up the SSL certificate.
  11505. * If it returns 1, civetweb assumes the calback already did this.
  11506. * If it returns -1, initializing ssl fails. */
  11507. if (callback_ret < 0) {
  11508. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11509. return 0;
  11510. }
  11511. if (callback_ret > 0) {
  11512. if (pem != NULL) {
  11513. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11514. }
  11515. return 1;
  11516. }
  11517. /* Use some UID as session context ID. */
  11518. md5_init(&md5state);
  11519. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  11520. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  11521. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  11522. md5_append(&md5state,
  11523. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  11524. strlen(ctx->config[LISTENING_PORTS]));
  11525. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  11526. md5_finish(&md5state, ssl_context_id);
  11527. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  11528. (const unsigned char *)&ssl_context_id,
  11529. sizeof(ssl_context_id));
  11530. if (pem != NULL) {
  11531. if (!ssl_use_pem_file(ctx, pem, chain)) {
  11532. return 0;
  11533. }
  11534. }
  11535. /* Should we support client certificates? */
  11536. /* Default is "no". */
  11537. should_verify_peer = 0;
  11538. peer_certificate_optional = 0;
  11539. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11540. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  11541. /* Yes, they are mandatory */
  11542. should_verify_peer = 1;
  11543. peer_certificate_optional = 0;
  11544. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  11545. == 0) {
  11546. /* Yes, they are optional */
  11547. should_verify_peer = 1;
  11548. peer_certificate_optional = 1;
  11549. }
  11550. }
  11551. use_default_verify_paths =
  11552. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  11553. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  11554. if (should_verify_peer) {
  11555. ca_path = ctx->config[SSL_CA_PATH];
  11556. ca_file = ctx->config[SSL_CA_FILE];
  11557. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  11558. != 1) {
  11559. mg_cry(fc(ctx),
  11560. "SSL_CTX_load_verify_locations error: %s "
  11561. "ssl_verify_peer requires setting "
  11562. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11563. "present in "
  11564. "the .conf file?",
  11565. ssl_error());
  11566. return 0;
  11567. }
  11568. if (peer_certificate_optional) {
  11569. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  11570. } else {
  11571. SSL_CTX_set_verify(ctx->ssl_ctx,
  11572. SSL_VERIFY_PEER
  11573. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11574. NULL);
  11575. }
  11576. if (use_default_verify_paths
  11577. && (SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1)) {
  11578. mg_cry(fc(ctx),
  11579. "SSL_CTX_set_default_verify_paths error: %s",
  11580. ssl_error());
  11581. return 0;
  11582. }
  11583. if (ctx->config[SSL_VERIFY_DEPTH]) {
  11584. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  11585. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  11586. }
  11587. }
  11588. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  11589. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  11590. != 1) {
  11591. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  11592. }
  11593. }
  11594. return 1;
  11595. }
  11596. static void
  11597. uninitialize_ssl(void)
  11598. {
  11599. #ifdef OPENSSL_API_1_1
  11600. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11601. /* Shutdown according to
  11602. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11603. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11604. */
  11605. CONF_modules_unload(1);
  11606. #else
  11607. int i;
  11608. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11609. /* Shutdown according to
  11610. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11611. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11612. */
  11613. CRYPTO_set_locking_callback(NULL);
  11614. CRYPTO_set_id_callback(NULL);
  11615. ENGINE_cleanup();
  11616. CONF_modules_unload(1);
  11617. ERR_free_strings();
  11618. EVP_cleanup();
  11619. CRYPTO_cleanup_all_ex_data();
  11620. ERR_remove_state(0);
  11621. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11622. pthread_mutex_destroy(&ssl_mutexes[i]);
  11623. }
  11624. mg_free(ssl_mutexes);
  11625. ssl_mutexes = NULL;
  11626. #endif /* OPENSSL_API_1_1 */
  11627. }
  11628. }
  11629. #endif /* !NO_SSL */
  11630. static int
  11631. set_gpass_option(struct mg_context *ctx)
  11632. {
  11633. if (ctx) {
  11634. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11635. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  11636. if ((path != NULL) && !mg_stat(fc(ctx), path, &file.stat)) {
  11637. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  11638. return 0;
  11639. }
  11640. return 1;
  11641. }
  11642. return 0;
  11643. }
  11644. static int
  11645. set_acl_option(struct mg_context *ctx)
  11646. {
  11647. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  11648. }
  11649. static void
  11650. reset_per_request_attributes(struct mg_connection *conn)
  11651. {
  11652. if (!conn) {
  11653. return;
  11654. }
  11655. conn->path_info = NULL;
  11656. conn->num_bytes_sent = conn->consumed_content = 0;
  11657. conn->status_code = -1;
  11658. conn->is_chunked = 0;
  11659. conn->must_close = conn->request_len = conn->throttle = 0;
  11660. conn->request_info.content_length = -1;
  11661. conn->request_info.remote_user = NULL;
  11662. conn->request_info.request_method = NULL;
  11663. conn->request_info.request_uri = NULL;
  11664. conn->request_info.local_uri = NULL;
  11665. #if defined(MG_LEGACY_INTERFACE)
  11666. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  11667. * local_uri and request_uri */
  11668. #endif
  11669. conn->request_info.http_version = NULL;
  11670. conn->request_info.num_headers = 0;
  11671. conn->data_len = 0;
  11672. conn->chunk_remainder = 0;
  11673. }
  11674. #if 0
  11675. /* Note: set_sock_timeout is not required for non-blocking sockets.
  11676. * Leave this function here (commented out) for reference until
  11677. * CivetWeb 1.9 is tested, and the tests confirme this function is
  11678. * no longer required.
  11679. */
  11680. static int
  11681. set_sock_timeout(SOCKET sock, int milliseconds)
  11682. {
  11683. int r0 = 0, r1, r2;
  11684. #ifdef _WIN32
  11685. /* Windows specific */
  11686. DWORD tv = (DWORD)milliseconds;
  11687. #else
  11688. /* Linux, ... (not Windows) */
  11689. struct timeval tv;
  11690. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  11691. * max. time waiting for the acknowledged of TCP data before the connection
  11692. * will be forcefully closed and ETIMEDOUT is returned to the application.
  11693. * If this option is not set, the default timeout of 20-30 minutes is used.
  11694. */
  11695. /* #define TCP_USER_TIMEOUT (18) */
  11696. #if defined(TCP_USER_TIMEOUT)
  11697. unsigned int uto = (unsigned int)milliseconds;
  11698. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  11699. #endif
  11700. memset(&tv, 0, sizeof(tv));
  11701. tv.tv_sec = milliseconds / 1000;
  11702. tv.tv_usec = (milliseconds * 1000) % 1000000;
  11703. #endif /* _WIN32 */
  11704. r1 = setsockopt(
  11705. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11706. r2 = setsockopt(
  11707. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11708. return r0 || r1 || r2;
  11709. }
  11710. #endif
  11711. static int
  11712. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11713. {
  11714. if (setsockopt(sock,
  11715. IPPROTO_TCP,
  11716. TCP_NODELAY,
  11717. (SOCK_OPT_TYPE)&nodelay_on,
  11718. sizeof(nodelay_on)) != 0) {
  11719. /* Error */
  11720. return 1;
  11721. }
  11722. /* OK */
  11723. return 0;
  11724. }
  11725. static void
  11726. close_socket_gracefully(struct mg_connection *conn)
  11727. {
  11728. #if defined(_WIN32)
  11729. char buf[MG_BUF_LEN];
  11730. int n;
  11731. #endif
  11732. struct linger linger;
  11733. int error_code = 0;
  11734. int linger_timeout = -2;
  11735. socklen_t opt_len = sizeof(error_code);
  11736. if (!conn) {
  11737. return;
  11738. }
  11739. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  11740. * "Note that enabling a nonzero timeout on a nonblocking socket
  11741. * is not recommended.", so set it to blocking now */
  11742. set_blocking_mode(conn->client.sock, 1);
  11743. /* Send FIN to the client */
  11744. shutdown(conn->client.sock, SHUTDOWN_WR);
  11745. #if defined(_WIN32)
  11746. /* Read and discard pending incoming data. If we do not do that and
  11747. * close
  11748. * the socket, the data in the send buffer may be discarded. This
  11749. * behaviour is seen on Windows, when client keeps sending data
  11750. * when server decides to close the connection; then when client
  11751. * does recv() it gets no data back. */
  11752. do {
  11753. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  11754. } while (n > 0);
  11755. #endif
  11756. if (conn->ctx->config[LINGER_TIMEOUT]) {
  11757. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  11758. }
  11759. /* Set linger option according to configuration */
  11760. if (linger_timeout >= 0) {
  11761. /* Set linger option to avoid socket hanging out after close. This
  11762. * prevent ephemeral port exhaust problem under high QPS. */
  11763. linger.l_onoff = 1;
  11764. #if defined(_MSC_VER)
  11765. #pragma warning(push)
  11766. #pragma warning(disable : 4244)
  11767. #endif
  11768. linger.l_linger = (linger_timeout + 999) / 1000;
  11769. #if defined(_MSC_VER)
  11770. #pragma warning(pop)
  11771. #endif
  11772. } else {
  11773. linger.l_onoff = 0;
  11774. linger.l_linger = 0;
  11775. }
  11776. if (linger_timeout < -1) {
  11777. /* Default: don't configure any linger */
  11778. } else if (getsockopt(conn->client.sock,
  11779. SOL_SOCKET,
  11780. SO_ERROR,
  11781. (char *)&error_code,
  11782. &opt_len) != 0) {
  11783. /* Cannot determine if socket is already closed. This should
  11784. * not occur and never did in a test. Log an error message
  11785. * and continue. */
  11786. mg_cry(conn,
  11787. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  11788. __func__,
  11789. strerror(ERRNO));
  11790. } else if (error_code == ECONNRESET) {
  11791. /* Socket already closed by client/peer, close socket without linger */
  11792. } else {
  11793. /* Set linger timeout */
  11794. if (setsockopt(conn->client.sock,
  11795. SOL_SOCKET,
  11796. SO_LINGER,
  11797. (char *)&linger,
  11798. sizeof(linger)) != 0) {
  11799. mg_cry(conn,
  11800. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  11801. __func__,
  11802. linger.l_onoff,
  11803. linger.l_linger,
  11804. strerror(ERRNO));
  11805. }
  11806. }
  11807. /* Now we know that our FIN is ACK-ed, safe to close */
  11808. closesocket(conn->client.sock);
  11809. conn->client.sock = INVALID_SOCKET;
  11810. }
  11811. static void
  11812. close_connection(struct mg_connection *conn)
  11813. {
  11814. if (!conn || !conn->ctx) {
  11815. return;
  11816. }
  11817. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11818. if (conn->lua_websocket_state) {
  11819. lua_websocket_close(conn, conn->lua_websocket_state);
  11820. conn->lua_websocket_state = NULL;
  11821. }
  11822. #endif
  11823. /* call the connection_close callback if assigned */
  11824. if ((conn->ctx->callbacks.connection_close != NULL)
  11825. && (conn->ctx->context_type == 1)) {
  11826. conn->ctx->callbacks.connection_close(conn);
  11827. }
  11828. mg_lock_connection(conn);
  11829. conn->must_close = 1;
  11830. #ifndef NO_SSL
  11831. if (conn->ssl != NULL) {
  11832. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11833. */
  11834. SSL_shutdown(conn->ssl);
  11835. SSL_free(conn->ssl);
  11836. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11837. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11838. #ifndef OPENSSL_API_1_1
  11839. ERR_remove_state(0);
  11840. #endif
  11841. conn->ssl = NULL;
  11842. }
  11843. #endif
  11844. if (conn->client.sock != INVALID_SOCKET) {
  11845. close_socket_gracefully(conn);
  11846. conn->client.sock = INVALID_SOCKET;
  11847. }
  11848. mg_unlock_connection(conn);
  11849. }
  11850. void
  11851. mg_close_connection(struct mg_connection *conn)
  11852. {
  11853. #if defined(USE_WEBSOCKET)
  11854. struct mg_context *client_ctx = NULL;
  11855. #endif /* defined(USE_WEBSOCKET) */
  11856. if (conn == NULL) {
  11857. return;
  11858. }
  11859. #if defined(USE_WEBSOCKET)
  11860. if (conn->ctx->context_type == 2) {
  11861. unsigned int i;
  11862. /* ws/wss client */
  11863. client_ctx = conn->ctx;
  11864. /* client context: loops must end */
  11865. conn->ctx->stop_flag = 1;
  11866. /* We need to get the client thread out of the select/recv call here. */
  11867. /* Since we use a sleep quantum of some seconds to check for recv
  11868. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11869. /* join worker thread */
  11870. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11871. if (client_ctx->worker_threadids[i] != 0) {
  11872. mg_join_thread(client_ctx->worker_threadids[i]);
  11873. }
  11874. }
  11875. }
  11876. #endif /* defined(USE_WEBSOCKET) */
  11877. close_connection(conn);
  11878. #ifndef NO_SSL
  11879. if (conn->client_ssl_ctx != NULL) {
  11880. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11881. }
  11882. #endif
  11883. #if defined(USE_WEBSOCKET)
  11884. if (client_ctx != NULL) {
  11885. /* free context */
  11886. mg_free(client_ctx->worker_threadids);
  11887. mg_free(client_ctx);
  11888. (void)pthread_mutex_destroy(&conn->mutex);
  11889. mg_free(conn);
  11890. } else if (conn->ctx->context_type == 0) { /* Client */
  11891. mg_free(conn);
  11892. }
  11893. #else
  11894. if (conn->ctx->context_type == 0) { /* Client */
  11895. mg_free(conn);
  11896. }
  11897. #endif /* defined(USE_WEBSOCKET) */
  11898. }
  11899. static struct mg_context common_client_context;
  11900. static struct mg_connection *
  11901. mg_connect_client_impl(const struct mg_client_options *client_options,
  11902. int use_ssl,
  11903. char *ebuf,
  11904. size_t ebuf_len)
  11905. {
  11906. struct mg_connection *conn = NULL;
  11907. SOCKET sock;
  11908. union usa sa;
  11909. unsigned max_req_size =
  11910. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  11911. if (!connect_socket(&common_client_context,
  11912. client_options->host,
  11913. client_options->port,
  11914. use_ssl,
  11915. ebuf,
  11916. ebuf_len,
  11917. &sock,
  11918. &sa)) {
  11919. return NULL;
  11920. }
  11921. if ((conn = (struct mg_connection *)mg_calloc_ctx(
  11922. 1, sizeof(*conn) + max_req_size, &common_client_context))
  11923. == NULL) {
  11924. mg_snprintf(NULL,
  11925. NULL, /* No truncation check for ebuf */
  11926. ebuf,
  11927. ebuf_len,
  11928. "calloc(): %s",
  11929. strerror(ERRNO));
  11930. closesocket(sock);
  11931. return NULL;
  11932. }
  11933. #ifndef NO_SSL
  11934. #ifdef OPENSSL_API_1_1
  11935. if (use_ssl
  11936. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  11937. mg_snprintf(NULL,
  11938. NULL, /* No truncation check for ebuf */
  11939. ebuf,
  11940. ebuf_len,
  11941. "SSL_CTX_new error");
  11942. closesocket(sock);
  11943. mg_free(conn);
  11944. return NULL;
  11945. }
  11946. #else
  11947. if (use_ssl
  11948. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11949. == NULL) {
  11950. mg_snprintf(NULL,
  11951. NULL, /* No truncation check for ebuf */
  11952. ebuf,
  11953. ebuf_len,
  11954. "SSL_CTX_new error");
  11955. closesocket(sock);
  11956. mg_free(conn);
  11957. return NULL;
  11958. }
  11959. #endif /* OPENSSL_API_1_1 */
  11960. #endif /* NO_SSL */
  11961. #ifdef USE_IPV6
  11962. socklen_t len = (sa.sa.sa_family == AF_INET)
  11963. ? sizeof(conn->client.rsa.sin)
  11964. : sizeof(conn->client.rsa.sin6);
  11965. struct sockaddr *psa = (sa.sa.sa_family == AF_INET)
  11966. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11967. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11968. #else
  11969. socklen_t len = sizeof(conn->client.rsa.sin);
  11970. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11971. #endif
  11972. conn->buf_size = (int)max_req_size;
  11973. conn->buf = (char *)(conn + 1);
  11974. conn->ctx = &common_client_context;
  11975. conn->client.sock = sock;
  11976. conn->client.lsa = sa;
  11977. if (getsockname(sock, psa, &len) != 0) {
  11978. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  11979. }
  11980. conn->client.is_ssl = use_ssl ? 1 : 0;
  11981. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11982. #ifndef NO_SSL
  11983. if (use_ssl) {
  11984. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  11985. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11986. * SSL_CTX_set_verify call is needed to switch off server
  11987. * certificate checking, which is off by default in OpenSSL and
  11988. * on in yaSSL. */
  11989. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11990. * SSL_VERIFY_PEER, verify_ssl_server); */
  11991. if (client_options->client_cert) {
  11992. if (!ssl_use_pem_file(&common_client_context,
  11993. client_options->client_cert,
  11994. NULL)) {
  11995. mg_snprintf(NULL,
  11996. NULL, /* No truncation check for ebuf */
  11997. ebuf,
  11998. ebuf_len,
  11999. "Can not use SSL client certificate");
  12000. SSL_CTX_free(conn->client_ssl_ctx);
  12001. closesocket(sock);
  12002. mg_free(conn);
  12003. return NULL;
  12004. }
  12005. }
  12006. if (client_options->server_cert) {
  12007. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  12008. client_options->server_cert,
  12009. NULL);
  12010. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  12011. } else {
  12012. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  12013. }
  12014. if (!sslize(conn,
  12015. conn->client_ssl_ctx,
  12016. SSL_connect,
  12017. &(conn->ctx->stop_flag))) {
  12018. mg_snprintf(NULL,
  12019. NULL, /* No truncation check for ebuf */
  12020. ebuf,
  12021. ebuf_len,
  12022. "SSL connection error");
  12023. SSL_CTX_free(conn->client_ssl_ctx);
  12024. closesocket(sock);
  12025. mg_free(conn);
  12026. return NULL;
  12027. }
  12028. }
  12029. #endif
  12030. set_blocking_mode(sock, 0);
  12031. return conn;
  12032. }
  12033. CIVETWEB_API struct mg_connection *
  12034. mg_connect_client_secure(const struct mg_client_options *client_options,
  12035. char *error_buffer,
  12036. size_t error_buffer_size)
  12037. {
  12038. return mg_connect_client_impl(client_options,
  12039. 1,
  12040. error_buffer,
  12041. error_buffer_size);
  12042. }
  12043. struct mg_connection *
  12044. mg_connect_client(const char *host,
  12045. int port,
  12046. int use_ssl,
  12047. char *error_buffer,
  12048. size_t error_buffer_size)
  12049. {
  12050. struct mg_client_options opts;
  12051. memset(&opts, 0, sizeof(opts));
  12052. opts.host = host;
  12053. opts.port = port;
  12054. return mg_connect_client_impl(&opts,
  12055. use_ssl,
  12056. error_buffer,
  12057. error_buffer_size);
  12058. }
  12059. static const struct {
  12060. const char *proto;
  12061. size_t proto_len;
  12062. unsigned default_port;
  12063. } abs_uri_protocols[] = {{"http://", 7, 80},
  12064. {"https://", 8, 443},
  12065. {"ws://", 5, 80},
  12066. {"wss://", 6, 443},
  12067. {NULL, 0, 0}};
  12068. /* Check if the uri is valid.
  12069. * return 0 for invalid uri,
  12070. * return 1 for *,
  12071. * return 2 for relative uri,
  12072. * return 3 for absolute uri without port,
  12073. * return 4 for absolute uri with port */
  12074. static int
  12075. get_uri_type(const char *uri)
  12076. {
  12077. int i;
  12078. const char *hostend, *portbegin;
  12079. char *portend;
  12080. unsigned long port;
  12081. /* According to the HTTP standard
  12082. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  12083. * URI can be an asterisk (*) or should start with slash (relative uri),
  12084. * or it should start with the protocol (absolute uri). */
  12085. if ((uri[0] == '*') && (uri[1] == '\0')) {
  12086. /* asterisk */
  12087. return 1;
  12088. }
  12089. /* Valid URIs according to RFC 3986
  12090. * (https://www.ietf.org/rfc/rfc3986.txt)
  12091. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  12092. * and unreserved characters A-Z a-z 0-9 and -._~
  12093. * and % encoded symbols.
  12094. */
  12095. for (i = 0; uri[i] != 0; i++) {
  12096. if (uri[i] < 33) {
  12097. /* control characters and spaces are invalid */
  12098. return 0;
  12099. }
  12100. if (uri[i] > 126) {
  12101. /* non-ascii characters must be % encoded */
  12102. return 0;
  12103. } else {
  12104. switch (uri[i]) {
  12105. case '"': /* 34 */
  12106. case '<': /* 60 */
  12107. case '>': /* 62 */
  12108. case '\\': /* 92 */
  12109. case '^': /* 94 */
  12110. case '`': /* 96 */
  12111. case '{': /* 123 */
  12112. case '|': /* 124 */
  12113. case '}': /* 125 */
  12114. return 0;
  12115. default:
  12116. /* character is ok */
  12117. break;
  12118. }
  12119. }
  12120. }
  12121. /* A relative uri starts with a / character */
  12122. if (uri[0] == '/') {
  12123. /* relative uri */
  12124. return 2;
  12125. }
  12126. /* It could be an absolute uri: */
  12127. /* This function only checks if the uri is valid, not if it is
  12128. * addressing the current server. So civetweb can also be used
  12129. * as a proxy server. */
  12130. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  12131. if (mg_strncasecmp(uri,
  12132. abs_uri_protocols[i].proto,
  12133. abs_uri_protocols[i].proto_len) == 0) {
  12134. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  12135. if (!hostend) {
  12136. return 0;
  12137. }
  12138. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  12139. if (!portbegin) {
  12140. return 3;
  12141. }
  12142. port = strtoul(portbegin + 1, &portend, 10);
  12143. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  12144. return 0;
  12145. }
  12146. return 4;
  12147. }
  12148. }
  12149. return 0;
  12150. }
  12151. /* Return NULL or the relative uri at the current server */
  12152. static const char *
  12153. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  12154. {
  12155. const char *server_domain;
  12156. size_t server_domain_len;
  12157. size_t request_domain_len = 0;
  12158. unsigned long port = 0;
  12159. int i, auth_domain_check_enabled;
  12160. const char *hostbegin = NULL;
  12161. const char *hostend = NULL;
  12162. const char *portbegin;
  12163. char *portend;
  12164. auth_domain_check_enabled =
  12165. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  12166. if (!auth_domain_check_enabled) {
  12167. return 0;
  12168. }
  12169. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  12170. if (!server_domain) {
  12171. return 0;
  12172. }
  12173. server_domain_len = strlen(server_domain);
  12174. if (!server_domain_len) {
  12175. return 0;
  12176. }
  12177. /* DNS is case insensitive, so use case insensitive string compare here
  12178. */
  12179. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  12180. if (mg_strncasecmp(uri,
  12181. abs_uri_protocols[i].proto,
  12182. abs_uri_protocols[i].proto_len) == 0) {
  12183. hostbegin = uri + abs_uri_protocols[i].proto_len;
  12184. hostend = strchr(hostbegin, '/');
  12185. if (!hostend) {
  12186. return 0;
  12187. }
  12188. portbegin = strchr(hostbegin, ':');
  12189. if ((!portbegin) || (portbegin > hostend)) {
  12190. port = abs_uri_protocols[i].default_port;
  12191. request_domain_len = (size_t)(hostend - hostbegin);
  12192. } else {
  12193. port = strtoul(portbegin + 1, &portend, 10);
  12194. if ((portend != hostend) || (port <= 0)
  12195. || !is_valid_port(port)) {
  12196. return 0;
  12197. }
  12198. request_domain_len = (size_t)(portbegin - hostbegin);
  12199. }
  12200. /* protocol found, port set */
  12201. break;
  12202. }
  12203. }
  12204. if (!port) {
  12205. /* port remains 0 if the protocol is not found */
  12206. return 0;
  12207. }
  12208. /* Check if the request is directed to a different server. */
  12209. /* First check if the port is the same (IPv4 and IPv6). */
  12210. #if defined(USE_IPV6)
  12211. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  12212. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  12213. /* Request is directed to a different port */
  12214. return 0;
  12215. }
  12216. } else
  12217. #endif
  12218. {
  12219. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  12220. /* Request is directed to a different port */
  12221. return 0;
  12222. }
  12223. }
  12224. /* Finally check if the server corresponds to the authentication
  12225. * domain of the server (the server domain).
  12226. * Allow full matches (like http://mydomain.com/path/file.ext), and
  12227. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  12228. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  12229. * or http://mydomain.com.fake/path/file.ext).
  12230. */
  12231. if (auth_domain_check_enabled) {
  12232. if ((request_domain_len == server_domain_len)
  12233. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  12234. /* Request is directed to this server - full name match. */
  12235. } else {
  12236. if (request_domain_len < (server_domain_len + 2)) {
  12237. /* Request is directed to another server: The server name is
  12238. * longer
  12239. * than
  12240. * the request name. Drop this case here to avoid overflows in
  12241. * the
  12242. * following checks. */
  12243. return 0;
  12244. }
  12245. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  12246. /* Request is directed to another server: It could be a
  12247. * substring
  12248. * like notmyserver.com */
  12249. return 0;
  12250. }
  12251. if (0 != memcmp(server_domain,
  12252. hostbegin + request_domain_len - server_domain_len,
  12253. server_domain_len)) {
  12254. /* Request is directed to another server:
  12255. * The server name is different. */
  12256. return 0;
  12257. }
  12258. }
  12259. }
  12260. return hostend;
  12261. }
  12262. static int
  12263. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12264. {
  12265. const char *cl;
  12266. if (ebuf_len > 0) {
  12267. ebuf[0] = '\0';
  12268. }
  12269. *err = 0;
  12270. reset_per_request_attributes(conn);
  12271. if (!conn) {
  12272. mg_snprintf(conn,
  12273. NULL, /* No truncation check for ebuf */
  12274. ebuf,
  12275. ebuf_len,
  12276. "%s",
  12277. "Internal error");
  12278. *err = 500;
  12279. return 0;
  12280. }
  12281. /* Set the time the request was received. This value should be used for
  12282. * timeouts. */
  12283. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  12284. conn->request_len =
  12285. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  12286. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  12287. */
  12288. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  12289. mg_snprintf(conn,
  12290. NULL, /* No truncation check for ebuf */
  12291. ebuf,
  12292. ebuf_len,
  12293. "%s",
  12294. "Invalid request size");
  12295. *err = 500;
  12296. return 0;
  12297. }
  12298. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  12299. mg_snprintf(conn,
  12300. NULL, /* No truncation check for ebuf */
  12301. ebuf,
  12302. ebuf_len,
  12303. "%s",
  12304. "Request Too Large");
  12305. *err = 413;
  12306. return 0;
  12307. } else if (conn->request_len <= 0) {
  12308. if (conn->data_len > 0) {
  12309. mg_snprintf(conn,
  12310. NULL, /* No truncation check for ebuf */
  12311. ebuf,
  12312. ebuf_len,
  12313. "%s",
  12314. "Client sent malformed request");
  12315. *err = 400;
  12316. } else {
  12317. /* Server did not recv anything -> just close the connection */
  12318. conn->must_close = 1;
  12319. mg_snprintf(conn,
  12320. NULL, /* No truncation check for ebuf */
  12321. ebuf,
  12322. ebuf_len,
  12323. "%s",
  12324. "Client did not send a request");
  12325. *err = 0;
  12326. }
  12327. return 0;
  12328. } else if (parse_http_message(conn->buf,
  12329. conn->buf_size,
  12330. &conn->request_info) <= 0) {
  12331. mg_snprintf(conn,
  12332. NULL, /* No truncation check for ebuf */
  12333. ebuf,
  12334. ebuf_len,
  12335. "%s",
  12336. "Bad Request");
  12337. *err = 400;
  12338. return 0;
  12339. } else {
  12340. /* Message is a valid request or response */
  12341. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  12342. /* Request/response has content length set */
  12343. char *endptr = NULL;
  12344. conn->content_len = strtoll(cl, &endptr, 10);
  12345. if (endptr == cl) {
  12346. mg_snprintf(conn,
  12347. NULL, /* No truncation check for ebuf */
  12348. ebuf,
  12349. ebuf_len,
  12350. "%s",
  12351. "Bad Request");
  12352. *err = 411;
  12353. return 0;
  12354. }
  12355. /* Publish the content length back to the request info. */
  12356. conn->request_info.content_length = conn->content_len;
  12357. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  12358. != NULL
  12359. && !mg_strcasecmp(cl, "chunked")) {
  12360. conn->is_chunked = 1;
  12361. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  12362. || !mg_strcasecmp(conn->request_info.request_method,
  12363. "PUT")) {
  12364. /* POST or PUT request without content length set */
  12365. conn->content_len = -1;
  12366. } else if (!mg_strncasecmp(conn->request_info.request_method,
  12367. "HTTP/",
  12368. 5)) {
  12369. /* Response without content length set */
  12370. conn->content_len = -1;
  12371. } else {
  12372. /* Other request */
  12373. conn->content_len = 0;
  12374. }
  12375. }
  12376. return 1;
  12377. }
  12378. int
  12379. mg_get_response(struct mg_connection *conn,
  12380. char *ebuf,
  12381. size_t ebuf_len,
  12382. int timeout)
  12383. {
  12384. if (conn) {
  12385. /* Implementation of API function for HTTP clients */
  12386. int err, ret;
  12387. struct mg_context *octx = conn->ctx;
  12388. struct mg_context rctx = *(conn->ctx);
  12389. char txt[32]; /* will not overflow */
  12390. if (timeout >= 0) {
  12391. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  12392. rctx.config[REQUEST_TIMEOUT] = txt;
  12393. /* Not required for non-blocking sockets.
  12394. set_sock_timeout(conn->client.sock, timeout);
  12395. */
  12396. } else {
  12397. rctx.config[REQUEST_TIMEOUT] = NULL;
  12398. }
  12399. conn->ctx = &rctx;
  12400. ret = getreq(conn, ebuf, ebuf_len, &err);
  12401. conn->ctx = octx;
  12402. #if defined(MG_LEGACY_INTERFACE)
  12403. /* TODO: 1) uri is deprecated;
  12404. * 2) here, ri.uri is the http response code */
  12405. conn->request_info.uri = conn->request_info.request_uri;
  12406. #endif
  12407. conn->request_info.local_uri = conn->request_info.request_uri;
  12408. /* TODO (mid): Define proper return values - maybe return length?
  12409. * For the first test use <0 for error and >0 for OK */
  12410. return (ret == 0) ? -1 : +1;
  12411. }
  12412. return -1;
  12413. }
  12414. struct mg_connection *
  12415. mg_download(const char *host,
  12416. int port,
  12417. int use_ssl,
  12418. char *ebuf,
  12419. size_t ebuf_len,
  12420. const char *fmt,
  12421. ...)
  12422. {
  12423. struct mg_connection *conn;
  12424. va_list ap;
  12425. int i;
  12426. int reqerr;
  12427. va_start(ap, fmt);
  12428. ebuf[0] = '\0';
  12429. /* open a connection */
  12430. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  12431. if (conn != NULL) {
  12432. i = mg_vprintf(conn, fmt, ap);
  12433. if (i <= 0) {
  12434. mg_snprintf(conn,
  12435. NULL, /* No truncation check for ebuf */
  12436. ebuf,
  12437. ebuf_len,
  12438. "%s",
  12439. "Error sending request");
  12440. } else {
  12441. getreq(conn, ebuf, ebuf_len, &reqerr);
  12442. #if defined(MG_LEGACY_INTERFACE)
  12443. /* TODO: 1) uri is deprecated;
  12444. * 2) here, ri.uri is the http response code */
  12445. conn->request_info.uri = conn->request_info.request_uri;
  12446. #endif
  12447. conn->request_info.local_uri = conn->request_info.request_uri;
  12448. }
  12449. }
  12450. /* if an error occured, close the connection */
  12451. if (ebuf[0] != '\0' && conn != NULL) {
  12452. mg_close_connection(conn);
  12453. conn = NULL;
  12454. }
  12455. va_end(ap);
  12456. return conn;
  12457. }
  12458. struct websocket_client_thread_data {
  12459. struct mg_connection *conn;
  12460. mg_websocket_data_handler data_handler;
  12461. mg_websocket_close_handler close_handler;
  12462. void *callback_data;
  12463. };
  12464. #if defined(USE_WEBSOCKET)
  12465. #ifdef _WIN32
  12466. static unsigned __stdcall websocket_client_thread(void *data)
  12467. #else
  12468. static void *
  12469. websocket_client_thread(void *data)
  12470. #endif
  12471. {
  12472. struct websocket_client_thread_data *cdata =
  12473. (struct websocket_client_thread_data *)data;
  12474. mg_set_thread_name("ws-clnt");
  12475. if (cdata->conn->ctx) {
  12476. if (cdata->conn->ctx->callbacks.init_thread) {
  12477. /* 3 indicates a websocket client thread */
  12478. /* TODO: check if conn->ctx can be set */
  12479. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  12480. }
  12481. }
  12482. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  12483. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  12484. if (cdata->close_handler != NULL) {
  12485. cdata->close_handler(cdata->conn, cdata->callback_data);
  12486. }
  12487. /* The websocket_client context has only this thread. If it runs out,
  12488. set the stop_flag to 2 (= "stopped"). */
  12489. cdata->conn->ctx->stop_flag = 2;
  12490. mg_free((void *)cdata);
  12491. #ifdef _WIN32
  12492. return 0;
  12493. #else
  12494. return NULL;
  12495. #endif
  12496. }
  12497. #endif
  12498. struct mg_connection *
  12499. mg_connect_websocket_client(const char *host,
  12500. int port,
  12501. int use_ssl,
  12502. char *error_buffer,
  12503. size_t error_buffer_size,
  12504. const char *path,
  12505. const char *origin,
  12506. mg_websocket_data_handler data_func,
  12507. mg_websocket_close_handler close_func,
  12508. void *user_data)
  12509. {
  12510. struct mg_connection *conn = NULL;
  12511. #if defined(USE_WEBSOCKET)
  12512. struct mg_context *newctx = NULL;
  12513. struct websocket_client_thread_data *thread_data;
  12514. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  12515. static const char *handshake_req;
  12516. if (origin != NULL) {
  12517. handshake_req = "GET %s HTTP/1.1\r\n"
  12518. "Host: %s\r\n"
  12519. "Upgrade: websocket\r\n"
  12520. "Connection: Upgrade\r\n"
  12521. "Sec-WebSocket-Key: %s\r\n"
  12522. "Sec-WebSocket-Version: 13\r\n"
  12523. "Origin: %s\r\n"
  12524. "\r\n";
  12525. } else {
  12526. handshake_req = "GET %s HTTP/1.1\r\n"
  12527. "Host: %s\r\n"
  12528. "Upgrade: websocket\r\n"
  12529. "Connection: Upgrade\r\n"
  12530. "Sec-WebSocket-Key: %s\r\n"
  12531. "Sec-WebSocket-Version: 13\r\n"
  12532. "\r\n";
  12533. }
  12534. /* Establish the client connection and request upgrade */
  12535. conn = mg_download(host,
  12536. port,
  12537. use_ssl,
  12538. error_buffer,
  12539. error_buffer_size,
  12540. handshake_req,
  12541. path,
  12542. host,
  12543. magic,
  12544. origin);
  12545. /* Connection object will be null if something goes wrong */
  12546. if ((conn == NULL)
  12547. || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  12548. if (!*error_buffer) {
  12549. /* if there is a connection, but it did not return 101,
  12550. * error_buffer is not yet set */
  12551. mg_snprintf(conn,
  12552. NULL, /* No truncation check for ebuf */
  12553. error_buffer,
  12554. error_buffer_size,
  12555. "Unexpected server reply");
  12556. }
  12557. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  12558. if (conn != NULL) {
  12559. mg_free(conn);
  12560. conn = NULL;
  12561. }
  12562. return conn;
  12563. }
  12564. /* For client connections, mg_context is fake. Since we need to set a
  12565. * callback function, we need to create a copy and modify it. */
  12566. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  12567. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  12568. newctx->user_data = user_data;
  12569. newctx->context_type = 2; /* ws/wss client context type */
  12570. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  12571. newctx->worker_threadids =
  12572. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  12573. sizeof(pthread_t),
  12574. newctx);
  12575. conn->ctx = newctx;
  12576. thread_data = (struct websocket_client_thread_data *)
  12577. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  12578. thread_data->conn = conn;
  12579. thread_data->data_handler = data_func;
  12580. thread_data->close_handler = close_func;
  12581. thread_data->callback_data = user_data;
  12582. /* Start a thread to read the websocket client connection
  12583. * This thread will automatically stop when mg_disconnect is
  12584. * called on the client connection */
  12585. if (mg_start_thread_with_id(websocket_client_thread,
  12586. (void *)thread_data,
  12587. newctx->worker_threadids) != 0) {
  12588. mg_free((void *)thread_data);
  12589. mg_free((void *)newctx->worker_threadids);
  12590. mg_free((void *)newctx);
  12591. mg_free((void *)conn);
  12592. conn = NULL;
  12593. DEBUG_TRACE("%s",
  12594. "Websocket client connect thread could not be started\r\n");
  12595. }
  12596. #else
  12597. /* Appease "unused parameter" warnings */
  12598. (void)host;
  12599. (void)port;
  12600. (void)use_ssl;
  12601. (void)error_buffer;
  12602. (void)error_buffer_size;
  12603. (void)path;
  12604. (void)origin;
  12605. (void)user_data;
  12606. (void)data_func;
  12607. (void)close_func;
  12608. #endif
  12609. return conn;
  12610. }
  12611. static void
  12612. process_new_connection(struct mg_connection *conn)
  12613. {
  12614. if (conn && conn->ctx) {
  12615. struct mg_request_info *ri = &conn->request_info;
  12616. int keep_alive_enabled, keep_alive, discard_len;
  12617. char ebuf[100];
  12618. const char *hostend;
  12619. int reqerr, uri_type;
  12620. #if defined(USE_SERVER_STATS)
  12621. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  12622. mg_atomic_add(&(conn->ctx->total_connections), 1);
  12623. if (mcon > (conn->ctx->max_connections)) {
  12624. /* could use atomic compare exchange, but this
  12625. * seems overkill for statistics data */
  12626. conn->ctx->max_connections = mcon;
  12627. }
  12628. #endif
  12629. keep_alive_enabled =
  12630. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  12631. /* Important: on new connection, reset the receiving buffer. Credit
  12632. * goes to crule42. */
  12633. conn->data_len = 0;
  12634. conn->handled_requests = 0;
  12635. do {
  12636. DEBUG_TRACE("calling getreq (%i times for this connection)",
  12637. conn->handled_requests + 1);
  12638. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  12639. /* The request sent by the client could not be understood by
  12640. * the server, or it was incomplete or a timeout. Send an
  12641. * error message and close the connection. */
  12642. if (reqerr > 0) {
  12643. /*assert(ebuf[0] != '\0');*/
  12644. mg_send_http_error(conn, reqerr, "%s", ebuf);
  12645. }
  12646. } else if (strcmp(ri->http_version, "1.0")
  12647. && strcmp(ri->http_version, "1.1")) {
  12648. mg_snprintf(conn,
  12649. NULL, /* No truncation check for ebuf */
  12650. ebuf,
  12651. sizeof(ebuf),
  12652. "Bad HTTP version: [%s]",
  12653. ri->http_version);
  12654. mg_send_http_error(conn, 505, "%s", ebuf);
  12655. }
  12656. if (ebuf[0] == '\0') {
  12657. uri_type = get_uri_type(conn->request_info.request_uri);
  12658. switch (uri_type) {
  12659. case 1:
  12660. /* Asterisk */
  12661. conn->request_info.local_uri = NULL;
  12662. break;
  12663. case 2:
  12664. /* relative uri */
  12665. conn->request_info.local_uri =
  12666. conn->request_info.request_uri;
  12667. break;
  12668. case 3:
  12669. case 4:
  12670. /* absolute uri (with/without port) */
  12671. hostend = get_rel_url_at_current_server(
  12672. conn->request_info.request_uri, conn);
  12673. if (hostend) {
  12674. conn->request_info.local_uri = hostend;
  12675. } else {
  12676. conn->request_info.local_uri = NULL;
  12677. }
  12678. break;
  12679. default:
  12680. mg_snprintf(conn,
  12681. NULL, /* No truncation check for ebuf */
  12682. ebuf,
  12683. sizeof(ebuf),
  12684. "Invalid URI");
  12685. mg_send_http_error(conn, 400, "%s", ebuf);
  12686. conn->request_info.local_uri = NULL;
  12687. break;
  12688. }
  12689. #if defined(MG_LEGACY_INTERFACE)
  12690. /* TODO: cleanup uri, local_uri and request_uri */
  12691. conn->request_info.uri = conn->request_info.local_uri;
  12692. #endif
  12693. }
  12694. DEBUG_TRACE("http: %s, error: %s",
  12695. (ri->http_version ? ri->http_version : "none"),
  12696. (ebuf[0] ? ebuf : "none"));
  12697. if (ebuf[0] == '\0') {
  12698. if (conn->request_info.local_uri) {
  12699. /* handle request to local server */
  12700. handle_request(conn);
  12701. DEBUG_TRACE("%s", "handle_request done");
  12702. if (conn->ctx->callbacks.end_request != NULL) {
  12703. conn->ctx->callbacks.end_request(conn,
  12704. conn->status_code);
  12705. DEBUG_TRACE("%s", "end_request callback done");
  12706. }
  12707. log_access(conn);
  12708. } else {
  12709. /* TODO: handle non-local request (PROXY) */
  12710. conn->must_close = 1;
  12711. }
  12712. } else {
  12713. conn->must_close = 1;
  12714. }
  12715. if (ri->remote_user != NULL) {
  12716. mg_free((void *)ri->remote_user);
  12717. /* Important! When having connections with and without auth
  12718. * would cause double free and then crash */
  12719. ri->remote_user = NULL;
  12720. }
  12721. /* NOTE(lsm): order is important here. should_keep_alive() call
  12722. * is
  12723. * using parsed request, which will be invalid after memmove's
  12724. * below.
  12725. * Therefore, memorize should_keep_alive() result now for later
  12726. * use
  12727. * in loop exit condition. */
  12728. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  12729. && (conn->content_len >= 0) && should_keep_alive(conn);
  12730. /* Discard all buffered data for this request */
  12731. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  12732. && ((conn->request_len + conn->content_len)
  12733. < (int64_t)conn->data_len))
  12734. ? (int)(conn->request_len + conn->content_len)
  12735. : conn->data_len;
  12736. /*assert(discard_len >= 0);*/
  12737. if (discard_len < 0) {
  12738. DEBUG_TRACE("internal error: discard_len = %li",
  12739. (long int)discard_len);
  12740. break;
  12741. }
  12742. conn->data_len -= discard_len;
  12743. if (conn->data_len > 0) {
  12744. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  12745. memmove(conn->buf,
  12746. conn->buf + discard_len,
  12747. (size_t)conn->data_len);
  12748. }
  12749. /* assert(conn->data_len >= 0); */
  12750. /* assert(conn->data_len <= conn->buf_size); */
  12751. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  12752. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  12753. (long int)conn->data_len,
  12754. (long int)conn->buf_size);
  12755. break;
  12756. }
  12757. conn->handled_requests++;
  12758. } while (keep_alive);
  12759. #if defined(USE_SERVER_STATS)
  12760. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  12761. mg_atomic_dec(&(conn->ctx->active_connections));
  12762. #endif
  12763. }
  12764. }
  12765. #if defined(ALTERNATIVE_QUEUE)
  12766. static void
  12767. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12768. {
  12769. unsigned int i;
  12770. for (;;) {
  12771. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12772. /* find a free worker slot and signal it */
  12773. if (ctx->client_socks[i].in_use == 0) {
  12774. ctx->client_socks[i] = *sp;
  12775. ctx->client_socks[i].in_use = 1;
  12776. event_signal(ctx->client_wait_events[i]);
  12777. return;
  12778. }
  12779. }
  12780. /* queue is full */
  12781. mg_sleep(1);
  12782. }
  12783. }
  12784. static int
  12785. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12786. {
  12787. DEBUG_TRACE("%s", "going idle");
  12788. ctx->client_socks[thread_index].in_use = 0;
  12789. event_wait(ctx->client_wait_events[thread_index]);
  12790. *sp = ctx->client_socks[thread_index];
  12791. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12792. return !ctx->stop_flag;
  12793. }
  12794. #else /* ALTERNATIVE_QUEUE */
  12795. /* Worker threads take accepted socket from the queue */
  12796. static int
  12797. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12798. {
  12799. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12800. (void)thread_index;
  12801. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12802. DEBUG_TRACE("%s", "going idle");
  12803. /* If the queue is empty, wait. We're idle at this point. */
  12804. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  12805. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  12806. }
  12807. /* If we're stopping, sq_head may be equal to sq_tail. */
  12808. if (ctx->sq_head > ctx->sq_tail) {
  12809. /* Copy socket from the queue and increment tail */
  12810. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  12811. ctx->sq_tail++;
  12812. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12813. /* Wrap pointers if needed */
  12814. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  12815. ctx->sq_tail -= QUEUE_SIZE(ctx);
  12816. ctx->sq_head -= QUEUE_SIZE(ctx);
  12817. }
  12818. }
  12819. (void)pthread_cond_signal(&ctx->sq_empty);
  12820. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12821. return !ctx->stop_flag;
  12822. #undef QUEUE_SIZE
  12823. }
  12824. /* Master thread adds accepted socket to a queue */
  12825. static void
  12826. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12827. {
  12828. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12829. if (!ctx) {
  12830. return;
  12831. }
  12832. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12833. /* If the queue is full, wait */
  12834. while ((ctx->stop_flag == 0)
  12835. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  12836. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  12837. }
  12838. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  12839. /* Copy socket to the queue and increment head */
  12840. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  12841. ctx->sq_head++;
  12842. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12843. }
  12844. (void)pthread_cond_signal(&ctx->sq_full);
  12845. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12846. #undef QUEUE_SIZE
  12847. }
  12848. #endif /* ALTERNATIVE_QUEUE */
  12849. struct worker_thread_args {
  12850. struct mg_context *ctx;
  12851. int index;
  12852. };
  12853. static void *
  12854. worker_thread_run(struct worker_thread_args *thread_args)
  12855. {
  12856. struct mg_context *ctx = thread_args->ctx;
  12857. struct mg_connection *conn;
  12858. struct mg_workerTLS tls;
  12859. #if defined(MG_LEGACY_INTERFACE)
  12860. uint32_t addr;
  12861. #endif
  12862. mg_set_thread_name("worker");
  12863. tls.is_master = 0;
  12864. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12865. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12866. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12867. #endif
  12868. /* Initialize thread local storage before calling any callback */
  12869. pthread_setspecific(sTlsKey, &tls);
  12870. if (ctx->callbacks.init_thread) {
  12871. /* call init_thread for a worker thread (type 1) */
  12872. ctx->callbacks.init_thread(ctx, 1);
  12873. }
  12874. /* Connection structure has been pre-allocated */
  12875. if (((int)thread_args->index < 0)
  12876. || ((unsigned)thread_args->index
  12877. >= (unsigned)ctx->cfg_worker_threads)) {
  12878. mg_cry(fc(ctx),
  12879. "Internal error: Invalid worker index %i",
  12880. (int)thread_args->index);
  12881. return NULL;
  12882. }
  12883. conn = ctx->worker_connections + thread_args->index;
  12884. /* Request buffers are not pre-allocated. They are private to the
  12885. * request and do not contain any state information that might be
  12886. * of interest to anyone observing a server status. */
  12887. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->ctx);
  12888. if (conn->buf == NULL) {
  12889. mg_cry(fc(ctx),
  12890. "Out of memory: Cannot allocate buffer for worker %i",
  12891. (int)thread_args->index);
  12892. return NULL;
  12893. }
  12894. conn->buf_size = (int)ctx->max_request_size;
  12895. conn->ctx = ctx;
  12896. conn->thread_index = thread_args->index;
  12897. conn->request_info.user_data = ctx->user_data;
  12898. /* Allocate a mutex for this connection to allow communication both
  12899. * within the request handler and from elsewhere in the application
  12900. */
  12901. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12902. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12903. * signal sq_empty condvar to wake up the master waiting in
  12904. * produce_socket() */
  12905. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12906. conn->conn_birth_time = time(NULL);
  12907. /* Fill in IP, port info early so even if SSL setup below fails,
  12908. * error handler would have the corresponding info.
  12909. * Thanks to Johannes Winkelmann for the patch.
  12910. */
  12911. #if defined(USE_IPV6)
  12912. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12913. conn->request_info.remote_port =
  12914. ntohs(conn->client.rsa.sin6.sin6_port);
  12915. } else
  12916. #endif
  12917. {
  12918. conn->request_info.remote_port =
  12919. ntohs(conn->client.rsa.sin.sin_port);
  12920. }
  12921. sockaddr_to_string(conn->request_info.remote_addr,
  12922. sizeof(conn->request_info.remote_addr),
  12923. &conn->client.rsa);
  12924. DEBUG_TRACE("Start processing connection from %s",
  12925. conn->request_info.remote_addr);
  12926. #if defined(MG_LEGACY_INTERFACE)
  12927. /* This legacy interface only works for the IPv4 case */
  12928. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12929. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12930. #endif
  12931. conn->request_info.is_ssl = conn->client.is_ssl;
  12932. if (conn->client.is_ssl) {
  12933. #ifndef NO_SSL
  12934. /* HTTPS connection */
  12935. if (sslize(conn,
  12936. conn->ctx->ssl_ctx,
  12937. SSL_accept,
  12938. &(conn->ctx->stop_flag))) {
  12939. /* Get SSL client certificate information (if set) */
  12940. ssl_get_client_cert_info(conn);
  12941. /* process HTTPS connection */
  12942. process_new_connection(conn);
  12943. /* Free client certificate info */
  12944. if (conn->request_info.client_cert) {
  12945. mg_free((void *)(conn->request_info.client_cert->subject));
  12946. mg_free((void *)(conn->request_info.client_cert->issuer));
  12947. mg_free((void *)(conn->request_info.client_cert->serial));
  12948. mg_free((void *)(conn->request_info.client_cert->finger));
  12949. conn->request_info.client_cert->subject = 0;
  12950. conn->request_info.client_cert->issuer = 0;
  12951. conn->request_info.client_cert->serial = 0;
  12952. conn->request_info.client_cert->finger = 0;
  12953. mg_free(conn->request_info.client_cert);
  12954. conn->request_info.client_cert = 0;
  12955. }
  12956. }
  12957. #endif
  12958. } else {
  12959. /* process HTTP connection */
  12960. process_new_connection(conn);
  12961. }
  12962. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12963. conn->request_info.remote_addr,
  12964. difftime(time(NULL), conn->conn_birth_time));
  12965. close_connection(conn);
  12966. DEBUG_TRACE("%s", "Connection closed");
  12967. }
  12968. pthread_setspecific(sTlsKey, NULL);
  12969. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12970. CloseHandle(tls.pthread_cond_helper_mutex);
  12971. #endif
  12972. pthread_mutex_destroy(&conn->mutex);
  12973. /* Free the request buffer. */
  12974. conn->buf_size = 0;
  12975. mg_free(conn->buf);
  12976. conn->buf = NULL;
  12977. DEBUG_TRACE("%s", "exiting");
  12978. return NULL;
  12979. }
  12980. /* Threads have different return types on Windows and Unix. */
  12981. #ifdef _WIN32
  12982. static unsigned __stdcall worker_thread(void *thread_func_param)
  12983. {
  12984. struct worker_thread_args *pwta =
  12985. (struct worker_thread_args *)thread_func_param;
  12986. worker_thread_run(pwta);
  12987. mg_free(thread_func_param);
  12988. return 0;
  12989. }
  12990. #else
  12991. static void *
  12992. worker_thread(void *thread_func_param)
  12993. {
  12994. struct worker_thread_args *pwta =
  12995. (struct worker_thread_args *)thread_func_param;
  12996. worker_thread_run(pwta);
  12997. mg_free(thread_func_param);
  12998. return NULL;
  12999. }
  13000. #endif /* _WIN32 */
  13001. static void
  13002. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  13003. {
  13004. struct socket so;
  13005. char src_addr[IP_ADDR_STR_LEN];
  13006. socklen_t len = sizeof(so.rsa);
  13007. int on = 1;
  13008. if (!listener) {
  13009. return;
  13010. }
  13011. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  13012. == INVALID_SOCKET) {
  13013. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  13014. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  13015. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  13016. closesocket(so.sock);
  13017. } else {
  13018. /* Put so socket structure into the queue */
  13019. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  13020. set_close_on_exec(so.sock, fc(ctx));
  13021. so.is_ssl = listener->is_ssl;
  13022. so.ssl_redir = listener->ssl_redir;
  13023. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  13024. mg_cry(fc(ctx),
  13025. "%s: getsockname() failed: %s",
  13026. __func__,
  13027. strerror(ERRNO));
  13028. }
  13029. /* Set TCP keep-alive. This is needed because if HTTP-level
  13030. * keep-alive
  13031. * is enabled, and client resets the connection, server won't get
  13032. * TCP FIN or RST and will keep the connection open forever. With
  13033. * TCP keep-alive, next keep-alive handshake will figure out that
  13034. * the client is down and will close the server end.
  13035. * Thanks to Igor Klopov who suggested the patch. */
  13036. if (setsockopt(so.sock,
  13037. SOL_SOCKET,
  13038. SO_KEEPALIVE,
  13039. (SOCK_OPT_TYPE)&on,
  13040. sizeof(on)) != 0) {
  13041. mg_cry(fc(ctx),
  13042. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  13043. __func__,
  13044. strerror(ERRNO));
  13045. }
  13046. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  13047. * to effectively fill up the underlying IP packet payload and
  13048. * reduce the overhead of sending lots of small buffers. However
  13049. * this hurts the server's throughput (ie. operations per second)
  13050. * when HTTP 1.1 persistent connections are used and the responses
  13051. * are relatively small (eg. less than 1400 bytes).
  13052. */
  13053. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  13054. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  13055. if (set_tcp_nodelay(so.sock, 1) != 0) {
  13056. mg_cry(fc(ctx),
  13057. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  13058. __func__,
  13059. strerror(ERRNO));
  13060. }
  13061. }
  13062. /* We are using non-blocking sockets. Thus, the
  13063. * set_sock_timeout(so.sock, timeout);
  13064. * call is no longer required. */
  13065. set_blocking_mode(so.sock, 0);
  13066. so.in_use = 0;
  13067. produce_socket(ctx, &so);
  13068. }
  13069. }
  13070. static void
  13071. master_thread_run(void *thread_func_param)
  13072. {
  13073. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  13074. struct mg_workerTLS tls;
  13075. struct pollfd *pfd;
  13076. unsigned int i;
  13077. unsigned int workerthreadcount;
  13078. if (!ctx) {
  13079. return;
  13080. }
  13081. mg_set_thread_name("master");
  13082. /* Increase priority of the master thread */
  13083. #if defined(_WIN32)
  13084. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  13085. #elif defined(USE_MASTER_THREAD_PRIORITY)
  13086. int min_prio = sched_get_priority_min(SCHED_RR);
  13087. int max_prio = sched_get_priority_max(SCHED_RR);
  13088. if ((min_prio >= 0) && (max_prio >= 0)
  13089. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  13090. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  13091. struct sched_param sched_param = {0};
  13092. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  13093. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  13094. }
  13095. #endif
  13096. /* Initialize thread local storage */
  13097. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13098. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13099. #endif
  13100. tls.is_master = 1;
  13101. pthread_setspecific(sTlsKey, &tls);
  13102. if (ctx->callbacks.init_thread) {
  13103. /* Callback for the master thread (type 0) */
  13104. ctx->callbacks.init_thread(ctx, 0);
  13105. }
  13106. /* Server starts *now* */
  13107. ctx->start_time = time(NULL);
  13108. /* Start the server */
  13109. pfd = ctx->listening_socket_fds;
  13110. while (ctx->stop_flag == 0) {
  13111. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13112. pfd[i].fd = ctx->listening_sockets[i].sock;
  13113. pfd[i].events = POLLIN;
  13114. }
  13115. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  13116. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13117. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  13118. * successful poll, and POLLIN is defined as
  13119. * (POLLRDNORM | POLLRDBAND)
  13120. * Therefore, we're checking pfd[i].revents & POLLIN, not
  13121. * pfd[i].revents == POLLIN. */
  13122. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  13123. accept_new_connection(&ctx->listening_sockets[i], ctx);
  13124. }
  13125. }
  13126. }
  13127. }
  13128. /* Here stop_flag is 1 - Initiate shutdown. */
  13129. DEBUG_TRACE("%s", "stopping workers");
  13130. /* Stop signal received: somebody called mg_stop. Quit. */
  13131. close_all_listening_sockets(ctx);
  13132. /* Wakeup workers that are waiting for connections to handle. */
  13133. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13134. #if defined(ALTERNATIVE_QUEUE)
  13135. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13136. event_signal(ctx->client_wait_events[i]);
  13137. /* Since we know all sockets, we can shutdown the connections. */
  13138. if (ctx->client_socks[i].in_use) {
  13139. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  13140. }
  13141. }
  13142. #else
  13143. pthread_cond_broadcast(&ctx->sq_full);
  13144. #endif
  13145. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13146. /* Join all worker threads to avoid leaking threads. */
  13147. workerthreadcount = ctx->cfg_worker_threads;
  13148. for (i = 0; i < workerthreadcount; i++) {
  13149. if (ctx->worker_threadids[i] != 0) {
  13150. mg_join_thread(ctx->worker_threadids[i]);
  13151. }
  13152. }
  13153. #if defined(USE_LUA)
  13154. /* Free Lua state of lua background task */
  13155. if (ctx->lua_background_state) {
  13156. lua_close((lua_State *)ctx->lua_background_state);
  13157. ctx->lua_background_state = 0;
  13158. }
  13159. #endif
  13160. #if !defined(NO_SSL)
  13161. if (ctx->ssl_ctx != NULL) {
  13162. uninitialize_ssl();
  13163. }
  13164. #endif
  13165. DEBUG_TRACE("%s", "exiting");
  13166. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13167. CloseHandle(tls.pthread_cond_helper_mutex);
  13168. #endif
  13169. pthread_setspecific(sTlsKey, NULL);
  13170. /* Signal mg_stop() that we're done.
  13171. * WARNING: This must be the very last thing this
  13172. * thread does, as ctx becomes invalid after this line. */
  13173. ctx->stop_flag = 2;
  13174. }
  13175. /* Threads have different return types on Windows and Unix. */
  13176. #ifdef _WIN32
  13177. static unsigned __stdcall master_thread(void *thread_func_param)
  13178. {
  13179. master_thread_run(thread_func_param);
  13180. return 0;
  13181. }
  13182. #else
  13183. static void *
  13184. master_thread(void *thread_func_param)
  13185. {
  13186. master_thread_run(thread_func_param);
  13187. return NULL;
  13188. }
  13189. #endif /* _WIN32 */
  13190. static void
  13191. free_context(struct mg_context *ctx)
  13192. {
  13193. int i;
  13194. struct mg_handler_info *tmp_rh;
  13195. if (ctx == NULL) {
  13196. return;
  13197. }
  13198. if (ctx->callbacks.exit_context) {
  13199. ctx->callbacks.exit_context(ctx);
  13200. }
  13201. /* All threads exited, no sync is needed. Destroy thread mutex and
  13202. * condvars
  13203. */
  13204. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  13205. #if defined(ALTERNATIVE_QUEUE)
  13206. mg_free(ctx->client_socks);
  13207. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13208. event_destroy(ctx->client_wait_events[i]);
  13209. }
  13210. mg_free(ctx->client_wait_events);
  13211. #else
  13212. (void)pthread_cond_destroy(&ctx->sq_empty);
  13213. (void)pthread_cond_destroy(&ctx->sq_full);
  13214. #endif
  13215. /* Destroy other context global data structures mutex */
  13216. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  13217. #if defined(USE_TIMERS)
  13218. timers_exit(ctx);
  13219. #endif
  13220. /* Deallocate config parameters */
  13221. for (i = 0; i < NUM_OPTIONS; i++) {
  13222. if (ctx->config[i] != NULL) {
  13223. #if defined(_MSC_VER)
  13224. #pragma warning(suppress : 6001)
  13225. #endif
  13226. mg_free(ctx->config[i]);
  13227. }
  13228. }
  13229. /* Deallocate request handlers */
  13230. while (ctx->handlers) {
  13231. tmp_rh = ctx->handlers;
  13232. ctx->handlers = tmp_rh->next;
  13233. mg_free(tmp_rh->uri);
  13234. mg_free(tmp_rh);
  13235. }
  13236. #ifndef NO_SSL
  13237. /* Deallocate SSL context */
  13238. if (ctx->ssl_ctx != NULL) {
  13239. SSL_CTX_free(ctx->ssl_ctx);
  13240. }
  13241. #endif /* !NO_SSL */
  13242. /* Deallocate worker thread ID array */
  13243. if (ctx->worker_threadids != NULL) {
  13244. mg_free(ctx->worker_threadids);
  13245. }
  13246. /* Deallocate worker thread ID array */
  13247. if (ctx->worker_connections != NULL) {
  13248. mg_free(ctx->worker_connections);
  13249. }
  13250. /* Deallocate the tls variable */
  13251. if (mg_atomic_dec(&sTlsInit) == 0) {
  13252. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13253. DeleteCriticalSection(&global_log_file_lock);
  13254. #endif /* _WIN32 && !__SYMBIAN32__ */
  13255. #if !defined(_WIN32)
  13256. pthread_mutexattr_destroy(&pthread_mutex_attr);
  13257. #endif
  13258. pthread_key_delete(sTlsKey);
  13259. #if defined(USE_LUA)
  13260. lua_exit_optional_libraries();
  13261. #endif
  13262. }
  13263. /* deallocate system name string */
  13264. mg_free(ctx->systemName);
  13265. /* Deallocate context itself */
  13266. mg_free(ctx);
  13267. }
  13268. void
  13269. mg_stop(struct mg_context *ctx)
  13270. {
  13271. pthread_t mt;
  13272. if (!ctx) {
  13273. return;
  13274. }
  13275. /* We don't use a lock here. Calling mg_stop with the same ctx from
  13276. * two threads is not allowed. */
  13277. mt = ctx->masterthreadid;
  13278. if (mt == 0) {
  13279. return;
  13280. }
  13281. ctx->masterthreadid = 0;
  13282. /* Set stop flag, so all threads know they have to exit. */
  13283. ctx->stop_flag = 1;
  13284. /* Wait until everything has stopped. */
  13285. while (ctx->stop_flag != 2) {
  13286. (void)mg_sleep(10);
  13287. }
  13288. mg_join_thread(mt);
  13289. free_context(ctx);
  13290. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13291. (void)WSACleanup();
  13292. #endif /* _WIN32 && !__SYMBIAN32__ */
  13293. }
  13294. static void
  13295. get_system_name(char **sysName)
  13296. {
  13297. #if defined(_WIN32)
  13298. #if !defined(__SYMBIAN32__)
  13299. #if defined(_WIN32_WCE)
  13300. *sysName = mg_strdup("WinCE");
  13301. #else
  13302. char name[128];
  13303. DWORD dwVersion = 0;
  13304. DWORD dwMajorVersion = 0;
  13305. DWORD dwMinorVersion = 0;
  13306. DWORD dwBuild = 0;
  13307. BOOL wowRet, isWoW = FALSE;
  13308. #ifdef _MSC_VER
  13309. #pragma warning(push)
  13310. /* GetVersion was declared deprecated */
  13311. #pragma warning(disable : 4996)
  13312. #endif
  13313. dwVersion = GetVersion();
  13314. #ifdef _MSC_VER
  13315. #pragma warning(pop)
  13316. #endif
  13317. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13318. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13319. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  13320. (void)dwBuild;
  13321. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  13322. sprintf(name,
  13323. "Windows %u.%u%s",
  13324. (unsigned)dwMajorVersion,
  13325. (unsigned)dwMinorVersion,
  13326. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  13327. *sysName = mg_strdup(name);
  13328. #endif
  13329. #else
  13330. *sysName = mg_strdup("Symbian");
  13331. #endif
  13332. #else
  13333. struct utsname name;
  13334. memset(&name, 0, sizeof(name));
  13335. uname(&name);
  13336. *sysName = mg_strdup(name.sysname);
  13337. #endif
  13338. }
  13339. struct mg_context *
  13340. mg_start(const struct mg_callbacks *callbacks,
  13341. void *user_data,
  13342. const char **options)
  13343. {
  13344. struct mg_context *ctx;
  13345. const char *name, *value, *default_value;
  13346. int idx, ok, workerthreadcount;
  13347. unsigned int i;
  13348. int itmp;
  13349. void (*exit_callback)(const struct mg_context *ctx) = 0;
  13350. struct mg_workerTLS tls;
  13351. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13352. WSADATA data;
  13353. WSAStartup(MAKEWORD(2, 2), &data);
  13354. #endif /* _WIN32 && !__SYMBIAN32__ */
  13355. /* Allocate context and initialize reasonable general case defaults. */
  13356. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  13357. return NULL;
  13358. }
  13359. /* Random number generator will initialize at the first call */
  13360. ctx->auth_nonce_mask =
  13361. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  13362. if (mg_atomic_inc(&sTlsInit) == 1) {
  13363. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13364. InitializeCriticalSection(&global_log_file_lock);
  13365. #endif /* _WIN32 && !__SYMBIAN32__ */
  13366. #if !defined(_WIN32)
  13367. pthread_mutexattr_init(&pthread_mutex_attr);
  13368. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  13369. #endif
  13370. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  13371. /* Fatal error - abort start. However, this situation should
  13372. * never occur in practice. */
  13373. mg_atomic_dec(&sTlsInit);
  13374. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  13375. mg_free(ctx);
  13376. return NULL;
  13377. }
  13378. #if defined(USE_LUA)
  13379. lua_init_optional_libraries();
  13380. #endif
  13381. } else {
  13382. /* TODO (low): instead of sleeping, check if sTlsKey is already
  13383. * initialized. */
  13384. mg_sleep(1);
  13385. }
  13386. tls.is_master = -1;
  13387. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13388. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13389. tls.pthread_cond_helper_mutex = NULL;
  13390. #endif
  13391. pthread_setspecific(sTlsKey, &tls);
  13392. /* Dummy use this function - in some #ifdef combinations it's used,
  13393. * while it's not used in others, but GCC seems to stupid to understand
  13394. * #pragma GCC diagnostic ignored "-Wunused-function"
  13395. * in cases the function is unused, and it also complains on
  13396. * __attribute((unused))__ in cases it is used.
  13397. * So dummy use it, to have our peace. */
  13398. (void)mg_current_thread_id();
  13399. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  13400. #if !defined(ALTERNATIVE_QUEUE)
  13401. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  13402. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  13403. #endif
  13404. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  13405. if (!ok) {
  13406. /* Fatal error - abort start. However, this situation should never
  13407. * occur in practice. */
  13408. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  13409. mg_free(ctx);
  13410. pthread_setspecific(sTlsKey, NULL);
  13411. return NULL;
  13412. }
  13413. if (callbacks) {
  13414. ctx->callbacks = *callbacks;
  13415. exit_callback = callbacks->exit_context;
  13416. ctx->callbacks.exit_context = 0;
  13417. }
  13418. ctx->user_data = user_data;
  13419. ctx->handlers = NULL;
  13420. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13421. ctx->shared_lua_websockets = 0;
  13422. #endif
  13423. while (options && (name = *options++) != NULL) {
  13424. if ((idx = get_option_index(name)) == -1) {
  13425. mg_cry(fc(ctx), "Invalid option: %s", name);
  13426. free_context(ctx);
  13427. pthread_setspecific(sTlsKey, NULL);
  13428. return NULL;
  13429. } else if ((value = *options++) == NULL) {
  13430. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  13431. free_context(ctx);
  13432. pthread_setspecific(sTlsKey, NULL);
  13433. return NULL;
  13434. }
  13435. if (ctx->config[idx] != NULL) {
  13436. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  13437. mg_free(ctx->config[idx]);
  13438. }
  13439. ctx->config[idx] = mg_strdup(value);
  13440. DEBUG_TRACE("[%s] -> [%s]", name, value);
  13441. }
  13442. /* Set default value if needed */
  13443. for (i = 0; config_options[i].name != NULL; i++) {
  13444. default_value = config_options[i].default_value;
  13445. if ((ctx->config[i] == NULL) && (default_value != NULL)) {
  13446. ctx->config[i] = mg_strdup(default_value);
  13447. }
  13448. }
  13449. itmp = atoi(ctx->config[MAX_REQUEST_SIZE]);
  13450. if (itmp < 1024) {
  13451. mg_cry(fc(ctx), "max_request_size too small");
  13452. free_context(ctx);
  13453. pthread_setspecific(sTlsKey, NULL);
  13454. return NULL;
  13455. }
  13456. ctx->max_request_size = (unsigned)itmp;
  13457. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  13458. if (workerthreadcount > MAX_WORKER_THREADS) {
  13459. mg_cry(fc(ctx), "Too many worker threads");
  13460. free_context(ctx);
  13461. pthread_setspecific(sTlsKey, NULL);
  13462. return NULL;
  13463. }
  13464. if (workerthreadcount <= 0) {
  13465. mg_cry(fc(ctx), "Invalid number of worker threads");
  13466. free_context(ctx);
  13467. pthread_setspecific(sTlsKey, NULL);
  13468. return NULL;
  13469. }
  13470. #if defined(NO_FILES)
  13471. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  13472. mg_cry(fc(ctx), "%s", "Document root must not be set");
  13473. free_context(ctx);
  13474. pthread_setspecific(sTlsKey, NULL);
  13475. return NULL;
  13476. }
  13477. #endif
  13478. get_system_name(&ctx->systemName);
  13479. #if defined(USE_LUA)
  13480. /* If a Lua background script has been configured, start it. */
  13481. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  13482. char ebuf[256];
  13483. void *state = (void *)mg_prepare_lua_context_script(
  13484. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  13485. if (!state) {
  13486. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  13487. free_context(ctx);
  13488. pthread_setspecific(sTlsKey, NULL);
  13489. return NULL;
  13490. }
  13491. ctx->lua_background_state = state;
  13492. } else {
  13493. ctx->lua_background_state = 0;
  13494. }
  13495. #endif
  13496. /* NOTE(lsm): order is important here. SSL certificates must
  13497. * be initialized before listening ports. UID must be set last. */
  13498. if (!set_gpass_option(ctx) ||
  13499. #if !defined(NO_SSL)
  13500. !set_ssl_option(ctx) ||
  13501. #endif
  13502. !set_ports_option(ctx) ||
  13503. #if !defined(_WIN32)
  13504. !set_uid_option(ctx) ||
  13505. #endif
  13506. !set_acl_option(ctx)) {
  13507. free_context(ctx);
  13508. pthread_setspecific(sTlsKey, NULL);
  13509. return NULL;
  13510. }
  13511. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  13512. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  13513. * won't kill the whole process. */
  13514. (void)signal(SIGPIPE, SIG_IGN);
  13515. #endif /* !_WIN32 && !__SYMBIAN32__ */
  13516. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  13517. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13518. sizeof(pthread_t),
  13519. ctx);
  13520. if (ctx->worker_threadids == NULL) {
  13521. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  13522. free_context(ctx);
  13523. pthread_setspecific(sTlsKey, NULL);
  13524. return NULL;
  13525. }
  13526. ctx->worker_connections =
  13527. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13528. sizeof(struct mg_connection),
  13529. ctx);
  13530. if (ctx->worker_connections == NULL) {
  13531. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  13532. free_context(ctx);
  13533. pthread_setspecific(sTlsKey, NULL);
  13534. return NULL;
  13535. }
  13536. #if defined(ALTERNATIVE_QUEUE)
  13537. ctx->client_wait_events = mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  13538. ctx->cfg_worker_threads,
  13539. ctx);
  13540. if (ctx->client_wait_events == NULL) {
  13541. mg_cry(fc(ctx), "Not enough memory for worker event array");
  13542. mg_free(ctx->worker_threadids);
  13543. free_context(ctx);
  13544. pthread_setspecific(sTlsKey, NULL);
  13545. return NULL;
  13546. }
  13547. ctx->client_socks = mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  13548. ctx->cfg_worker_threads,
  13549. ctx);
  13550. if (ctx->client_wait_events == NULL) {
  13551. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  13552. mg_free(ctx->client_socks);
  13553. mg_free(ctx->worker_threadids);
  13554. free_context(ctx);
  13555. pthread_setspecific(sTlsKey, NULL);
  13556. return NULL;
  13557. }
  13558. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13559. ctx->client_wait_events[i] = event_create();
  13560. if (ctx->client_wait_events[i] == 0) {
  13561. mg_cry(fc(ctx), "Error creating worker event %i", i);
  13562. while (i > 0) {
  13563. i--;
  13564. event_destroy(ctx->client_wait_events[i]);
  13565. }
  13566. mg_free(ctx->client_socks);
  13567. mg_free(ctx->worker_threadids);
  13568. free_context(ctx);
  13569. pthread_setspecific(sTlsKey, NULL);
  13570. return NULL;
  13571. }
  13572. }
  13573. #endif
  13574. #if defined(USE_TIMERS)
  13575. if (timers_init(ctx) != 0) {
  13576. mg_cry(fc(ctx), "Error creating timers");
  13577. free_context(ctx);
  13578. pthread_setspecific(sTlsKey, NULL);
  13579. return NULL;
  13580. }
  13581. #endif
  13582. /* Context has been created - init user libraries */
  13583. if (ctx->callbacks.init_context) {
  13584. ctx->callbacks.init_context(ctx);
  13585. }
  13586. ctx->callbacks.exit_context = exit_callback;
  13587. ctx->context_type = 1; /* server context */
  13588. /* Start master (listening) thread */
  13589. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  13590. /* Start worker threads */
  13591. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13592. struct worker_thread_args *wta = (struct worker_thread_args *)
  13593. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  13594. if (wta) {
  13595. wta->ctx = ctx;
  13596. wta->index = (int)i;
  13597. }
  13598. if ((wta == NULL)
  13599. || (mg_start_thread_with_id(worker_thread,
  13600. wta,
  13601. &ctx->worker_threadids[i]) != 0)) {
  13602. /* thread was not created */
  13603. if (wta != NULL) {
  13604. mg_free(wta);
  13605. }
  13606. if (i > 0) {
  13607. mg_cry(fc(ctx),
  13608. "Cannot start worker thread %i: error %ld",
  13609. i + 1,
  13610. (long)ERRNO);
  13611. } else {
  13612. mg_cry(fc(ctx),
  13613. "Cannot create threads: error %ld",
  13614. (long)ERRNO);
  13615. free_context(ctx);
  13616. pthread_setspecific(sTlsKey, NULL);
  13617. return NULL;
  13618. }
  13619. break;
  13620. }
  13621. }
  13622. pthread_setspecific(sTlsKey, NULL);
  13623. return ctx;
  13624. }
  13625. /* Feature check API function */
  13626. unsigned
  13627. mg_check_feature(unsigned feature)
  13628. {
  13629. static const unsigned feature_set = 0
  13630. /* Set bits for available features according to API documentation.
  13631. * This bit mask is created at compile time, according to the active
  13632. * preprocessor defines. It is a single const value at runtime. */
  13633. #if !defined(NO_FILES)
  13634. | 0x0001u
  13635. #endif
  13636. #if !defined(NO_SSL)
  13637. | 0x0002u
  13638. #endif
  13639. #if !defined(NO_CGI)
  13640. | 0x0004u
  13641. #endif
  13642. #if defined(USE_IPV6)
  13643. | 0x0008u
  13644. #endif
  13645. #if defined(USE_WEBSOCKET)
  13646. | 0x0010u
  13647. #endif
  13648. #if defined(USE_LUA)
  13649. | 0x0020u
  13650. #endif
  13651. #if defined(USE_DUKTAPE)
  13652. | 0x0040u
  13653. #endif
  13654. #if !defined(NO_CACHING)
  13655. | 0x0080u
  13656. #endif
  13657. #if defined(USE_SERVER_STATS)
  13658. | 0x0100u
  13659. #endif
  13660. /* Set some extra bits not defined in the API documentation.
  13661. * These bits may change without further notice. */
  13662. #if defined(MG_LEGACY_INTERFACE)
  13663. | 0x8000u
  13664. #endif
  13665. #if defined(MEMORY_DEBUGGING)
  13666. | 0x0100u
  13667. #endif
  13668. #if defined(USE_TIMERS)
  13669. | 0x0200u
  13670. #endif
  13671. #if !defined(NO_NONCE_CHECK)
  13672. | 0x0400u
  13673. #endif
  13674. #if !defined(NO_POPEN)
  13675. | 0x0800u
  13676. #endif
  13677. ;
  13678. return (feature & feature_set);
  13679. }
  13680. /* Get system information. It can be printed or stored by the caller.
  13681. * Return the size of available information. */
  13682. static int
  13683. mg_get_system_info_impl(char *buffer, int buflen)
  13684. {
  13685. char block[256];
  13686. int system_info_length = 0;
  13687. #if defined(_WIN32)
  13688. const char *eol = "\r\n";
  13689. #else
  13690. const char *eol = "\n";
  13691. #endif
  13692. if (buffer == NULL) {
  13693. /* Avoid some warning (although, if some dillweed supplies
  13694. * buffer==NULL combined with buflen>0, he deserves a crash).
  13695. */
  13696. buflen = 0;
  13697. }
  13698. /* Server version */
  13699. {
  13700. const char *version = mg_version();
  13701. mg_snprintf(NULL,
  13702. NULL,
  13703. block,
  13704. sizeof(block),
  13705. "Server Version: %s%s",
  13706. version,
  13707. eol);
  13708. system_info_length += (int)strlen(block);
  13709. if (system_info_length < buflen) {
  13710. strcat(buffer, block);
  13711. }
  13712. }
  13713. /* System info */
  13714. {
  13715. #if defined(_WIN32)
  13716. #if !defined(__SYMBIAN32__)
  13717. DWORD dwVersion = 0;
  13718. DWORD dwMajorVersion = 0;
  13719. DWORD dwMinorVersion = 0;
  13720. SYSTEM_INFO si;
  13721. GetSystemInfo(&si);
  13722. #ifdef _MSC_VER
  13723. #pragma warning(push)
  13724. /* GetVersion was declared deprecated */
  13725. #pragma warning(disable : 4996)
  13726. #endif
  13727. dwVersion = GetVersion();
  13728. #ifdef _MSC_VER
  13729. #pragma warning(pop)
  13730. #endif
  13731. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13732. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13733. mg_snprintf(NULL,
  13734. NULL,
  13735. block,
  13736. sizeof(block),
  13737. "Windows %u.%u%s",
  13738. (unsigned)dwMajorVersion,
  13739. (unsigned)dwMinorVersion,
  13740. eol);
  13741. system_info_length += (int)strlen(block);
  13742. if (system_info_length < buflen) {
  13743. strcat(buffer, block);
  13744. }
  13745. mg_snprintf(NULL,
  13746. NULL,
  13747. block,
  13748. sizeof(block),
  13749. "CPU: type %u, cores %u, mask %x%s",
  13750. (unsigned)si.wProcessorArchitecture,
  13751. (unsigned)si.dwNumberOfProcessors,
  13752. (unsigned)si.dwActiveProcessorMask,
  13753. eol);
  13754. system_info_length += (int)strlen(block);
  13755. if (system_info_length < buflen) {
  13756. strcat(buffer, block);
  13757. }
  13758. #else
  13759. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  13760. system_info_length += (int)strlen(block);
  13761. if (system_info_length < buflen) {
  13762. strcat(buffer, block);
  13763. }
  13764. #endif
  13765. #else
  13766. struct utsname name;
  13767. memset(&name, 0, sizeof(name));
  13768. uname(&name);
  13769. mg_snprintf(NULL,
  13770. NULL,
  13771. block,
  13772. sizeof(block),
  13773. "%s %s (%s) - %s%s",
  13774. name.sysname,
  13775. name.version,
  13776. name.release,
  13777. name.machine,
  13778. eol);
  13779. system_info_length += (int)strlen(block);
  13780. if (system_info_length < buflen) {
  13781. strcat(buffer, block);
  13782. }
  13783. #endif
  13784. }
  13785. /* Features */
  13786. {
  13787. mg_snprintf(NULL,
  13788. NULL,
  13789. block,
  13790. sizeof(block),
  13791. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  13792. mg_check_feature(0xFFFFFFFFu),
  13793. eol,
  13794. mg_check_feature(1) ? " Files" : "",
  13795. mg_check_feature(2) ? " HTTPS" : "",
  13796. mg_check_feature(4) ? " CGI" : "",
  13797. mg_check_feature(8) ? " IPv6" : "",
  13798. mg_check_feature(16) ? " WebSockets" : "",
  13799. mg_check_feature(32) ? " Lua" : "",
  13800. mg_check_feature(64) ? " JavaScript" : "",
  13801. mg_check_feature(128) ? " Cache" : "",
  13802. eol);
  13803. system_info_length += (int)strlen(block);
  13804. if (system_info_length < buflen) {
  13805. strcat(buffer, block);
  13806. }
  13807. #ifdef USE_LUA
  13808. mg_snprintf(NULL,
  13809. NULL,
  13810. block,
  13811. sizeof(block),
  13812. "Lua Version: %u (%s)%s",
  13813. (unsigned)LUA_VERSION_NUM,
  13814. LUA_RELEASE,
  13815. eol);
  13816. system_info_length += (int)strlen(block);
  13817. if (system_info_length < buflen) {
  13818. strcat(buffer, block);
  13819. }
  13820. #endif
  13821. #if defined(USE_DUKTAPE)
  13822. mg_snprintf(NULL,
  13823. NULL,
  13824. block,
  13825. sizeof(block),
  13826. "JavaScript: Duktape %u.%u.%u%s",
  13827. (unsigned)DUK_VERSION / 10000,
  13828. ((unsigned)DUK_VERSION / 100) % 100,
  13829. (unsigned)DUK_VERSION % 100,
  13830. eol);
  13831. system_info_length += (int)strlen(block);
  13832. if (system_info_length < buflen) {
  13833. strcat(buffer, block);
  13834. }
  13835. #endif
  13836. }
  13837. /* Build date */
  13838. {
  13839. mg_snprintf(
  13840. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  13841. system_info_length += (int)strlen(block);
  13842. if (system_info_length < buflen) {
  13843. strcat(buffer, block);
  13844. }
  13845. }
  13846. /* Compiler information */
  13847. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  13848. {
  13849. #if defined(_MSC_VER)
  13850. mg_snprintf(NULL,
  13851. NULL,
  13852. block,
  13853. sizeof(block),
  13854. "MSC: %u (%u)%s",
  13855. (unsigned)_MSC_VER,
  13856. (unsigned)_MSC_FULL_VER,
  13857. eol);
  13858. system_info_length += (int)strlen(block);
  13859. if (system_info_length < buflen) {
  13860. strcat(buffer, block);
  13861. }
  13862. #elif defined(__MINGW64__)
  13863. mg_snprintf(NULL,
  13864. NULL,
  13865. block,
  13866. sizeof(block),
  13867. "MinGW64: %u.%u%s",
  13868. (unsigned)__MINGW64_VERSION_MAJOR,
  13869. (unsigned)__MINGW64_VERSION_MINOR,
  13870. eol);
  13871. system_info_length += (int)strlen(block);
  13872. if (system_info_length < buflen) {
  13873. strcat(buffer, block);
  13874. }
  13875. mg_snprintf(NULL,
  13876. NULL,
  13877. block,
  13878. sizeof(block),
  13879. "MinGW32: %u.%u%s",
  13880. (unsigned)__MINGW32_MAJOR_VERSION,
  13881. (unsigned)__MINGW32_MINOR_VERSION,
  13882. eol);
  13883. system_info_length += (int)strlen(block);
  13884. if (system_info_length < buflen) {
  13885. strcat(buffer, block);
  13886. }
  13887. #elif defined(__MINGW32__)
  13888. mg_snprintf(NULL,
  13889. NULL,
  13890. block,
  13891. sizeof(block),
  13892. "MinGW32: %u.%u%s",
  13893. (unsigned)__MINGW32_MAJOR_VERSION,
  13894. (unsigned)__MINGW32_MINOR_VERSION,
  13895. eol);
  13896. system_info_length += (int)strlen(block);
  13897. if (system_info_length < buflen) {
  13898. strcat(buffer, block);
  13899. }
  13900. #elif defined(__clang__)
  13901. mg_snprintf(NULL,
  13902. NULL,
  13903. block,
  13904. sizeof(block),
  13905. "clang: %u.%u.%u (%s)%s",
  13906. __clang_major__,
  13907. __clang_minor__,
  13908. __clang_patchlevel__,
  13909. __clang_version__,
  13910. eol);
  13911. system_info_length += (int)strlen(block);
  13912. if (system_info_length < buflen) {
  13913. strcat(buffer, block);
  13914. }
  13915. #elif defined(__GNUC__)
  13916. mg_snprintf(NULL,
  13917. NULL,
  13918. block,
  13919. sizeof(block),
  13920. "gcc: %u.%u.%u%s",
  13921. (unsigned)__GNUC__,
  13922. (unsigned)__GNUC_MINOR__,
  13923. (unsigned)__GNUC_PATCHLEVEL__,
  13924. eol);
  13925. system_info_length += (int)strlen(block);
  13926. if (system_info_length < buflen) {
  13927. strcat(buffer, block);
  13928. }
  13929. #elif defined(__INTEL_COMPILER)
  13930. mg_snprintf(NULL,
  13931. NULL,
  13932. block,
  13933. sizeof(block),
  13934. "Intel C/C++: %u%s",
  13935. (unsigned)__INTEL_COMPILER,
  13936. eol);
  13937. system_info_length += (int)strlen(block);
  13938. if (system_info_length < buflen) {
  13939. strcat(buffer, block);
  13940. }
  13941. #elif defined(__BORLANDC__)
  13942. mg_snprintf(NULL,
  13943. NULL,
  13944. block,
  13945. sizeof(block),
  13946. "Borland C: 0x%x%s",
  13947. (unsigned)__BORLANDC__,
  13948. eol);
  13949. system_info_length += (int)strlen(block);
  13950. if (system_info_length < buflen) {
  13951. strcat(buffer, block);
  13952. }
  13953. #elif defined(__SUNPRO_C)
  13954. mg_snprintf(NULL,
  13955. NULL,
  13956. block,
  13957. sizeof(block),
  13958. "Solaris: 0x%x%s",
  13959. (unsigned)__SUNPRO_C,
  13960. eol);
  13961. system_info_length += (int)strlen(block);
  13962. if (system_info_length < buflen) {
  13963. strcat(buffer, block);
  13964. }
  13965. #else
  13966. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13967. system_info_length += (int)strlen(block);
  13968. if (system_info_length < buflen) {
  13969. strcat(buffer, block);
  13970. }
  13971. #endif
  13972. }
  13973. /* Determine 32/64 bit data mode.
  13974. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13975. {
  13976. mg_snprintf(NULL,
  13977. NULL,
  13978. block,
  13979. sizeof(block),
  13980. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13981. "ptr:%u, size:%u, time:%u%s",
  13982. (unsigned)sizeof(short),
  13983. (unsigned)sizeof(int),
  13984. (unsigned)sizeof(long),
  13985. (unsigned)sizeof(long long),
  13986. (unsigned)sizeof(float),
  13987. (unsigned)sizeof(double),
  13988. (unsigned)sizeof(long double),
  13989. (unsigned)sizeof(char),
  13990. (unsigned)sizeof(wchar_t),
  13991. (unsigned)sizeof(void *),
  13992. (unsigned)sizeof(size_t),
  13993. (unsigned)sizeof(time_t),
  13994. eol);
  13995. system_info_length += (int)strlen(block);
  13996. if (system_info_length < buflen) {
  13997. strcat(buffer, block);
  13998. }
  13999. }
  14000. return system_info_length;
  14001. }
  14002. #if defined(USE_SERVER_STATS)
  14003. /* Get context information. It can be printed or stored by the caller.
  14004. * Return the size of available information. */
  14005. static int
  14006. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  14007. {
  14008. char block[256];
  14009. int context_info_length = 0;
  14010. #if defined(_WIN32)
  14011. const char *eol = "\r\n";
  14012. #else
  14013. const char *eol = "\n";
  14014. #endif
  14015. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  14016. const char *eoobj = "}";
  14017. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  14018. if ((buffer == NULL) || (buflen < 10)) {
  14019. buflen = 0;
  14020. }
  14021. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  14022. context_info_length += (int)strlen(block);
  14023. if (context_info_length < buflen) {
  14024. strcat(buffer, block);
  14025. }
  14026. /* Memory information */
  14027. if (ms) {
  14028. mg_snprintf(NULL,
  14029. NULL,
  14030. block,
  14031. sizeof(block),
  14032. "\"memory\" : {%s"
  14033. "\"blocks\" : %i,%s"
  14034. "\"used\" : %" INT64_FMT ",%s"
  14035. "\"maxUsed\" : %" INT64_FMT "%s"
  14036. "}%s%s",
  14037. eol,
  14038. ms->blockCount,
  14039. eol,
  14040. ms->totalMemUsed,
  14041. eol,
  14042. ms->maxMemUsed,
  14043. eol,
  14044. (ctx ? "," : ""),
  14045. eol);
  14046. context_info_length += (int)strlen(block);
  14047. if (context_info_length + reserved_len < buflen) {
  14048. strcat(buffer, block);
  14049. }
  14050. }
  14051. /* Connections information */
  14052. if (ctx) {
  14053. mg_snprintf(NULL,
  14054. NULL,
  14055. block,
  14056. sizeof(block),
  14057. "\"connections\" : {%s"
  14058. "\"active\" : %i,%s"
  14059. "\"maxActive\" : %i,%s"
  14060. "\"total\" : %" INT64_FMT "%s"
  14061. "},%s",
  14062. eol,
  14063. ctx->active_connections,
  14064. eol,
  14065. ctx->max_connections,
  14066. eol,
  14067. ctx->total_connections,
  14068. eol,
  14069. eol);
  14070. context_info_length += (int)strlen(block);
  14071. if (context_info_length + reserved_len < buflen) {
  14072. strcat(buffer, block);
  14073. }
  14074. }
  14075. /* Requests information */
  14076. if (ctx) {
  14077. mg_snprintf(NULL,
  14078. NULL,
  14079. block,
  14080. sizeof(block),
  14081. "\"requests\" : {%s"
  14082. "\"total\" : %" INT64_FMT "%s"
  14083. "}%s",
  14084. eol,
  14085. ctx->total_requests,
  14086. eol,
  14087. eol);
  14088. context_info_length += (int)strlen(block);
  14089. if (context_info_length + reserved_len < buflen) {
  14090. strcat(buffer, block);
  14091. }
  14092. }
  14093. if ((buflen > 0) && buffer && buffer[0]) {
  14094. if (context_info_length < buflen) {
  14095. strcat(buffer, eoobj);
  14096. strcat(buffer, eol);
  14097. context_info_length += reserved_len;
  14098. }
  14099. }
  14100. return context_info_length;
  14101. }
  14102. #endif
  14103. /* Get system information. It can be printed or stored by the caller.
  14104. * Return the size of available information. */
  14105. int
  14106. mg_get_system_info(char *buffer, int buflen)
  14107. {
  14108. if ((buffer == NULL) || (buflen < 1)) {
  14109. return mg_get_system_info_impl(NULL, 0);
  14110. } else {
  14111. /* Reset buffer, so we can always use strcat. */
  14112. buffer[0] = 0;
  14113. return mg_get_system_info_impl(buffer, buflen);
  14114. }
  14115. }
  14116. /* Get context information. It can be printed or stored by the caller.
  14117. * Return the size of available information. */
  14118. int
  14119. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  14120. {
  14121. #if defined(USE_SERVER_STATS)
  14122. if ((buffer == NULL) || (buflen < 1)) {
  14123. return mg_get_context_info_impl(ctx, NULL, 0);
  14124. } else {
  14125. /* Reset buffer, so we can always use strcat. */
  14126. buffer[0] = 0;
  14127. return mg_get_context_info_impl(ctx, buffer, buflen);
  14128. }
  14129. #else
  14130. (void)ctx;
  14131. if ((buffer != NULL) && (buflen > 0)) {
  14132. buffer[0] = 0;
  14133. }
  14134. return 0;
  14135. #endif
  14136. }
  14137. /* mg_init_library counter */
  14138. static int mg_init_library_called = 0;
  14139. #if !defined(NO_SSL)
  14140. static int mg_ssl_initialized = 0;
  14141. #endif
  14142. /* Initialize this library. This function does not need to be thread safe. */
  14143. unsigned
  14144. mg_init_library(unsigned features)
  14145. {
  14146. #if !defined(NO_SSL)
  14147. char ebuf[128];
  14148. #endif
  14149. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  14150. unsigned features_inited = features_to_init;
  14151. #if !defined(NO_SSL)
  14152. if (features_to_init & 2) {
  14153. if (!mg_ssl_initialized) {
  14154. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  14155. mg_ssl_initialized = 1;
  14156. } else {
  14157. (void)ebuf;
  14158. /* TODO: print error */
  14159. features_inited &= ~(2u);
  14160. }
  14161. } else {
  14162. /* ssl already initialized */
  14163. }
  14164. }
  14165. #endif
  14166. /* Start Windows. */
  14167. if (mg_init_library_called <= 0) {
  14168. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14169. WSADATA data;
  14170. WSAStartup(MAKEWORD(2, 2), &data);
  14171. #endif /* _WIN32 && !__SYMBIAN32__ */
  14172. mg_init_library_called = 1;
  14173. } else {
  14174. mg_init_library_called++;
  14175. }
  14176. return features_inited;
  14177. }
  14178. /* Un-initialize this library. */
  14179. unsigned
  14180. mg_exit_library(void)
  14181. {
  14182. if (mg_init_library_called <= 0) {
  14183. return 0;
  14184. }
  14185. mg_init_library_called--;
  14186. if (mg_init_library_called == 0) {
  14187. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14188. (void)WSACleanup();
  14189. #endif /* _WIN32 && !__SYMBIAN32__ */
  14190. #if !defined(NO_SSL)
  14191. if (mg_ssl_initialized) {
  14192. uninitialize_ssl();
  14193. mg_ssl_initialized = 0;
  14194. }
  14195. #endif
  14196. }
  14197. return 1;
  14198. }
  14199. /* End of civetweb.c */