civetweb.c 425 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143
  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()
  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. ERROR_PAGES,
  1616. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1617. * socket option typedef TCP_NODELAY. */
  1618. #if !defined(NO_CACHING)
  1619. STATIC_FILE_MAX_AGE,
  1620. #endif
  1621. #if !defined(NO_SSL)
  1622. STRICT_HTTPS_MAX_AGE,
  1623. #endif
  1624. #if defined(__linux__)
  1625. ALLOW_SENDFILE_CALL,
  1626. #endif
  1627. #if defined(_WIN32)
  1628. CASE_SENSITIVE_FILES,
  1629. #endif
  1630. #if defined(USE_LUA)
  1631. LUA_BACKGROUND_SCRIPT,
  1632. #endif
  1633. ADDITIONAL_HEADER,
  1634. MAX_REQUEST_SIZE,
  1635. NUM_OPTIONS
  1636. };
  1637. /* Config option name, config types, default value */
  1638. static struct mg_option config_options[] = {
  1639. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1640. {"cgi_environment", CONFIG_TYPE_STRING_LIST, NULL},
  1641. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1642. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1643. {"protect_uri", CONFIG_TYPE_STRING_LIST, NULL},
  1644. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1645. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1646. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1647. {"throttle", CONFIG_TYPE_STRING_LIST, NULL},
  1648. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1649. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1650. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1651. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1652. {"index_files",
  1653. CONFIG_TYPE_STRING_LIST,
  1654. #ifdef USE_LUA
  1655. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1656. "index.shtml,index.php"},
  1657. #else
  1658. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1659. #endif
  1660. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1661. {"access_control_list", CONFIG_TYPE_STRING_LIST, NULL},
  1662. {"extra_mime_types", CONFIG_TYPE_STRING_LIST, NULL},
  1663. {"listening_ports", CONFIG_TYPE_STRING_LIST, "8080"},
  1664. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1665. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1666. {"ssl_certificate_chain", CONFIG_TYPE_FILE, NULL},
  1667. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1668. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1669. {"url_rewrite_patterns", CONFIG_TYPE_STRING_LIST, NULL},
  1670. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1671. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1672. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1673. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1674. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1675. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1676. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1677. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1678. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1679. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1680. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1681. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1682. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1683. #if defined(USE_WEBSOCKET)
  1684. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1685. #endif
  1686. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1687. #if defined(USE_LUA)
  1688. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1689. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1690. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1691. #endif
  1692. #if defined(USE_DUKTAPE)
  1693. /* The support for duktape is still in alpha version state.
  1694. * The name of this config option might change. */
  1695. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1696. #endif
  1697. #if defined(USE_WEBSOCKET)
  1698. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1699. #endif
  1700. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1701. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1702. #endif
  1703. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1704. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1705. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1706. #if !defined(NO_CACHING)
  1707. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1708. #endif
  1709. #if !defined(NO_SSL)
  1710. {"strict_transport_security_max_age", CONFIG_TYPE_NUMBER, NULL},
  1711. #endif
  1712. #if defined(__linux__)
  1713. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1714. #endif
  1715. #if defined(_WIN32)
  1716. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1717. #endif
  1718. #if defined(USE_LUA)
  1719. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1720. #endif
  1721. {"additional_header", CONFIG_TYPE_STRING_MULTILINE, NULL},
  1722. {"max_request_size", CONFIG_TYPE_NUMBER, "16384"},
  1723. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1724. /* Check if the config_options and the corresponding enum have compatible
  1725. * sizes. */
  1726. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1727. == (NUM_OPTIONS + 1),
  1728. "config_options and enum not sync");
  1729. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1730. struct mg_handler_info {
  1731. /* Name/Pattern of the URI. */
  1732. char *uri;
  1733. size_t uri_len;
  1734. /* handler type */
  1735. int handler_type;
  1736. /* Handler for http/https or authorization requests. */
  1737. mg_request_handler handler;
  1738. /* Handler for ws/wss (websocket) requests. */
  1739. mg_websocket_connect_handler connect_handler;
  1740. mg_websocket_ready_handler ready_handler;
  1741. mg_websocket_data_handler data_handler;
  1742. mg_websocket_close_handler close_handler;
  1743. /* accepted subprotocols for ws/wss requests. */
  1744. struct mg_websocket_subprotocols *subprotocols;
  1745. /* Handler for authorization requests */
  1746. mg_authorization_handler auth_handler;
  1747. /* User supplied argument for the handler function. */
  1748. void *cbdata;
  1749. /* next handler in a linked list */
  1750. struct mg_handler_info *next;
  1751. };
  1752. struct mg_context {
  1753. volatile int stop_flag; /* Should we stop event loop */
  1754. SSL_CTX *ssl_ctx; /* SSL context */
  1755. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1756. struct mg_callbacks callbacks; /* User-defined callback function */
  1757. void *user_data; /* User-defined data */
  1758. int context_type; /* 1 = server context,
  1759. * 2 = ws/wss client context,
  1760. */
  1761. struct socket *listening_sockets;
  1762. struct pollfd *listening_socket_fds;
  1763. unsigned int num_listening_sockets;
  1764. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1765. #ifdef ALTERNATIVE_QUEUE
  1766. struct socket *client_socks;
  1767. void **client_wait_events;
  1768. #else
  1769. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1770. volatile int sq_head; /* Head of the socket queue */
  1771. volatile int sq_tail; /* Tail of the socket queue */
  1772. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1773. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1774. #endif
  1775. unsigned int max_request_size; /* The max request size */
  1776. pthread_t masterthreadid; /* The master thread ID */
  1777. unsigned int
  1778. cfg_worker_threads; /* The number of configured worker threads. */
  1779. pthread_t *worker_threadids; /* The worker thread IDs */
  1780. struct mg_connection *worker_connections; /* The connection struct, pre-
  1781. * allocated for each worker */
  1782. time_t start_time; /* Server start time, used for authentication */
  1783. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1784. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1785. unsigned long nonce_count; /* Used nonces, used for authentication */
  1786. char *systemName; /* What operating system is running */
  1787. /* linked list of uri handlers */
  1788. struct mg_handler_info *handlers;
  1789. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1790. /* linked list of shared lua websockets */
  1791. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1792. #endif
  1793. #if defined(USE_TIMERS)
  1794. struct ttimers *timers;
  1795. #endif
  1796. #if defined(USE_LUA)
  1797. void *lua_background_state;
  1798. #endif
  1799. #if defined(USE_SERVER_STATS)
  1800. int active_connections;
  1801. int max_connections;
  1802. int64_t total_connections;
  1803. int64_t total_requests;
  1804. struct mg_memory_stat ctx_memory;
  1805. #endif
  1806. };
  1807. #if defined(USE_SERVER_STATS)
  1808. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  1809. static struct mg_memory_stat *
  1810. get_memory_stat(struct mg_context *ctx)
  1811. {
  1812. if (ctx) {
  1813. return &(ctx->ctx_memory);
  1814. }
  1815. return &mg_common_memory;
  1816. }
  1817. #endif
  1818. struct mg_connection {
  1819. struct mg_request_info request_info;
  1820. struct mg_context *ctx;
  1821. SSL *ssl; /* SSL descriptor */
  1822. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1823. struct socket client; /* Connected client */
  1824. time_t conn_birth_time; /* Time (wall clock) when connection was
  1825. * established */
  1826. struct timespec req_time; /* Time (since system start) when the request
  1827. * was received */
  1828. int64_t num_bytes_sent; /* Total bytes sent to client */
  1829. int64_t content_len; /* Content-Length header value */
  1830. int64_t consumed_content; /* How many bytes of content have been read */
  1831. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1832. * data available, 2: all data read */
  1833. size_t chunk_remainder; /* Unread data from the last chunk */
  1834. char *buf; /* Buffer for received data */
  1835. char *path_info; /* PATH_INFO part of the URL */
  1836. int must_close; /* 1 if connection must be closed */
  1837. int in_error_handler; /* 1 if in handler for user defined error
  1838. * pages */
  1839. int handled_requests; /* Number of requests handled by this connection */
  1840. int buf_size; /* Buffer size */
  1841. int request_len; /* Size of the request + headers in a buffer */
  1842. int data_len; /* Total size of data in a buffer */
  1843. int status_code; /* HTTP reply status code, e.g. 200 */
  1844. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1845. * throttle */
  1846. time_t last_throttle_time; /* Last time throttled data was sent */
  1847. int64_t last_throttle_bytes; /* Bytes sent this second */
  1848. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1849. * atomic transmissions for websockets */
  1850. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1851. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1852. #endif
  1853. int thread_index; /* Thread index within ctx */
  1854. };
  1855. /* Directory entry */
  1856. struct de {
  1857. struct mg_connection *conn;
  1858. char *file_name;
  1859. struct mg_file_stat file;
  1860. };
  1861. #if defined(USE_WEBSOCKET)
  1862. static int is_websocket_protocol(const struct mg_connection *conn);
  1863. #else
  1864. #define is_websocket_protocol(conn) (0)
  1865. #endif
  1866. #if !defined(NO_THREAD_NAME)
  1867. #if defined(_WIN32) && defined(_MSC_VER)
  1868. /* Set the thread name for debugging purposes in Visual Studio
  1869. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1870. */
  1871. #pragma pack(push, 8)
  1872. typedef struct tagTHREADNAME_INFO {
  1873. DWORD dwType; /* Must be 0x1000. */
  1874. LPCSTR szName; /* Pointer to name (in user addr space). */
  1875. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1876. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1877. } THREADNAME_INFO;
  1878. #pragma pack(pop)
  1879. #elif defined(__linux__)
  1880. #include <sys/prctl.h>
  1881. #include <sys/sendfile.h>
  1882. #include <sys/eventfd.h>
  1883. #if defined(ALTERNATIVE_QUEUE)
  1884. static void *
  1885. event_create(void)
  1886. {
  1887. int ret = eventfd(0, EFD_CLOEXEC);
  1888. if (ret == -1) {
  1889. /* Linux uses -1 on error, Windows NULL. */
  1890. /* However, Linux does not return 0 on success either. */
  1891. return 0;
  1892. }
  1893. return (void *)ret;
  1894. }
  1895. static int
  1896. event_wait(void *eventhdl)
  1897. {
  1898. uint64_t u;
  1899. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1900. if (s != sizeof(uint64_t)) {
  1901. /* error */
  1902. return 0;
  1903. }
  1904. (void)u; /* the value is not required */
  1905. return 1;
  1906. }
  1907. static int
  1908. event_signal(void *eventhdl)
  1909. {
  1910. uint64_t u = 1;
  1911. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1912. if (s != sizeof(uint64_t)) {
  1913. /* error */
  1914. return 0;
  1915. }
  1916. return 1;
  1917. }
  1918. static void
  1919. event_destroy(void *eventhdl)
  1920. {
  1921. close((int)eventhdl);
  1922. }
  1923. #endif
  1924. #endif
  1925. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1926. struct posix_event {
  1927. pthread_mutex_t mutex;
  1928. pthread_cond_t cond;
  1929. };
  1930. static void *
  1931. event_create(void)
  1932. {
  1933. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1934. if (ret == 0) {
  1935. /* out of memory */
  1936. return 0;
  1937. }
  1938. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1939. /* pthread mutex not available */
  1940. mg_free(ret);
  1941. return 0;
  1942. }
  1943. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1944. /* pthread cond not available */
  1945. pthread_mutex_destroy(&(ret->mutex));
  1946. mg_free(ret);
  1947. return 0;
  1948. }
  1949. return (void *)ret;
  1950. }
  1951. static int
  1952. event_wait(void *eventhdl)
  1953. {
  1954. struct posix_event *ev = (struct posix_event *)eventhdl;
  1955. pthread_mutex_lock(&(ev->mutex));
  1956. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1957. pthread_mutex_unlock(&(ev->mutex));
  1958. return 1;
  1959. }
  1960. static int
  1961. event_signal(void *eventhdl)
  1962. {
  1963. struct posix_event *ev = (struct posix_event *)eventhdl;
  1964. pthread_mutex_lock(&(ev->mutex));
  1965. pthread_cond_signal(&(ev->cond));
  1966. pthread_mutex_unlock(&(ev->mutex));
  1967. return 1;
  1968. }
  1969. static void
  1970. event_destroy(void *eventhdl)
  1971. {
  1972. struct posix_event *ev = (struct posix_event *)eventhdl;
  1973. pthread_cond_destroy(&(ev->cond));
  1974. pthread_mutex_destroy(&(ev->mutex));
  1975. mg_free(ev);
  1976. }
  1977. #endif
  1978. static void
  1979. mg_set_thread_name(const char *name)
  1980. {
  1981. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1982. mg_snprintf(
  1983. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1984. #if defined(_WIN32)
  1985. #if defined(_MSC_VER)
  1986. /* Windows and Visual Studio Compiler */
  1987. __try
  1988. {
  1989. THREADNAME_INFO info;
  1990. info.dwType = 0x1000;
  1991. info.szName = threadName;
  1992. info.dwThreadID = ~0U;
  1993. info.dwFlags = 0;
  1994. RaiseException(0x406D1388,
  1995. 0,
  1996. sizeof(info) / sizeof(ULONG_PTR),
  1997. (ULONG_PTR *)&info);
  1998. }
  1999. __except(EXCEPTION_EXECUTE_HANDLER)
  2000. {
  2001. }
  2002. #elif defined(__MINGW32__)
  2003. /* No option known to set thread name for MinGW */
  2004. #endif
  2005. #elif defined(__GLIBC__) \
  2006. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2007. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2008. (void)pthread_setname_np(pthread_self(), threadName);
  2009. #elif defined(__linux__)
  2010. /* on linux we can use the old prctl function */
  2011. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2012. #endif
  2013. }
  2014. #else /* !defined(NO_THREAD_NAME) */
  2015. void
  2016. mg_set_thread_name(const char *threadName)
  2017. {
  2018. }
  2019. #endif
  2020. #if defined(MG_LEGACY_INTERFACE)
  2021. const char **
  2022. mg_get_valid_option_names(void)
  2023. {
  2024. /* This function is deprecated. Use mg_get_valid_options instead. */
  2025. static const char *
  2026. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2027. int i;
  2028. for (i = 0; config_options[i].name != NULL; i++) {
  2029. data[i * 2] = config_options[i].name;
  2030. data[i * 2 + 1] = config_options[i].default_value;
  2031. }
  2032. return data;
  2033. }
  2034. #endif
  2035. const struct mg_option *
  2036. mg_get_valid_options(void)
  2037. {
  2038. return config_options;
  2039. }
  2040. /* Do not open file (used in is_file_in_memory) */
  2041. #define MG_FOPEN_MODE_NONE (0)
  2042. /* Open file for read only access */
  2043. #define MG_FOPEN_MODE_READ (1)
  2044. /* Open file for writing, create and overwrite */
  2045. #define MG_FOPEN_MODE_WRITE (2)
  2046. /* Open file for writing, create and append */
  2047. #define MG_FOPEN_MODE_APPEND (4)
  2048. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2049. * output filep and return 1, otherwise return 0 and don't modify anything. */
  2050. static int
  2051. open_file_in_memory(const struct mg_connection *conn,
  2052. const char *path,
  2053. struct mg_file *filep,
  2054. int mode)
  2055. {
  2056. #if defined(MG_USE_OPEN_FILE)
  2057. size_t size = 0;
  2058. const char *buf = NULL;
  2059. if (!conn) {
  2060. return 0;
  2061. }
  2062. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2063. return 0;
  2064. }
  2065. if (conn->ctx->callbacks.open_file) {
  2066. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2067. if (buf != NULL) {
  2068. if (filep == NULL) {
  2069. /* This is a file in memory, but we cannot store the properties
  2070. * now.
  2071. * Called from "is_file_in_memory" function. */
  2072. return 1;
  2073. }
  2074. /* NOTE: override filep->size only on success. Otherwise, it might
  2075. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2076. filep->access.membuf = buf;
  2077. filep->access.fp = NULL;
  2078. /* Size was set by the callback */
  2079. filep->stat.size = size;
  2080. /* Assume the data may change during runtime by setting
  2081. * last_modified = now */
  2082. filep->stat.last_modified = time(NULL);
  2083. filep->stat.is_directory = 0;
  2084. filep->stat.is_gzipped = 0;
  2085. }
  2086. }
  2087. return (buf != NULL);
  2088. #else
  2089. (void)conn;
  2090. (void)path;
  2091. (void)filep;
  2092. (void)mode;
  2093. return 0;
  2094. #endif
  2095. }
  2096. static int
  2097. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2098. {
  2099. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2100. }
  2101. static int
  2102. is_file_opened(const struct mg_file_access *fileacc)
  2103. {
  2104. if (!fileacc) {
  2105. return 0;
  2106. }
  2107. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2108. }
  2109. static int mg_stat(const struct mg_connection *conn,
  2110. const char *path,
  2111. struct mg_file_stat *filep);
  2112. /* mg_fopen will open a file either in memory or on the disk.
  2113. * The input parameter path is a string in UTF-8 encoding.
  2114. * The input parameter mode is MG_FOPEN_MODE_*
  2115. * On success, either fp or membuf will be set in the output
  2116. * struct file. All status members will also be set.
  2117. * The function returns 1 on success, 0 on error. */
  2118. static int
  2119. mg_fopen(const struct mg_connection *conn,
  2120. const char *path,
  2121. int mode,
  2122. struct mg_file *filep)
  2123. {
  2124. int found;
  2125. if (!filep) {
  2126. return 0;
  2127. }
  2128. filep->access.fp = NULL;
  2129. filep->access.membuf = NULL;
  2130. if (!is_file_in_memory(conn, path)) {
  2131. /* filep is initialized in mg_stat: all fields with memset to,
  2132. * some fields like size and modification date with values */
  2133. found = mg_stat(conn, path, &(filep->stat));
  2134. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2135. /* file does not exist and will not be created */
  2136. return 0;
  2137. }
  2138. #ifdef _WIN32
  2139. {
  2140. wchar_t wbuf[PATH_MAX];
  2141. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2142. switch (mode) {
  2143. case MG_FOPEN_MODE_READ:
  2144. filep->access.fp = _wfopen(wbuf, L"rb");
  2145. break;
  2146. case MG_FOPEN_MODE_WRITE:
  2147. filep->access.fp = _wfopen(wbuf, L"wb");
  2148. break;
  2149. case MG_FOPEN_MODE_APPEND:
  2150. filep->access.fp = _wfopen(wbuf, L"ab");
  2151. break;
  2152. }
  2153. }
  2154. #else
  2155. /* Linux et al already use unicode. No need to convert. */
  2156. switch (mode) {
  2157. case MG_FOPEN_MODE_READ:
  2158. filep->access.fp = fopen(path, "r");
  2159. break;
  2160. case MG_FOPEN_MODE_WRITE:
  2161. filep->access.fp = fopen(path, "w");
  2162. break;
  2163. case MG_FOPEN_MODE_APPEND:
  2164. filep->access.fp = fopen(path, "a");
  2165. break;
  2166. }
  2167. #endif
  2168. if (!found) {
  2169. /* File did not exist before fopen was called.
  2170. * Maybe it has been created now. Get stat info
  2171. * like creation time now. */
  2172. found = mg_stat(conn, path, &(filep->stat));
  2173. (void)found;
  2174. }
  2175. /* file is on disk */
  2176. return (filep->access.fp != NULL);
  2177. } else {
  2178. /* is_file_in_memory returned true */
  2179. if (open_file_in_memory(conn, path, filep, mode)) {
  2180. /* file is in memory */
  2181. return (filep->access.membuf != NULL);
  2182. }
  2183. }
  2184. /* Open failed */
  2185. return 0;
  2186. }
  2187. /* return 0 on success, just like fclose */
  2188. static int
  2189. mg_fclose(struct mg_file_access *fileacc)
  2190. {
  2191. int ret = -1;
  2192. if (fileacc != NULL) {
  2193. if (fileacc->fp != NULL) {
  2194. ret = fclose(fileacc->fp);
  2195. } else if (fileacc->membuf != NULL) {
  2196. ret = 0;
  2197. }
  2198. /* reset all members of fileacc */
  2199. memset(fileacc, 0, sizeof(*fileacc));
  2200. }
  2201. return ret;
  2202. }
  2203. static void
  2204. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2205. {
  2206. for (; *src != '\0' && n > 1; n--) {
  2207. *dst++ = *src++;
  2208. }
  2209. *dst = '\0';
  2210. }
  2211. static int
  2212. lowercase(const char *s)
  2213. {
  2214. return tolower(*(const unsigned char *)s);
  2215. }
  2216. int
  2217. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2218. {
  2219. int diff = 0;
  2220. if (len > 0) {
  2221. do {
  2222. diff = lowercase(s1++) - lowercase(s2++);
  2223. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2224. }
  2225. return diff;
  2226. }
  2227. int
  2228. mg_strcasecmp(const char *s1, const char *s2)
  2229. {
  2230. int diff;
  2231. do {
  2232. diff = lowercase(s1++) - lowercase(s2++);
  2233. } while (diff == 0 && s1[-1] != '\0');
  2234. return diff;
  2235. }
  2236. static char *
  2237. mg_strndup(const char *ptr, size_t len)
  2238. {
  2239. char *p;
  2240. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2241. mg_strlcpy(p, ptr, len + 1);
  2242. }
  2243. return p;
  2244. }
  2245. static char *
  2246. mg_strdup(const char *str)
  2247. {
  2248. return mg_strndup(str, strlen(str));
  2249. }
  2250. static const char *
  2251. mg_strcasestr(const char *big_str, const char *small_str)
  2252. {
  2253. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2254. if (big_len >= small_len) {
  2255. for (i = 0; i <= (big_len - small_len); i++) {
  2256. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2257. return big_str + i;
  2258. }
  2259. }
  2260. }
  2261. return NULL;
  2262. }
  2263. /* Return null terminated string of given maximum length.
  2264. * Report errors if length is exceeded. */
  2265. static void
  2266. mg_vsnprintf(const struct mg_connection *conn,
  2267. int *truncated,
  2268. char *buf,
  2269. size_t buflen,
  2270. const char *fmt,
  2271. va_list ap)
  2272. {
  2273. int n, ok;
  2274. if (buflen == 0) {
  2275. return;
  2276. }
  2277. #ifdef __clang__
  2278. #pragma clang diagnostic push
  2279. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2280. /* Using fmt as a non-literal is intended here, since it is mostly called
  2281. * indirectly by mg_snprintf */
  2282. #endif
  2283. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2284. ok = (n >= 0) && ((size_t)n < buflen);
  2285. #ifdef __clang__
  2286. #pragma clang diagnostic pop
  2287. #endif
  2288. if (ok) {
  2289. if (truncated) {
  2290. *truncated = 0;
  2291. }
  2292. } else {
  2293. if (truncated) {
  2294. *truncated = 1;
  2295. }
  2296. mg_cry(conn,
  2297. "truncating vsnprintf buffer: [%.*s]",
  2298. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2299. buf);
  2300. n = (int)buflen - 1;
  2301. }
  2302. buf[n] = '\0';
  2303. }
  2304. static void
  2305. mg_snprintf(const struct mg_connection *conn,
  2306. int *truncated,
  2307. char *buf,
  2308. size_t buflen,
  2309. const char *fmt,
  2310. ...)
  2311. {
  2312. va_list ap;
  2313. va_start(ap, fmt);
  2314. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2315. va_end(ap);
  2316. }
  2317. static int
  2318. get_option_index(const char *name)
  2319. {
  2320. int i;
  2321. for (i = 0; config_options[i].name != NULL; i++) {
  2322. if (strcmp(config_options[i].name, name) == 0) {
  2323. return i;
  2324. }
  2325. }
  2326. return -1;
  2327. }
  2328. const char *
  2329. mg_get_option(const struct mg_context *ctx, const char *name)
  2330. {
  2331. int i;
  2332. if ((i = get_option_index(name)) == -1) {
  2333. return NULL;
  2334. } else if (!ctx || ctx->config[i] == NULL) {
  2335. return "";
  2336. } else {
  2337. return ctx->config[i];
  2338. }
  2339. }
  2340. struct mg_context *
  2341. mg_get_context(const struct mg_connection *conn)
  2342. {
  2343. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2344. }
  2345. void *
  2346. mg_get_user_data(const struct mg_context *ctx)
  2347. {
  2348. return (ctx == NULL) ? NULL : ctx->user_data;
  2349. }
  2350. void
  2351. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2352. {
  2353. if (conn != NULL) {
  2354. conn->request_info.conn_data = data;
  2355. }
  2356. }
  2357. void *
  2358. mg_get_user_connection_data(const struct mg_connection *conn)
  2359. {
  2360. if (conn != NULL) {
  2361. return conn->request_info.conn_data;
  2362. }
  2363. return NULL;
  2364. }
  2365. #if defined(MG_LEGACY_INTERFACE)
  2366. /* Deprecated: Use mg_get_server_ports instead. */
  2367. size_t
  2368. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2369. {
  2370. size_t i;
  2371. if (!ctx) {
  2372. return 0;
  2373. }
  2374. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2375. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2376. ports[i] =
  2377. #if defined(USE_IPV6)
  2378. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2379. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2380. :
  2381. #endif
  2382. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2383. }
  2384. return i;
  2385. }
  2386. #endif
  2387. int
  2388. mg_get_server_ports(const struct mg_context *ctx,
  2389. int size,
  2390. struct mg_server_ports *ports)
  2391. {
  2392. int i, cnt = 0;
  2393. if (size <= 0) {
  2394. return -1;
  2395. }
  2396. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2397. if (!ctx) {
  2398. return -1;
  2399. }
  2400. if (!ctx->listening_sockets) {
  2401. return -1;
  2402. }
  2403. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2404. ports[cnt].port =
  2405. #if defined(USE_IPV6)
  2406. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2407. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2408. :
  2409. #endif
  2410. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2411. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2412. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2413. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2414. /* IPv4 */
  2415. ports[cnt].protocol = 1;
  2416. cnt++;
  2417. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2418. /* IPv6 */
  2419. ports[cnt].protocol = 3;
  2420. cnt++;
  2421. }
  2422. }
  2423. return cnt;
  2424. }
  2425. static void
  2426. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2427. {
  2428. buf[0] = '\0';
  2429. if (!usa) {
  2430. return;
  2431. }
  2432. if (usa->sa.sa_family == AF_INET) {
  2433. getnameinfo(&usa->sa,
  2434. sizeof(usa->sin),
  2435. buf,
  2436. (unsigned)len,
  2437. NULL,
  2438. 0,
  2439. NI_NUMERICHOST);
  2440. }
  2441. #if defined(USE_IPV6)
  2442. else if (usa->sa.sa_family == AF_INET6) {
  2443. getnameinfo(&usa->sa,
  2444. sizeof(usa->sin6),
  2445. buf,
  2446. (unsigned)len,
  2447. NULL,
  2448. 0,
  2449. NI_NUMERICHOST);
  2450. }
  2451. #endif
  2452. }
  2453. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2454. * included in all responses other than 100, 101, 5xx. */
  2455. static void
  2456. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2457. {
  2458. struct tm *tm;
  2459. tm = ((t != NULL) ? gmtime(t) : NULL);
  2460. if (tm != NULL) {
  2461. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2462. } else {
  2463. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2464. buf[buf_len - 1] = '\0';
  2465. }
  2466. }
  2467. /* difftime for struct timespec. Return value is in seconds. */
  2468. static double
  2469. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2470. {
  2471. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2472. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2473. }
  2474. /* Print error message to the opened error log stream. */
  2475. void
  2476. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2477. {
  2478. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2479. va_list ap;
  2480. struct mg_file fi;
  2481. time_t timestamp;
  2482. va_start(ap, fmt);
  2483. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2484. va_end(ap);
  2485. buf[sizeof(buf) - 1] = 0;
  2486. if (!conn) {
  2487. puts(buf);
  2488. return;
  2489. }
  2490. /* Do not lock when getting the callback value, here and below.
  2491. * I suppose this is fine, since function cannot disappear in the
  2492. * same way string option can. */
  2493. if ((conn->ctx->callbacks.log_message == NULL)
  2494. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2495. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2496. if (mg_fopen(conn,
  2497. conn->ctx->config[ERROR_LOG_FILE],
  2498. MG_FOPEN_MODE_APPEND,
  2499. &fi) == 0) {
  2500. fi.access.fp = NULL;
  2501. }
  2502. } else {
  2503. fi.access.fp = NULL;
  2504. }
  2505. if (fi.access.fp != NULL) {
  2506. flockfile(fi.access.fp);
  2507. timestamp = time(NULL);
  2508. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2509. fprintf(fi.access.fp,
  2510. "[%010lu] [error] [client %s] ",
  2511. (unsigned long)timestamp,
  2512. src_addr);
  2513. if (conn->request_info.request_method != NULL) {
  2514. fprintf(fi.access.fp,
  2515. "%s %s: ",
  2516. conn->request_info.request_method,
  2517. conn->request_info.request_uri);
  2518. }
  2519. fprintf(fi.access.fp, "%s", buf);
  2520. fputc('\n', fi.access.fp);
  2521. fflush(fi.access.fp);
  2522. funlockfile(fi.access.fp);
  2523. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2524. * mg_cry here anyway ;-) */
  2525. }
  2526. }
  2527. }
  2528. /* Return fake connection structure. Used for logging, if connection
  2529. * is not applicable at the moment of logging. */
  2530. static struct mg_connection *
  2531. fc(struct mg_context *ctx)
  2532. {
  2533. static struct mg_connection fake_connection;
  2534. fake_connection.ctx = ctx;
  2535. return &fake_connection;
  2536. }
  2537. const char *
  2538. mg_version(void)
  2539. {
  2540. return CIVETWEB_VERSION;
  2541. }
  2542. const struct mg_request_info *
  2543. mg_get_request_info(const struct mg_connection *conn)
  2544. {
  2545. if (!conn) {
  2546. return NULL;
  2547. }
  2548. return &conn->request_info;
  2549. }
  2550. int
  2551. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2552. {
  2553. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2554. return -1;
  2555. } else {
  2556. int truncated = 0;
  2557. const struct mg_request_info *ri = &conn->request_info;
  2558. #ifdef __clang__
  2559. #pragma clang diagnostic push
  2560. #pragma clang diagnostic ignored "-Wunreachable-code"
  2561. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2562. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2563. * unreachable, but splitting into four different #ifdef clauses here is more
  2564. * complicated.
  2565. */
  2566. #endif
  2567. const char *proto =
  2568. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2569. : (ri->is_ssl ? "https" : "http"));
  2570. #ifdef __clang__
  2571. #pragma clang diagnostic pop
  2572. #endif
  2573. if (ri->local_uri == NULL) {
  2574. return -1;
  2575. }
  2576. if ((ri->request_uri != NULL)
  2577. && strcmp(ri->local_uri, ri->request_uri)) {
  2578. mg_snprintf(conn,
  2579. &truncated,
  2580. buf,
  2581. buflen,
  2582. "%s://%s",
  2583. proto,
  2584. ri->request_uri);
  2585. if (truncated) {
  2586. return -1;
  2587. }
  2588. return 0;
  2589. } else {
  2590. #if defined(USE_IPV6)
  2591. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2592. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2593. : htons(conn->client.lsa.sin.sin_port);
  2594. #else
  2595. int port = htons(conn->client.lsa.sin.sin_port);
  2596. #endif
  2597. int def_port = ri->is_ssl ? 443 : 80;
  2598. int auth_domain_check_enabled =
  2599. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2600. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2601. "yes"));
  2602. const char *server_domain =
  2603. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2604. char portstr[16];
  2605. char server_ip[48];
  2606. if (port != def_port) {
  2607. sprintf(portstr, ":%u", (unsigned)port);
  2608. } else {
  2609. portstr[0] = 0;
  2610. }
  2611. if (!auth_domain_check_enabled || !server_domain) {
  2612. sockaddr_to_string(server_ip,
  2613. sizeof(server_ip),
  2614. &conn->client.lsa);
  2615. server_domain = server_ip;
  2616. }
  2617. mg_snprintf(conn,
  2618. &truncated,
  2619. buf,
  2620. buflen,
  2621. "%s://%s%s%s",
  2622. proto,
  2623. server_domain,
  2624. portstr,
  2625. ri->local_uri);
  2626. if (truncated) {
  2627. return -1;
  2628. }
  2629. return 0;
  2630. }
  2631. }
  2632. }
  2633. /* Skip the characters until one of the delimiters characters found.
  2634. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2635. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2636. * Delimiters can be quoted with quotechar. */
  2637. static char *
  2638. skip_quoted(char **buf,
  2639. const char *delimiters,
  2640. const char *whitespace,
  2641. char quotechar)
  2642. {
  2643. char *p, *begin_word, *end_word, *end_whitespace;
  2644. begin_word = *buf;
  2645. end_word = begin_word + strcspn(begin_word, delimiters);
  2646. /* Check for quotechar */
  2647. if (end_word > begin_word) {
  2648. p = end_word - 1;
  2649. while (*p == quotechar) {
  2650. /* While the delimiter is quoted, look for the next delimiter. */
  2651. /* This happens, e.g., in calls from parse_auth_header,
  2652. * if the user name contains a " character. */
  2653. /* If there is anything beyond end_word, copy it. */
  2654. if (*end_word != '\0') {
  2655. size_t end_off = strcspn(end_word + 1, delimiters);
  2656. memmove(p, end_word, end_off + 1);
  2657. p += end_off; /* p must correspond to end_word - 1 */
  2658. end_word += end_off + 1;
  2659. } else {
  2660. *p = '\0';
  2661. break;
  2662. }
  2663. }
  2664. for (p++; p < end_word; p++) {
  2665. *p = '\0';
  2666. }
  2667. }
  2668. if (*end_word == '\0') {
  2669. *buf = end_word;
  2670. } else {
  2671. #if defined(__GNUC__) || defined(__MINGW32__)
  2672. /* Disable spurious conversion warning for GCC */
  2673. #pragma GCC diagnostic push
  2674. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2675. #endif
  2676. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2677. #if defined(__GNUC__) || defined(__MINGW32__)
  2678. #pragma GCC diagnostic pop
  2679. #endif
  2680. for (p = end_word; p < end_whitespace; p++) {
  2681. *p = '\0';
  2682. }
  2683. *buf = end_whitespace;
  2684. }
  2685. return begin_word;
  2686. }
  2687. /* Simplified version of skip_quoted without quote char
  2688. * and whitespace == delimiters */
  2689. static char *
  2690. skip(char **buf, const char *delimiters)
  2691. {
  2692. return skip_quoted(buf, delimiters, delimiters, 0);
  2693. }
  2694. /* Return HTTP header value, or NULL if not found. */
  2695. static const char *
  2696. get_header(const struct mg_request_info *ri, const char *name)
  2697. {
  2698. int i;
  2699. if (ri) {
  2700. for (i = 0; i < ri->num_headers; i++) {
  2701. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2702. return ri->http_headers[i].value;
  2703. }
  2704. }
  2705. }
  2706. return NULL;
  2707. }
  2708. const char *
  2709. mg_get_header(const struct mg_connection *conn, const char *name)
  2710. {
  2711. if (!conn) {
  2712. return NULL;
  2713. }
  2714. return get_header(&conn->request_info, name);
  2715. }
  2716. /* A helper function for traversing a comma separated list of values.
  2717. * It returns a list pointer shifted to the next value, or NULL if the end
  2718. * of the list found.
  2719. * Value is stored in val vector. If value has form "x=y", then eq_val
  2720. * vector is initialized to point to the "y" part, and val vector length
  2721. * is adjusted to point only to "x". */
  2722. static const char *
  2723. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2724. {
  2725. int end;
  2726. reparse:
  2727. if (val == NULL || list == NULL || *list == '\0') {
  2728. /* End of the list */
  2729. list = NULL;
  2730. } else {
  2731. /* Skip over leading LWS */
  2732. while (*list == ' ' || *list == '\t')
  2733. list++;
  2734. val->ptr = list;
  2735. if ((list = strchr(val->ptr, ',')) != NULL) {
  2736. /* Comma found. Store length and shift the list ptr */
  2737. val->len = ((size_t)(list - val->ptr));
  2738. list++;
  2739. } else {
  2740. /* This value is the last one */
  2741. list = val->ptr + strlen(val->ptr);
  2742. val->len = ((size_t)(list - val->ptr));
  2743. }
  2744. /* Adjust length for trailing LWS */
  2745. end = (int)val->len - 1;
  2746. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2747. end--;
  2748. val->len = (size_t)(end + 1);
  2749. if (val->len == 0) {
  2750. /* Ignore any empty entries. */
  2751. goto reparse;
  2752. }
  2753. if (eq_val != NULL) {
  2754. /* Value has form "x=y", adjust pointers and lengths
  2755. * so that val points to "x", and eq_val points to "y". */
  2756. eq_val->len = 0;
  2757. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2758. if (eq_val->ptr != NULL) {
  2759. eq_val->ptr++; /* Skip over '=' character */
  2760. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2761. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2762. }
  2763. }
  2764. }
  2765. return list;
  2766. }
  2767. /* A helper function for checking if a comma separated list of values contains
  2768. * the given option (case insensitvely).
  2769. * 'header' can be NULL, in which case false is returned. */
  2770. static int
  2771. header_has_option(const char *header, const char *option)
  2772. {
  2773. struct vec opt_vec;
  2774. struct vec eq_vec;
  2775. assert(option != NULL);
  2776. assert(option[0] != '\0');
  2777. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2778. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2779. return 1;
  2780. }
  2781. return 0;
  2782. }
  2783. /* Perform case-insensitive match of string against pattern */
  2784. static int
  2785. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2786. {
  2787. const char *or_str;
  2788. size_t i;
  2789. int j, len, res;
  2790. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2791. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2792. return (res > 0) ? res : match_prefix(or_str + 1,
  2793. (size_t)((pattern + pattern_len)
  2794. - (or_str + 1)),
  2795. str);
  2796. }
  2797. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2798. if (pattern[i] == '?' && str[j] != '\0') {
  2799. continue;
  2800. } else if (pattern[i] == '$') {
  2801. return (str[j] == '\0') ? j : -1;
  2802. } else if (pattern[i] == '*') {
  2803. i++;
  2804. if (pattern[i] == '*') {
  2805. i++;
  2806. len = (int)strlen(str + j);
  2807. } else {
  2808. len = (int)strcspn(str + j, "/");
  2809. }
  2810. if (i == pattern_len) {
  2811. return j + len;
  2812. }
  2813. do {
  2814. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2815. } while (res == -1 && len-- > 0);
  2816. return (res == -1) ? -1 : j + res + len;
  2817. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2818. return -1;
  2819. }
  2820. }
  2821. return j;
  2822. }
  2823. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2824. * This function must tolerate situations when connection info is not
  2825. * set up, for example if request parsing failed. */
  2826. static int
  2827. should_keep_alive(const struct mg_connection *conn)
  2828. {
  2829. if (conn != NULL) {
  2830. const char *http_version = conn->request_info.http_version;
  2831. const char *header = mg_get_header(conn, "Connection");
  2832. if (conn->must_close || conn->status_code == 401
  2833. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2834. || (header != NULL && !header_has_option(header, "keep-alive"))
  2835. || (header == NULL && http_version
  2836. && 0 != strcmp(http_version, "1.1"))) {
  2837. return 0;
  2838. }
  2839. return 1;
  2840. }
  2841. return 0;
  2842. }
  2843. static int
  2844. should_decode_url(const struct mg_connection *conn)
  2845. {
  2846. if (!conn || !conn->ctx) {
  2847. return 0;
  2848. }
  2849. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2850. }
  2851. static const char *
  2852. suggest_connection_header(const struct mg_connection *conn)
  2853. {
  2854. return should_keep_alive(conn) ? "keep-alive" : "close";
  2855. }
  2856. static int
  2857. send_no_cache_header(struct mg_connection *conn)
  2858. {
  2859. /* Send all current and obsolete cache opt-out directives. */
  2860. return mg_printf(conn,
  2861. "Cache-Control: no-cache, no-store, "
  2862. "must-revalidate, private, max-age=0\r\n"
  2863. "Pragma: no-cache\r\n"
  2864. "Expires: 0\r\n");
  2865. }
  2866. static int
  2867. send_static_cache_header(struct mg_connection *conn)
  2868. {
  2869. #if !defined(NO_CACHING)
  2870. /* Read the server config to check how long a file may be cached.
  2871. * The configuration is in seconds. */
  2872. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2873. if (max_age <= 0) {
  2874. /* 0 means "do not cache". All values <0 are reserved
  2875. * and may be used differently in the future. */
  2876. /* If a file should not be cached, do not only send
  2877. * max-age=0, but also pragmas and Expires headers. */
  2878. return send_no_cache_header(conn);
  2879. }
  2880. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2881. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2882. /* See also https://www.mnot.net/cache_docs/ */
  2883. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2884. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2885. * year to 31622400 seconds. For the moment, we just send whatever has
  2886. * been configured, still the behavior for >1 year should be considered
  2887. * as undefined. */
  2888. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2889. #else /* NO_CACHING */
  2890. return send_no_cache_header(conn);
  2891. #endif /* !NO_CACHING */
  2892. }
  2893. static int
  2894. send_additional_header(struct mg_connection *conn)
  2895. {
  2896. int i = 0;
  2897. const char *header = conn->ctx->config[ADDITIONAL_HEADER];
  2898. #if !defined(NO_SSL)
  2899. if (conn->ctx->config[STRICT_HTTPS_MAX_AGE]) {
  2900. int max_age = atoi(conn->ctx->config[STRICT_HTTPS_MAX_AGE]);
  2901. if (max_age >= 0) {
  2902. i += mg_printf(conn,
  2903. "Strict-Transport-Security: max-age=%u\r\n",
  2904. (unsigned)max_age);
  2905. }
  2906. }
  2907. #endif
  2908. if (header && header[0]) {
  2909. i += mg_printf(conn, "%s\r\n", header);
  2910. }
  2911. return i;
  2912. }
  2913. static void handle_file_based_request(struct mg_connection *conn,
  2914. const char *path,
  2915. struct mg_file *filep);
  2916. const char *
  2917. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  2918. {
  2919. /* See IANA HTTP status code assignment:
  2920. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2921. */
  2922. switch (response_code) {
  2923. /* RFC2616 Section 10.1 - Informational 1xx */
  2924. case 100:
  2925. return "Continue"; /* RFC2616 Section 10.1.1 */
  2926. case 101:
  2927. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2928. case 102:
  2929. return "Processing"; /* RFC2518 Section 10.1 */
  2930. /* RFC2616 Section 10.2 - Successful 2xx */
  2931. case 200:
  2932. return "OK"; /* RFC2616 Section 10.2.1 */
  2933. case 201:
  2934. return "Created"; /* RFC2616 Section 10.2.2 */
  2935. case 202:
  2936. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2937. case 203:
  2938. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2939. case 204:
  2940. return "No Content"; /* RFC2616 Section 10.2.5 */
  2941. case 205:
  2942. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2943. case 206:
  2944. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2945. case 207:
  2946. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2947. case 208:
  2948. return "Already Reported"; /* RFC5842 Section 7.1 */
  2949. case 226:
  2950. return "IM used"; /* RFC3229 Section 10.4.1 */
  2951. /* RFC2616 Section 10.3 - Redirection 3xx */
  2952. case 300:
  2953. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2954. case 301:
  2955. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2956. case 302:
  2957. return "Found"; /* RFC2616 Section 10.3.3 */
  2958. case 303:
  2959. return "See Other"; /* RFC2616 Section 10.3.4 */
  2960. case 304:
  2961. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2962. case 305:
  2963. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2964. case 307:
  2965. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2966. case 308:
  2967. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2968. /* RFC2616 Section 10.4 - Client Error 4xx */
  2969. case 400:
  2970. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2971. case 401:
  2972. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2973. case 402:
  2974. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2975. case 403:
  2976. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2977. case 404:
  2978. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2979. case 405:
  2980. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2981. case 406:
  2982. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2983. case 407:
  2984. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2985. case 408:
  2986. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2987. case 409:
  2988. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2989. case 410:
  2990. return "Gone"; /* RFC2616 Section 10.4.11 */
  2991. case 411:
  2992. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2993. case 412:
  2994. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2995. case 413:
  2996. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2997. case 414:
  2998. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2999. case 415:
  3000. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3001. case 416:
  3002. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  3003. case 417:
  3004. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3005. case 421:
  3006. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3007. case 422:
  3008. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3009. * Section 11.2 */
  3010. case 423:
  3011. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3012. case 424:
  3013. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3014. * Section 11.4 */
  3015. case 426:
  3016. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3017. case 428:
  3018. return "Precondition Required"; /* RFC 6585, Section 3 */
  3019. case 429:
  3020. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3021. case 431:
  3022. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3023. case 451:
  3024. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3025. * Section 3 */
  3026. /* RFC2616 Section 10.5 - Server Error 5xx */
  3027. case 500:
  3028. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3029. case 501:
  3030. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3031. case 502:
  3032. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3033. case 503:
  3034. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3035. case 504:
  3036. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3037. case 505:
  3038. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3039. case 506:
  3040. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3041. case 507:
  3042. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3043. * Section 11.5 */
  3044. case 508:
  3045. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3046. case 510:
  3047. return "Not Extended"; /* RFC 2774, Section 7 */
  3048. case 511:
  3049. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3050. /* Other status codes, not shown in the IANA HTTP status code assignment.
  3051. * E.g., "de facto" standards due to common use, ... */
  3052. case 418:
  3053. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3054. case 419:
  3055. return "Authentication Timeout"; /* common use */
  3056. case 420:
  3057. return "Enhance Your Calm"; /* common use */
  3058. case 440:
  3059. return "Login Timeout"; /* common use */
  3060. case 509:
  3061. return "Bandwidth Limit Exceeded"; /* common use */
  3062. default:
  3063. /* This error code is unknown. This should not happen. */
  3064. if (conn) {
  3065. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3066. }
  3067. /* Return at least a category according to RFC 2616 Section 10. */
  3068. if (response_code >= 100 && response_code < 200) {
  3069. /* Unknown informational status code */
  3070. return "Information";
  3071. }
  3072. if (response_code >= 200 && response_code < 300) {
  3073. /* Unknown success code */
  3074. return "Success";
  3075. }
  3076. if (response_code >= 300 && response_code < 400) {
  3077. /* Unknown redirection code */
  3078. return "Redirection";
  3079. }
  3080. if (response_code >= 400 && response_code < 500) {
  3081. /* Unknown request error code */
  3082. return "Client Error";
  3083. }
  3084. if (response_code >= 500 && response_code < 600) {
  3085. /* Unknown server error code */
  3086. return "Server Error";
  3087. }
  3088. /* Response code not even within reasonable range */
  3089. return "";
  3090. }
  3091. }
  3092. void
  3093. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3094. {
  3095. char buf[MG_BUF_LEN];
  3096. va_list ap;
  3097. int len, i, page_handler_found, scope, truncated, has_body;
  3098. char date[64];
  3099. time_t curtime = time(NULL);
  3100. const char *error_handler = NULL;
  3101. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3102. const char *error_page_file_ext, *tstr;
  3103. const char *status_text = mg_get_response_code_text(conn, status);
  3104. if (conn == NULL) {
  3105. return;
  3106. }
  3107. conn->status_code = status;
  3108. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  3109. || conn->ctx->callbacks.http_error(conn, status)) {
  3110. if (!conn->in_error_handler) {
  3111. /* Send user defined error pages, if defined */
  3112. error_handler = conn->ctx->config[ERROR_PAGES];
  3113. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3114. page_handler_found = 0;
  3115. if (error_handler != NULL) {
  3116. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3117. switch (scope) {
  3118. case 1: /* Handler for specific error, e.g. 404 error */
  3119. mg_snprintf(conn,
  3120. &truncated,
  3121. buf,
  3122. sizeof(buf) - 32,
  3123. "%serror%03u.",
  3124. error_handler,
  3125. status);
  3126. break;
  3127. case 2: /* Handler for error group, e.g., 5xx error handler
  3128. * for all server errors (500-599) */
  3129. mg_snprintf(conn,
  3130. &truncated,
  3131. buf,
  3132. sizeof(buf) - 32,
  3133. "%serror%01uxx.",
  3134. error_handler,
  3135. status / 100);
  3136. break;
  3137. default: /* Handler for all errors */
  3138. mg_snprintf(conn,
  3139. &truncated,
  3140. buf,
  3141. sizeof(buf) - 32,
  3142. "%serror.",
  3143. error_handler);
  3144. break;
  3145. }
  3146. /* String truncation in buf may only occur if error_handler
  3147. * is too long. This string is from the config, not from a
  3148. * client. */
  3149. (void)truncated;
  3150. len = (int)strlen(buf);
  3151. tstr = strchr(error_page_file_ext, '.');
  3152. while (tstr) {
  3153. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  3154. i++)
  3155. buf[len + i - 1] = tstr[i];
  3156. buf[len + i - 1] = 0;
  3157. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3158. page_handler_found = 1;
  3159. break;
  3160. }
  3161. tstr = strchr(tstr + i, '.');
  3162. }
  3163. }
  3164. }
  3165. if (page_handler_found) {
  3166. conn->in_error_handler = 1;
  3167. handle_file_based_request(conn, buf, &error_page_file);
  3168. conn->in_error_handler = 0;
  3169. return;
  3170. }
  3171. }
  3172. /* No custom error page. Send default error page. */
  3173. gmt_time_string(date, sizeof(date), &curtime);
  3174. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3175. has_body = (status > 199 && status != 204 && status != 304);
  3176. conn->must_close = 1;
  3177. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3178. send_no_cache_header(conn);
  3179. send_additional_header(conn);
  3180. if (has_body) {
  3181. mg_printf(conn,
  3182. "%s",
  3183. "Content-Type: text/plain; charset=utf-8\r\n");
  3184. }
  3185. mg_printf(conn,
  3186. "Date: %s\r\n"
  3187. "Connection: close\r\n\r\n",
  3188. date);
  3189. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3190. if (has_body) {
  3191. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3192. if (fmt != NULL) {
  3193. va_start(ap, fmt);
  3194. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3195. va_end(ap);
  3196. mg_write(conn, buf, strlen(buf));
  3197. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3198. }
  3199. } else {
  3200. /* No body allowed. Close the connection. */
  3201. DEBUG_TRACE("Error %i", status);
  3202. }
  3203. }
  3204. }
  3205. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3206. /* Create substitutes for POSIX functions in Win32. */
  3207. #if defined(__MINGW32__)
  3208. /* Show no warning in case system functions are not used. */
  3209. #pragma GCC diagnostic push
  3210. #pragma GCC diagnostic ignored "-Wunused-function"
  3211. #endif
  3212. static int
  3213. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3214. {
  3215. (void)unused;
  3216. *mutex = CreateMutex(NULL, FALSE, NULL);
  3217. return (*mutex == NULL) ? -1 : 0;
  3218. }
  3219. static int
  3220. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3221. {
  3222. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3223. }
  3224. static int
  3225. pthread_mutex_lock(pthread_mutex_t *mutex)
  3226. {
  3227. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3228. }
  3229. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3230. static int
  3231. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3232. {
  3233. switch (WaitForSingleObject(*mutex, 0)) {
  3234. case WAIT_OBJECT_0:
  3235. return 0;
  3236. case WAIT_TIMEOUT:
  3237. return -2; /* EBUSY */
  3238. }
  3239. return -1;
  3240. }
  3241. #endif
  3242. static int
  3243. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3244. {
  3245. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3246. }
  3247. static int
  3248. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3249. {
  3250. (void)unused;
  3251. InitializeCriticalSection(&cv->threadIdSec);
  3252. cv->waiting_thread = NULL;
  3253. return 0;
  3254. }
  3255. static int
  3256. pthread_cond_timedwait(pthread_cond_t *cv,
  3257. pthread_mutex_t *mutex,
  3258. const struct timespec *abstime)
  3259. {
  3260. struct mg_workerTLS **ptls,
  3261. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3262. int ok;
  3263. int64_t nsnow, nswaitabs, nswaitrel;
  3264. DWORD mswaitrel;
  3265. EnterCriticalSection(&cv->threadIdSec);
  3266. /* Add this thread to cv's waiting list */
  3267. ptls = &cv->waiting_thread;
  3268. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3269. ;
  3270. tls->next_waiting_thread = NULL;
  3271. *ptls = tls;
  3272. LeaveCriticalSection(&cv->threadIdSec);
  3273. if (abstime) {
  3274. nsnow = mg_get_current_time_ns();
  3275. nswaitabs =
  3276. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3277. nswaitrel = nswaitabs - nsnow;
  3278. if (nswaitrel < 0) {
  3279. nswaitrel = 0;
  3280. }
  3281. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3282. } else {
  3283. mswaitrel = INFINITE;
  3284. }
  3285. pthread_mutex_unlock(mutex);
  3286. ok = (WAIT_OBJECT_0
  3287. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3288. if (!ok) {
  3289. ok = 1;
  3290. EnterCriticalSection(&cv->threadIdSec);
  3291. ptls = &cv->waiting_thread;
  3292. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3293. if (*ptls == tls) {
  3294. *ptls = tls->next_waiting_thread;
  3295. ok = 0;
  3296. break;
  3297. }
  3298. }
  3299. LeaveCriticalSection(&cv->threadIdSec);
  3300. if (ok) {
  3301. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3302. }
  3303. }
  3304. /* This thread has been removed from cv's waiting list */
  3305. pthread_mutex_lock(mutex);
  3306. return ok ? 0 : -1;
  3307. }
  3308. static int
  3309. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3310. {
  3311. return pthread_cond_timedwait(cv, mutex, NULL);
  3312. }
  3313. static int
  3314. pthread_cond_signal(pthread_cond_t *cv)
  3315. {
  3316. HANDLE wkup = NULL;
  3317. BOOL ok = FALSE;
  3318. EnterCriticalSection(&cv->threadIdSec);
  3319. if (cv->waiting_thread) {
  3320. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3321. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3322. ok = SetEvent(wkup);
  3323. assert(ok);
  3324. }
  3325. LeaveCriticalSection(&cv->threadIdSec);
  3326. return ok ? 0 : 1;
  3327. }
  3328. static int
  3329. pthread_cond_broadcast(pthread_cond_t *cv)
  3330. {
  3331. EnterCriticalSection(&cv->threadIdSec);
  3332. while (cv->waiting_thread) {
  3333. pthread_cond_signal(cv);
  3334. }
  3335. LeaveCriticalSection(&cv->threadIdSec);
  3336. return 0;
  3337. }
  3338. static int
  3339. pthread_cond_destroy(pthread_cond_t *cv)
  3340. {
  3341. EnterCriticalSection(&cv->threadIdSec);
  3342. assert(cv->waiting_thread == NULL);
  3343. LeaveCriticalSection(&cv->threadIdSec);
  3344. DeleteCriticalSection(&cv->threadIdSec);
  3345. return 0;
  3346. }
  3347. #ifdef ALTERNATIVE_QUEUE
  3348. static void *
  3349. event_create(void)
  3350. {
  3351. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3352. }
  3353. static int
  3354. event_wait(void *eventhdl)
  3355. {
  3356. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3357. return (res == WAIT_OBJECT_0);
  3358. }
  3359. static int
  3360. event_signal(void *eventhdl)
  3361. {
  3362. return (int)SetEvent((HANDLE)eventhdl);
  3363. }
  3364. static void
  3365. event_destroy(void *eventhdl)
  3366. {
  3367. CloseHandle((HANDLE)eventhdl);
  3368. }
  3369. #endif
  3370. #if defined(__MINGW32__)
  3371. /* Enable unused function warning again */
  3372. #pragma GCC diagnostic pop
  3373. #endif
  3374. /* For Windows, change all slashes to backslashes in path names. */
  3375. static void
  3376. change_slashes_to_backslashes(char *path)
  3377. {
  3378. int i;
  3379. for (i = 0; path[i] != '\0'; i++) {
  3380. if (path[i] == '/') {
  3381. path[i] = '\\';
  3382. }
  3383. /* remove double backslash (check i > 0 to preserve UNC paths,
  3384. * like \\server\file.txt) */
  3385. if ((path[i] == '\\') && (i > 0)) {
  3386. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3387. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3388. }
  3389. }
  3390. }
  3391. }
  3392. static int
  3393. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3394. {
  3395. int diff;
  3396. do {
  3397. diff = tolower(*s1) - tolower(*s2);
  3398. s1++;
  3399. s2++;
  3400. } while (diff == 0 && s1[-1] != '\0');
  3401. return diff;
  3402. }
  3403. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3404. * wbuf and wbuf_len is a target buffer and its length. */
  3405. static void
  3406. path_to_unicode(const struct mg_connection *conn,
  3407. const char *path,
  3408. wchar_t *wbuf,
  3409. size_t wbuf_len)
  3410. {
  3411. char buf[PATH_MAX], buf2[PATH_MAX];
  3412. wchar_t wbuf2[MAX_PATH + 1];
  3413. DWORD long_len, err;
  3414. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3415. mg_strlcpy(buf, path, sizeof(buf));
  3416. change_slashes_to_backslashes(buf);
  3417. /* Convert to Unicode and back. If doubly-converted string does not
  3418. * match the original, something is fishy, reject. */
  3419. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3420. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3421. WideCharToMultiByte(
  3422. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3423. if (strcmp(buf, buf2) != 0) {
  3424. wbuf[0] = L'\0';
  3425. }
  3426. /* Windows file systems are not case sensitive, but you can still use
  3427. * uppercase and lowercase letters (on all modern file systems).
  3428. * The server can check if the URI uses the same upper/lowercase
  3429. * letters an the file system, effectively making Windows servers
  3430. * case sensitive (like Linux servers are). It is still not possible
  3431. * to use two files with the same name in different cases on Windows
  3432. * (like /a and /A) - this would be possible in Linux.
  3433. * As a default, Windows is not case sensitive, but the case sensitive
  3434. * file name check can be activated by an additional configuration. */
  3435. if (conn) {
  3436. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3437. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3438. /* Use case sensitive compare function */
  3439. fcompare = wcscmp;
  3440. }
  3441. }
  3442. (void)conn; /* conn is currently unused */
  3443. #if !defined(_WIN32_WCE)
  3444. /* Only accept a full file path, not a Windows short (8.3) path. */
  3445. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3446. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3447. if (long_len == 0) {
  3448. err = GetLastError();
  3449. if (err == ERROR_FILE_NOT_FOUND) {
  3450. /* File does not exist. This is not always a problem here. */
  3451. return;
  3452. }
  3453. }
  3454. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3455. /* Short name is used. */
  3456. wbuf[0] = L'\0';
  3457. }
  3458. #else
  3459. (void)long_len;
  3460. (void)wbuf2;
  3461. (void)err;
  3462. if (strchr(path, '~')) {
  3463. wbuf[0] = L'\0';
  3464. }
  3465. #endif
  3466. }
  3467. /* Windows happily opens files with some garbage at the end of file name.
  3468. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3469. * "a.cgi", despite one would expect an error back.
  3470. * This function returns non-0 if path ends with some garbage. */
  3471. static int
  3472. path_cannot_disclose_cgi(const char *path)
  3473. {
  3474. static const char *allowed_last_characters = "_-";
  3475. int last = path[strlen(path) - 1];
  3476. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3477. }
  3478. static int
  3479. mg_stat(const struct mg_connection *conn,
  3480. const char *path,
  3481. struct mg_file_stat *filep)
  3482. {
  3483. wchar_t wbuf[PATH_MAX];
  3484. WIN32_FILE_ATTRIBUTE_DATA info;
  3485. time_t creation_time;
  3486. if (!filep) {
  3487. return 0;
  3488. }
  3489. memset(filep, 0, sizeof(*filep));
  3490. if (conn && is_file_in_memory(conn, path)) {
  3491. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3492. * memset */
  3493. /* Quick fix (for 1.9.x): */
  3494. /* mg_stat must fill all fields, also for files in memory */
  3495. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3496. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3497. filep->size = tmp_file.stat.size;
  3498. filep->location = 2;
  3499. /* TODO: for 1.10: restructure how files in memory are handled */
  3500. /* The "file in memory" feature is a candidate for deletion.
  3501. * Please join the discussion at
  3502. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3503. */
  3504. filep->last_modified = time(NULL); /* TODO */
  3505. /* last_modified = now ... assumes the file may change during runtime,
  3506. * so every mg_fopen call may return different data */
  3507. /* last_modified = conn->ctx.start_time;
  3508. * May be used it the data does not change during runtime. This allows
  3509. * browser caching. Since we do not know, we have to assume the file
  3510. * in memory may change. */
  3511. return 1;
  3512. }
  3513. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3514. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3515. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3516. filep->last_modified =
  3517. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3518. info.ftLastWriteTime.dwHighDateTime);
  3519. /* On Windows, the file creation time can be higher than the
  3520. * modification time, e.g. when a file is copied.
  3521. * Since the Last-Modified timestamp is used for caching
  3522. * it should be based on the most recent timestamp. */
  3523. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3524. info.ftCreationTime.dwHighDateTime);
  3525. if (creation_time > filep->last_modified) {
  3526. filep->last_modified = creation_time;
  3527. }
  3528. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3529. /* If file name is fishy, reset the file structure and return
  3530. * error.
  3531. * Note it is important to reset, not just return the error, cause
  3532. * functions like is_file_opened() check the struct. */
  3533. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3534. memset(filep, 0, sizeof(*filep));
  3535. return 0;
  3536. }
  3537. return 1;
  3538. }
  3539. return 0;
  3540. }
  3541. static int
  3542. mg_remove(const struct mg_connection *conn, const char *path)
  3543. {
  3544. wchar_t wbuf[PATH_MAX];
  3545. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3546. return DeleteFileW(wbuf) ? 0 : -1;
  3547. }
  3548. static int
  3549. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3550. {
  3551. wchar_t wbuf[PATH_MAX];
  3552. (void)mode;
  3553. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3554. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3555. }
  3556. /* Create substitutes for POSIX functions in Win32. */
  3557. #if defined(__MINGW32__)
  3558. /* Show no warning in case system functions are not used. */
  3559. #pragma GCC diagnostic push
  3560. #pragma GCC diagnostic ignored "-Wunused-function"
  3561. #endif
  3562. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3563. static DIR *
  3564. mg_opendir(const struct mg_connection *conn, const char *name)
  3565. {
  3566. DIR *dir = NULL;
  3567. wchar_t wpath[PATH_MAX];
  3568. DWORD attrs;
  3569. if (name == NULL) {
  3570. SetLastError(ERROR_BAD_ARGUMENTS);
  3571. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3572. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3573. } else {
  3574. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3575. attrs = GetFileAttributesW(wpath);
  3576. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3577. == FILE_ATTRIBUTE_DIRECTORY)) {
  3578. (void)wcscat(wpath, L"\\*");
  3579. dir->handle = FindFirstFileW(wpath, &dir->info);
  3580. dir->result.d_name[0] = '\0';
  3581. } else {
  3582. mg_free(dir);
  3583. dir = NULL;
  3584. }
  3585. }
  3586. return dir;
  3587. }
  3588. static int
  3589. mg_closedir(DIR *dir)
  3590. {
  3591. int result = 0;
  3592. if (dir != NULL) {
  3593. if (dir->handle != INVALID_HANDLE_VALUE)
  3594. result = FindClose(dir->handle) ? 0 : -1;
  3595. mg_free(dir);
  3596. } else {
  3597. result = -1;
  3598. SetLastError(ERROR_BAD_ARGUMENTS);
  3599. }
  3600. return result;
  3601. }
  3602. static struct dirent *
  3603. mg_readdir(DIR *dir)
  3604. {
  3605. struct dirent *result = 0;
  3606. if (dir) {
  3607. if (dir->handle != INVALID_HANDLE_VALUE) {
  3608. result = &dir->result;
  3609. (void)WideCharToMultiByte(CP_UTF8,
  3610. 0,
  3611. dir->info.cFileName,
  3612. -1,
  3613. result->d_name,
  3614. sizeof(result->d_name),
  3615. NULL,
  3616. NULL);
  3617. if (!FindNextFileW(dir->handle, &dir->info)) {
  3618. (void)FindClose(dir->handle);
  3619. dir->handle = INVALID_HANDLE_VALUE;
  3620. }
  3621. } else {
  3622. SetLastError(ERROR_FILE_NOT_FOUND);
  3623. }
  3624. } else {
  3625. SetLastError(ERROR_BAD_ARGUMENTS);
  3626. }
  3627. return result;
  3628. }
  3629. #ifndef HAVE_POLL
  3630. static int
  3631. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3632. {
  3633. struct timeval tv;
  3634. fd_set set;
  3635. unsigned int i;
  3636. int result;
  3637. SOCKET maxfd = 0;
  3638. memset(&tv, 0, sizeof(tv));
  3639. tv.tv_sec = milliseconds / 1000;
  3640. tv.tv_usec = (milliseconds % 1000) * 1000;
  3641. FD_ZERO(&set);
  3642. for (i = 0; i < n; i++) {
  3643. FD_SET((SOCKET)pfd[i].fd, &set);
  3644. pfd[i].revents = 0;
  3645. if (pfd[i].fd > maxfd) {
  3646. maxfd = pfd[i].fd;
  3647. }
  3648. }
  3649. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3650. for (i = 0; i < n; i++) {
  3651. if (FD_ISSET(pfd[i].fd, &set)) {
  3652. pfd[i].revents = POLLIN;
  3653. }
  3654. }
  3655. }
  3656. /* We should subtract the time used in select from remaining
  3657. * "milliseconds", in particular if called from mg_poll with a
  3658. * timeout quantum.
  3659. * Unfortunately, the remaining time is not stored in "tv" in all
  3660. * implementations, so the result in "tv" must be considered undefined.
  3661. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3662. return result;
  3663. }
  3664. #endif /* HAVE_POLL */
  3665. #if defined(__MINGW32__)
  3666. /* Enable unused function warning again */
  3667. #pragma GCC diagnostic pop
  3668. #endif
  3669. static void
  3670. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3671. {
  3672. (void)conn; /* Unused. */
  3673. #if defined(_WIN32_WCE)
  3674. (void)sock;
  3675. #else
  3676. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3677. #endif
  3678. }
  3679. int
  3680. mg_start_thread(mg_thread_func_t f, void *p)
  3681. {
  3682. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3683. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3684. */
  3685. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3686. == ((uintptr_t)(-1L)))
  3687. ? -1
  3688. : 0);
  3689. #else
  3690. return (
  3691. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3692. ? -1
  3693. : 0);
  3694. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3695. }
  3696. /* Start a thread storing the thread context. */
  3697. static int
  3698. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3699. void *p,
  3700. pthread_t *threadidptr)
  3701. {
  3702. uintptr_t uip;
  3703. HANDLE threadhandle;
  3704. int result = -1;
  3705. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3706. threadhandle = (HANDLE)uip;
  3707. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3708. *threadidptr = threadhandle;
  3709. result = 0;
  3710. }
  3711. return result;
  3712. }
  3713. /* Wait for a thread to finish. */
  3714. static int
  3715. mg_join_thread(pthread_t threadid)
  3716. {
  3717. int result;
  3718. DWORD dwevent;
  3719. result = -1;
  3720. dwevent = WaitForSingleObject(threadid, INFINITE);
  3721. if (dwevent == WAIT_FAILED) {
  3722. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3723. } else {
  3724. if (dwevent == WAIT_OBJECT_0) {
  3725. CloseHandle(threadid);
  3726. result = 0;
  3727. }
  3728. }
  3729. return result;
  3730. }
  3731. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3732. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3733. /* Create substitutes for POSIX functions in Win32. */
  3734. #if defined(__MINGW32__)
  3735. /* Show no warning in case system functions are not used. */
  3736. #pragma GCC diagnostic push
  3737. #pragma GCC diagnostic ignored "-Wunused-function"
  3738. #endif
  3739. static HANDLE
  3740. dlopen(const char *dll_name, int flags)
  3741. {
  3742. wchar_t wbuf[PATH_MAX];
  3743. (void)flags;
  3744. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3745. return LoadLibraryW(wbuf);
  3746. }
  3747. static int
  3748. dlclose(void *handle)
  3749. {
  3750. int result;
  3751. if (FreeLibrary((HMODULE)handle) != 0) {
  3752. result = 0;
  3753. } else {
  3754. result = -1;
  3755. }
  3756. return result;
  3757. }
  3758. #if defined(__MINGW32__)
  3759. /* Enable unused function warning again */
  3760. #pragma GCC diagnostic pop
  3761. #endif
  3762. #endif
  3763. #if !defined(NO_CGI)
  3764. #define SIGKILL (0)
  3765. static int
  3766. kill(pid_t pid, int sig_num)
  3767. {
  3768. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3769. (void)CloseHandle((HANDLE)pid);
  3770. return 0;
  3771. }
  3772. static void
  3773. trim_trailing_whitespaces(char *s)
  3774. {
  3775. char *e = s + strlen(s) - 1;
  3776. while (e > s && isspace(*(unsigned char *)e)) {
  3777. *e-- = '\0';
  3778. }
  3779. }
  3780. static pid_t
  3781. spawn_process(struct mg_connection *conn,
  3782. const char *prog,
  3783. char *envblk,
  3784. char *envp[],
  3785. int fdin[2],
  3786. int fdout[2],
  3787. int fderr[2],
  3788. const char *dir)
  3789. {
  3790. HANDLE me;
  3791. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3792. cmdline[PATH_MAX], buf[PATH_MAX];
  3793. int truncated;
  3794. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3795. STARTUPINFOA si;
  3796. PROCESS_INFORMATION pi = {0};
  3797. (void)envp;
  3798. memset(&si, 0, sizeof(si));
  3799. si.cb = sizeof(si);
  3800. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3801. si.wShowWindow = SW_HIDE;
  3802. me = GetCurrentProcess();
  3803. DuplicateHandle(me,
  3804. (HANDLE)_get_osfhandle(fdin[0]),
  3805. me,
  3806. &si.hStdInput,
  3807. 0,
  3808. TRUE,
  3809. DUPLICATE_SAME_ACCESS);
  3810. DuplicateHandle(me,
  3811. (HANDLE)_get_osfhandle(fdout[1]),
  3812. me,
  3813. &si.hStdOutput,
  3814. 0,
  3815. TRUE,
  3816. DUPLICATE_SAME_ACCESS);
  3817. DuplicateHandle(me,
  3818. (HANDLE)_get_osfhandle(fderr[1]),
  3819. me,
  3820. &si.hStdError,
  3821. 0,
  3822. TRUE,
  3823. DUPLICATE_SAME_ACCESS);
  3824. /* Mark handles that should not be inherited. See
  3825. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3826. */
  3827. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3828. HANDLE_FLAG_INHERIT,
  3829. 0);
  3830. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3831. HANDLE_FLAG_INHERIT,
  3832. 0);
  3833. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3834. HANDLE_FLAG_INHERIT,
  3835. 0);
  3836. /* If CGI file is a script, try to read the interpreter line */
  3837. interp = conn->ctx->config[CGI_INTERPRETER];
  3838. if (interp == NULL) {
  3839. buf[0] = buf[1] = '\0';
  3840. /* Read the first line of the script into the buffer */
  3841. mg_snprintf(
  3842. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3843. if (truncated) {
  3844. pi.hProcess = (pid_t)-1;
  3845. goto spawn_cleanup;
  3846. }
  3847. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3848. p = (char *)file.access.membuf;
  3849. mg_fgets(buf, sizeof(buf), &file, &p);
  3850. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3851. buf[sizeof(buf) - 1] = '\0';
  3852. }
  3853. if (buf[0] == '#' && buf[1] == '!') {
  3854. trim_trailing_whitespaces(buf + 2);
  3855. } else {
  3856. buf[2] = '\0';
  3857. }
  3858. interp = buf + 2;
  3859. }
  3860. if (interp[0] != '\0') {
  3861. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3862. interp = full_interp;
  3863. }
  3864. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3865. if (interp[0] != '\0') {
  3866. mg_snprintf(conn,
  3867. &truncated,
  3868. cmdline,
  3869. sizeof(cmdline),
  3870. "\"%s\" \"%s\\%s\"",
  3871. interp,
  3872. full_dir,
  3873. prog);
  3874. } else {
  3875. mg_snprintf(conn,
  3876. &truncated,
  3877. cmdline,
  3878. sizeof(cmdline),
  3879. "\"%s\\%s\"",
  3880. full_dir,
  3881. prog);
  3882. }
  3883. if (truncated) {
  3884. pi.hProcess = (pid_t)-1;
  3885. goto spawn_cleanup;
  3886. }
  3887. DEBUG_TRACE("Running [%s]", cmdline);
  3888. if (CreateProcessA(NULL,
  3889. cmdline,
  3890. NULL,
  3891. NULL,
  3892. TRUE,
  3893. CREATE_NEW_PROCESS_GROUP,
  3894. envblk,
  3895. NULL,
  3896. &si,
  3897. &pi) == 0) {
  3898. mg_cry(
  3899. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3900. pi.hProcess = (pid_t)-1;
  3901. /* goto spawn_cleanup; */
  3902. }
  3903. spawn_cleanup:
  3904. (void)CloseHandle(si.hStdOutput);
  3905. (void)CloseHandle(si.hStdError);
  3906. (void)CloseHandle(si.hStdInput);
  3907. if (pi.hThread != NULL) {
  3908. (void)CloseHandle(pi.hThread);
  3909. }
  3910. return (pid_t)pi.hProcess;
  3911. }
  3912. #endif /* !NO_CGI */
  3913. static int
  3914. set_blocking_mode(SOCKET sock, int blocking)
  3915. {
  3916. unsigned long non_blocking = !blocking;
  3917. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3918. }
  3919. #else
  3920. static int
  3921. mg_stat(const struct mg_connection *conn,
  3922. const char *path,
  3923. struct mg_file_stat *filep)
  3924. {
  3925. struct stat st;
  3926. if (!filep) {
  3927. return 0;
  3928. }
  3929. memset(filep, 0, sizeof(*filep));
  3930. if (conn && is_file_in_memory(conn, path)) {
  3931. /* Quick fix (for 1.9.x): */
  3932. /* mg_stat must fill all fields, also for files in memory */
  3933. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3934. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3935. filep->size = tmp_file.stat.size;
  3936. filep->last_modified = time(NULL);
  3937. filep->location = 2;
  3938. /* TODO: for 1.10: restructure how files in memory are handled */
  3939. return 1;
  3940. }
  3941. if (0 == stat(path, &st)) {
  3942. filep->size = (uint64_t)(st.st_size);
  3943. filep->last_modified = st.st_mtime;
  3944. filep->is_directory = S_ISDIR(st.st_mode);
  3945. return 1;
  3946. }
  3947. return 0;
  3948. }
  3949. static void
  3950. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3951. {
  3952. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3953. if (conn) {
  3954. mg_cry(conn,
  3955. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3956. __func__,
  3957. strerror(ERRNO));
  3958. }
  3959. }
  3960. }
  3961. int
  3962. mg_start_thread(mg_thread_func_t func, void *param)
  3963. {
  3964. pthread_t thread_id;
  3965. pthread_attr_t attr;
  3966. int result;
  3967. (void)pthread_attr_init(&attr);
  3968. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3969. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3970. /* Compile-time option to control stack size,
  3971. * e.g. -DUSE_STACK_SIZE=16384 */
  3972. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3973. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3974. result = pthread_create(&thread_id, &attr, func, param);
  3975. pthread_attr_destroy(&attr);
  3976. return result;
  3977. }
  3978. /* Start a thread storing the thread context. */
  3979. static int
  3980. mg_start_thread_with_id(mg_thread_func_t func,
  3981. void *param,
  3982. pthread_t *threadidptr)
  3983. {
  3984. pthread_t thread_id;
  3985. pthread_attr_t attr;
  3986. int result;
  3987. (void)pthread_attr_init(&attr);
  3988. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3989. /* Compile-time option to control stack size,
  3990. * e.g. -DUSE_STACK_SIZE=16384 */
  3991. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3992. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3993. result = pthread_create(&thread_id, &attr, func, param);
  3994. pthread_attr_destroy(&attr);
  3995. if ((result == 0) && (threadidptr != NULL)) {
  3996. *threadidptr = thread_id;
  3997. }
  3998. return result;
  3999. }
  4000. /* Wait for a thread to finish. */
  4001. static int
  4002. mg_join_thread(pthread_t threadid)
  4003. {
  4004. int result;
  4005. result = pthread_join(threadid, NULL);
  4006. return result;
  4007. }
  4008. #ifndef NO_CGI
  4009. static pid_t
  4010. spawn_process(struct mg_connection *conn,
  4011. const char *prog,
  4012. char *envblk,
  4013. char *envp[],
  4014. int fdin[2],
  4015. int fdout[2],
  4016. int fderr[2],
  4017. const char *dir)
  4018. {
  4019. pid_t pid;
  4020. const char *interp;
  4021. (void)envblk;
  4022. if (conn == NULL) {
  4023. return 0;
  4024. }
  4025. if ((pid = fork()) == -1) {
  4026. /* Parent */
  4027. mg_send_http_error(conn,
  4028. 500,
  4029. "Error: Creating CGI process\nfork(): %s",
  4030. strerror(ERRNO));
  4031. } else if (pid == 0) {
  4032. /* Child */
  4033. if (chdir(dir) != 0) {
  4034. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4035. } else if (dup2(fdin[0], 0) == -1) {
  4036. mg_cry(conn,
  4037. "%s: dup2(%d, 0): %s",
  4038. __func__,
  4039. fdin[0],
  4040. strerror(ERRNO));
  4041. } else if (dup2(fdout[1], 1) == -1) {
  4042. mg_cry(conn,
  4043. "%s: dup2(%d, 1): %s",
  4044. __func__,
  4045. fdout[1],
  4046. strerror(ERRNO));
  4047. } else if (dup2(fderr[1], 2) == -1) {
  4048. mg_cry(conn,
  4049. "%s: dup2(%d, 2): %s",
  4050. __func__,
  4051. fderr[1],
  4052. strerror(ERRNO));
  4053. } else {
  4054. /* Keep stderr and stdout in two different pipes.
  4055. * Stdout will be sent back to the client,
  4056. * stderr should go into a server error log. */
  4057. (void)close(fdin[0]);
  4058. (void)close(fdout[1]);
  4059. (void)close(fderr[1]);
  4060. /* Close write end fdin and read end fdout and fderr */
  4061. (void)close(fdin[1]);
  4062. (void)close(fdout[0]);
  4063. (void)close(fderr[0]);
  4064. /* After exec, all signal handlers are restored to their default
  4065. * values, with one exception of SIGCHLD. According to
  4066. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4067. * leave unchanged after exec if it was set to be ignored. Restore
  4068. * it to default action. */
  4069. signal(SIGCHLD, SIG_DFL);
  4070. interp = conn->ctx->config[CGI_INTERPRETER];
  4071. if (interp == NULL) {
  4072. (void)execle(prog, prog, NULL, envp);
  4073. mg_cry(conn,
  4074. "%s: execle(%s): %s",
  4075. __func__,
  4076. prog,
  4077. strerror(ERRNO));
  4078. } else {
  4079. (void)execle(interp, interp, prog, NULL, envp);
  4080. mg_cry(conn,
  4081. "%s: execle(%s %s): %s",
  4082. __func__,
  4083. interp,
  4084. prog,
  4085. strerror(ERRNO));
  4086. }
  4087. }
  4088. exit(EXIT_FAILURE);
  4089. }
  4090. return pid;
  4091. }
  4092. #endif /* !NO_CGI */
  4093. static int
  4094. set_blocking_mode(SOCKET sock, int blocking)
  4095. {
  4096. int flags;
  4097. flags = fcntl(sock, F_GETFL, 0);
  4098. if (blocking) {
  4099. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  4100. } else {
  4101. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  4102. }
  4103. return 0;
  4104. }
  4105. #endif /* _WIN32 */
  4106. /* End of initial operating system specific define block. */
  4107. /* Get a random number (independent of C rand function) */
  4108. static uint64_t
  4109. get_random(void)
  4110. {
  4111. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4112. static uint64_t lcg = 0; /* Linear congruential generator */
  4113. uint64_t now = mg_get_current_time_ns();
  4114. if (lfsr == 0) {
  4115. /* lfsr will be only 0 if has not been initialized,
  4116. * so this code is called only once. */
  4117. lfsr = mg_get_current_time_ns();
  4118. lcg = mg_get_current_time_ns();
  4119. } else {
  4120. /* Get the next step of both random number generators. */
  4121. lfsr = (lfsr >> 1)
  4122. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4123. << 63);
  4124. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  4125. }
  4126. /* Combining two pseudo-random number generators and a high resolution part
  4127. * of the current server time will make it hard (impossible?) to guess the
  4128. * next number. */
  4129. return (lfsr ^ lcg ^ now);
  4130. }
  4131. static int
  4132. mg_poll(struct pollfd *pfd,
  4133. unsigned int n,
  4134. int milliseconds,
  4135. volatile int *stop_server)
  4136. {
  4137. int ms_now, result;
  4138. /* Call poll, but only for a maximum time of a few seconds.
  4139. * This will allow to stop the server after some seconds, instead
  4140. * of having to wait for a long socket timeout. */
  4141. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4142. do {
  4143. if (*stop_server) {
  4144. /* Shut down signal */
  4145. return -2;
  4146. }
  4147. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4148. ms_now = milliseconds;
  4149. }
  4150. result = poll(pfd, n, ms_now);
  4151. if (result != 0) {
  4152. /* Poll returned either success (1) or error (-1).
  4153. * Forward both to the caller. */
  4154. return result;
  4155. }
  4156. /* Poll returned timeout (0). */
  4157. if (milliseconds > 0) {
  4158. milliseconds -= ms_now;
  4159. }
  4160. } while (milliseconds != 0);
  4161. return result;
  4162. }
  4163. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4164. * descriptor. Return number of bytes written. */
  4165. static int
  4166. push(struct mg_context *ctx,
  4167. FILE *fp,
  4168. SOCKET sock,
  4169. SSL *ssl,
  4170. const char *buf,
  4171. int len,
  4172. double timeout)
  4173. {
  4174. uint64_t start = 0, now = 0, timeout_ns = 0;
  4175. int n, err;
  4176. #ifdef _WIN32
  4177. typedef int len_t;
  4178. #else
  4179. typedef size_t len_t;
  4180. #endif
  4181. if (timeout > 0) {
  4182. start = mg_get_current_time_ns();
  4183. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4184. }
  4185. if (ctx == NULL) {
  4186. return -1;
  4187. }
  4188. #ifdef NO_SSL
  4189. if (ssl) {
  4190. return -1;
  4191. }
  4192. #endif
  4193. do {
  4194. #ifndef NO_SSL
  4195. if (ssl != NULL) {
  4196. n = SSL_write(ssl, buf, len);
  4197. if (n <= 0) {
  4198. err = SSL_get_error(ssl, n);
  4199. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4200. err = ERRNO;
  4201. } else if ((err == SSL_ERROR_WANT_READ)
  4202. || (err == SSL_ERROR_WANT_WRITE)) {
  4203. n = 0;
  4204. } else {
  4205. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4206. return -1;
  4207. }
  4208. } else {
  4209. err = 0;
  4210. }
  4211. } else
  4212. #endif
  4213. if (fp != NULL) {
  4214. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4215. if (ferror(fp)) {
  4216. n = -1;
  4217. err = ERRNO;
  4218. } else {
  4219. err = 0;
  4220. }
  4221. } else {
  4222. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4223. err = (n < 0) ? ERRNO : 0;
  4224. #ifdef _WIN32
  4225. if (err == WSAEWOULDBLOCK) {
  4226. err = 0;
  4227. n = 0;
  4228. }
  4229. #else
  4230. if (err == EWOULDBLOCK) {
  4231. err = 0;
  4232. n = 0;
  4233. }
  4234. #endif
  4235. if (n < 0) {
  4236. /* shutdown of the socket at client side */
  4237. return -1;
  4238. }
  4239. }
  4240. if (ctx->stop_flag) {
  4241. return -1;
  4242. }
  4243. if ((n > 0) || (n == 0 && len == 0)) {
  4244. /* some data has been read, or no data was requested */
  4245. return n;
  4246. }
  4247. if (n < 0) {
  4248. /* socket error - check errno */
  4249. DEBUG_TRACE("send() failed, error %d", err);
  4250. /* TODO (mid): error handling depending on the error code.
  4251. * These codes are different between Windows and Linux.
  4252. * Currently there is no problem with failing send calls,
  4253. * if there is a reproducible situation, it should be
  4254. * investigated in detail.
  4255. */
  4256. return -1;
  4257. }
  4258. /* Only in case n=0 (timeout), repeat calling the write function */
  4259. if (timeout >= 0) {
  4260. now = mg_get_current_time_ns();
  4261. }
  4262. } while ((timeout <= 0) || ((now - start) <= timeout_ns));
  4263. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4264. used */
  4265. return -1;
  4266. }
  4267. static int64_t
  4268. push_all(struct mg_context *ctx,
  4269. FILE *fp,
  4270. SOCKET sock,
  4271. SSL *ssl,
  4272. const char *buf,
  4273. int64_t len)
  4274. {
  4275. double timeout = -1.0;
  4276. int64_t n, nwritten = 0;
  4277. if (ctx == NULL) {
  4278. return -1;
  4279. }
  4280. if (ctx->config[REQUEST_TIMEOUT]) {
  4281. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4282. }
  4283. while (len > 0 && ctx->stop_flag == 0) {
  4284. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4285. if (n < 0) {
  4286. if (nwritten == 0) {
  4287. nwritten = n; /* Propagate the error */
  4288. }
  4289. break;
  4290. } else if (n == 0) {
  4291. break; /* No more data to write */
  4292. } else {
  4293. nwritten += n;
  4294. len -= n;
  4295. }
  4296. }
  4297. return nwritten;
  4298. }
  4299. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4300. * Return value:
  4301. * >=0 .. number of bytes successfully read
  4302. * -1 .. timeout
  4303. * -2 .. error
  4304. */
  4305. static int
  4306. pull_inner(FILE *fp,
  4307. struct mg_connection *conn,
  4308. char *buf,
  4309. int len,
  4310. double timeout)
  4311. {
  4312. int nread, err = 0;
  4313. #ifdef _WIN32
  4314. typedef int len_t;
  4315. #else
  4316. typedef size_t len_t;
  4317. #endif
  4318. #ifndef NO_SSL
  4319. int ssl_pending;
  4320. #endif
  4321. /* We need an additional wait loop around this, because in some cases
  4322. * with TLSwe may get data from the socket but not from SSL_read.
  4323. * In this case we need to repeat at least once.
  4324. */
  4325. if (fp != NULL) {
  4326. #if !defined(_WIN32_WCE)
  4327. /* Use read() instead of fread(), because if we're reading from the
  4328. * CGI pipe, fread() may block until IO buffer is filled up. We
  4329. * cannot afford to block and must pass all read bytes immediately
  4330. * to the client. */
  4331. nread = (int)read(fileno(fp), buf, (size_t)len);
  4332. #else
  4333. /* WinCE does not support CGI pipes */
  4334. nread = (int)fread(buf, 1, (size_t)len, fp);
  4335. #endif
  4336. err = (nread < 0) ? ERRNO : 0;
  4337. #ifndef NO_SSL
  4338. } else if ((conn->ssl != NULL)
  4339. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4340. /* We already know there is no more data buffered in conn->buf
  4341. * but there is more available in the SSL layer. So don't poll
  4342. * conn->client.sock yet. */
  4343. if (ssl_pending > len) {
  4344. ssl_pending = len;
  4345. }
  4346. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4347. if (nread <= 0) {
  4348. err = SSL_get_error(conn->ssl, nread);
  4349. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4350. err = ERRNO;
  4351. } else if ((err == SSL_ERROR_WANT_READ)
  4352. || (err == SSL_ERROR_WANT_WRITE)) {
  4353. nread = 0;
  4354. } else {
  4355. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4356. return -1;
  4357. }
  4358. } else {
  4359. err = 0;
  4360. }
  4361. } else if (conn->ssl != NULL) {
  4362. struct pollfd pfd[1];
  4363. int pollres;
  4364. pfd[0].fd = conn->client.sock;
  4365. pfd[0].events = POLLIN;
  4366. pollres =
  4367. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4368. if (conn->ctx->stop_flag) {
  4369. return -2;
  4370. }
  4371. if (pollres > 0) {
  4372. nread = SSL_read(conn->ssl, buf, len);
  4373. if (nread <= 0) {
  4374. err = SSL_get_error(conn->ssl, nread);
  4375. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4376. err = ERRNO;
  4377. } else if ((err == SSL_ERROR_WANT_READ)
  4378. || (err == SSL_ERROR_WANT_WRITE)) {
  4379. nread = 0;
  4380. } else {
  4381. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4382. return -2;
  4383. }
  4384. } else {
  4385. err = 0;
  4386. }
  4387. } else if (pollres < 0) {
  4388. /* Error */
  4389. return -2;
  4390. } else {
  4391. /* pollres = 0 means timeout */
  4392. nread = 0;
  4393. }
  4394. #endif
  4395. } else {
  4396. struct pollfd pfd[1];
  4397. int pollres;
  4398. pfd[0].fd = conn->client.sock;
  4399. pfd[0].events = POLLIN;
  4400. pollres =
  4401. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4402. if (conn->ctx->stop_flag) {
  4403. return -2;
  4404. }
  4405. if (pollres > 0) {
  4406. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4407. err = (nread < 0) ? ERRNO : 0;
  4408. if (nread <= 0) {
  4409. /* shutdown of the socket at client side */
  4410. return -2;
  4411. }
  4412. } else if (pollres < 0) {
  4413. /* error callint poll */
  4414. return -2;
  4415. } else {
  4416. /* pollres = 0 means timeout */
  4417. nread = 0;
  4418. }
  4419. }
  4420. if (conn->ctx->stop_flag) {
  4421. return -2;
  4422. }
  4423. if ((nread > 0) || (nread == 0 && len == 0)) {
  4424. /* some data has been read, or no data was requested */
  4425. return nread;
  4426. }
  4427. if (nread < 0) {
  4428. /* socket error - check errno */
  4429. #ifdef _WIN32
  4430. if (err == WSAEWOULDBLOCK) {
  4431. /* TODO (low): check if this is still required */
  4432. /* standard case if called from close_socket_gracefully */
  4433. return -2;
  4434. } else if (err == WSAETIMEDOUT) {
  4435. /* TODO (low): check if this is still required */
  4436. /* timeout is handled by the while loop */
  4437. return 0;
  4438. } else if (err == WSAECONNABORTED) {
  4439. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4440. return -2;
  4441. } else {
  4442. DEBUG_TRACE("recv() failed, error %d", err);
  4443. return -2;
  4444. }
  4445. #else
  4446. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4447. * if the timeout is reached and if the socket was set to non-
  4448. * blocking in close_socket_gracefully, so we can not distinguish
  4449. * here. We have to wait for the timeout in both cases for now.
  4450. */
  4451. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4452. /* TODO (low): check if this is still required */
  4453. /* EAGAIN/EWOULDBLOCK:
  4454. * standard case if called from close_socket_gracefully
  4455. * => should return -1 */
  4456. /* or timeout occured
  4457. * => the code must stay in the while loop */
  4458. /* EINTR can be generated on a socket with a timeout set even
  4459. * when SA_RESTART is effective for all relevant signals
  4460. * (see signal(7)).
  4461. * => stay in the while loop */
  4462. } else {
  4463. DEBUG_TRACE("recv() failed, error %d", err);
  4464. return -2;
  4465. }
  4466. #endif
  4467. }
  4468. /* Timeout occured, but no data available. */
  4469. return -1;
  4470. }
  4471. static int
  4472. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4473. {
  4474. int n, nread = 0;
  4475. double timeout = -1.0;
  4476. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4477. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4478. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4479. }
  4480. if (timeout >= 0.0) {
  4481. start_time = mg_get_current_time_ns();
  4482. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4483. }
  4484. while (len > 0 && conn->ctx->stop_flag == 0) {
  4485. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4486. if (n == -2) {
  4487. if (nread == 0) {
  4488. nread = -1; /* Propagate the error */
  4489. }
  4490. break;
  4491. } else if (n == -1) {
  4492. /* timeout */
  4493. if (timeout >= 0.0) {
  4494. now = mg_get_current_time_ns();
  4495. if ((now - start_time) <= timeout_ns) {
  4496. continue;
  4497. }
  4498. }
  4499. break;
  4500. } else if (n == 0) {
  4501. break; /* No more data to read */
  4502. } else {
  4503. conn->consumed_content += n;
  4504. nread += n;
  4505. len -= n;
  4506. }
  4507. }
  4508. return nread;
  4509. }
  4510. static void
  4511. discard_unread_request_data(struct mg_connection *conn)
  4512. {
  4513. char buf[MG_BUF_LEN];
  4514. size_t to_read;
  4515. int nread;
  4516. if (conn == NULL) {
  4517. return;
  4518. }
  4519. to_read = sizeof(buf);
  4520. if (conn->is_chunked) {
  4521. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4522. * completely */
  4523. while (conn->is_chunked == 1) {
  4524. nread = mg_read(conn, buf, to_read);
  4525. if (nread <= 0) {
  4526. break;
  4527. }
  4528. }
  4529. } else {
  4530. /* Not chunked: content length is known */
  4531. while (conn->consumed_content < conn->content_len) {
  4532. if (to_read
  4533. > (size_t)(conn->content_len - conn->consumed_content)) {
  4534. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4535. }
  4536. nread = mg_read(conn, buf, to_read);
  4537. if (nread <= 0) {
  4538. break;
  4539. }
  4540. }
  4541. }
  4542. }
  4543. static int
  4544. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4545. {
  4546. int64_t n, buffered_len, nread;
  4547. int64_t len64 =
  4548. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4549. * int, we may not read more
  4550. * bytes */
  4551. const char *body;
  4552. if (conn == NULL) {
  4553. return 0;
  4554. }
  4555. /* If Content-Length is not set for a PUT or POST request, read until
  4556. * socket is closed */
  4557. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4558. conn->content_len = INT64_MAX;
  4559. conn->must_close = 1;
  4560. }
  4561. nread = 0;
  4562. if (conn->consumed_content < conn->content_len) {
  4563. /* Adjust number of bytes to read. */
  4564. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4565. if (left_to_read < len64) {
  4566. /* Do not read more than the total content length of the request.
  4567. */
  4568. len64 = left_to_read;
  4569. }
  4570. /* Return buffered data */
  4571. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4572. - conn->consumed_content;
  4573. if (buffered_len > 0) {
  4574. if (len64 < buffered_len) {
  4575. buffered_len = len64;
  4576. }
  4577. body = conn->buf + conn->request_len + conn->consumed_content;
  4578. memcpy(buf, body, (size_t)buffered_len);
  4579. len64 -= buffered_len;
  4580. conn->consumed_content += buffered_len;
  4581. nread += buffered_len;
  4582. buf = (char *)buf + buffered_len;
  4583. }
  4584. /* We have returned all buffered data. Read new data from the remote
  4585. * socket.
  4586. */
  4587. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4588. nread += n;
  4589. } else {
  4590. nread = ((nread > 0) ? nread : n);
  4591. }
  4592. }
  4593. return (int)nread;
  4594. }
  4595. static char
  4596. mg_getc(struct mg_connection *conn)
  4597. {
  4598. char c;
  4599. if (conn == NULL) {
  4600. return 0;
  4601. }
  4602. conn->content_len++;
  4603. if (mg_read_inner(conn, &c, 1) <= 0) {
  4604. return (char)0;
  4605. }
  4606. return c;
  4607. }
  4608. int
  4609. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4610. {
  4611. if (len > INT_MAX) {
  4612. len = INT_MAX;
  4613. }
  4614. if (conn == NULL) {
  4615. return 0;
  4616. }
  4617. if (conn->is_chunked) {
  4618. size_t all_read = 0;
  4619. while (len > 0) {
  4620. if (conn->is_chunked == 2) {
  4621. /* No more data left to read */
  4622. return 0;
  4623. }
  4624. if (conn->chunk_remainder) {
  4625. /* copy from the remainder of the last received chunk */
  4626. long read_ret;
  4627. size_t read_now =
  4628. ((conn->chunk_remainder > len) ? (len)
  4629. : (conn->chunk_remainder));
  4630. conn->content_len += (int)read_now;
  4631. read_ret =
  4632. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4633. if (read_ret < 1) {
  4634. /* read error */
  4635. return -1;
  4636. }
  4637. all_read += (size_t)read_ret;
  4638. conn->chunk_remainder -= (size_t)read_ret;
  4639. len -= (size_t)read_ret;
  4640. if (conn->chunk_remainder == 0) {
  4641. /* Add data bytes in the current chunk have been read,
  4642. * so we are expecting \r\n now. */
  4643. char x1 = mg_getc(conn);
  4644. char x2 = mg_getc(conn);
  4645. if ((x1 != '\r') || (x2 != '\n')) {
  4646. /* Protocol violation */
  4647. return -1;
  4648. }
  4649. }
  4650. } else {
  4651. /* fetch a new chunk */
  4652. int i = 0;
  4653. char lenbuf[64];
  4654. char *end = 0;
  4655. unsigned long chunkSize = 0;
  4656. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4657. lenbuf[i] = mg_getc(conn);
  4658. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4659. continue;
  4660. }
  4661. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4662. lenbuf[i + 1] = 0;
  4663. chunkSize = strtoul(lenbuf, &end, 16);
  4664. if (chunkSize == 0) {
  4665. /* regular end of content */
  4666. conn->is_chunked = 2;
  4667. }
  4668. break;
  4669. }
  4670. if (!isxdigit(lenbuf[i])) {
  4671. /* illegal character for chunk length */
  4672. return -1;
  4673. }
  4674. }
  4675. if ((end == NULL) || (*end != '\r')) {
  4676. /* chunksize not set correctly */
  4677. return -1;
  4678. }
  4679. if (chunkSize == 0) {
  4680. break;
  4681. }
  4682. conn->chunk_remainder = chunkSize;
  4683. }
  4684. }
  4685. return (int)all_read;
  4686. }
  4687. return mg_read_inner(conn, buf, len);
  4688. }
  4689. int
  4690. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4691. {
  4692. time_t now;
  4693. int64_t n, total, allowed;
  4694. if (conn == NULL) {
  4695. return 0;
  4696. }
  4697. if (conn->throttle > 0) {
  4698. if ((now = time(NULL)) != conn->last_throttle_time) {
  4699. conn->last_throttle_time = now;
  4700. conn->last_throttle_bytes = 0;
  4701. }
  4702. allowed = conn->throttle - conn->last_throttle_bytes;
  4703. if (allowed > (int64_t)len) {
  4704. allowed = (int64_t)len;
  4705. }
  4706. if ((total = push_all(conn->ctx,
  4707. NULL,
  4708. conn->client.sock,
  4709. conn->ssl,
  4710. (const char *)buf,
  4711. (int64_t)allowed)) == allowed) {
  4712. buf = (const char *)buf + total;
  4713. conn->last_throttle_bytes += total;
  4714. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4715. allowed = (conn->throttle > ((int64_t)len - total))
  4716. ? (int64_t)len - total
  4717. : conn->throttle;
  4718. if ((n = push_all(conn->ctx,
  4719. NULL,
  4720. conn->client.sock,
  4721. conn->ssl,
  4722. (const char *)buf,
  4723. (int64_t)allowed)) != allowed) {
  4724. break;
  4725. }
  4726. sleep(1);
  4727. conn->last_throttle_bytes = allowed;
  4728. conn->last_throttle_time = time(NULL);
  4729. buf = (const char *)buf + n;
  4730. total += n;
  4731. }
  4732. }
  4733. } else {
  4734. total = push_all(conn->ctx,
  4735. NULL,
  4736. conn->client.sock,
  4737. conn->ssl,
  4738. (const char *)buf,
  4739. (int64_t)len);
  4740. }
  4741. if (total > 0) {
  4742. conn->num_bytes_sent += total;
  4743. }
  4744. return (int)total;
  4745. }
  4746. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  4747. int
  4748. mg_send_chunk(struct mg_connection *conn,
  4749. const char *chunk,
  4750. unsigned int chunk_len)
  4751. {
  4752. char lenbuf[16];
  4753. size_t lenbuf_len;
  4754. int ret;
  4755. int t;
  4756. /* First store the length information in a text buffer. */
  4757. sprintf(lenbuf, "%x\r\n", chunk_len);
  4758. lenbuf_len = strlen(lenbuf);
  4759. /* Then send length information, chunk and terminating \r\n. */
  4760. ret = mg_write(conn, lenbuf, lenbuf_len);
  4761. if (ret != (int)lenbuf_len) {
  4762. return -1;
  4763. }
  4764. t = ret;
  4765. ret = mg_write(conn, chunk, chunk_len);
  4766. if (ret != (int)chunk_len) {
  4767. return -1;
  4768. }
  4769. t += ret;
  4770. ret = mg_write(conn, "\r\n", 2);
  4771. if (ret != 2) {
  4772. return -1;
  4773. }
  4774. t += ret;
  4775. return t;
  4776. }
  4777. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4778. static int
  4779. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4780. {
  4781. va_list ap_copy;
  4782. size_t size = MG_BUF_LEN / 4;
  4783. int len = -1;
  4784. *buf = NULL;
  4785. while (len < 0) {
  4786. if (*buf) {
  4787. mg_free(*buf);
  4788. }
  4789. size *= 4;
  4790. *buf = (char *)mg_malloc(size);
  4791. if (!*buf) {
  4792. break;
  4793. }
  4794. va_copy(ap_copy, ap);
  4795. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4796. va_end(ap_copy);
  4797. (*buf)[size - 1] = 0;
  4798. }
  4799. return len;
  4800. }
  4801. /* Print message to buffer. If buffer is large enough to hold the message,
  4802. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4803. * and return allocated buffer. */
  4804. static int
  4805. alloc_vprintf(char **out_buf,
  4806. char *prealloc_buf,
  4807. size_t prealloc_size,
  4808. const char *fmt,
  4809. va_list ap)
  4810. {
  4811. va_list ap_copy;
  4812. int len;
  4813. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4814. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4815. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4816. * Therefore, we make two passes: on first pass, get required message
  4817. * length.
  4818. * On second pass, actually print the message. */
  4819. va_copy(ap_copy, ap);
  4820. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4821. va_end(ap_copy);
  4822. if (len < 0) {
  4823. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4824. * Switch to alternative code path that uses incremental allocations.
  4825. */
  4826. va_copy(ap_copy, ap);
  4827. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4828. va_end(ap_copy);
  4829. } else if ((size_t)(len) >= prealloc_size) {
  4830. /* The pre-allocated buffer not large enough. */
  4831. /* Allocate a new buffer. */
  4832. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4833. if (!*out_buf) {
  4834. /* Allocation failed. Return -1 as "out of memory" error. */
  4835. return -1;
  4836. }
  4837. /* Buffer allocation successful. Store the string there. */
  4838. va_copy(ap_copy, ap);
  4839. IGNORE_UNUSED_RESULT(
  4840. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4841. va_end(ap_copy);
  4842. } else {
  4843. /* The pre-allocated buffer is large enough.
  4844. * Use it to store the string and return the address. */
  4845. va_copy(ap_copy, ap);
  4846. IGNORE_UNUSED_RESULT(
  4847. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4848. va_end(ap_copy);
  4849. *out_buf = prealloc_buf;
  4850. }
  4851. return len;
  4852. }
  4853. static int
  4854. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4855. {
  4856. char mem[MG_BUF_LEN];
  4857. char *buf = NULL;
  4858. int len;
  4859. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4860. len = mg_write(conn, buf, (size_t)len);
  4861. }
  4862. if (buf != mem && buf != NULL) {
  4863. mg_free(buf);
  4864. }
  4865. return len;
  4866. }
  4867. int
  4868. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4869. {
  4870. va_list ap;
  4871. int result;
  4872. va_start(ap, fmt);
  4873. result = mg_vprintf(conn, fmt, ap);
  4874. va_end(ap);
  4875. return result;
  4876. }
  4877. int
  4878. mg_url_decode(const char *src,
  4879. int src_len,
  4880. char *dst,
  4881. int dst_len,
  4882. int is_form_url_encoded)
  4883. {
  4884. int i, j, a, b;
  4885. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4886. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4887. if (i < src_len - 2 && src[i] == '%'
  4888. && isxdigit(*(const unsigned char *)(src + i + 1))
  4889. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4890. a = tolower(*(const unsigned char *)(src + i + 1));
  4891. b = tolower(*(const unsigned char *)(src + i + 2));
  4892. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4893. i += 2;
  4894. } else if (is_form_url_encoded && src[i] == '+') {
  4895. dst[j] = ' ';
  4896. } else {
  4897. dst[j] = src[i];
  4898. }
  4899. }
  4900. dst[j] = '\0'; /* Null-terminate the destination */
  4901. return (i >= src_len) ? j : -1;
  4902. }
  4903. int
  4904. mg_get_var(const char *data,
  4905. size_t data_len,
  4906. const char *name,
  4907. char *dst,
  4908. size_t dst_len)
  4909. {
  4910. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4911. }
  4912. int
  4913. mg_get_var2(const char *data,
  4914. size_t data_len,
  4915. const char *name,
  4916. char *dst,
  4917. size_t dst_len,
  4918. size_t occurrence)
  4919. {
  4920. const char *p, *e, *s;
  4921. size_t name_len;
  4922. int len;
  4923. if (dst == NULL || dst_len == 0) {
  4924. len = -2;
  4925. } else if (data == NULL || name == NULL || data_len == 0) {
  4926. len = -1;
  4927. dst[0] = '\0';
  4928. } else {
  4929. name_len = strlen(name);
  4930. e = data + data_len;
  4931. len = -1;
  4932. dst[0] = '\0';
  4933. /* data is "var1=val1&var2=val2...". Find variable first */
  4934. for (p = data; p + name_len < e; p++) {
  4935. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4936. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4937. /* Point p to variable value */
  4938. p += name_len + 1;
  4939. /* Point s to the end of the value */
  4940. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4941. if (s == NULL) {
  4942. s = e;
  4943. }
  4944. /* assert(s >= p); */
  4945. if (s < p) {
  4946. return -3;
  4947. }
  4948. /* Decode variable into destination buffer */
  4949. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4950. /* Redirect error code from -1 to -2 (destination buffer too
  4951. * small). */
  4952. if (len == -1) {
  4953. len = -2;
  4954. }
  4955. break;
  4956. }
  4957. }
  4958. }
  4959. return len;
  4960. }
  4961. /* HCP24: some changes to compare hole var_name */
  4962. int
  4963. mg_get_cookie(const char *cookie_header,
  4964. const char *var_name,
  4965. char *dst,
  4966. size_t dst_size)
  4967. {
  4968. const char *s, *p, *end;
  4969. int name_len, len = -1;
  4970. if (dst == NULL || dst_size == 0) {
  4971. return -2;
  4972. }
  4973. dst[0] = '\0';
  4974. if (var_name == NULL || (s = cookie_header) == NULL) {
  4975. return -1;
  4976. }
  4977. name_len = (int)strlen(var_name);
  4978. end = s + strlen(s);
  4979. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4980. if (s[name_len] == '=') {
  4981. /* HCP24: now check is it a substring or a full cookie name */
  4982. if ((s == cookie_header) || (s[-1] == ' ')) {
  4983. s += name_len + 1;
  4984. if ((p = strchr(s, ' ')) == NULL) {
  4985. p = end;
  4986. }
  4987. if (p[-1] == ';') {
  4988. p--;
  4989. }
  4990. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4991. s++;
  4992. p--;
  4993. }
  4994. if ((size_t)(p - s) < dst_size) {
  4995. len = (int)(p - s);
  4996. mg_strlcpy(dst, s, (size_t)len + 1);
  4997. } else {
  4998. len = -3;
  4999. }
  5000. break;
  5001. }
  5002. }
  5003. }
  5004. return len;
  5005. }
  5006. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5007. static void
  5008. base64_encode(const unsigned char *src, int src_len, char *dst)
  5009. {
  5010. static const char *b64 =
  5011. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5012. int i, j, a, b, c;
  5013. for (i = j = 0; i < src_len; i += 3) {
  5014. a = src[i];
  5015. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5016. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5017. dst[j++] = b64[a >> 2];
  5018. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5019. if (i + 1 < src_len) {
  5020. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5021. }
  5022. if (i + 2 < src_len) {
  5023. dst[j++] = b64[c & 63];
  5024. }
  5025. }
  5026. while (j % 4 != 0) {
  5027. dst[j++] = '=';
  5028. }
  5029. dst[j++] = '\0';
  5030. }
  5031. #endif
  5032. #if defined(USE_LUA)
  5033. static unsigned char
  5034. b64reverse(char letter)
  5035. {
  5036. if (letter >= 'A' && letter <= 'Z') {
  5037. return letter - 'A';
  5038. }
  5039. if (letter >= 'a' && letter <= 'z') {
  5040. return letter - 'a' + 26;
  5041. }
  5042. if (letter >= '0' && letter <= '9') {
  5043. return letter - '0' + 52;
  5044. }
  5045. if (letter == '+') {
  5046. return 62;
  5047. }
  5048. if (letter == '/') {
  5049. return 63;
  5050. }
  5051. if (letter == '=') {
  5052. return 255; /* normal end */
  5053. }
  5054. return 254; /* error */
  5055. }
  5056. static int
  5057. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5058. {
  5059. int i;
  5060. unsigned char a, b, c, d;
  5061. *dst_len = 0;
  5062. for (i = 0; i < src_len; i += 4) {
  5063. a = b64reverse(src[i]);
  5064. if (a >= 254) {
  5065. return i;
  5066. }
  5067. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5068. if (b >= 254) {
  5069. return i + 1;
  5070. }
  5071. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5072. if (c == 254) {
  5073. return i + 2;
  5074. }
  5075. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5076. if (d == 254) {
  5077. return i + 3;
  5078. }
  5079. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5080. if (c != 255) {
  5081. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5082. if (d != 255) {
  5083. dst[(*dst_len)++] = (c << 6) + d;
  5084. }
  5085. }
  5086. }
  5087. return -1;
  5088. }
  5089. #endif
  5090. static int
  5091. is_put_or_delete_method(const struct mg_connection *conn)
  5092. {
  5093. if (conn) {
  5094. const char *s = conn->request_info.request_method;
  5095. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5096. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5097. }
  5098. return 0;
  5099. }
  5100. #if !defined(NO_FILES)
  5101. static int
  5102. extention_matches_script(
  5103. struct mg_connection *conn, /* in: request (must be valid) */
  5104. const char *filename /* in: filename (must be valid) */
  5105. )
  5106. {
  5107. #if !defined(NO_CGI)
  5108. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5109. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5110. filename) > 0) {
  5111. return 1;
  5112. }
  5113. #endif
  5114. #if defined(USE_LUA)
  5115. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5116. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5117. filename) > 0) {
  5118. return 1;
  5119. }
  5120. #endif
  5121. #if defined(USE_DUKTAPE)
  5122. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5123. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5124. filename) > 0) {
  5125. return 1;
  5126. }
  5127. #endif
  5128. /* filename and conn could be unused, if all preocessor conditions
  5129. * are false (no script language supported). */
  5130. (void)filename;
  5131. (void)conn;
  5132. return 0;
  5133. }
  5134. /* For given directory path, substitute it to valid index file.
  5135. * Return 1 if index file has been found, 0 if not found.
  5136. * If the file is found, it's stats is returned in stp. */
  5137. static int
  5138. substitute_index_file(struct mg_connection *conn,
  5139. char *path,
  5140. size_t path_len,
  5141. struct mg_file_stat *filestat)
  5142. {
  5143. const char *list = conn->ctx->config[INDEX_FILES];
  5144. struct vec filename_vec;
  5145. size_t n = strlen(path);
  5146. int found = 0;
  5147. /* The 'path' given to us points to the directory. Remove all trailing
  5148. * directory separator characters from the end of the path, and
  5149. * then append single directory separator character. */
  5150. while (n > 0 && path[n - 1] == '/') {
  5151. n--;
  5152. }
  5153. path[n] = '/';
  5154. /* Traverse index files list. For each entry, append it to the given
  5155. * path and see if the file exists. If it exists, break the loop */
  5156. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5157. /* Ignore too long entries that may overflow path buffer */
  5158. if (filename_vec.len > path_len - (n + 2)) {
  5159. continue;
  5160. }
  5161. /* Prepare full path to the index file */
  5162. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5163. /* Does it exist? */
  5164. if (mg_stat(conn, path, filestat)) {
  5165. /* Yes it does, break the loop */
  5166. found = 1;
  5167. break;
  5168. }
  5169. }
  5170. /* If no index file exists, restore directory path */
  5171. if (!found) {
  5172. path[n] = '\0';
  5173. }
  5174. return found;
  5175. }
  5176. #endif
  5177. static void
  5178. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5179. char *filename, /* out: filename */
  5180. size_t filename_buf_len, /* in: size of filename buffer */
  5181. struct mg_file_stat *filestat, /* out: file status structure */
  5182. int *is_found, /* out: file found (directly) */
  5183. int *is_script_resource, /* out: handled by a script? */
  5184. int *is_websocket_request, /* out: websocket connetion? */
  5185. int *is_put_or_delete_request /* out: put/delete a file? */
  5186. )
  5187. {
  5188. #if !defined(NO_FILES)
  5189. const char *uri = conn->request_info.local_uri;
  5190. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5191. const char *rewrite;
  5192. struct vec a, b;
  5193. int match_len;
  5194. char gz_path[PATH_MAX];
  5195. char const *accept_encoding;
  5196. int truncated;
  5197. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5198. char *tmp_str;
  5199. size_t tmp_str_len, sep_pos;
  5200. #endif
  5201. #else
  5202. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5203. #endif
  5204. /* Step 1: Set all initially unknown outputs to zero */
  5205. memset(filestat, 0, sizeof(*filestat));
  5206. *filename = 0;
  5207. *is_found = 0;
  5208. *is_script_resource = 0;
  5209. /* Step 2: Check if the request attempts to modify the file system */
  5210. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5211. /* Step 3: Check if it is a websocket request, and modify the document
  5212. * root if required */
  5213. #if defined(USE_WEBSOCKET)
  5214. *is_websocket_request = is_websocket_protocol(conn);
  5215. #if !defined(NO_FILES)
  5216. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5217. root = conn->ctx->config[WEBSOCKET_ROOT];
  5218. }
  5219. #endif /* !NO_FILES */
  5220. #else /* USE_WEBSOCKET */
  5221. *is_websocket_request = 0;
  5222. #endif /* USE_WEBSOCKET */
  5223. #if !defined(NO_FILES)
  5224. /* Step 4: If there is no root directory, don't look for files. */
  5225. /* Note that root == NULL is a regular use case here. This occurs,
  5226. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5227. * config is not required. */
  5228. if (root == NULL) {
  5229. /* all file related outputs have already been set to 0, just return
  5230. */
  5231. return;
  5232. }
  5233. /* Step 5: Determine the local file path from the root path and the
  5234. * request uri. */
  5235. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5236. * part of the path one byte on the right. */
  5237. mg_snprintf(
  5238. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5239. if (truncated) {
  5240. goto interpret_cleanup;
  5241. }
  5242. /* Step 6: URI rewriting */
  5243. rewrite = conn->ctx->config[URL_REWRITE_PATTERN];
  5244. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5245. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5246. mg_snprintf(conn,
  5247. &truncated,
  5248. filename,
  5249. filename_buf_len - 1,
  5250. "%.*s%s",
  5251. (int)b.len,
  5252. b.ptr,
  5253. uri + match_len);
  5254. break;
  5255. }
  5256. }
  5257. if (truncated) {
  5258. goto interpret_cleanup;
  5259. }
  5260. /* Step 7: Check if the file exists at the server */
  5261. /* Local file path and name, corresponding to requested URI
  5262. * is now stored in "filename" variable. */
  5263. if (mg_stat(conn, filename, filestat)) {
  5264. /* 7.1: File exists. */
  5265. *is_found = 1;
  5266. /* 7.2: Check if it is a script type. */
  5267. if (extention_matches_script(conn, filename)) {
  5268. /* The request addresses a CGI resource, Lua script or
  5269. * server-side javascript.
  5270. * The URI corresponds to the script itself (like
  5271. * /path/script.cgi), and there is no additional resource
  5272. * path (like /path/script.cgi/something).
  5273. * Requests that modify (replace or delete) a resource, like
  5274. * PUT and DELETE requests, should replace/delete the script
  5275. * file.
  5276. * Requests that read or write from/to a resource, like GET and
  5277. * POST requests, should call the script and return the
  5278. * generated response. */
  5279. *is_script_resource = (!*is_put_or_delete_request);
  5280. }
  5281. /* 7.3: If the request target is a directory, there could be
  5282. * a substitute file (index.html, index.cgi, ...). */
  5283. if (filestat->is_directory) {
  5284. /* Use a local copy here, since substitute_index_file will
  5285. * change the content of the file status */
  5286. struct mg_file_stat tmp_filestat;
  5287. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5288. if (substitute_index_file(
  5289. conn, filename, filename_buf_len, &tmp_filestat)) {
  5290. /* Substitute file found. Copy stat to the output, then
  5291. * check if the file is a script file */
  5292. *filestat = tmp_filestat;
  5293. if (extention_matches_script(conn, filename)) {
  5294. /* Substitute file is a script file */
  5295. *is_script_resource = 1;
  5296. } else {
  5297. /* Substitute file is a regular file */
  5298. *is_script_resource = 0;
  5299. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5300. }
  5301. }
  5302. /* If there is no substitute file, the server could return
  5303. * a directory listing in a later step */
  5304. }
  5305. return;
  5306. }
  5307. /* Step 8: Check for zipped files: */
  5308. /* If we can't find the actual file, look for the file
  5309. * with the same name but a .gz extension. If we find it,
  5310. * use that and set the gzipped flag in the file struct
  5311. * to indicate that the response need to have the content-
  5312. * encoding: gzip header.
  5313. * We can only do this if the browser declares support. */
  5314. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5315. if (strstr(accept_encoding, "gzip") != NULL) {
  5316. mg_snprintf(
  5317. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5318. if (truncated) {
  5319. goto interpret_cleanup;
  5320. }
  5321. if (mg_stat(conn, gz_path, filestat)) {
  5322. if (filestat) {
  5323. filestat->is_gzipped = 1;
  5324. *is_found = 1;
  5325. }
  5326. /* Currently gz files can not be scripts. */
  5327. return;
  5328. }
  5329. }
  5330. }
  5331. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5332. /* Step 9: Script resources may handle sub-resources */
  5333. /* Support PATH_INFO for CGI scripts. */
  5334. tmp_str_len = strlen(filename);
  5335. tmp_str = mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->ctx);
  5336. if (!tmp_str) {
  5337. /* Out of memory */
  5338. goto interpret_cleanup;
  5339. }
  5340. memcpy(tmp_str, filename, tmp_str_len + 1);
  5341. sep_pos = tmp_str_len;
  5342. while (sep_pos > 0) {
  5343. sep_pos--;
  5344. if (tmp_str[sep_pos] == '/') {
  5345. int is_script = 0, does_exist = 0;
  5346. tmp_str[sep_pos] = 0;
  5347. if (tmp_str[0]) {
  5348. is_script = extention_matches_script(conn, tmp_str);
  5349. does_exist = mg_stat(conn, tmp_str, filestat);
  5350. }
  5351. if (does_exist && is_script) {
  5352. filename[sep_pos] = 0;
  5353. memmove(filename + sep_pos + 2,
  5354. filename + sep_pos + 1,
  5355. strlen(filename + sep_pos + 1) + 1);
  5356. conn->path_info = filename + sep_pos + 1;
  5357. filename[sep_pos + 1] = '/';
  5358. *is_script_resource = 1;
  5359. *is_found = 1;
  5360. break;
  5361. }
  5362. if (substitute_index_file(
  5363. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5364. /* some intermediate directory has an index file */
  5365. if (extention_matches_script(conn, tmp_str)) {
  5366. /* this index file is a script */
  5367. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5368. mg_snprintf(conn,
  5369. &truncated,
  5370. filename,
  5371. filename_buf_len,
  5372. "%s//%s",
  5373. tmp_str,
  5374. tmp_str2);
  5375. mg_free(tmp_str2);
  5376. if (truncated) {
  5377. mg_free(tmp_str);
  5378. tmp_str = NULL;
  5379. goto interpret_cleanup;
  5380. }
  5381. sep_pos = strlen(tmp_str);
  5382. filename[sep_pos] = 0;
  5383. conn->path_info = filename + sep_pos + 1;
  5384. *is_script_resource = 1;
  5385. *is_found = 1;
  5386. break;
  5387. } else {
  5388. /* non-script files will not have sub-resources */
  5389. filename[sep_pos] = 0;
  5390. conn->path_info = 0;
  5391. *is_script_resource = 0;
  5392. *is_found = 0;
  5393. break;
  5394. }
  5395. }
  5396. tmp_str[sep_pos] = '/';
  5397. }
  5398. }
  5399. mg_free(tmp_str);
  5400. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5401. #endif /* !defined(NO_FILES) */
  5402. return;
  5403. #if !defined(NO_FILES)
  5404. /* Reset all outputs */
  5405. interpret_cleanup:
  5406. memset(filestat, 0, sizeof(*filestat));
  5407. *filename = 0;
  5408. *is_found = 0;
  5409. *is_script_resource = 0;
  5410. *is_websocket_request = 0;
  5411. *is_put_or_delete_request = 0;
  5412. #endif /* !defined(NO_FILES) */
  5413. }
  5414. /* Check whether full request is buffered. Return:
  5415. * -1 if request is malformed
  5416. * 0 if request is not yet fully buffered
  5417. * >0 actual request length, including last \r\n\r\n */
  5418. static int
  5419. get_request_len(const char *buf, int buflen)
  5420. {
  5421. const char *s, *e;
  5422. int len = 0;
  5423. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  5424. /* Control characters are not allowed but >=128 is. */
  5425. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  5426. && *(const unsigned char *)s < 128) {
  5427. len = -1;
  5428. break; /* [i_a] abort scan as soon as one malformed character is
  5429. * found; */
  5430. /* don't let subsequent \r\n\r\n win us over anyhow */
  5431. } else if (s[0] == '\n' && s[1] == '\n') {
  5432. len = (int)(s - buf) + 2;
  5433. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  5434. len = (int)(s - buf) + 3;
  5435. }
  5436. return len;
  5437. }
  5438. #if !defined(NO_CACHING)
  5439. /* Convert month to the month number. Return -1 on error, or month number */
  5440. static int
  5441. get_month_index(const char *s)
  5442. {
  5443. size_t i;
  5444. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5445. if (!strcmp(s, month_names[i])) {
  5446. return (int)i;
  5447. }
  5448. }
  5449. return -1;
  5450. }
  5451. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5452. static time_t
  5453. parse_date_string(const char *datetime)
  5454. {
  5455. char month_str[32] = {0};
  5456. int second, minute, hour, day, month, year;
  5457. time_t result = (time_t)0;
  5458. struct tm tm;
  5459. if ((sscanf(datetime,
  5460. "%d/%3s/%d %d:%d:%d",
  5461. &day,
  5462. month_str,
  5463. &year,
  5464. &hour,
  5465. &minute,
  5466. &second) == 6) || (sscanf(datetime,
  5467. "%d %3s %d %d:%d:%d",
  5468. &day,
  5469. month_str,
  5470. &year,
  5471. &hour,
  5472. &minute,
  5473. &second) == 6)
  5474. || (sscanf(datetime,
  5475. "%*3s, %d %3s %d %d:%d:%d",
  5476. &day,
  5477. month_str,
  5478. &year,
  5479. &hour,
  5480. &minute,
  5481. &second) == 6) || (sscanf(datetime,
  5482. "%d-%3s-%d %d:%d:%d",
  5483. &day,
  5484. month_str,
  5485. &year,
  5486. &hour,
  5487. &minute,
  5488. &second) == 6)) {
  5489. month = get_month_index(month_str);
  5490. if ((month >= 0) && (year >= 1970)) {
  5491. memset(&tm, 0, sizeof(tm));
  5492. tm.tm_year = year - 1900;
  5493. tm.tm_mon = month;
  5494. tm.tm_mday = day;
  5495. tm.tm_hour = hour;
  5496. tm.tm_min = minute;
  5497. tm.tm_sec = second;
  5498. result = timegm(&tm);
  5499. }
  5500. }
  5501. return result;
  5502. }
  5503. #endif /* !NO_CACHING */
  5504. /* Protect against directory disclosure attack by removing '..',
  5505. * excessive '/' and '\' characters */
  5506. static void
  5507. remove_double_dots_and_double_slashes(char *s)
  5508. {
  5509. char *p = s;
  5510. while ((s[0] == '.') && (s[1] == '.')) {
  5511. s++;
  5512. }
  5513. while (*s != '\0') {
  5514. *p++ = *s++;
  5515. if (s[-1] == '/' || s[-1] == '\\') {
  5516. /* Skip all following slashes, backslashes and double-dots */
  5517. while (s[0] != '\0') {
  5518. if (s[0] == '/' || s[0] == '\\') {
  5519. s++;
  5520. } else if (s[0] == '.' && s[1] == '.') {
  5521. s += 2;
  5522. } else {
  5523. break;
  5524. }
  5525. }
  5526. }
  5527. }
  5528. *p = '\0';
  5529. }
  5530. static const struct {
  5531. const char *extension;
  5532. size_t ext_len;
  5533. const char *mime_type;
  5534. } builtin_mime_types[] = {
  5535. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5536. * application types */
  5537. {".doc", 4, "application/msword"},
  5538. {".eps", 4, "application/postscript"},
  5539. {".exe", 4, "application/octet-stream"},
  5540. {".js", 3, "application/javascript"},
  5541. {".json", 5, "application/json"},
  5542. {".pdf", 4, "application/pdf"},
  5543. {".ps", 3, "application/postscript"},
  5544. {".rtf", 4, "application/rtf"},
  5545. {".xhtml", 6, "application/xhtml+xml"},
  5546. {".xsl", 4, "application/xml"},
  5547. {".xslt", 5, "application/xml"},
  5548. /* fonts */
  5549. {".ttf", 4, "application/font-sfnt"},
  5550. {".cff", 4, "application/font-sfnt"},
  5551. {".otf", 4, "application/font-sfnt"},
  5552. {".aat", 4, "application/font-sfnt"},
  5553. {".sil", 4, "application/font-sfnt"},
  5554. {".pfr", 4, "application/font-tdpfr"},
  5555. {".woff", 5, "application/font-woff"},
  5556. /* audio */
  5557. {".mp3", 4, "audio/mpeg"},
  5558. {".oga", 4, "audio/ogg"},
  5559. {".ogg", 4, "audio/ogg"},
  5560. /* image */
  5561. {".gif", 4, "image/gif"},
  5562. {".ief", 4, "image/ief"},
  5563. {".jpeg", 5, "image/jpeg"},
  5564. {".jpg", 4, "image/jpeg"},
  5565. {".jpm", 4, "image/jpm"},
  5566. {".jpx", 4, "image/jpx"},
  5567. {".png", 4, "image/png"},
  5568. {".svg", 4, "image/svg+xml"},
  5569. {".tif", 4, "image/tiff"},
  5570. {".tiff", 5, "image/tiff"},
  5571. /* model */
  5572. {".wrl", 4, "model/vrml"},
  5573. /* text */
  5574. {".css", 4, "text/css"},
  5575. {".csv", 4, "text/csv"},
  5576. {".htm", 4, "text/html"},
  5577. {".html", 5, "text/html"},
  5578. {".sgm", 4, "text/sgml"},
  5579. {".shtm", 5, "text/html"},
  5580. {".shtml", 6, "text/html"},
  5581. {".txt", 4, "text/plain"},
  5582. {".xml", 4, "text/xml"},
  5583. /* video */
  5584. {".mov", 4, "video/quicktime"},
  5585. {".mp4", 4, "video/mp4"},
  5586. {".mpeg", 5, "video/mpeg"},
  5587. {".mpg", 4, "video/mpeg"},
  5588. {".ogv", 4, "video/ogg"},
  5589. {".qt", 3, "video/quicktime"},
  5590. /* not registered types
  5591. * (http://reference.sitepoint.com/html/mime-types-full,
  5592. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5593. {".arj", 4, "application/x-arj-compressed"},
  5594. {".gz", 3, "application/x-gunzip"},
  5595. {".rar", 4, "application/x-arj-compressed"},
  5596. {".swf", 4, "application/x-shockwave-flash"},
  5597. {".tar", 4, "application/x-tar"},
  5598. {".tgz", 4, "application/x-tar-gz"},
  5599. {".torrent", 8, "application/x-bittorrent"},
  5600. {".ppt", 4, "application/x-mspowerpoint"},
  5601. {".xls", 4, "application/x-msexcel"},
  5602. {".zip", 4, "application/x-zip-compressed"},
  5603. {".aac",
  5604. 4,
  5605. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5606. {".aif", 4, "audio/x-aif"},
  5607. {".m3u", 4, "audio/x-mpegurl"},
  5608. {".mid", 4, "audio/x-midi"},
  5609. {".ra", 3, "audio/x-pn-realaudio"},
  5610. {".ram", 4, "audio/x-pn-realaudio"},
  5611. {".wav", 4, "audio/x-wav"},
  5612. {".bmp", 4, "image/bmp"},
  5613. {".ico", 4, "image/x-icon"},
  5614. {".pct", 4, "image/x-pct"},
  5615. {".pict", 5, "image/pict"},
  5616. {".rgb", 4, "image/x-rgb"},
  5617. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5618. {".asf", 4, "video/x-ms-asf"},
  5619. {".avi", 4, "video/x-msvideo"},
  5620. {".m4v", 4, "video/x-m4v"},
  5621. {NULL, 0, NULL}};
  5622. const char *
  5623. mg_get_builtin_mime_type(const char *path)
  5624. {
  5625. const char *ext;
  5626. size_t i, path_len;
  5627. path_len = strlen(path);
  5628. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5629. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5630. if (path_len > builtin_mime_types[i].ext_len
  5631. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5632. return builtin_mime_types[i].mime_type;
  5633. }
  5634. }
  5635. return "text/plain";
  5636. }
  5637. /* Look at the "path" extension and figure what mime type it has.
  5638. * Store mime type in the vector. */
  5639. static void
  5640. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5641. {
  5642. struct vec ext_vec, mime_vec;
  5643. const char *list, *ext;
  5644. size_t path_len;
  5645. path_len = strlen(path);
  5646. if (ctx == NULL || vec == NULL) {
  5647. return;
  5648. }
  5649. /* Scan user-defined mime types first, in case user wants to
  5650. * override default mime types. */
  5651. list = ctx->config[EXTRA_MIME_TYPES];
  5652. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5653. /* ext now points to the path suffix */
  5654. ext = path + path_len - ext_vec.len;
  5655. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5656. *vec = mime_vec;
  5657. return;
  5658. }
  5659. }
  5660. vec->ptr = mg_get_builtin_mime_type(path);
  5661. vec->len = strlen(vec->ptr);
  5662. }
  5663. /* Stringify binary data. Output buffer must be twice as big as input,
  5664. * because each byte takes 2 bytes in string representation */
  5665. static void
  5666. bin2str(char *to, const unsigned char *p, size_t len)
  5667. {
  5668. static const char *hex = "0123456789abcdef";
  5669. for (; len--; p++) {
  5670. *to++ = hex[p[0] >> 4];
  5671. *to++ = hex[p[0] & 0x0f];
  5672. }
  5673. *to = '\0';
  5674. }
  5675. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5676. char *
  5677. mg_md5(char buf[33], ...)
  5678. {
  5679. md5_byte_t hash[16];
  5680. const char *p;
  5681. va_list ap;
  5682. md5_state_t ctx;
  5683. md5_init(&ctx);
  5684. va_start(ap, buf);
  5685. while ((p = va_arg(ap, const char *)) != NULL) {
  5686. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5687. }
  5688. va_end(ap);
  5689. md5_finish(&ctx, hash);
  5690. bin2str(buf, hash, sizeof(hash));
  5691. return buf;
  5692. }
  5693. /* Check the user's password, return 1 if OK */
  5694. static int
  5695. check_password(const char *method,
  5696. const char *ha1,
  5697. const char *uri,
  5698. const char *nonce,
  5699. const char *nc,
  5700. const char *cnonce,
  5701. const char *qop,
  5702. const char *response)
  5703. {
  5704. char ha2[32 + 1], expected_response[32 + 1];
  5705. /* Some of the parameters may be NULL */
  5706. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5707. || qop == NULL
  5708. || response == NULL) {
  5709. return 0;
  5710. }
  5711. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5712. if (strlen(response) != 32) {
  5713. return 0;
  5714. }
  5715. mg_md5(ha2, method, ":", uri, NULL);
  5716. mg_md5(expected_response,
  5717. ha1,
  5718. ":",
  5719. nonce,
  5720. ":",
  5721. nc,
  5722. ":",
  5723. cnonce,
  5724. ":",
  5725. qop,
  5726. ":",
  5727. ha2,
  5728. NULL);
  5729. return mg_strcasecmp(response, expected_response) == 0;
  5730. }
  5731. /* Use the global passwords file, if specified by auth_gpass option,
  5732. * or search for .htpasswd in the requested directory. */
  5733. static void
  5734. open_auth_file(struct mg_connection *conn,
  5735. const char *path,
  5736. struct mg_file *filep)
  5737. {
  5738. if (conn != NULL && conn->ctx != NULL) {
  5739. char name[PATH_MAX];
  5740. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5741. int truncated;
  5742. if (gpass != NULL) {
  5743. /* Use global passwords file */
  5744. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5745. #ifdef DEBUG
  5746. /* Use mg_cry here, since gpass has been configured. */
  5747. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5748. #endif
  5749. }
  5750. /* Important: using local struct mg_file to test path for
  5751. * is_directory flag. If filep is used, mg_stat() makes it
  5752. * appear as if auth file was opened.
  5753. * TODO(mid): Check if this is still required after rewriting
  5754. * mg_stat */
  5755. } else if (mg_stat(conn, path, &filep->stat)
  5756. && filep->stat.is_directory) {
  5757. mg_snprintf(conn,
  5758. &truncated,
  5759. name,
  5760. sizeof(name),
  5761. "%s/%s",
  5762. path,
  5763. PASSWORDS_FILE_NAME);
  5764. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5765. #ifdef DEBUG
  5766. /* Don't use mg_cry here, but only a trace, since this is
  5767. * a typical case. It will occur for every directory
  5768. * without a password file. */
  5769. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5770. #endif
  5771. }
  5772. } else {
  5773. /* Try to find .htpasswd in requested directory. */
  5774. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5775. if (e[0] == '/') {
  5776. break;
  5777. }
  5778. }
  5779. mg_snprintf(conn,
  5780. &truncated,
  5781. name,
  5782. sizeof(name),
  5783. "%.*s/%s",
  5784. (int)(e - p),
  5785. p,
  5786. PASSWORDS_FILE_NAME);
  5787. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5788. #ifdef DEBUG
  5789. /* Don't use mg_cry here, but only a trace, since this is
  5790. * a typical case. It will occur for every directory
  5791. * without a password file. */
  5792. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5793. #endif
  5794. }
  5795. }
  5796. }
  5797. }
  5798. /* Parsed Authorization header */
  5799. struct ah {
  5800. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5801. };
  5802. /* Return 1 on success. Always initializes the ah structure. */
  5803. static int
  5804. parse_auth_header(struct mg_connection *conn,
  5805. char *buf,
  5806. size_t buf_size,
  5807. struct ah *ah)
  5808. {
  5809. char *name, *value, *s;
  5810. const char *auth_header;
  5811. uint64_t nonce;
  5812. if (!ah || !conn) {
  5813. return 0;
  5814. }
  5815. (void)memset(ah, 0, sizeof(*ah));
  5816. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5817. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5818. return 0;
  5819. }
  5820. /* Make modifiable copy of the auth header */
  5821. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5822. s = buf;
  5823. /* Parse authorization header */
  5824. for (;;) {
  5825. /* Gobble initial spaces */
  5826. while (isspace(*(unsigned char *)s)) {
  5827. s++;
  5828. }
  5829. name = skip_quoted(&s, "=", " ", 0);
  5830. /* Value is either quote-delimited, or ends at first comma or space. */
  5831. if (s[0] == '\"') {
  5832. s++;
  5833. value = skip_quoted(&s, "\"", " ", '\\');
  5834. if (s[0] == ',') {
  5835. s++;
  5836. }
  5837. } else {
  5838. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5839. * spaces */
  5840. }
  5841. if (*name == '\0') {
  5842. break;
  5843. }
  5844. if (!strcmp(name, "username")) {
  5845. ah->user = value;
  5846. } else if (!strcmp(name, "cnonce")) {
  5847. ah->cnonce = value;
  5848. } else if (!strcmp(name, "response")) {
  5849. ah->response = value;
  5850. } else if (!strcmp(name, "uri")) {
  5851. ah->uri = value;
  5852. } else if (!strcmp(name, "qop")) {
  5853. ah->qop = value;
  5854. } else if (!strcmp(name, "nc")) {
  5855. ah->nc = value;
  5856. } else if (!strcmp(name, "nonce")) {
  5857. ah->nonce = value;
  5858. }
  5859. }
  5860. #ifndef NO_NONCE_CHECK
  5861. /* Read the nonce from the response. */
  5862. if (ah->nonce == NULL) {
  5863. return 0;
  5864. }
  5865. s = NULL;
  5866. nonce = strtoull(ah->nonce, &s, 10);
  5867. if ((s == NULL) || (*s != 0)) {
  5868. return 0;
  5869. }
  5870. /* Convert the nonce from the client to a number. */
  5871. nonce ^= conn->ctx->auth_nonce_mask;
  5872. /* The converted number corresponds to the time the nounce has been
  5873. * created. This should not be earlier than the server start. */
  5874. /* Server side nonce check is valuable in all situations but one:
  5875. * if the server restarts frequently, but the client should not see
  5876. * that, so the server should accept nonces from previous starts. */
  5877. /* However, the reasonable default is to not accept a nonce from a
  5878. * previous start, so if anyone changed the access rights between
  5879. * two restarts, a new login is required. */
  5880. if (nonce < (uint64_t)conn->ctx->start_time) {
  5881. /* nonce is from a previous start of the server and no longer valid
  5882. * (replay attack?) */
  5883. return 0;
  5884. }
  5885. /* Check if the nonce is too high, so it has not (yet) been used by the
  5886. * server. */
  5887. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5888. return 0;
  5889. }
  5890. #else
  5891. (void)nonce;
  5892. #endif
  5893. /* CGI needs it as REMOTE_USER */
  5894. if (ah->user != NULL) {
  5895. conn->request_info.remote_user = mg_strdup(ah->user);
  5896. } else {
  5897. return 0;
  5898. }
  5899. return 1;
  5900. }
  5901. static const char *
  5902. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5903. {
  5904. const char *eof;
  5905. size_t len;
  5906. const char *memend;
  5907. if (!filep) {
  5908. return NULL;
  5909. }
  5910. if (filep->access.membuf != NULL && *p != NULL) {
  5911. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5912. /* Search for \n from p till the end of stream */
  5913. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5914. if (eof != NULL) {
  5915. eof += 1; /* Include \n */
  5916. } else {
  5917. eof = memend; /* Copy remaining data */
  5918. }
  5919. len =
  5920. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5921. memcpy(buf, *p, len);
  5922. buf[len] = '\0';
  5923. *p += len;
  5924. return len ? eof : NULL;
  5925. } else if (filep->access.fp != NULL) {
  5926. return fgets(buf, (int)size, filep->access.fp);
  5927. } else {
  5928. return NULL;
  5929. }
  5930. }
  5931. /* Define the initial recursion depth for procesesing htpasswd files that
  5932. * include other htpasswd
  5933. * (or even the same) files. It is not difficult to provide a file or files
  5934. * s.t. they force civetweb
  5935. * to infinitely recurse and then crash.
  5936. */
  5937. #define INITIAL_DEPTH 9
  5938. #if INITIAL_DEPTH <= 0
  5939. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5940. #endif
  5941. struct read_auth_file_struct {
  5942. struct mg_connection *conn;
  5943. struct ah ah;
  5944. char *domain;
  5945. char buf[256 + 256 + 40];
  5946. char *f_user;
  5947. char *f_domain;
  5948. char *f_ha1;
  5949. };
  5950. static int
  5951. read_auth_file(struct mg_file *filep,
  5952. struct read_auth_file_struct *workdata,
  5953. int depth)
  5954. {
  5955. char *p;
  5956. int is_authorized = 0;
  5957. struct mg_file fp;
  5958. size_t l;
  5959. if (!filep || !workdata || 0 == depth) {
  5960. return 0;
  5961. }
  5962. /* Loop over passwords file */
  5963. p = (char *)filep->access.membuf;
  5964. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5965. l = strlen(workdata->buf);
  5966. while (l > 0) {
  5967. if (isspace(workdata->buf[l - 1])
  5968. || iscntrl(workdata->buf[l - 1])) {
  5969. l--;
  5970. workdata->buf[l] = 0;
  5971. } else
  5972. break;
  5973. }
  5974. if (l < 1) {
  5975. continue;
  5976. }
  5977. workdata->f_user = workdata->buf;
  5978. if (workdata->f_user[0] == ':') {
  5979. /* user names may not contain a ':' and may not be empty,
  5980. * so lines starting with ':' may be used for a special purpose */
  5981. if (workdata->f_user[1] == '#') {
  5982. /* :# is a comment */
  5983. continue;
  5984. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5985. if (mg_fopen(workdata->conn,
  5986. workdata->f_user + 9,
  5987. MG_FOPEN_MODE_READ,
  5988. &fp)) {
  5989. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5990. (void)mg_fclose(
  5991. &fp.access); /* ignore error on read only file */
  5992. /* No need to continue processing files once we have a
  5993. * match, since nothing will reset it back
  5994. * to 0.
  5995. */
  5996. if (is_authorized) {
  5997. return is_authorized;
  5998. }
  5999. } else {
  6000. mg_cry(workdata->conn,
  6001. "%s: cannot open authorization file: %s",
  6002. __func__,
  6003. workdata->buf);
  6004. }
  6005. continue;
  6006. }
  6007. /* everything is invalid for the moment (might change in the
  6008. * future) */
  6009. mg_cry(workdata->conn,
  6010. "%s: syntax error in authorization file: %s",
  6011. __func__,
  6012. workdata->buf);
  6013. continue;
  6014. }
  6015. workdata->f_domain = strchr(workdata->f_user, ':');
  6016. if (workdata->f_domain == NULL) {
  6017. mg_cry(workdata->conn,
  6018. "%s: syntax error in authorization file: %s",
  6019. __func__,
  6020. workdata->buf);
  6021. continue;
  6022. }
  6023. *(workdata->f_domain) = 0;
  6024. (workdata->f_domain)++;
  6025. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6026. if (workdata->f_ha1 == NULL) {
  6027. mg_cry(workdata->conn,
  6028. "%s: syntax error in authorization file: %s",
  6029. __func__,
  6030. workdata->buf);
  6031. continue;
  6032. }
  6033. *(workdata->f_ha1) = 0;
  6034. (workdata->f_ha1)++;
  6035. if (!strcmp(workdata->ah.user, workdata->f_user)
  6036. && !strcmp(workdata->domain, workdata->f_domain)) {
  6037. return check_password(workdata->conn->request_info.request_method,
  6038. workdata->f_ha1,
  6039. workdata->ah.uri,
  6040. workdata->ah.nonce,
  6041. workdata->ah.nc,
  6042. workdata->ah.cnonce,
  6043. workdata->ah.qop,
  6044. workdata->ah.response);
  6045. }
  6046. }
  6047. return is_authorized;
  6048. }
  6049. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6050. static int
  6051. authorize(struct mg_connection *conn, struct mg_file *filep)
  6052. {
  6053. struct read_auth_file_struct workdata;
  6054. char buf[MG_BUF_LEN];
  6055. if (!conn || !conn->ctx) {
  6056. return 0;
  6057. }
  6058. memset(&workdata, 0, sizeof(workdata));
  6059. workdata.conn = conn;
  6060. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6061. return 0;
  6062. }
  6063. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6064. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6065. }
  6066. /* Return 1 if request is authorised, 0 otherwise. */
  6067. static int
  6068. check_authorization(struct mg_connection *conn, const char *path)
  6069. {
  6070. char fname[PATH_MAX];
  6071. struct vec uri_vec, filename_vec;
  6072. const char *list;
  6073. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6074. int authorized = 1, truncated;
  6075. if (!conn || !conn->ctx) {
  6076. return 0;
  6077. }
  6078. list = conn->ctx->config[PROTECT_URI];
  6079. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6080. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6081. mg_snprintf(conn,
  6082. &truncated,
  6083. fname,
  6084. sizeof(fname),
  6085. "%.*s",
  6086. (int)filename_vec.len,
  6087. filename_vec.ptr);
  6088. if (truncated
  6089. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6090. mg_cry(conn,
  6091. "%s: cannot open %s: %s",
  6092. __func__,
  6093. fname,
  6094. strerror(errno));
  6095. }
  6096. break;
  6097. }
  6098. }
  6099. if (!is_file_opened(&file.access)) {
  6100. open_auth_file(conn, path, &file);
  6101. }
  6102. if (is_file_opened(&file.access)) {
  6103. authorized = authorize(conn, &file);
  6104. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6105. }
  6106. return authorized;
  6107. }
  6108. static void
  6109. send_authorization_request(struct mg_connection *conn)
  6110. {
  6111. char date[64];
  6112. time_t curtime = time(NULL);
  6113. if (conn && conn->ctx) {
  6114. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6115. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6116. nonce += conn->ctx->nonce_count;
  6117. ++conn->ctx->nonce_count;
  6118. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6119. nonce ^= conn->ctx->auth_nonce_mask;
  6120. conn->status_code = 401;
  6121. conn->must_close = 1;
  6122. gmt_time_string(date, sizeof(date), &curtime);
  6123. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6124. send_no_cache_header(conn);
  6125. send_additional_header(conn);
  6126. mg_printf(conn,
  6127. "Date: %s\r\n"
  6128. "Connection: %s\r\n"
  6129. "Content-Length: 0\r\n"
  6130. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6131. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6132. date,
  6133. suggest_connection_header(conn),
  6134. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6135. nonce);
  6136. }
  6137. }
  6138. #if !defined(NO_FILES)
  6139. static int
  6140. is_authorized_for_put(struct mg_connection *conn)
  6141. {
  6142. if (conn) {
  6143. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6144. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6145. int ret = 0;
  6146. if (passfile != NULL
  6147. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6148. ret = authorize(conn, &file);
  6149. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6150. }
  6151. return ret;
  6152. }
  6153. return 0;
  6154. }
  6155. #endif
  6156. int
  6157. mg_modify_passwords_file(const char *fname,
  6158. const char *domain,
  6159. const char *user,
  6160. const char *pass)
  6161. {
  6162. int found, i;
  6163. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6164. FILE *fp, *fp2;
  6165. found = 0;
  6166. fp = fp2 = NULL;
  6167. /* Regard empty password as no password - remove user record. */
  6168. if (pass != NULL && pass[0] == '\0') {
  6169. pass = NULL;
  6170. }
  6171. /* Other arguments must not be empty */
  6172. if (fname == NULL || domain == NULL || user == NULL) {
  6173. return 0;
  6174. }
  6175. /* Using the given file format, user name and domain must not contain ':'
  6176. */
  6177. if (strchr(user, ':') != NULL) {
  6178. return 0;
  6179. }
  6180. if (strchr(domain, ':') != NULL) {
  6181. return 0;
  6182. }
  6183. /* Do not allow control characters like newline in user name and domain.
  6184. * Do not allow excessively long names either. */
  6185. for (i = 0; i < 255 && user[i] != 0; i++) {
  6186. if (iscntrl(user[i])) {
  6187. return 0;
  6188. }
  6189. }
  6190. if (user[i]) {
  6191. return 0;
  6192. }
  6193. for (i = 0; i < 255 && domain[i] != 0; i++) {
  6194. if (iscntrl(domain[i])) {
  6195. return 0;
  6196. }
  6197. }
  6198. if (domain[i]) {
  6199. return 0;
  6200. }
  6201. /* The maximum length of the path to the password file is limited */
  6202. if ((strlen(fname) + 4) >= PATH_MAX) {
  6203. return 0;
  6204. }
  6205. /* Create a temporary file name. Length has been checked before. */
  6206. strcpy(tmp, fname);
  6207. strcat(tmp, ".tmp");
  6208. /* Create the file if does not exist */
  6209. /* Use of fopen here is OK, since fname is only ASCII */
  6210. if ((fp = fopen(fname, "a+")) != NULL) {
  6211. (void)fclose(fp);
  6212. }
  6213. /* Open the given file and temporary file */
  6214. if ((fp = fopen(fname, "r")) == NULL) {
  6215. return 0;
  6216. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6217. fclose(fp);
  6218. return 0;
  6219. }
  6220. /* Copy the stuff to temporary file */
  6221. while (fgets(line, sizeof(line), fp) != NULL) {
  6222. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6223. continue;
  6224. }
  6225. u[255] = 0;
  6226. d[255] = 0;
  6227. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6228. found++;
  6229. if (pass != NULL) {
  6230. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6231. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6232. }
  6233. } else {
  6234. fprintf(fp2, "%s", line);
  6235. }
  6236. }
  6237. /* If new user, just add it */
  6238. if (!found && pass != NULL) {
  6239. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6240. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6241. }
  6242. /* Close files */
  6243. fclose(fp);
  6244. fclose(fp2);
  6245. /* Put the temp file in place of real file */
  6246. IGNORE_UNUSED_RESULT(remove(fname));
  6247. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6248. return 1;
  6249. }
  6250. static int
  6251. is_valid_port(unsigned long port)
  6252. {
  6253. return (port <= 0xffff);
  6254. }
  6255. static int
  6256. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6257. {
  6258. struct addrinfo hints, *res, *ressave;
  6259. int func_ret = 0;
  6260. int gai_ret;
  6261. memset(&hints, 0, sizeof(struct addrinfo));
  6262. hints.ai_family = af;
  6263. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6264. if (gai_ret != 0) {
  6265. /* gai_strerror could be used to convert gai_ret to a string */
  6266. /* POSIX return values: see
  6267. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6268. */
  6269. /* Windows return values: see
  6270. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6271. */
  6272. return 0;
  6273. }
  6274. ressave = res;
  6275. while (res) {
  6276. if (dstlen >= res->ai_addrlen) {
  6277. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6278. func_ret = 1;
  6279. }
  6280. res = res->ai_next;
  6281. }
  6282. freeaddrinfo(ressave);
  6283. return func_ret;
  6284. }
  6285. static int
  6286. connect_socket(struct mg_context *ctx /* may be NULL */,
  6287. const char *host,
  6288. int port,
  6289. int use_ssl,
  6290. char *ebuf,
  6291. size_t ebuf_len,
  6292. SOCKET *sock /* output: socket, must not be NULL */,
  6293. union usa *sa /* output: socket address, must not be NULL */
  6294. )
  6295. {
  6296. int ip_ver = 0;
  6297. *sock = INVALID_SOCKET;
  6298. memset(sa, 0, sizeof(*sa));
  6299. if (ebuf_len > 0) {
  6300. *ebuf = 0;
  6301. }
  6302. if (host == NULL) {
  6303. mg_snprintf(NULL,
  6304. NULL, /* No truncation check for ebuf */
  6305. ebuf,
  6306. ebuf_len,
  6307. "%s",
  6308. "NULL host");
  6309. return 0;
  6310. }
  6311. if (port <= 0 || !is_valid_port((unsigned)port)) {
  6312. mg_snprintf(NULL,
  6313. NULL, /* No truncation check for ebuf */
  6314. ebuf,
  6315. ebuf_len,
  6316. "%s",
  6317. "invalid port");
  6318. return 0;
  6319. }
  6320. #if !defined(NO_SSL)
  6321. #if !defined(NO_SSL_DL)
  6322. #ifdef OPENSSL_API_1_1
  6323. if (use_ssl && (TLS_client_method == NULL)) {
  6324. mg_snprintf(NULL,
  6325. NULL, /* No truncation check for ebuf */
  6326. ebuf,
  6327. ebuf_len,
  6328. "%s",
  6329. "SSL is not initialized");
  6330. return 0;
  6331. }
  6332. #else
  6333. if (use_ssl && (SSLv23_client_method == NULL)) {
  6334. mg_snprintf(NULL,
  6335. NULL, /* No truncation check for ebuf */
  6336. ebuf,
  6337. ebuf_len,
  6338. "%s",
  6339. "SSL is not initialized");
  6340. return 0;
  6341. }
  6342. #endif /* OPENSSL_API_1_1 */
  6343. #else
  6344. (void)use_ssl;
  6345. #endif /* NO_SSL_DL */
  6346. #else
  6347. (void)use_ssl;
  6348. #endif /* !defined(NO_SSL) */
  6349. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6350. sa->sin.sin_port = htons((uint16_t)port);
  6351. ip_ver = 4;
  6352. #ifdef USE_IPV6
  6353. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6354. sa->sin6.sin6_port = htons((uint16_t)port);
  6355. ip_ver = 6;
  6356. } else if (host[0] == '[') {
  6357. /* While getaddrinfo on Windows will work with [::1],
  6358. * getaddrinfo on Linux only works with ::1 (without []). */
  6359. size_t l = strlen(host + 1);
  6360. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6361. if (h) {
  6362. h[l - 1] = 0;
  6363. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6364. sa->sin6.sin6_port = htons((uint16_t)port);
  6365. ip_ver = 6;
  6366. }
  6367. mg_free(h);
  6368. }
  6369. #endif
  6370. }
  6371. if (ip_ver == 0) {
  6372. mg_snprintf(NULL,
  6373. NULL, /* No truncation check for ebuf */
  6374. ebuf,
  6375. ebuf_len,
  6376. "%s",
  6377. "host not found");
  6378. return 0;
  6379. }
  6380. if (ip_ver == 4) {
  6381. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6382. }
  6383. #ifdef USE_IPV6
  6384. else if (ip_ver == 6) {
  6385. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6386. }
  6387. #endif
  6388. if (*sock == INVALID_SOCKET) {
  6389. mg_snprintf(NULL,
  6390. NULL, /* No truncation check for ebuf */
  6391. ebuf,
  6392. ebuf_len,
  6393. "socket(): %s",
  6394. strerror(ERRNO));
  6395. return 0;
  6396. }
  6397. set_close_on_exec(*sock, fc(ctx));
  6398. if ((ip_ver == 4)
  6399. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6400. == 0)) {
  6401. /* connected with IPv4 */
  6402. set_blocking_mode(*sock, 0);
  6403. return 1;
  6404. }
  6405. #ifdef USE_IPV6
  6406. if ((ip_ver == 6)
  6407. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6408. == 0)) {
  6409. /* connected with IPv6 */
  6410. set_blocking_mode(*sock, 0);
  6411. return 1;
  6412. }
  6413. #endif
  6414. /* Not connected */
  6415. mg_snprintf(NULL,
  6416. NULL, /* No truncation check for ebuf */
  6417. ebuf,
  6418. ebuf_len,
  6419. "connect(%s:%d): %s",
  6420. host,
  6421. port,
  6422. strerror(ERRNO));
  6423. closesocket(*sock);
  6424. *sock = INVALID_SOCKET;
  6425. return 0;
  6426. }
  6427. int
  6428. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6429. {
  6430. static const char *dont_escape = "._-$,;~()";
  6431. static const char *hex = "0123456789abcdef";
  6432. char *pos = dst;
  6433. const char *end = dst + dst_len - 1;
  6434. for (; *src != '\0' && pos < end; src++, pos++) {
  6435. if (isalnum(*(const unsigned char *)src)
  6436. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  6437. *pos = *src;
  6438. } else if (pos + 2 < end) {
  6439. pos[0] = '%';
  6440. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6441. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6442. pos += 2;
  6443. } else {
  6444. break;
  6445. }
  6446. }
  6447. *pos = '\0';
  6448. return (*src == '\0') ? (int)(pos - dst) : -1;
  6449. }
  6450. static void
  6451. print_dir_entry(struct de *de)
  6452. {
  6453. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6454. struct tm *tm;
  6455. if (de->file.is_directory) {
  6456. mg_snprintf(de->conn,
  6457. NULL, /* Buffer is big enough */
  6458. size,
  6459. sizeof(size),
  6460. "%s",
  6461. "[DIRECTORY]");
  6462. } else {
  6463. /* We use (signed) cast below because MSVC 6 compiler cannot
  6464. * convert unsigned __int64 to double. Sigh. */
  6465. if (de->file.size < 1024) {
  6466. mg_snprintf(de->conn,
  6467. NULL, /* Buffer is big enough */
  6468. size,
  6469. sizeof(size),
  6470. "%d",
  6471. (int)de->file.size);
  6472. } else if (de->file.size < 0x100000) {
  6473. mg_snprintf(de->conn,
  6474. NULL, /* Buffer is big enough */
  6475. size,
  6476. sizeof(size),
  6477. "%.1fk",
  6478. (double)de->file.size / 1024.0);
  6479. } else if (de->file.size < 0x40000000) {
  6480. mg_snprintf(de->conn,
  6481. NULL, /* Buffer is big enough */
  6482. size,
  6483. sizeof(size),
  6484. "%.1fM",
  6485. (double)de->file.size / 1048576);
  6486. } else {
  6487. mg_snprintf(de->conn,
  6488. NULL, /* Buffer is big enough */
  6489. size,
  6490. sizeof(size),
  6491. "%.1fG",
  6492. (double)de->file.size / 1073741824);
  6493. }
  6494. }
  6495. /* Note: mg_snprintf will not cause a buffer overflow above.
  6496. * So, string truncation checks are not required here. */
  6497. tm = localtime(&de->file.last_modified);
  6498. if (tm != NULL) {
  6499. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6500. } else {
  6501. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6502. mod[sizeof(mod) - 1] = '\0';
  6503. }
  6504. mg_url_encode(de->file_name, href, sizeof(href));
  6505. mg_printf(de->conn,
  6506. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6507. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6508. de->conn->request_info.local_uri,
  6509. href,
  6510. de->file.is_directory ? "/" : "",
  6511. de->file_name,
  6512. de->file.is_directory ? "/" : "",
  6513. mod,
  6514. size);
  6515. }
  6516. /* This function is called from send_directory() and used for
  6517. * sorting directory entries by size, or name, or modification time.
  6518. * On windows, __cdecl specification is needed in case if project is built
  6519. * with __stdcall convention. qsort always requires __cdels callback. */
  6520. static int WINCDECL
  6521. compare_dir_entries(const void *p1, const void *p2)
  6522. {
  6523. if (p1 && p2) {
  6524. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6525. const char *query_string = a->conn->request_info.query_string;
  6526. int cmp_result = 0;
  6527. if (query_string == NULL) {
  6528. query_string = "na";
  6529. }
  6530. if (a->file.is_directory && !b->file.is_directory) {
  6531. return -1; /* Always put directories on top */
  6532. } else if (!a->file.is_directory && b->file.is_directory) {
  6533. return 1; /* Always put directories on top */
  6534. } else if (*query_string == 'n') {
  6535. cmp_result = strcmp(a->file_name, b->file_name);
  6536. } else if (*query_string == 's') {
  6537. cmp_result = (a->file.size == b->file.size)
  6538. ? 0
  6539. : ((a->file.size > b->file.size) ? 1 : -1);
  6540. } else if (*query_string == 'd') {
  6541. cmp_result =
  6542. (a->file.last_modified == b->file.last_modified)
  6543. ? 0
  6544. : ((a->file.last_modified > b->file.last_modified) ? 1
  6545. : -1);
  6546. }
  6547. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6548. }
  6549. return 0;
  6550. }
  6551. static int
  6552. must_hide_file(struct mg_connection *conn, const char *path)
  6553. {
  6554. if (conn && conn->ctx) {
  6555. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6556. const char *pattern = conn->ctx->config[HIDE_FILES];
  6557. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6558. || (pattern != NULL
  6559. && match_prefix(pattern, strlen(pattern), path) > 0);
  6560. }
  6561. return 0;
  6562. }
  6563. static int
  6564. scan_directory(struct mg_connection *conn,
  6565. const char *dir,
  6566. void *data,
  6567. void (*cb)(struct de *, void *))
  6568. {
  6569. char path[PATH_MAX];
  6570. struct dirent *dp;
  6571. DIR *dirp;
  6572. struct de de;
  6573. int truncated;
  6574. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6575. return 0;
  6576. } else {
  6577. de.conn = conn;
  6578. while ((dp = mg_readdir(dirp)) != NULL) {
  6579. /* Do not show current dir and hidden files */
  6580. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6581. || must_hide_file(conn, dp->d_name)) {
  6582. continue;
  6583. }
  6584. mg_snprintf(
  6585. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6586. /* If we don't memset stat structure to zero, mtime will have
  6587. * garbage and strftime() will segfault later on in
  6588. * print_dir_entry(). memset is required only if mg_stat()
  6589. * fails. For more details, see
  6590. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6591. memset(&de.file, 0, sizeof(de.file));
  6592. if (truncated) {
  6593. /* If the path is not complete, skip processing. */
  6594. continue;
  6595. }
  6596. if (!mg_stat(conn, path, &de.file)) {
  6597. mg_cry(conn,
  6598. "%s: mg_stat(%s) failed: %s",
  6599. __func__,
  6600. path,
  6601. strerror(ERRNO));
  6602. }
  6603. de.file_name = dp->d_name;
  6604. cb(&de, data);
  6605. }
  6606. (void)mg_closedir(dirp);
  6607. }
  6608. return 1;
  6609. }
  6610. #if !defined(NO_FILES)
  6611. static int
  6612. remove_directory(struct mg_connection *conn, const char *dir)
  6613. {
  6614. char path[PATH_MAX];
  6615. struct dirent *dp;
  6616. DIR *dirp;
  6617. struct de de;
  6618. int truncated;
  6619. int ok = 1;
  6620. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6621. return 0;
  6622. } else {
  6623. de.conn = conn;
  6624. while ((dp = mg_readdir(dirp)) != NULL) {
  6625. /* Do not show current dir (but show hidden files as they will
  6626. * also be removed) */
  6627. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6628. continue;
  6629. }
  6630. mg_snprintf(
  6631. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6632. /* If we don't memset stat structure to zero, mtime will have
  6633. * garbage and strftime() will segfault later on in
  6634. * print_dir_entry(). memset is required only if mg_stat()
  6635. * fails. For more details, see
  6636. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6637. memset(&de.file, 0, sizeof(de.file));
  6638. if (truncated) {
  6639. /* Do not delete anything shorter */
  6640. ok = 0;
  6641. continue;
  6642. }
  6643. if (!mg_stat(conn, path, &de.file)) {
  6644. mg_cry(conn,
  6645. "%s: mg_stat(%s) failed: %s",
  6646. __func__,
  6647. path,
  6648. strerror(ERRNO));
  6649. ok = 0;
  6650. }
  6651. if (de.file.is_directory) {
  6652. if (remove_directory(conn, path) == 0) {
  6653. ok = 0;
  6654. }
  6655. } else {
  6656. /* This will fail file is the file is in memory */
  6657. if (mg_remove(conn, path) == 0) {
  6658. ok = 0;
  6659. }
  6660. }
  6661. }
  6662. (void)mg_closedir(dirp);
  6663. IGNORE_UNUSED_RESULT(rmdir(dir));
  6664. }
  6665. return ok;
  6666. }
  6667. #endif
  6668. struct dir_scan_data {
  6669. struct de *entries;
  6670. unsigned int num_entries;
  6671. unsigned int arr_size;
  6672. };
  6673. /* Behaves like realloc(), but frees original pointer on failure */
  6674. static void *
  6675. realloc2(void *ptr, size_t size)
  6676. {
  6677. void *new_ptr = mg_realloc(ptr, size);
  6678. if (new_ptr == NULL) {
  6679. mg_free(ptr);
  6680. }
  6681. return new_ptr;
  6682. }
  6683. static void
  6684. dir_scan_callback(struct de *de, void *data)
  6685. {
  6686. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6687. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6688. dsd->arr_size *= 2;
  6689. dsd->entries =
  6690. (struct de *)realloc2(dsd->entries,
  6691. dsd->arr_size * sizeof(dsd->entries[0]));
  6692. }
  6693. if (dsd->entries == NULL) {
  6694. /* TODO(lsm, low): propagate an error to the caller */
  6695. dsd->num_entries = 0;
  6696. } else {
  6697. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6698. dsd->entries[dsd->num_entries].file = de->file;
  6699. dsd->entries[dsd->num_entries].conn = de->conn;
  6700. dsd->num_entries++;
  6701. }
  6702. }
  6703. static void
  6704. handle_directory_request(struct mg_connection *conn, const char *dir)
  6705. {
  6706. unsigned int i;
  6707. int sort_direction;
  6708. struct dir_scan_data data = {NULL, 0, 128};
  6709. char date[64];
  6710. time_t curtime = time(NULL);
  6711. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6712. mg_send_http_error(conn,
  6713. 500,
  6714. "Error: Cannot open directory\nopendir(%s): %s",
  6715. dir,
  6716. strerror(ERRNO));
  6717. return;
  6718. }
  6719. gmt_time_string(date, sizeof(date), &curtime);
  6720. if (!conn) {
  6721. return;
  6722. }
  6723. sort_direction = ((conn->request_info.query_string != NULL)
  6724. && (conn->request_info.query_string[1] == 'd'))
  6725. ? 'a'
  6726. : 'd';
  6727. conn->must_close = 1;
  6728. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6729. send_static_cache_header(conn);
  6730. send_additional_header(conn);
  6731. mg_printf(conn,
  6732. "Date: %s\r\n"
  6733. "Connection: close\r\n"
  6734. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6735. date);
  6736. mg_printf(conn,
  6737. "<html><head><title>Index of %s</title>"
  6738. "<style>th {text-align: left;}</style></head>"
  6739. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6740. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6741. "<th><a href=\"?d%c\">Modified</a></th>"
  6742. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6743. "<tr><td colspan=\"3\"><hr></td></tr>",
  6744. conn->request_info.local_uri,
  6745. conn->request_info.local_uri,
  6746. sort_direction,
  6747. sort_direction,
  6748. sort_direction);
  6749. /* Print first entry - link to a parent directory */
  6750. mg_printf(conn,
  6751. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6752. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6753. conn->request_info.local_uri,
  6754. "..",
  6755. "Parent directory",
  6756. "-",
  6757. "-");
  6758. /* Sort and print directory entries */
  6759. if (data.entries != NULL) {
  6760. qsort(data.entries,
  6761. (size_t)data.num_entries,
  6762. sizeof(data.entries[0]),
  6763. compare_dir_entries);
  6764. for (i = 0; i < data.num_entries; i++) {
  6765. print_dir_entry(&data.entries[i]);
  6766. mg_free(data.entries[i].file_name);
  6767. }
  6768. mg_free(data.entries);
  6769. }
  6770. mg_printf(conn, "%s", "</table></body></html>");
  6771. conn->status_code = 200;
  6772. }
  6773. /* Send len bytes from the opened file to the client. */
  6774. static void
  6775. send_file_data(struct mg_connection *conn,
  6776. struct mg_file *filep,
  6777. int64_t offset,
  6778. int64_t len)
  6779. {
  6780. char buf[MG_BUF_LEN];
  6781. int to_read, num_read, num_written;
  6782. int64_t size;
  6783. if (!filep || !conn) {
  6784. return;
  6785. }
  6786. /* Sanity check the offset */
  6787. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6788. : (int64_t)(filep->stat.size);
  6789. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6790. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6791. /* file stored in memory */
  6792. if (len > size - offset) {
  6793. len = size - offset;
  6794. }
  6795. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6796. } else if (len > 0 && filep->access.fp != NULL) {
  6797. /* file stored on disk */
  6798. #if defined(__linux__)
  6799. /* sendfile is only available for Linux */
  6800. if ((conn->ssl == 0) && (conn->throttle == 0)
  6801. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6802. "yes"))) {
  6803. off_t sf_offs = (off_t)offset;
  6804. ssize_t sf_sent;
  6805. int sf_file = fileno(filep->access.fp);
  6806. int loop_cnt = 0;
  6807. do {
  6808. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6809. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6810. size_t sf_tosend =
  6811. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6812. sf_sent =
  6813. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6814. if (sf_sent > 0) {
  6815. len -= sf_sent;
  6816. offset += sf_sent;
  6817. } else if (loop_cnt == 0) {
  6818. /* This file can not be sent using sendfile.
  6819. * This might be the case for pseudo-files in the
  6820. * /sys/ and /proc/ file system.
  6821. * Use the regular user mode copy code instead. */
  6822. break;
  6823. } else if (sf_sent == 0) {
  6824. /* No error, but 0 bytes sent. May be EOF? */
  6825. return;
  6826. }
  6827. loop_cnt++;
  6828. } while ((len > 0) && (sf_sent >= 0));
  6829. if (sf_sent > 0) {
  6830. return; /* OK */
  6831. }
  6832. /* sf_sent<0 means error, thus fall back to the classic way */
  6833. /* This is always the case, if sf_file is not a "normal" file,
  6834. * e.g., for sending data from the output of a CGI process. */
  6835. offset = (int64_t)sf_offs;
  6836. }
  6837. #endif
  6838. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6839. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6840. mg_send_http_error(
  6841. conn,
  6842. 500,
  6843. "%s",
  6844. "Error: Unable to access file at requested position.");
  6845. } else {
  6846. while (len > 0) {
  6847. /* Calculate how much to read from the file in the buffer */
  6848. to_read = sizeof(buf);
  6849. if ((int64_t)to_read > len) {
  6850. to_read = (int)len;
  6851. }
  6852. /* Read from file, exit the loop on error */
  6853. if ((num_read =
  6854. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6855. <= 0) {
  6856. break;
  6857. }
  6858. /* Send read bytes to the client, exit the loop on error */
  6859. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6860. != num_read) {
  6861. break;
  6862. }
  6863. /* Both read and were successful, adjust counters */
  6864. len -= num_written;
  6865. }
  6866. }
  6867. }
  6868. }
  6869. static int
  6870. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6871. {
  6872. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6873. }
  6874. static void
  6875. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6876. {
  6877. if (filestat != NULL && buf != NULL) {
  6878. mg_snprintf(NULL,
  6879. NULL, /* All calls to construct_etag use 64 byte buffer */
  6880. buf,
  6881. buf_len,
  6882. "\"%lx.%" INT64_FMT "\"",
  6883. (unsigned long)filestat->last_modified,
  6884. filestat->size);
  6885. }
  6886. }
  6887. static void
  6888. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6889. {
  6890. if (filep != NULL && filep->fp != NULL) {
  6891. #ifdef _WIN32
  6892. (void)conn; /* Unused. */
  6893. #else
  6894. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6895. mg_cry(conn,
  6896. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6897. __func__,
  6898. strerror(ERRNO));
  6899. }
  6900. #endif
  6901. }
  6902. }
  6903. static void
  6904. handle_static_file_request(struct mg_connection *conn,
  6905. const char *path,
  6906. struct mg_file *filep,
  6907. const char *mime_type,
  6908. const char *additional_headers)
  6909. {
  6910. char date[64], lm[64], etag[64];
  6911. char range[128]; /* large enough, so there will be no overflow */
  6912. const char *msg = "OK", *hdr;
  6913. time_t curtime = time(NULL);
  6914. int64_t cl, r1, r2;
  6915. struct vec mime_vec;
  6916. int n, truncated;
  6917. char gz_path[PATH_MAX];
  6918. const char *encoding = "";
  6919. const char *cors1, *cors2, *cors3;
  6920. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6921. return;
  6922. }
  6923. if (mime_type == NULL) {
  6924. get_mime_type(conn->ctx, path, &mime_vec);
  6925. } else {
  6926. mime_vec.ptr = mime_type;
  6927. mime_vec.len = strlen(mime_type);
  6928. }
  6929. if (filep->stat.size > INT64_MAX) {
  6930. mg_send_http_error(conn,
  6931. 500,
  6932. "Error: File size is too large to send\n%" INT64_FMT,
  6933. filep->stat.size);
  6934. }
  6935. cl = (int64_t)filep->stat.size;
  6936. conn->status_code = 200;
  6937. range[0] = '\0';
  6938. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6939. * it's important to rewrite the filename after resolving
  6940. * the mime type from it, to preserve the actual file's type */
  6941. if (filep->stat.is_gzipped) {
  6942. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6943. if (truncated) {
  6944. mg_send_http_error(conn,
  6945. 500,
  6946. "Error: Path of zipped file too long (%s)",
  6947. path);
  6948. return;
  6949. }
  6950. path = gz_path;
  6951. encoding = "Content-Encoding: gzip\r\n";
  6952. }
  6953. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6954. mg_send_http_error(conn,
  6955. 500,
  6956. "Error: Cannot open file\nfopen(%s): %s",
  6957. path,
  6958. strerror(ERRNO));
  6959. return;
  6960. }
  6961. fclose_on_exec(&filep->access, conn);
  6962. /* If Range: header specified, act accordingly */
  6963. r1 = r2 = 0;
  6964. hdr = mg_get_header(conn, "Range");
  6965. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6966. && r2 >= 0) {
  6967. /* actually, range requests don't play well with a pre-gzipped
  6968. * file (since the range is specified in the uncompressed space) */
  6969. if (filep->stat.is_gzipped) {
  6970. mg_send_http_error(
  6971. conn,
  6972. 416, /* 416 = Range Not Satisfiable */
  6973. "%s",
  6974. "Error: Range requests in gzipped files are not supported");
  6975. (void)mg_fclose(
  6976. &filep->access); /* ignore error on read only file */
  6977. return;
  6978. }
  6979. conn->status_code = 206;
  6980. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6981. mg_snprintf(conn,
  6982. NULL, /* range buffer is big enough */
  6983. range,
  6984. sizeof(range),
  6985. "Content-Range: bytes "
  6986. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6987. r1,
  6988. r1 + cl - 1,
  6989. filep->stat.size);
  6990. msg = "Partial Content";
  6991. }
  6992. hdr = mg_get_header(conn, "Origin");
  6993. if (hdr) {
  6994. /* Cross-origin resource sharing (CORS), see
  6995. * http://www.html5rocks.com/en/tutorials/cors/,
  6996. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6997. * preflight is not supported for files. */
  6998. cors1 = "Access-Control-Allow-Origin: ";
  6999. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7000. cors3 = "\r\n";
  7001. } else {
  7002. cors1 = cors2 = cors3 = "";
  7003. }
  7004. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  7005. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7006. gmt_time_string(date, sizeof(date), &curtime);
  7007. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7008. construct_etag(etag, sizeof(etag), &filep->stat);
  7009. (void)mg_printf(conn,
  7010. "HTTP/1.1 %d %s\r\n"
  7011. "%s%s%s"
  7012. "Date: %s\r\n",
  7013. conn->status_code,
  7014. msg,
  7015. cors1,
  7016. cors2,
  7017. cors3,
  7018. date);
  7019. send_static_cache_header(conn);
  7020. send_additional_header(conn);
  7021. (void)mg_printf(conn,
  7022. "Last-Modified: %s\r\n"
  7023. "Etag: %s\r\n"
  7024. "Content-Type: %.*s\r\n"
  7025. "Content-Length: %" INT64_FMT "\r\n"
  7026. "Connection: %s\r\n"
  7027. "Accept-Ranges: bytes\r\n"
  7028. "%s%s",
  7029. lm,
  7030. etag,
  7031. (int)mime_vec.len,
  7032. mime_vec.ptr,
  7033. cl,
  7034. suggest_connection_header(conn),
  7035. range,
  7036. encoding);
  7037. /* The previous code must not add any header starting with X- to make
  7038. * sure no one of the additional_headers is included twice */
  7039. if (additional_headers != NULL) {
  7040. (void)mg_printf(conn,
  7041. "%.*s\r\n\r\n",
  7042. (int)strlen(additional_headers),
  7043. additional_headers);
  7044. } else {
  7045. (void)mg_printf(conn, "\r\n");
  7046. }
  7047. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7048. send_file_data(conn, filep, r1, cl);
  7049. }
  7050. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7051. }
  7052. #if !defined(NO_CACHING)
  7053. static void
  7054. handle_not_modified_static_file_request(struct mg_connection *conn,
  7055. struct mg_file *filep)
  7056. {
  7057. char date[64], lm[64], etag[64];
  7058. time_t curtime = time(NULL);
  7059. if (conn == NULL || filep == NULL) {
  7060. return;
  7061. }
  7062. conn->status_code = 304;
  7063. gmt_time_string(date, sizeof(date), &curtime);
  7064. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7065. construct_etag(etag, sizeof(etag), &filep->stat);
  7066. (void)mg_printf(conn,
  7067. "HTTP/1.1 %d %s\r\n"
  7068. "Date: %s\r\n",
  7069. conn->status_code,
  7070. mg_get_response_code_text(conn, conn->status_code),
  7071. date);
  7072. send_static_cache_header(conn);
  7073. send_additional_header(conn);
  7074. (void)mg_printf(conn,
  7075. "Last-Modified: %s\r\n"
  7076. "Etag: %s\r\n"
  7077. "Connection: %s\r\n"
  7078. "\r\n",
  7079. lm,
  7080. etag,
  7081. suggest_connection_header(conn));
  7082. }
  7083. #endif
  7084. void
  7085. mg_send_file(struct mg_connection *conn, const char *path)
  7086. {
  7087. mg_send_mime_file(conn, path, NULL);
  7088. }
  7089. void
  7090. mg_send_mime_file(struct mg_connection *conn,
  7091. const char *path,
  7092. const char *mime_type)
  7093. {
  7094. mg_send_mime_file2(conn, path, mime_type, NULL);
  7095. }
  7096. void
  7097. mg_send_mime_file2(struct mg_connection *conn,
  7098. const char *path,
  7099. const char *mime_type,
  7100. const char *additional_headers)
  7101. {
  7102. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7103. if (mg_stat(conn, path, &file.stat)) {
  7104. if (file.stat.is_directory) {
  7105. if (!conn) {
  7106. return;
  7107. }
  7108. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7109. "yes")) {
  7110. handle_directory_request(conn, path);
  7111. } else {
  7112. mg_send_http_error(conn,
  7113. 403,
  7114. "%s",
  7115. "Error: Directory listing denied");
  7116. }
  7117. } else {
  7118. handle_static_file_request(
  7119. conn, path, &file, mime_type, additional_headers);
  7120. }
  7121. } else {
  7122. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7123. }
  7124. }
  7125. /* For a given PUT path, create all intermediate subdirectories.
  7126. * Return 0 if the path itself is a directory.
  7127. * Return 1 if the path leads to a file.
  7128. * Return -1 for if the path is too long.
  7129. * Return -2 if path can not be created.
  7130. */
  7131. static int
  7132. put_dir(struct mg_connection *conn, const char *path)
  7133. {
  7134. char buf[PATH_MAX];
  7135. const char *s, *p;
  7136. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7137. size_t len;
  7138. int res = 1;
  7139. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7140. len = (size_t)(p - path);
  7141. if (len >= sizeof(buf)) {
  7142. /* path too long */
  7143. res = -1;
  7144. break;
  7145. }
  7146. memcpy(buf, path, len);
  7147. buf[len] = '\0';
  7148. /* Try to create intermediate directory */
  7149. DEBUG_TRACE("mkdir(%s)", buf);
  7150. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7151. /* path does not exixt and can not be created */
  7152. res = -2;
  7153. break;
  7154. }
  7155. /* Is path itself a directory? */
  7156. if (p[1] == '\0') {
  7157. res = 0;
  7158. }
  7159. }
  7160. return res;
  7161. }
  7162. static void
  7163. remove_bad_file(const struct mg_connection *conn, const char *path)
  7164. {
  7165. int r = mg_remove(conn, path);
  7166. if (r != 0) {
  7167. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7168. }
  7169. }
  7170. long long
  7171. mg_store_body(struct mg_connection *conn, const char *path)
  7172. {
  7173. char buf[MG_BUF_LEN];
  7174. long long len = 0;
  7175. int ret, n;
  7176. struct mg_file fi;
  7177. if (conn->consumed_content != 0) {
  7178. mg_cry(conn, "%s: Contents already consumed", __func__);
  7179. return -11;
  7180. }
  7181. ret = put_dir(conn, path);
  7182. if (ret < 0) {
  7183. /* -1 for path too long,
  7184. * -2 for path can not be created. */
  7185. return ret;
  7186. }
  7187. if (ret != 1) {
  7188. /* Return 0 means, path itself is a directory. */
  7189. return 0;
  7190. }
  7191. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7192. return -12;
  7193. }
  7194. ret = mg_read(conn, buf, sizeof(buf));
  7195. while (ret > 0) {
  7196. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7197. if (n != ret) {
  7198. (void)mg_fclose(
  7199. &fi.access); /* File is bad and will be removed anyway. */
  7200. remove_bad_file(conn, path);
  7201. return -13;
  7202. }
  7203. len += ret;
  7204. ret = mg_read(conn, buf, sizeof(buf));
  7205. }
  7206. /* File is open for writing. If fclose fails, there was probably an
  7207. * error flushing the buffer to disk, so the file on disk might be
  7208. * broken. Delete it and return an error to the caller. */
  7209. if (mg_fclose(&fi.access) != 0) {
  7210. remove_bad_file(conn, path);
  7211. return -14;
  7212. }
  7213. return len;
  7214. }
  7215. /* Parse HTTP headers from the given buffer, advance buf pointer
  7216. * to the point where parsing stopped.
  7217. * All parameters must be valid pointers (not NULL).
  7218. * Return <0 on error. */
  7219. static int
  7220. parse_http_headers(char **buf, struct mg_request_info *ri)
  7221. {
  7222. int i;
  7223. ri->num_headers = 0;
  7224. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  7225. char *dp = *buf;
  7226. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7227. dp++;
  7228. }
  7229. if (dp == *buf) {
  7230. /* End of headers reached. */
  7231. break;
  7232. }
  7233. if (*dp != ':') {
  7234. /* This is not a valid field. */
  7235. return -1;
  7236. }
  7237. /* End of header key (*dp == ':') */
  7238. /* Truncate here and set the key name */
  7239. *dp = 0;
  7240. ri->http_headers[i].name = *buf;
  7241. do {
  7242. dp++;
  7243. } while (*dp == ' ');
  7244. /* The rest of the line is the value */
  7245. ri->http_headers[i].value = dp;
  7246. *buf = dp + strcspn(dp, "\r\n");
  7247. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7248. *buf = NULL;
  7249. }
  7250. ri->num_headers = i + 1;
  7251. if (*buf) {
  7252. (*buf)[0] = 0;
  7253. (*buf)[1] = 0;
  7254. *buf += 2;
  7255. } else {
  7256. *buf = dp;
  7257. break;
  7258. }
  7259. if ((*buf)[0] == '\r') {
  7260. /* This is the end of the header */
  7261. break;
  7262. }
  7263. }
  7264. return ri->num_headers;
  7265. }
  7266. static int
  7267. is_valid_http_method(const char *method)
  7268. {
  7269. /* Check if the method is known to the server. The list of all known
  7270. * HTTP methods can be found here at
  7271. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7272. */
  7273. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7274. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7275. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7276. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7277. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7278. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7279. /* TRACE method (RFC 2616) is not supported for security reasons */
  7280. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7281. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7282. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7283. /* Unsupported WEBDAV Methods: */
  7284. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7285. /* + 11 methods from RFC 3253 */
  7286. /* ORDERPATCH (RFC 3648) */
  7287. /* ACL (RFC 3744) */
  7288. /* SEARCH (RFC 5323) */
  7289. /* + MicroSoft extensions
  7290. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7291. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7292. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7293. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7294. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7295. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7296. * to be useful for REST in case a "GET request with body" is
  7297. * required. */
  7298. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7299. ;
  7300. }
  7301. /* Parse HTTP request, fill in mg_request_info structure.
  7302. * This function modifies the buffer by NUL-terminating
  7303. * HTTP request components, header names and header values.
  7304. * Parameters:
  7305. * buf (in/out): pointer to the HTTP header to parse and split
  7306. * len (in): length of HTTP header buffer
  7307. * re (out): parsed header as mg_request_info
  7308. * buf and ri must be valid pointers (not NULL), len>0.
  7309. * Returns <0 on error. */
  7310. static int
  7311. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  7312. {
  7313. int is_request, request_length;
  7314. char *start_line;
  7315. request_length = get_request_len(buf, len);
  7316. if (request_length > 0) {
  7317. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7318. * remote_port */
  7319. ri->remote_user = ri->request_method = ri->request_uri =
  7320. ri->http_version = NULL;
  7321. ri->num_headers = 0;
  7322. buf[request_length - 1] = '\0';
  7323. /* RFC says that all initial whitespaces should be ingored */
  7324. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  7325. buf++;
  7326. }
  7327. start_line = skip(&buf, "\r\n");
  7328. ri->request_method = skip(&start_line, " ");
  7329. ri->request_uri = skip(&start_line, " ");
  7330. ri->http_version = start_line;
  7331. /* HTTP message could be either HTTP request:
  7332. * "GET / HTTP/1.0 ..."
  7333. * or a HTTP response:
  7334. * "HTTP/1.0 200 OK ..."
  7335. * otherwise it is invalid.
  7336. */
  7337. is_request = is_valid_http_method(ri->request_method);
  7338. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  7339. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  7340. /* Not a valid request or response: invalid */
  7341. return -1;
  7342. }
  7343. if (is_request) {
  7344. ri->http_version += 5;
  7345. }
  7346. if (parse_http_headers(&buf, ri) < 0) {
  7347. /* Error while parsing headers */
  7348. return -1;
  7349. }
  7350. }
  7351. return request_length;
  7352. }
  7353. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7354. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7355. * buffer (which marks the end of HTTP request). Buffer buf may already
  7356. * have some data. The length of the data is stored in nread.
  7357. * Upon every read operation, increase nread by the number of bytes read. */
  7358. static int
  7359. read_request(FILE *fp,
  7360. struct mg_connection *conn,
  7361. char *buf,
  7362. int bufsiz,
  7363. int *nread)
  7364. {
  7365. int request_len, n = 0;
  7366. struct timespec last_action_time;
  7367. double request_timeout;
  7368. if (!conn) {
  7369. return 0;
  7370. }
  7371. memset(&last_action_time, 0, sizeof(last_action_time));
  7372. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7373. /* value of request_timeout is in seconds, config in milliseconds */
  7374. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7375. } else {
  7376. request_timeout = -1.0;
  7377. }
  7378. if (conn->handled_requests > 0) {
  7379. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7380. request_timeout =
  7381. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7382. }
  7383. }
  7384. request_len = get_request_len(buf, *nread);
  7385. /* first time reading from this connection */
  7386. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7387. while (request_len == 0) {
  7388. /* Full request not yet received */
  7389. if (conn->ctx->stop_flag != 0) {
  7390. /* Server is to be stopped. */
  7391. return -1;
  7392. }
  7393. if (*nread >= bufsiz) {
  7394. /* Request too long */
  7395. return -2;
  7396. }
  7397. n = pull_inner(
  7398. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7399. if (n == -2) {
  7400. /* Receive error */
  7401. return -1;
  7402. }
  7403. if (n > 0) {
  7404. *nread += n;
  7405. request_len = get_request_len(buf, *nread);
  7406. } else {
  7407. request_len = 0;
  7408. }
  7409. if ((request_len == 0) && (request_timeout >= 0)) {
  7410. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7411. > request_timeout) {
  7412. /* Timeout */
  7413. return -1;
  7414. }
  7415. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7416. }
  7417. }
  7418. return request_len;
  7419. }
  7420. #if !defined(NO_CACHING)
  7421. /* Return True if we should reply 304 Not Modified. */
  7422. static int
  7423. is_not_modified(const struct mg_connection *conn,
  7424. const struct mg_file_stat *filestat)
  7425. {
  7426. char etag[64];
  7427. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7428. const char *inm = mg_get_header(conn, "If-None-Match");
  7429. construct_etag(etag, sizeof(etag), filestat);
  7430. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7431. || ((ims != NULL)
  7432. && (filestat->last_modified <= parse_date_string(ims)));
  7433. }
  7434. #endif /* !NO_CACHING */
  7435. #if !defined(NO_CGI) || !defined(NO_FILES)
  7436. static int
  7437. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7438. {
  7439. const char *expect, *body;
  7440. char buf[MG_BUF_LEN];
  7441. int to_read, nread, success = 0;
  7442. int64_t buffered_len;
  7443. double timeout = -1.0;
  7444. if (!conn) {
  7445. return 0;
  7446. }
  7447. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7448. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7449. }
  7450. expect = mg_get_header(conn, "Expect");
  7451. /* assert(fp != NULL); */
  7452. if (!fp) {
  7453. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  7454. return 0;
  7455. }
  7456. if (conn->content_len == -1 && !conn->is_chunked) {
  7457. /* Content length is not specified by the client. */
  7458. mg_send_http_error(conn,
  7459. 411,
  7460. "%s",
  7461. "Error: Client did not specify content length");
  7462. } else if ((expect != NULL)
  7463. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7464. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7465. mg_send_http_error(conn,
  7466. 417,
  7467. "Error: Can not fulfill expectation %s",
  7468. expect);
  7469. } else {
  7470. if (expect != NULL) {
  7471. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7472. conn->status_code = 100;
  7473. } else {
  7474. conn->status_code = 200;
  7475. }
  7476. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7477. - conn->consumed_content;
  7478. /* assert(buffered_len >= 0); */
  7479. /* assert(conn->consumed_content == 0); */
  7480. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7481. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7482. return 0;
  7483. }
  7484. if (buffered_len > 0) {
  7485. if ((int64_t)buffered_len > conn->content_len) {
  7486. buffered_len = (int)conn->content_len;
  7487. }
  7488. body = conn->buf + conn->request_len + conn->consumed_content;
  7489. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7490. conn->consumed_content += buffered_len;
  7491. }
  7492. nread = 0;
  7493. while (conn->consumed_content < conn->content_len) {
  7494. to_read = sizeof(buf);
  7495. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7496. to_read = (int)(conn->content_len - conn->consumed_content);
  7497. }
  7498. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7499. if (nread == -2) {
  7500. /* error */
  7501. break;
  7502. }
  7503. if (nread > 0) {
  7504. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7505. break;
  7506. }
  7507. }
  7508. conn->consumed_content += nread;
  7509. }
  7510. if (conn->consumed_content == conn->content_len) {
  7511. success = (nread >= 0);
  7512. }
  7513. /* Each error code path in this function must send an error */
  7514. if (!success) {
  7515. /* NOTE: Maybe some data has already been sent. */
  7516. /* TODO (low): If some data has been sent, a correct error
  7517. * reply can no longer be sent, so just close the connection */
  7518. mg_send_http_error(conn, 500, "%s", "");
  7519. }
  7520. }
  7521. return success;
  7522. }
  7523. #endif
  7524. #if !defined(NO_CGI)
  7525. /* This structure helps to create an environment for the spawned CGI program.
  7526. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7527. * last element must be NULL.
  7528. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7529. * strings must reside in a contiguous buffer. The end of the buffer is
  7530. * marked by two '\0' characters.
  7531. * We satisfy both worlds: we create an envp array (which is vars), all
  7532. * entries are actually pointers inside buf. */
  7533. struct cgi_environment {
  7534. struct mg_connection *conn;
  7535. /* Data block */
  7536. char *buf; /* Environment buffer */
  7537. size_t buflen; /* Space available in buf */
  7538. size_t bufused; /* Space taken in buf */
  7539. /* Index block */
  7540. char **var; /* char **envp */
  7541. size_t varlen; /* Number of variables available in var */
  7542. size_t varused; /* Number of variables stored in var */
  7543. };
  7544. static void addenv(struct cgi_environment *env,
  7545. PRINTF_FORMAT_STRING(const char *fmt),
  7546. ...) PRINTF_ARGS(2, 3);
  7547. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7548. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7549. static void
  7550. addenv(struct cgi_environment *env, const char *fmt, ...)
  7551. {
  7552. size_t n, space;
  7553. int truncated = 0;
  7554. char *added;
  7555. va_list ap;
  7556. /* Calculate how much space is left in the buffer */
  7557. space = (env->buflen - env->bufused);
  7558. /* Calculate an estimate for the required space */
  7559. n = strlen(fmt) + 2 + 128;
  7560. do {
  7561. if (space <= n) {
  7562. /* Allocate new buffer */
  7563. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7564. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  7565. if (!added) {
  7566. /* Out of memory */
  7567. mg_cry(env->conn,
  7568. "%s: Cannot allocate memory for CGI variable [%s]",
  7569. __func__,
  7570. fmt);
  7571. return;
  7572. }
  7573. env->buf = added;
  7574. env->buflen = n;
  7575. space = (env->buflen - env->bufused);
  7576. }
  7577. /* Make a pointer to the free space int the buffer */
  7578. added = env->buf + env->bufused;
  7579. /* Copy VARIABLE=VALUE\0 string into the free space */
  7580. va_start(ap, fmt);
  7581. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7582. va_end(ap);
  7583. /* Do not add truncated strings to the environment */
  7584. if (truncated) {
  7585. /* Reallocate the buffer */
  7586. space = 0;
  7587. n = 1;
  7588. }
  7589. } while (truncated);
  7590. /* Calculate number of bytes added to the environment */
  7591. n = strlen(added) + 1;
  7592. env->bufused += n;
  7593. /* Now update the variable index */
  7594. space = (env->varlen - env->varused);
  7595. if (space < 2) {
  7596. mg_cry(env->conn,
  7597. "%s: Cannot register CGI variable [%s]",
  7598. __func__,
  7599. fmt);
  7600. return;
  7601. }
  7602. /* Append a pointer to the added string into the envp array */
  7603. env->var[env->varused] = added;
  7604. env->varused++;
  7605. }
  7606. static void
  7607. prepare_cgi_environment(struct mg_connection *conn,
  7608. const char *prog,
  7609. struct cgi_environment *env)
  7610. {
  7611. const char *s;
  7612. struct vec var_vec;
  7613. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7614. int i, truncated, uri_len;
  7615. if (conn == NULL || prog == NULL || env == NULL) {
  7616. return;
  7617. }
  7618. env->conn = conn;
  7619. env->buflen = CGI_ENVIRONMENT_SIZE;
  7620. env->bufused = 0;
  7621. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  7622. env->varlen = MAX_CGI_ENVIR_VARS;
  7623. env->varused = 0;
  7624. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  7625. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7626. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7627. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7628. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7629. /* Prepare the environment block */
  7630. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7631. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7632. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7633. #if defined(USE_IPV6)
  7634. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7635. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7636. } else
  7637. #endif
  7638. {
  7639. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7640. }
  7641. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7642. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7643. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7644. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7645. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7646. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7647. /* SCRIPT_NAME */
  7648. uri_len = (int)strlen(conn->request_info.local_uri);
  7649. if (conn->path_info == NULL) {
  7650. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7651. /* URI: /path_to_script/script.cgi */
  7652. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7653. } else {
  7654. /* URI: /path_to_script/ ... using index.cgi */
  7655. const char *index_file = strrchr(prog, '/');
  7656. if (index_file) {
  7657. addenv(env,
  7658. "SCRIPT_NAME=%s%s",
  7659. conn->request_info.local_uri,
  7660. index_file + 1);
  7661. }
  7662. }
  7663. } else {
  7664. /* URI: /path_to_script/script.cgi/path_info */
  7665. addenv(env,
  7666. "SCRIPT_NAME=%.*s",
  7667. uri_len - (int)strlen(conn->path_info),
  7668. conn->request_info.local_uri);
  7669. }
  7670. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7671. if (conn->path_info == NULL) {
  7672. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7673. } else {
  7674. addenv(env,
  7675. "PATH_TRANSLATED=%s%s",
  7676. conn->ctx->config[DOCUMENT_ROOT],
  7677. conn->path_info);
  7678. }
  7679. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7680. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7681. addenv(env, "CONTENT_TYPE=%s", s);
  7682. }
  7683. if (conn->request_info.query_string != NULL) {
  7684. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7685. }
  7686. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7687. addenv(env, "CONTENT_LENGTH=%s", s);
  7688. }
  7689. if ((s = getenv("PATH")) != NULL) {
  7690. addenv(env, "PATH=%s", s);
  7691. }
  7692. if (conn->path_info != NULL) {
  7693. addenv(env, "PATH_INFO=%s", conn->path_info);
  7694. }
  7695. if (conn->status_code > 0) {
  7696. /* CGI error handler should show the status code */
  7697. addenv(env, "STATUS=%d", conn->status_code);
  7698. }
  7699. #if defined(_WIN32)
  7700. if ((s = getenv("COMSPEC")) != NULL) {
  7701. addenv(env, "COMSPEC=%s", s);
  7702. }
  7703. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7704. addenv(env, "SYSTEMROOT=%s", s);
  7705. }
  7706. if ((s = getenv("SystemDrive")) != NULL) {
  7707. addenv(env, "SystemDrive=%s", s);
  7708. }
  7709. if ((s = getenv("ProgramFiles")) != NULL) {
  7710. addenv(env, "ProgramFiles=%s", s);
  7711. }
  7712. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7713. addenv(env, "ProgramFiles(x86)=%s", s);
  7714. }
  7715. #else
  7716. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7717. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7718. }
  7719. #endif /* _WIN32 */
  7720. if ((s = getenv("PERLLIB")) != NULL) {
  7721. addenv(env, "PERLLIB=%s", s);
  7722. }
  7723. if (conn->request_info.remote_user != NULL) {
  7724. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7725. addenv(env, "%s", "AUTH_TYPE=Digest");
  7726. }
  7727. /* Add all headers as HTTP_* variables */
  7728. for (i = 0; i < conn->request_info.num_headers; i++) {
  7729. (void)mg_snprintf(conn,
  7730. &truncated,
  7731. http_var_name,
  7732. sizeof(http_var_name),
  7733. "HTTP_%s",
  7734. conn->request_info.http_headers[i].name);
  7735. if (truncated) {
  7736. mg_cry(conn,
  7737. "%s: HTTP header variable too long [%s]",
  7738. __func__,
  7739. conn->request_info.http_headers[i].name);
  7740. continue;
  7741. }
  7742. /* Convert variable name into uppercase, and change - to _ */
  7743. for (p = http_var_name; *p != '\0'; p++) {
  7744. if (*p == '-') {
  7745. *p = '_';
  7746. }
  7747. *p = (char)toupper(*(unsigned char *)p);
  7748. }
  7749. addenv(env,
  7750. "%s=%s",
  7751. http_var_name,
  7752. conn->request_info.http_headers[i].value);
  7753. }
  7754. /* Add user-specified variables */
  7755. s = conn->ctx->config[CGI_ENVIRONMENT];
  7756. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7757. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7758. }
  7759. env->var[env->varused] = NULL;
  7760. env->buf[env->bufused] = '\0';
  7761. }
  7762. static void
  7763. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7764. {
  7765. char *buf;
  7766. size_t buflen;
  7767. int headers_len, data_len, i, truncated;
  7768. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7769. const char *status, *status_text, *connection_state;
  7770. char *pbuf, dir[PATH_MAX], *p;
  7771. struct mg_request_info ri;
  7772. struct cgi_environment blk;
  7773. FILE *in = NULL, *out = NULL, *err = NULL;
  7774. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7775. pid_t pid = (pid_t)-1;
  7776. if (conn == NULL) {
  7777. return;
  7778. }
  7779. buf = NULL;
  7780. buflen = 16384;
  7781. prepare_cgi_environment(conn, prog, &blk);
  7782. /* CGI must be executed in its own directory. 'dir' must point to the
  7783. * directory containing executable program, 'p' must point to the
  7784. * executable program name relative to 'dir'. */
  7785. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7786. if (truncated) {
  7787. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7788. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7789. goto done;
  7790. }
  7791. if ((p = strrchr(dir, '/')) != NULL) {
  7792. *p++ = '\0';
  7793. } else {
  7794. dir[0] = '.', dir[1] = '\0';
  7795. p = (char *)prog;
  7796. }
  7797. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7798. status = strerror(ERRNO);
  7799. mg_cry(conn,
  7800. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7801. prog,
  7802. status);
  7803. mg_send_http_error(conn,
  7804. 500,
  7805. "Error: Cannot create CGI pipe: %s",
  7806. status);
  7807. goto done;
  7808. }
  7809. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7810. if (pid == (pid_t)-1) {
  7811. status = strerror(ERRNO);
  7812. mg_cry(conn,
  7813. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7814. prog,
  7815. status);
  7816. mg_send_http_error(conn,
  7817. 500,
  7818. "Error: Cannot spawn CGI process [%s]: %s",
  7819. prog,
  7820. status);
  7821. goto done;
  7822. }
  7823. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7824. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7825. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7826. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7827. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7828. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7829. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7830. /* Parent closes only one side of the pipes.
  7831. * If we don't mark them as closed, close() attempt before
  7832. * return from this function throws an exception on Windows.
  7833. * Windows does not like when closed descriptor is closed again. */
  7834. (void)close(fdin[0]);
  7835. (void)close(fdout[1]);
  7836. (void)close(fderr[1]);
  7837. fdin[0] = fdout[1] = fderr[1] = -1;
  7838. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7839. status = strerror(ERRNO);
  7840. mg_cry(conn,
  7841. "Error: CGI program \"%s\": Can not open stdin: %s",
  7842. prog,
  7843. status);
  7844. mg_send_http_error(conn,
  7845. 500,
  7846. "Error: CGI can not open fdin\nfopen: %s",
  7847. status);
  7848. goto done;
  7849. }
  7850. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7851. status = strerror(ERRNO);
  7852. mg_cry(conn,
  7853. "Error: CGI program \"%s\": Can not open stdout: %s",
  7854. prog,
  7855. status);
  7856. mg_send_http_error(conn,
  7857. 500,
  7858. "Error: CGI can not open fdout\nfopen: %s",
  7859. status);
  7860. goto done;
  7861. }
  7862. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7863. status = strerror(ERRNO);
  7864. mg_cry(conn,
  7865. "Error: CGI program \"%s\": Can not open stderr: %s",
  7866. prog,
  7867. status);
  7868. mg_send_http_error(conn,
  7869. 500,
  7870. "Error: CGI can not open fdout\nfopen: %s",
  7871. status);
  7872. goto done;
  7873. }
  7874. setbuf(in, NULL);
  7875. setbuf(out, NULL);
  7876. setbuf(err, NULL);
  7877. fout.access.fp = out;
  7878. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7879. /* This is a POST/PUT request, or another request with body data. */
  7880. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7881. /* Error sending the body data */
  7882. mg_cry(conn,
  7883. "Error: CGI program \"%s\": Forward body data failed",
  7884. prog);
  7885. goto done;
  7886. }
  7887. }
  7888. /* Close so child gets an EOF. */
  7889. fclose(in);
  7890. in = NULL;
  7891. fdin[1] = -1;
  7892. /* Now read CGI reply into a buffer. We need to set correct
  7893. * status code, thus we need to see all HTTP headers first.
  7894. * Do not send anything back to client, until we buffer in all
  7895. * HTTP headers. */
  7896. data_len = 0;
  7897. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  7898. if (buf == NULL) {
  7899. mg_send_http_error(conn,
  7900. 500,
  7901. "Error: Not enough memory for CGI buffer (%u bytes)",
  7902. (unsigned int)buflen);
  7903. mg_cry(conn,
  7904. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7905. "bytes)",
  7906. prog,
  7907. (unsigned int)buflen);
  7908. goto done;
  7909. }
  7910. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7911. if (headers_len <= 0) {
  7912. /* Could not parse the CGI response. Check if some error message on
  7913. * stderr. */
  7914. i = pull_all(err, conn, buf, (int)buflen);
  7915. if (i > 0) {
  7916. mg_cry(conn,
  7917. "Error: CGI program \"%s\" sent error "
  7918. "message: [%.*s]",
  7919. prog,
  7920. i,
  7921. buf);
  7922. mg_send_http_error(conn,
  7923. 500,
  7924. "Error: CGI program \"%s\" sent error "
  7925. "message: [%.*s]",
  7926. prog,
  7927. i,
  7928. buf);
  7929. } else {
  7930. mg_cry(conn,
  7931. "Error: CGI program sent malformed or too big "
  7932. "(>%u bytes) HTTP headers: [%.*s]",
  7933. (unsigned)buflen,
  7934. data_len,
  7935. buf);
  7936. mg_send_http_error(conn,
  7937. 500,
  7938. "Error: CGI program sent malformed or too big "
  7939. "(>%u bytes) HTTP headers: [%.*s]",
  7940. (unsigned)buflen,
  7941. data_len,
  7942. buf);
  7943. }
  7944. goto done;
  7945. }
  7946. pbuf = buf;
  7947. buf[headers_len - 1] = '\0';
  7948. parse_http_headers(&pbuf, &ri);
  7949. /* Make up and send the status line */
  7950. status_text = "OK";
  7951. if ((status = get_header(&ri, "Status")) != NULL) {
  7952. conn->status_code = atoi(status);
  7953. status_text = status;
  7954. while (isdigit(*(const unsigned char *)status_text)
  7955. || *status_text == ' ') {
  7956. status_text++;
  7957. }
  7958. } else if (get_header(&ri, "Location") != NULL) {
  7959. conn->status_code = 302;
  7960. } else {
  7961. conn->status_code = 200;
  7962. }
  7963. connection_state = get_header(&ri, "Connection");
  7964. if (!header_has_option(connection_state, "keep-alive")) {
  7965. conn->must_close = 1;
  7966. }
  7967. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7968. /* Send headers */
  7969. for (i = 0; i < ri.num_headers; i++) {
  7970. mg_printf(conn,
  7971. "%s: %s\r\n",
  7972. ri.http_headers[i].name,
  7973. ri.http_headers[i].value);
  7974. }
  7975. mg_write(conn, "\r\n", 2);
  7976. /* Send chunk of data that may have been read after the headers */
  7977. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7978. /* Read the rest of CGI output and send to the client */
  7979. send_file_data(conn, &fout, 0, INT64_MAX);
  7980. done:
  7981. mg_free(blk.var);
  7982. mg_free(blk.buf);
  7983. if (pid != (pid_t)-1) {
  7984. kill(pid, SIGKILL);
  7985. #if !defined(_WIN32)
  7986. {
  7987. int st;
  7988. while (waitpid(pid, &st, 0) != -1)
  7989. ; /* clean zombies */
  7990. }
  7991. #endif
  7992. }
  7993. if (fdin[0] != -1) {
  7994. close(fdin[0]);
  7995. }
  7996. if (fdout[1] != -1) {
  7997. close(fdout[1]);
  7998. }
  7999. if (in != NULL) {
  8000. fclose(in);
  8001. } else if (fdin[1] != -1) {
  8002. close(fdin[1]);
  8003. }
  8004. if (out != NULL) {
  8005. fclose(out);
  8006. } else if (fdout[0] != -1) {
  8007. close(fdout[0]);
  8008. }
  8009. if (err != NULL) {
  8010. fclose(err);
  8011. } else if (fderr[0] != -1) {
  8012. close(fderr[0]);
  8013. }
  8014. if (buf != NULL) {
  8015. mg_free(buf);
  8016. }
  8017. }
  8018. #endif /* !NO_CGI */
  8019. #if !defined(NO_FILES)
  8020. static void
  8021. mkcol(struct mg_connection *conn, const char *path)
  8022. {
  8023. int rc, body_len;
  8024. struct de de;
  8025. char date[64];
  8026. time_t curtime = time(NULL);
  8027. if (conn == NULL) {
  8028. return;
  8029. }
  8030. /* TODO (mid): Check the mg_send_http_error situations in this function */
  8031. memset(&de.file, 0, sizeof(de.file));
  8032. if (!mg_stat(conn, path, &de.file)) {
  8033. mg_cry(conn,
  8034. "%s: mg_stat(%s) failed: %s",
  8035. __func__,
  8036. path,
  8037. strerror(ERRNO));
  8038. }
  8039. if (de.file.last_modified) {
  8040. /* TODO (mid): This check does not seem to make any sense ! */
  8041. /* TODO (mid): Add a webdav unit test first, before changing
  8042. * anything here. */
  8043. mg_send_http_error(
  8044. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8045. return;
  8046. }
  8047. body_len = conn->data_len - conn->request_len;
  8048. if (body_len > 0) {
  8049. mg_send_http_error(
  8050. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8051. return;
  8052. }
  8053. rc = mg_mkdir(conn, path, 0755);
  8054. if (rc == 0) {
  8055. conn->status_code = 201;
  8056. gmt_time_string(date, sizeof(date), &curtime);
  8057. mg_printf(conn,
  8058. "HTTP/1.1 %d Created\r\n"
  8059. "Date: %s\r\n",
  8060. conn->status_code,
  8061. date);
  8062. send_static_cache_header(conn);
  8063. send_additional_header(conn);
  8064. mg_printf(conn,
  8065. "Content-Length: 0\r\n"
  8066. "Connection: %s\r\n\r\n",
  8067. suggest_connection_header(conn));
  8068. } else if (rc == -1) {
  8069. if (errno == EEXIST) {
  8070. mg_send_http_error(
  8071. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8072. } else if (errno == EACCES) {
  8073. mg_send_http_error(
  8074. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8075. } else if (errno == ENOENT) {
  8076. mg_send_http_error(
  8077. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8078. } else {
  8079. mg_send_http_error(
  8080. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8081. }
  8082. }
  8083. }
  8084. static void
  8085. put_file(struct mg_connection *conn, const char *path)
  8086. {
  8087. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8088. const char *range;
  8089. int64_t r1, r2;
  8090. int rc;
  8091. char date[64];
  8092. time_t curtime = time(NULL);
  8093. if (conn == NULL) {
  8094. return;
  8095. }
  8096. if (mg_stat(conn, path, &file.stat)) {
  8097. /* File already exists */
  8098. conn->status_code = 200;
  8099. if (file.stat.is_directory) {
  8100. /* This is an already existing directory,
  8101. * so there is nothing to do for the server. */
  8102. rc = 0;
  8103. } else {
  8104. /* File exists and is not a directory. */
  8105. /* Can it be replaced? */
  8106. if (file.access.membuf != NULL) {
  8107. /* This is an "in-memory" file, that can not be replaced */
  8108. mg_send_http_error(
  8109. conn,
  8110. 405,
  8111. "Error: Put not possible\nReplacing %s is not supported",
  8112. path);
  8113. return;
  8114. }
  8115. /* Check if the server may write this file */
  8116. if (access(path, W_OK) == 0) {
  8117. /* Access granted */
  8118. conn->status_code = 200;
  8119. rc = 1;
  8120. } else {
  8121. mg_send_http_error(
  8122. conn,
  8123. 403,
  8124. "Error: Put not possible\nReplacing %s is not allowed",
  8125. path);
  8126. return;
  8127. }
  8128. }
  8129. } else {
  8130. /* File should be created */
  8131. conn->status_code = 201;
  8132. rc = put_dir(conn, path);
  8133. }
  8134. if (rc == 0) {
  8135. /* put_dir returns 0 if path is a directory */
  8136. gmt_time_string(date, sizeof(date), &curtime);
  8137. mg_printf(conn,
  8138. "HTTP/1.1 %d %s\r\n",
  8139. conn->status_code,
  8140. mg_get_response_code_text(NULL, conn->status_code));
  8141. send_no_cache_header(conn);
  8142. send_additional_header(conn);
  8143. mg_printf(conn,
  8144. "Date: %s\r\n"
  8145. "Content-Length: 0\r\n"
  8146. "Connection: %s\r\n\r\n",
  8147. date,
  8148. suggest_connection_header(conn));
  8149. /* Request to create a directory has been fulfilled successfully.
  8150. * No need to put a file. */
  8151. return;
  8152. }
  8153. if (rc == -1) {
  8154. /* put_dir returns -1 if the path is too long */
  8155. mg_send_http_error(conn,
  8156. 414,
  8157. "Error: Path too long\nput_dir(%s): %s",
  8158. path,
  8159. strerror(ERRNO));
  8160. return;
  8161. }
  8162. if (rc == -2) {
  8163. /* put_dir returns -2 if the directory can not be created */
  8164. mg_send_http_error(conn,
  8165. 500,
  8166. "Error: Can not create directory\nput_dir(%s): %s",
  8167. path,
  8168. strerror(ERRNO));
  8169. return;
  8170. }
  8171. /* A file should be created or overwritten. */
  8172. /* Currently CivetWeb does not nead read+write access. */
  8173. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8174. || file.access.fp == NULL) {
  8175. (void)mg_fclose(&file.access);
  8176. mg_send_http_error(conn,
  8177. 500,
  8178. "Error: Can not create file\nfopen(%s): %s",
  8179. path,
  8180. strerror(ERRNO));
  8181. return;
  8182. }
  8183. fclose_on_exec(&file.access, conn);
  8184. range = mg_get_header(conn, "Content-Range");
  8185. r1 = r2 = 0;
  8186. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  8187. conn->status_code = 206; /* Partial content */
  8188. fseeko(file.access.fp, r1, SEEK_SET);
  8189. }
  8190. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8191. /* forward_body_data failed.
  8192. * The error code has already been sent to the client,
  8193. * and conn->status_code is already set. */
  8194. (void)mg_fclose(&file.access);
  8195. return;
  8196. }
  8197. if (mg_fclose(&file.access) != 0) {
  8198. /* fclose failed. This might have different reasons, but a likely
  8199. * one is "no space on disk", http 507. */
  8200. conn->status_code = 507;
  8201. }
  8202. gmt_time_string(date, sizeof(date), &curtime);
  8203. mg_printf(conn,
  8204. "HTTP/1.1 %d %s\r\n",
  8205. conn->status_code,
  8206. mg_get_response_code_text(NULL, conn->status_code));
  8207. send_no_cache_header(conn);
  8208. send_additional_header(conn);
  8209. mg_printf(conn,
  8210. "Date: %s\r\n"
  8211. "Content-Length: 0\r\n"
  8212. "Connection: %s\r\n\r\n",
  8213. date,
  8214. suggest_connection_header(conn));
  8215. }
  8216. static void
  8217. delete_file(struct mg_connection *conn, const char *path)
  8218. {
  8219. struct de de;
  8220. memset(&de.file, 0, sizeof(de.file));
  8221. if (!mg_stat(conn, path, &de.file)) {
  8222. /* mg_stat returns 0 if the file does not exist */
  8223. mg_send_http_error(conn,
  8224. 404,
  8225. "Error: Cannot delete file\nFile %s not found",
  8226. path);
  8227. return;
  8228. }
  8229. #if 0 /* Ignore if a file in memory is inside a folder */
  8230. if (de.access.membuf != NULL) {
  8231. /* the file is cached in memory */
  8232. mg_send_http_error(
  8233. conn,
  8234. 405,
  8235. "Error: Delete not possible\nDeleting %s is not supported",
  8236. path);
  8237. return;
  8238. }
  8239. #endif
  8240. if (de.file.is_directory) {
  8241. if (remove_directory(conn, path)) {
  8242. /* Delete is successful: Return 204 without content. */
  8243. mg_send_http_error(conn, 204, "%s", "");
  8244. } else {
  8245. /* Delete is not successful: Return 500 (Server error). */
  8246. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8247. }
  8248. return;
  8249. }
  8250. /* This is an existing file (not a directory).
  8251. * Check if write permission is granted. */
  8252. if (access(path, W_OK) != 0) {
  8253. /* File is read only */
  8254. mg_send_http_error(
  8255. conn,
  8256. 403,
  8257. "Error: Delete not possible\nDeleting %s is not allowed",
  8258. path);
  8259. return;
  8260. }
  8261. /* Try to delete it. */
  8262. if (mg_remove(conn, path) == 0) {
  8263. /* Delete was successful: Return 204 without content. */
  8264. mg_send_http_error(conn, 204, "%s", "");
  8265. } else {
  8266. /* Delete not successful (file locked). */
  8267. mg_send_http_error(conn,
  8268. 423,
  8269. "Error: Cannot delete file\nremove(%s): %s",
  8270. path,
  8271. strerror(ERRNO));
  8272. }
  8273. }
  8274. #endif /* !NO_FILES */
  8275. static void
  8276. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8277. static void
  8278. do_ssi_include(struct mg_connection *conn,
  8279. const char *ssi,
  8280. char *tag,
  8281. int include_level)
  8282. {
  8283. char file_name[MG_BUF_LEN], path[512], *p;
  8284. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8285. size_t len;
  8286. int truncated = 0;
  8287. if (conn == NULL) {
  8288. return;
  8289. }
  8290. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8291. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8292. * always < MG_BUF_LEN. */
  8293. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8294. /* File name is relative to the webserver root */
  8295. file_name[511] = 0;
  8296. (void)mg_snprintf(conn,
  8297. &truncated,
  8298. path,
  8299. sizeof(path),
  8300. "%s/%s",
  8301. conn->ctx->config[DOCUMENT_ROOT],
  8302. file_name);
  8303. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8304. /* File name is relative to the webserver working directory
  8305. * or it is absolute system path */
  8306. file_name[511] = 0;
  8307. (void)
  8308. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8309. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  8310. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  8311. /* File name is relative to the currect document */
  8312. file_name[511] = 0;
  8313. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8314. if (!truncated) {
  8315. if ((p = strrchr(path, '/')) != NULL) {
  8316. p[1] = '\0';
  8317. }
  8318. len = strlen(path);
  8319. (void)mg_snprintf(conn,
  8320. &truncated,
  8321. path + len,
  8322. sizeof(path) - len,
  8323. "%s",
  8324. file_name);
  8325. }
  8326. } else {
  8327. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8328. return;
  8329. }
  8330. if (truncated) {
  8331. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8332. return;
  8333. }
  8334. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8335. mg_cry(conn,
  8336. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8337. tag,
  8338. path,
  8339. strerror(ERRNO));
  8340. } else {
  8341. fclose_on_exec(&file.access, conn);
  8342. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8343. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8344. path) > 0) {
  8345. send_ssi_file(conn, path, &file, include_level + 1);
  8346. } else {
  8347. send_file_data(conn, &file, 0, INT64_MAX);
  8348. }
  8349. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8350. }
  8351. }
  8352. #if !defined(NO_POPEN)
  8353. static void
  8354. do_ssi_exec(struct mg_connection *conn, char *tag)
  8355. {
  8356. char cmd[1024] = "";
  8357. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8358. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8359. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8360. } else {
  8361. cmd[1023] = 0;
  8362. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8363. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8364. } else {
  8365. send_file_data(conn, &file, 0, INT64_MAX);
  8366. pclose(file.access.fp);
  8367. }
  8368. }
  8369. }
  8370. #endif /* !NO_POPEN */
  8371. static int
  8372. mg_fgetc(struct mg_file *filep, int offset)
  8373. {
  8374. if (filep == NULL) {
  8375. return EOF;
  8376. }
  8377. if (filep->access.membuf != NULL && offset >= 0
  8378. && ((unsigned int)(offset)) < filep->stat.size) {
  8379. return ((const unsigned char *)filep->access.membuf)[offset];
  8380. } else if (filep->access.fp != NULL) {
  8381. return fgetc(filep->access.fp);
  8382. } else {
  8383. return EOF;
  8384. }
  8385. }
  8386. static void
  8387. send_ssi_file(struct mg_connection *conn,
  8388. const char *path,
  8389. struct mg_file *filep,
  8390. int include_level)
  8391. {
  8392. char buf[MG_BUF_LEN];
  8393. int ch, offset, len, in_ssi_tag;
  8394. if (include_level > 10) {
  8395. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8396. return;
  8397. }
  8398. in_ssi_tag = len = offset = 0;
  8399. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  8400. if (in_ssi_tag && ch == '>') {
  8401. in_ssi_tag = 0;
  8402. buf[len++] = (char)ch;
  8403. buf[len] = '\0';
  8404. /* assert(len <= (int) sizeof(buf)); */
  8405. if (len > (int)sizeof(buf)) {
  8406. break;
  8407. }
  8408. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  8409. /* Not an SSI tag, pass it */
  8410. (void)mg_write(conn, buf, (size_t)len);
  8411. } else {
  8412. if (!memcmp(buf + 5, "include", 7)) {
  8413. do_ssi_include(conn, path, buf + 12, include_level);
  8414. #if !defined(NO_POPEN)
  8415. } else if (!memcmp(buf + 5, "exec", 4)) {
  8416. do_ssi_exec(conn, buf + 9);
  8417. #endif /* !NO_POPEN */
  8418. } else {
  8419. mg_cry(conn,
  8420. "%s: unknown SSI "
  8421. "command: \"%s\"",
  8422. path,
  8423. buf);
  8424. }
  8425. }
  8426. len = 0;
  8427. } else if (in_ssi_tag) {
  8428. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8429. /* Not an SSI tag */
  8430. in_ssi_tag = 0;
  8431. } else if (len == (int)sizeof(buf) - 2) {
  8432. mg_cry(conn, "%s: SSI tag is too large", path);
  8433. len = 0;
  8434. }
  8435. buf[len++] = (char)(ch & 0xff);
  8436. } else if (ch == '<') {
  8437. in_ssi_tag = 1;
  8438. if (len > 0) {
  8439. mg_write(conn, buf, (size_t)len);
  8440. }
  8441. len = 0;
  8442. buf[len++] = (char)(ch & 0xff);
  8443. } else {
  8444. buf[len++] = (char)(ch & 0xff);
  8445. if (len == (int)sizeof(buf)) {
  8446. mg_write(conn, buf, (size_t)len);
  8447. len = 0;
  8448. }
  8449. }
  8450. }
  8451. /* Send the rest of buffered data */
  8452. if (len > 0) {
  8453. mg_write(conn, buf, (size_t)len);
  8454. }
  8455. }
  8456. static void
  8457. handle_ssi_file_request(struct mg_connection *conn,
  8458. const char *path,
  8459. struct mg_file *filep)
  8460. {
  8461. char date[64];
  8462. time_t curtime = time(NULL);
  8463. const char *cors1, *cors2, *cors3;
  8464. if (conn == NULL || path == NULL || filep == NULL) {
  8465. return;
  8466. }
  8467. if (mg_get_header(conn, "Origin")) {
  8468. /* Cross-origin resource sharing (CORS). */
  8469. cors1 = "Access-Control-Allow-Origin: ";
  8470. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8471. cors3 = "\r\n";
  8472. } else {
  8473. cors1 = cors2 = cors3 = "";
  8474. }
  8475. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8476. /* File exists (precondition for calling this function),
  8477. * but can not be opened by the server. */
  8478. mg_send_http_error(conn,
  8479. 500,
  8480. "Error: Cannot read file\nfopen(%s): %s",
  8481. path,
  8482. strerror(ERRNO));
  8483. } else {
  8484. conn->must_close = 1;
  8485. gmt_time_string(date, sizeof(date), &curtime);
  8486. fclose_on_exec(&filep->access, conn);
  8487. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8488. send_no_cache_header(conn);
  8489. send_additional_header(conn);
  8490. mg_printf(conn,
  8491. "%s%s%s"
  8492. "Date: %s\r\n"
  8493. "Content-Type: text/html\r\n"
  8494. "Connection: %s\r\n\r\n",
  8495. cors1,
  8496. cors2,
  8497. cors3,
  8498. date,
  8499. suggest_connection_header(conn));
  8500. send_ssi_file(conn, path, filep, 0);
  8501. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8502. }
  8503. }
  8504. #if !defined(NO_FILES)
  8505. static void
  8506. send_options(struct mg_connection *conn)
  8507. {
  8508. char date[64];
  8509. time_t curtime = time(NULL);
  8510. if (!conn) {
  8511. return;
  8512. }
  8513. conn->status_code = 200;
  8514. conn->must_close = 1;
  8515. gmt_time_string(date, sizeof(date), &curtime);
  8516. /* We do not set a "Cache-Control" header here, but leave the default.
  8517. * Since browsers do not send an OPTIONS request, we can not test the
  8518. * effect anyway. */
  8519. mg_printf(conn,
  8520. "HTTP/1.1 200 OK\r\n"
  8521. "Date: %s\r\n"
  8522. "Connection: %s\r\n"
  8523. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8524. "PROPFIND, MKCOL\r\n"
  8525. "DAV: 1\r\n",
  8526. date,
  8527. suggest_connection_header(conn));
  8528. send_additional_header(conn);
  8529. mg_printf(conn, "\r\n");
  8530. }
  8531. /* Writes PROPFIND properties for a collection element */
  8532. static void
  8533. print_props(struct mg_connection *conn,
  8534. const char *uri,
  8535. struct mg_file_stat *filep)
  8536. {
  8537. char mtime[64];
  8538. if (conn == NULL || uri == NULL || filep == NULL) {
  8539. return;
  8540. }
  8541. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8542. mg_printf(conn,
  8543. "<d:response>"
  8544. "<d:href>%s</d:href>"
  8545. "<d:propstat>"
  8546. "<d:prop>"
  8547. "<d:resourcetype>%s</d:resourcetype>"
  8548. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8549. "<d:getlastmodified>%s</d:getlastmodified>"
  8550. "</d:prop>"
  8551. "<d:status>HTTP/1.1 200 OK</d:status>"
  8552. "</d:propstat>"
  8553. "</d:response>\n",
  8554. uri,
  8555. filep->is_directory ? "<d:collection/>" : "",
  8556. filep->size,
  8557. mtime);
  8558. }
  8559. static void
  8560. print_dav_dir_entry(struct de *de, void *data)
  8561. {
  8562. char href[PATH_MAX];
  8563. char href_encoded[PATH_MAX * 3 /* worst case */];
  8564. int truncated;
  8565. struct mg_connection *conn = (struct mg_connection *)data;
  8566. if (!de || !conn) {
  8567. return;
  8568. }
  8569. mg_snprintf(conn,
  8570. &truncated,
  8571. href,
  8572. sizeof(href),
  8573. "%s%s",
  8574. conn->request_info.local_uri,
  8575. de->file_name);
  8576. if (!truncated) {
  8577. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8578. print_props(conn, href_encoded, &de->file);
  8579. }
  8580. }
  8581. static void
  8582. handle_propfind(struct mg_connection *conn,
  8583. const char *path,
  8584. struct mg_file_stat *filep)
  8585. {
  8586. const char *depth = mg_get_header(conn, "Depth");
  8587. char date[64];
  8588. time_t curtime = time(NULL);
  8589. gmt_time_string(date, sizeof(date), &curtime);
  8590. if (!conn || !path || !filep || !conn->ctx) {
  8591. return;
  8592. }
  8593. conn->must_close = 1;
  8594. conn->status_code = 207;
  8595. mg_printf(conn,
  8596. "HTTP/1.1 207 Multi-Status\r\n"
  8597. "Date: %s\r\n",
  8598. date);
  8599. send_static_cache_header(conn);
  8600. send_additional_header(conn);
  8601. mg_printf(conn,
  8602. "Connection: %s\r\n"
  8603. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8604. suggest_connection_header(conn));
  8605. mg_printf(conn,
  8606. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8607. "<d:multistatus xmlns:d='DAV:'>\n");
  8608. /* Print properties for the requested resource itself */
  8609. print_props(conn, conn->request_info.local_uri, filep);
  8610. /* If it is a directory, print directory entries too if Depth is not 0 */
  8611. if (filep && filep->is_directory
  8612. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8613. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8614. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8615. }
  8616. mg_printf(conn, "%s\n", "</d:multistatus>");
  8617. }
  8618. #endif
  8619. void
  8620. mg_lock_connection(struct mg_connection *conn)
  8621. {
  8622. if (conn) {
  8623. (void)pthread_mutex_lock(&conn->mutex);
  8624. }
  8625. }
  8626. void
  8627. mg_unlock_connection(struct mg_connection *conn)
  8628. {
  8629. if (conn) {
  8630. (void)pthread_mutex_unlock(&conn->mutex);
  8631. }
  8632. }
  8633. void
  8634. mg_lock_context(struct mg_context *ctx)
  8635. {
  8636. if (ctx) {
  8637. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8638. }
  8639. }
  8640. void
  8641. mg_unlock_context(struct mg_context *ctx)
  8642. {
  8643. if (ctx) {
  8644. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8645. }
  8646. }
  8647. #if defined(USE_TIMERS)
  8648. #define TIMER_API static
  8649. #include "timer.inl"
  8650. #endif /* USE_TIMERS */
  8651. #ifdef USE_LUA
  8652. #include "mod_lua.inl"
  8653. #endif /* USE_LUA */
  8654. #ifdef USE_DUKTAPE
  8655. #include "mod_duktape.inl"
  8656. #endif /* USE_DUKTAPE */
  8657. #if defined(USE_WEBSOCKET)
  8658. #if !defined(NO_SSL_DL)
  8659. #define SHA_API static
  8660. #include "sha1.inl"
  8661. #endif
  8662. static int
  8663. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8664. {
  8665. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8666. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8667. SHA_CTX sha_ctx;
  8668. int truncated;
  8669. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8670. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8671. if (truncated) {
  8672. conn->must_close = 1;
  8673. return 0;
  8674. }
  8675. SHA1_Init(&sha_ctx);
  8676. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8677. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8678. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8679. mg_printf(conn,
  8680. "HTTP/1.1 101 Switching Protocols\r\n"
  8681. "Upgrade: websocket\r\n"
  8682. "Connection: Upgrade\r\n"
  8683. "Sec-WebSocket-Accept: %s\r\n",
  8684. b64_sha);
  8685. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8686. mg_printf(conn,
  8687. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8688. conn->request_info.acceptedWebSocketSubprotocol);
  8689. } else {
  8690. mg_printf(conn, "%s", "\r\n");
  8691. }
  8692. return 1;
  8693. }
  8694. static void
  8695. read_websocket(struct mg_connection *conn,
  8696. mg_websocket_data_handler ws_data_handler,
  8697. void *callback_data)
  8698. {
  8699. /* Pointer to the beginning of the portion of the incoming websocket
  8700. * message queue.
  8701. * The original websocket upgrade request is never removed, so the queue
  8702. * begins after it. */
  8703. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8704. int n, error, exit_by_callback;
  8705. /* body_len is the length of the entire queue in bytes
  8706. * len is the length of the current message
  8707. * data_len is the length of the current message's data payload
  8708. * header_len is the length of the current message's header */
  8709. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8710. /* "The masking key is a 32-bit value chosen at random by the client."
  8711. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8712. */
  8713. unsigned char mask[4];
  8714. /* data points to the place where the message is stored when passed to
  8715. * the
  8716. * websocket_data callback. This is either mem on the stack, or a
  8717. * dynamically allocated buffer if it is too large. */
  8718. unsigned char mem[4096];
  8719. unsigned char *data = mem;
  8720. unsigned char mop; /* mask flag and opcode */
  8721. double timeout = -1.0;
  8722. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8723. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8724. }
  8725. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8726. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8727. }
  8728. mg_set_thread_name("wsock");
  8729. /* Loop continuously, reading messages from the socket, invoking the
  8730. * callback, and waiting repeatedly until an error occurs. */
  8731. while (!conn->ctx->stop_flag) {
  8732. header_len = 0;
  8733. assert(conn->data_len >= conn->request_len);
  8734. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8735. len = buf[1] & 127;
  8736. mask_len = (buf[1] & 128) ? 4 : 0;
  8737. if ((len < 126) && (body_len >= mask_len)) {
  8738. /* inline 7-bit length field */
  8739. data_len = len;
  8740. header_len = 2 + mask_len;
  8741. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8742. /* 16-bit length field */
  8743. header_len = 4 + mask_len;
  8744. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8745. } else if (body_len >= (10 + mask_len)) {
  8746. /* 64-bit length field */
  8747. uint32_t l1, l2;
  8748. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  8749. memcpy(&l2, &buf[6], 4);
  8750. header_len = 10 + mask_len;
  8751. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  8752. }
  8753. }
  8754. if (header_len > 0 && body_len >= header_len) {
  8755. /* Allocate space to hold websocket payload */
  8756. data = mem;
  8757. if (data_len > sizeof(mem)) {
  8758. data = (unsigned char *)mg_malloc_ctx(data_len, conn->ctx);
  8759. if (data == NULL) {
  8760. /* Allocation failed, exit the loop and then close the
  8761. * connection */
  8762. mg_cry(conn, "websocket out of memory; closing connection");
  8763. break;
  8764. }
  8765. }
  8766. /* Copy the mask before we shift the queue and destroy it */
  8767. if (mask_len > 0) {
  8768. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8769. } else {
  8770. memset(mask, 0, sizeof(mask));
  8771. }
  8772. /* Read frame payload from the first message in the queue into
  8773. * data and advance the queue by moving the memory in place. */
  8774. assert(body_len >= header_len);
  8775. if (data_len + header_len > body_len) {
  8776. mop = buf[0]; /* current mask and opcode */
  8777. /* Overflow case */
  8778. len = body_len - header_len;
  8779. memcpy(data, buf + header_len, len);
  8780. error = 0;
  8781. while (len < data_len) {
  8782. n = pull_inner(NULL,
  8783. conn,
  8784. (char *)(data + len),
  8785. (int)(data_len - len),
  8786. timeout);
  8787. if (n <= -2) {
  8788. error = 1;
  8789. break;
  8790. } else if (n > 0) {
  8791. len += (size_t)n;
  8792. } else {
  8793. /* Timeout: should retry */
  8794. /* TODO: retry condition */
  8795. }
  8796. }
  8797. if (error) {
  8798. mg_cry(conn, "Websocket pull failed; closing connection");
  8799. break;
  8800. }
  8801. conn->data_len = conn->request_len;
  8802. } else {
  8803. mop = buf[0]; /* current mask and opcode, overwritten by
  8804. * memmove() */
  8805. /* Length of the message being read at the front of the
  8806. * queue */
  8807. len = data_len + header_len;
  8808. /* Copy the data payload into the data pointer for the
  8809. * callback */
  8810. memcpy(data, buf + header_len, data_len);
  8811. /* Move the queue forward len bytes */
  8812. memmove(buf, buf + len, body_len - len);
  8813. /* Mark the queue as advanced */
  8814. conn->data_len -= (int)len;
  8815. }
  8816. /* Apply mask if necessary */
  8817. if (mask_len > 0) {
  8818. for (i = 0; i < data_len; ++i) {
  8819. data[i] ^= mask[i & 3];
  8820. }
  8821. }
  8822. /* Exit the loop if callback signals to exit (server side),
  8823. * or "connection close" opcode received (client side). */
  8824. exit_by_callback = 0;
  8825. if ((ws_data_handler != NULL)
  8826. && !ws_data_handler(
  8827. conn, mop, (char *)data, data_len, callback_data)) {
  8828. exit_by_callback = 1;
  8829. }
  8830. if (data != mem) {
  8831. mg_free(data);
  8832. }
  8833. if (exit_by_callback
  8834. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8835. /* Opcode == 8, connection close */
  8836. break;
  8837. }
  8838. /* Not breaking the loop, process next websocket frame. */
  8839. } else {
  8840. /* Read from the socket into the next available location in the
  8841. * message queue. */
  8842. n = pull_inner(NULL,
  8843. conn,
  8844. conn->buf + conn->data_len,
  8845. conn->buf_size - conn->data_len,
  8846. timeout);
  8847. if (n <= -2) {
  8848. /* Error, no bytes read */
  8849. break;
  8850. }
  8851. if (n > 0) {
  8852. conn->data_len += n;
  8853. } else {
  8854. /* Timeout: should retry */
  8855. /* TODO: get timeout def */
  8856. }
  8857. }
  8858. }
  8859. mg_set_thread_name("worker");
  8860. }
  8861. static int
  8862. mg_websocket_write_exec(struct mg_connection *conn,
  8863. int opcode,
  8864. const char *data,
  8865. size_t dataLen,
  8866. uint32_t masking_key)
  8867. {
  8868. unsigned char header[14];
  8869. size_t headerLen = 1;
  8870. int retval = -1;
  8871. #if defined(__GNUC__) || defined(__MINGW32__)
  8872. /* Disable spurious conversion warning for GCC */
  8873. #pragma GCC diagnostic push
  8874. #pragma GCC diagnostic ignored "-Wconversion"
  8875. #endif
  8876. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8877. #if defined(__GNUC__) || defined(__MINGW32__)
  8878. #pragma GCC diagnostic pop
  8879. #endif
  8880. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8881. if (dataLen < 126) {
  8882. /* inline 7-bit length field */
  8883. header[1] = (unsigned char)dataLen;
  8884. headerLen = 2;
  8885. } else if (dataLen <= 0xFFFF) {
  8886. /* 16-bit length field */
  8887. uint16_t len = htons((uint16_t)dataLen);
  8888. header[1] = 126;
  8889. memcpy(header + 2, &len, 2);
  8890. headerLen = 4;
  8891. } else {
  8892. /* 64-bit length field */
  8893. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8894. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8895. header[1] = 127;
  8896. memcpy(header + 2, &len1, 4);
  8897. memcpy(header + 6, &len2, 4);
  8898. headerLen = 10;
  8899. }
  8900. if (masking_key) {
  8901. /* add mask */
  8902. header[1] |= 0x80;
  8903. memcpy(header + headerLen, &masking_key, 4);
  8904. headerLen += 4;
  8905. }
  8906. /* Note that POSIX/Winsock's send() is threadsafe
  8907. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8908. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8909. * push(), although that is only a problem if the packet is large or
  8910. * outgoing buffer is full). */
  8911. /* TODO: Check if this lock should be moved to user land.
  8912. * Currently the server sets this lock for websockets, but
  8913. * not for any other connection. It must be set for every
  8914. * conn read/written by more than one thread, no matter if
  8915. * it is a websocket or regular connection. */
  8916. (void)mg_lock_connection(conn);
  8917. retval = mg_write(conn, header, headerLen);
  8918. if (dataLen > 0) {
  8919. retval = mg_write(conn, data, dataLen);
  8920. }
  8921. /* TODO: Remove this unlock as well, when lock is moved. */
  8922. mg_unlock_connection(conn);
  8923. return retval;
  8924. }
  8925. int
  8926. mg_websocket_write(struct mg_connection *conn,
  8927. int opcode,
  8928. const char *data,
  8929. size_t dataLen)
  8930. {
  8931. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8932. }
  8933. static void
  8934. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8935. {
  8936. size_t i = 0;
  8937. i = 0;
  8938. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8939. /* Convert in 32 bit words, if data is 4 byte aligned */
  8940. while (i < (in_len - 3)) {
  8941. *(uint32_t *)(void *)(out + i) =
  8942. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8943. i += 4;
  8944. }
  8945. }
  8946. if (i != in_len) {
  8947. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8948. while (i < in_len) {
  8949. *(uint8_t *)(void *)(out + i) =
  8950. *(uint8_t *)(void *)(in + i)
  8951. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8952. i++;
  8953. }
  8954. }
  8955. }
  8956. int
  8957. mg_websocket_client_write(struct mg_connection *conn,
  8958. int opcode,
  8959. const char *data,
  8960. size_t dataLen)
  8961. {
  8962. int retval = -1;
  8963. char *masked_data =
  8964. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  8965. uint32_t masking_key = (uint32_t)get_random();
  8966. if (masked_data == NULL) {
  8967. /* Return -1 in an error case */
  8968. mg_cry(conn,
  8969. "Cannot allocate buffer for masked websocket response: "
  8970. "Out of memory");
  8971. return -1;
  8972. }
  8973. mask_data(data, dataLen, masking_key, masked_data);
  8974. retval = mg_websocket_write_exec(
  8975. conn, opcode, masked_data, dataLen, masking_key);
  8976. mg_free(masked_data);
  8977. return retval;
  8978. }
  8979. static void
  8980. handle_websocket_request(struct mg_connection *conn,
  8981. const char *path,
  8982. int is_callback_resource,
  8983. struct mg_websocket_subprotocols *subprotocols,
  8984. mg_websocket_connect_handler ws_connect_handler,
  8985. mg_websocket_ready_handler ws_ready_handler,
  8986. mg_websocket_data_handler ws_data_handler,
  8987. mg_websocket_close_handler ws_close_handler,
  8988. void *cbData)
  8989. {
  8990. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8991. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8992. int lua_websock = 0;
  8993. #if !defined(USE_LUA)
  8994. (void)path;
  8995. #endif
  8996. /* Step 1: Check websocket protocol version. */
  8997. /* Step 1.1: Check Sec-WebSocket-Key. */
  8998. if (!websock_key) {
  8999. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  9000. * requires a Sec-WebSocket-Key header.
  9001. */
  9002. /* It could be the hixie draft version
  9003. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  9004. */
  9005. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  9006. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  9007. char key3[8];
  9008. if ((key1 != NULL) && (key2 != NULL)) {
  9009. /* This version uses 8 byte body data in a GET request */
  9010. conn->content_len = 8;
  9011. if (8 == mg_read(conn, key3, 8)) {
  9012. /* This is the hixie version */
  9013. mg_send_http_error(conn,
  9014. 426,
  9015. "%s",
  9016. "Protocol upgrade to RFC 6455 required");
  9017. return;
  9018. }
  9019. }
  9020. /* This is an unknown version */
  9021. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  9022. return;
  9023. }
  9024. /* Step 1.2: Check websocket protocol version. */
  9025. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  9026. if (version == NULL || strcmp(version, "13") != 0) {
  9027. /* Reject wrong versions */
  9028. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  9029. return;
  9030. }
  9031. /* Step 1.3: Could check for "Host", but we do not really nead this
  9032. * value for anything, so just ignore it. */
  9033. /* Step 2: If a callback is responsible, call it. */
  9034. if (is_callback_resource) {
  9035. /* Step 2.1 check and select subprotocol */
  9036. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  9037. if (protocol && subprotocols) {
  9038. int idx;
  9039. unsigned long len;
  9040. const char *sep, *curSubProtocol,
  9041. *acceptedWebSocketSubprotocol = NULL;
  9042. /* look for matching subprotocol */
  9043. do {
  9044. sep = strchr(protocol, ',');
  9045. curSubProtocol = protocol;
  9046. len = sep ? (unsigned long)(sep - protocol)
  9047. : (unsigned long)strlen(protocol);
  9048. while (sep && isspace(*++sep)) {
  9049. ; /* ignore leading whitespaces */
  9050. }
  9051. protocol = sep;
  9052. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  9053. if ((strlen(subprotocols->subprotocols[idx]) == len)
  9054. && (strncmp(curSubProtocol,
  9055. subprotocols->subprotocols[idx],
  9056. len) == 0)) {
  9057. acceptedWebSocketSubprotocol =
  9058. subprotocols->subprotocols[idx];
  9059. break;
  9060. }
  9061. }
  9062. } while (sep && !acceptedWebSocketSubprotocol);
  9063. conn->request_info.acceptedWebSocketSubprotocol =
  9064. acceptedWebSocketSubprotocol;
  9065. } else if (protocol) {
  9066. /* keep legacy behavior */
  9067. /* The protocol is a comma seperated list of names. */
  9068. /* The server must only return one value from this list. */
  9069. /* First check if it is a list or just a single value. */
  9070. const char *sep = strrchr(protocol, ',');
  9071. if (sep == NULL) {
  9072. /* Just a single protocol -> accept it. */
  9073. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  9074. } else {
  9075. /* Multiple protocols -> accept the last one. */
  9076. /* This is just a quick fix if the client offers multiple
  9077. * protocols. The handler should have a list of accepted
  9078. * protocols on his own
  9079. * and use it to select one protocol among those the client has
  9080. * offered.
  9081. */
  9082. while (isspace(*++sep)) {
  9083. ; /* ignore leading whitespaces */
  9084. }
  9085. conn->request_info.acceptedWebSocketSubprotocol = sep;
  9086. }
  9087. }
  9088. if (ws_connect_handler != NULL
  9089. && ws_connect_handler(conn, cbData) != 0) {
  9090. /* C callback has returned non-zero, do not proceed with
  9091. * handshake.
  9092. */
  9093. /* Note that C callbacks are no longer called when Lua is
  9094. * responsible, so C can no longer filter callbacks for Lua. */
  9095. return;
  9096. }
  9097. }
  9098. #if defined(USE_LUA)
  9099. /* Step 3: No callback. Check if Lua is responsible. */
  9100. else {
  9101. /* Step 3.1: Check if Lua is responsible. */
  9102. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  9103. lua_websock =
  9104. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  9105. strlen(
  9106. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  9107. path);
  9108. }
  9109. if (lua_websock) {
  9110. /* Step 3.2: Lua is responsible: call it. */
  9111. conn->lua_websocket_state = lua_websocket_new(path, conn);
  9112. if (!conn->lua_websocket_state) {
  9113. /* Lua rejected the new client */
  9114. return;
  9115. }
  9116. }
  9117. }
  9118. #endif
  9119. /* Step 4: Check if there is a responsible websocket handler. */
  9120. if (!is_callback_resource && !lua_websock) {
  9121. /* There is no callback, and Lua is not responsible either. */
  9122. /* Reply with a 404 Not Found. We are still at a standard
  9123. * HTTP request here, before the websocket handshake, so
  9124. * we can still send standard HTTP error replies. */
  9125. mg_send_http_error(conn, 404, "%s", "Not found");
  9126. return;
  9127. }
  9128. /* Step 5: The websocket connection has been accepted */
  9129. if (!send_websocket_handshake(conn, websock_key)) {
  9130. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  9131. return;
  9132. }
  9133. /* Step 6: Call the ready handler */
  9134. if (is_callback_resource) {
  9135. if (ws_ready_handler != NULL) {
  9136. ws_ready_handler(conn, cbData);
  9137. }
  9138. #if defined(USE_LUA)
  9139. } else if (lua_websock) {
  9140. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9141. /* the ready handler returned false */
  9142. return;
  9143. }
  9144. #endif
  9145. }
  9146. /* Step 7: Enter the read loop */
  9147. if (is_callback_resource) {
  9148. read_websocket(conn, ws_data_handler, cbData);
  9149. #if defined(USE_LUA)
  9150. } else if (lua_websock) {
  9151. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9152. #endif
  9153. }
  9154. /* Step 8: Call the close handler */
  9155. if (ws_close_handler) {
  9156. ws_close_handler(conn, cbData);
  9157. }
  9158. }
  9159. static int
  9160. is_websocket_protocol(const struct mg_connection *conn)
  9161. {
  9162. const char *upgrade, *connection;
  9163. /* A websocket protocoll has the following HTTP headers:
  9164. *
  9165. * Connection: Upgrade
  9166. * Upgrade: Websocket
  9167. */
  9168. upgrade = mg_get_header(conn, "Upgrade");
  9169. if (upgrade == NULL) {
  9170. return 0; /* fail early, don't waste time checking other header
  9171. * fields
  9172. */
  9173. }
  9174. if (!mg_strcasestr(upgrade, "websocket")) {
  9175. return 0;
  9176. }
  9177. connection = mg_get_header(conn, "Connection");
  9178. if (connection == NULL) {
  9179. return 0;
  9180. }
  9181. if (!mg_strcasestr(connection, "upgrade")) {
  9182. return 0;
  9183. }
  9184. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9185. * "Sec-WebSocket-Version" are also required.
  9186. * Don't check them here, since even an unsupported websocket protocol
  9187. * request still IS a websocket request (in contrast to a standard HTTP
  9188. * request). It will fail later in handle_websocket_request.
  9189. */
  9190. return 1;
  9191. }
  9192. #endif /* !USE_WEBSOCKET */
  9193. static int
  9194. isbyte(int n)
  9195. {
  9196. return n >= 0 && n <= 255;
  9197. }
  9198. static int
  9199. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9200. {
  9201. int n, a, b, c, d, slash = 32, len = 0;
  9202. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  9203. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  9204. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  9205. && slash < 33) {
  9206. len = n;
  9207. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9208. | (uint32_t)d;
  9209. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9210. }
  9211. return len;
  9212. }
  9213. static int
  9214. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9215. {
  9216. int throttle = 0;
  9217. struct vec vec, val;
  9218. uint32_t net, mask;
  9219. char mult;
  9220. double v;
  9221. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9222. mult = ',';
  9223. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9224. || (v < 0) || ((lowercase(&mult) != 'k')
  9225. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9226. continue;
  9227. }
  9228. v *= (lowercase(&mult) == 'k')
  9229. ? 1024
  9230. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9231. if (vec.len == 1 && vec.ptr[0] == '*') {
  9232. throttle = (int)v;
  9233. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9234. if ((remote_ip & mask) == net) {
  9235. throttle = (int)v;
  9236. }
  9237. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9238. throttle = (int)v;
  9239. }
  9240. }
  9241. return throttle;
  9242. }
  9243. static uint32_t
  9244. get_remote_ip(const struct mg_connection *conn)
  9245. {
  9246. if (!conn) {
  9247. return 0;
  9248. }
  9249. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9250. }
  9251. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9252. #include "handle_form.inl"
  9253. #if defined(MG_LEGACY_INTERFACE)
  9254. /* Implement the deprecated mg_upload function by calling the new
  9255. * mg_handle_form_request function. While mg_upload could only handle
  9256. * HTML forms sent as POST request in multipart/form-data format
  9257. * containing only file input elements, mg_handle_form_request can
  9258. * handle all form input elements and all standard request methods. */
  9259. struct mg_upload_user_data {
  9260. struct mg_connection *conn;
  9261. const char *destination_dir;
  9262. int num_uploaded_files;
  9263. };
  9264. /* Helper function for deprecated mg_upload. */
  9265. static int
  9266. mg_upload_field_found(const char *key,
  9267. const char *filename,
  9268. char *path,
  9269. size_t pathlen,
  9270. void *user_data)
  9271. {
  9272. int truncated = 0;
  9273. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9274. (void)key;
  9275. if (!filename) {
  9276. mg_cry(fud->conn, "%s: No filename set", __func__);
  9277. return FORM_FIELD_STORAGE_ABORT;
  9278. }
  9279. mg_snprintf(fud->conn,
  9280. &truncated,
  9281. path,
  9282. pathlen - 1,
  9283. "%s/%s",
  9284. fud->destination_dir,
  9285. filename);
  9286. if (!truncated) {
  9287. mg_cry(fud->conn, "%s: File path too long", __func__);
  9288. return FORM_FIELD_STORAGE_ABORT;
  9289. }
  9290. return FORM_FIELD_STORAGE_STORE;
  9291. }
  9292. /* Helper function for deprecated mg_upload. */
  9293. static int
  9294. mg_upload_field_get(const char *key,
  9295. const char *value,
  9296. size_t value_size,
  9297. void *user_data)
  9298. {
  9299. /* Function should never be called */
  9300. (void)key;
  9301. (void)value;
  9302. (void)value_size;
  9303. (void)user_data;
  9304. return 0;
  9305. }
  9306. /* Helper function for deprecated mg_upload. */
  9307. static int
  9308. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9309. {
  9310. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9311. (void)file_size;
  9312. fud->num_uploaded_files++;
  9313. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9314. return 0;
  9315. }
  9316. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9317. int
  9318. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9319. {
  9320. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9321. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9322. mg_upload_field_get,
  9323. mg_upload_field_stored,
  9324. 0};
  9325. int ret;
  9326. fdh.user_data = (void *)&fud;
  9327. ret = mg_handle_form_request(conn, &fdh);
  9328. if (ret < 0) {
  9329. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9330. }
  9331. return fud.num_uploaded_files;
  9332. }
  9333. #endif
  9334. static int
  9335. get_first_ssl_listener_index(const struct mg_context *ctx)
  9336. {
  9337. unsigned int i;
  9338. int idx = -1;
  9339. if (ctx) {
  9340. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  9341. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9342. }
  9343. }
  9344. return idx;
  9345. }
  9346. static void
  9347. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9348. {
  9349. char host[1025];
  9350. const char *host_header;
  9351. size_t hostlen;
  9352. host_header = mg_get_header(conn, "Host");
  9353. hostlen = sizeof(host);
  9354. if (host_header != NULL) {
  9355. char *pos;
  9356. mg_strlcpy(host, host_header, hostlen);
  9357. host[hostlen - 1] = '\0';
  9358. pos = strchr(host, ':');
  9359. if (pos != NULL) {
  9360. *pos = '\0';
  9361. }
  9362. } else {
  9363. /* Cannot get host from the Host: header.
  9364. * Fallback to our IP address. */
  9365. if (conn) {
  9366. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9367. }
  9368. }
  9369. /* Send host, port, uri and (if it exists) ?query_string */
  9370. if (conn) {
  9371. mg_printf(conn,
  9372. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9373. host,
  9374. #if defined(USE_IPV6)
  9375. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9376. == AF_INET6)
  9377. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9378. .lsa.sin6.sin6_port)
  9379. :
  9380. #endif
  9381. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9382. .lsa.sin.sin_port),
  9383. conn->request_info.local_uri,
  9384. (conn->request_info.query_string == NULL) ? "" : "?",
  9385. (conn->request_info.query_string == NULL)
  9386. ? ""
  9387. : conn->request_info.query_string);
  9388. }
  9389. }
  9390. static void
  9391. mg_set_handler_type(struct mg_context *ctx,
  9392. const char *uri,
  9393. int handler_type,
  9394. int is_delete_request,
  9395. mg_request_handler handler,
  9396. struct mg_websocket_subprotocols *subprotocols,
  9397. mg_websocket_connect_handler connect_handler,
  9398. mg_websocket_ready_handler ready_handler,
  9399. mg_websocket_data_handler data_handler,
  9400. mg_websocket_close_handler close_handler,
  9401. mg_authorization_handler auth_handler,
  9402. void *cbdata)
  9403. {
  9404. struct mg_handler_info *tmp_rh, **lastref;
  9405. size_t urilen = strlen(uri);
  9406. if (handler_type == WEBSOCKET_HANDLER) {
  9407. /* assert(handler == NULL); */
  9408. /* assert(is_delete_request || connect_handler!=NULL ||
  9409. * ready_handler!=NULL || data_handler!=NULL ||
  9410. * close_handler!=NULL);
  9411. */
  9412. /* assert(auth_handler == NULL); */
  9413. if (handler != NULL) {
  9414. return;
  9415. }
  9416. if (!is_delete_request && connect_handler == NULL
  9417. && ready_handler == NULL
  9418. && data_handler == NULL
  9419. && close_handler == NULL) {
  9420. return;
  9421. }
  9422. if (auth_handler != NULL) {
  9423. return;
  9424. }
  9425. } else if (handler_type == REQUEST_HANDLER) {
  9426. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9427. * data_handler==NULL && close_handler==NULL); */
  9428. /* assert(is_delete_request || (handler!=NULL));
  9429. */
  9430. /* assert(auth_handler == NULL); */
  9431. if (connect_handler != NULL || ready_handler != NULL
  9432. || data_handler != NULL
  9433. || close_handler != NULL) {
  9434. return;
  9435. }
  9436. if (!is_delete_request && (handler == NULL)) {
  9437. return;
  9438. }
  9439. if (auth_handler != NULL) {
  9440. return;
  9441. }
  9442. } else { /* AUTH_HANDLER */
  9443. /* assert(handler == NULL); */
  9444. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9445. * data_handler==NULL && close_handler==NULL); */
  9446. /* assert(auth_handler != NULL); */
  9447. if (handler != NULL) {
  9448. return;
  9449. }
  9450. if (connect_handler != NULL || ready_handler != NULL
  9451. || data_handler != NULL
  9452. || close_handler != NULL) {
  9453. return;
  9454. }
  9455. if (!is_delete_request && (auth_handler == NULL)) {
  9456. return;
  9457. }
  9458. }
  9459. if (!ctx) {
  9460. return;
  9461. }
  9462. mg_lock_context(ctx);
  9463. /* first try to find an existing handler */
  9464. lastref = &(ctx->handlers);
  9465. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9466. if (tmp_rh->handler_type == handler_type) {
  9467. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9468. if (!is_delete_request) {
  9469. /* update existing handler */
  9470. if (handler_type == REQUEST_HANDLER) {
  9471. tmp_rh->handler = handler;
  9472. } else if (handler_type == WEBSOCKET_HANDLER) {
  9473. tmp_rh->subprotocols = subprotocols;
  9474. tmp_rh->connect_handler = connect_handler;
  9475. tmp_rh->ready_handler = ready_handler;
  9476. tmp_rh->data_handler = data_handler;
  9477. tmp_rh->close_handler = close_handler;
  9478. } else { /* AUTH_HANDLER */
  9479. tmp_rh->auth_handler = auth_handler;
  9480. }
  9481. tmp_rh->cbdata = cbdata;
  9482. } else {
  9483. /* remove existing handler */
  9484. *lastref = tmp_rh->next;
  9485. mg_free(tmp_rh->uri);
  9486. mg_free(tmp_rh);
  9487. }
  9488. mg_unlock_context(ctx);
  9489. return;
  9490. }
  9491. }
  9492. lastref = &(tmp_rh->next);
  9493. }
  9494. if (is_delete_request) {
  9495. /* no handler to set, this was a remove request to a non-existing
  9496. * handler */
  9497. mg_unlock_context(ctx);
  9498. return;
  9499. }
  9500. tmp_rh =
  9501. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  9502. 1,
  9503. ctx);
  9504. if (tmp_rh == NULL) {
  9505. mg_unlock_context(ctx);
  9506. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9507. return;
  9508. }
  9509. tmp_rh->uri = mg_strdup(uri);
  9510. if (!tmp_rh->uri) {
  9511. mg_unlock_context(ctx);
  9512. mg_free(tmp_rh);
  9513. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9514. return;
  9515. }
  9516. tmp_rh->uri_len = urilen;
  9517. if (handler_type == REQUEST_HANDLER) {
  9518. tmp_rh->handler = handler;
  9519. } else if (handler_type == WEBSOCKET_HANDLER) {
  9520. tmp_rh->subprotocols = subprotocols;
  9521. tmp_rh->connect_handler = connect_handler;
  9522. tmp_rh->ready_handler = ready_handler;
  9523. tmp_rh->data_handler = data_handler;
  9524. tmp_rh->close_handler = close_handler;
  9525. } else { /* AUTH_HANDLER */
  9526. tmp_rh->auth_handler = auth_handler;
  9527. }
  9528. tmp_rh->cbdata = cbdata;
  9529. tmp_rh->handler_type = handler_type;
  9530. tmp_rh->next = NULL;
  9531. *lastref = tmp_rh;
  9532. mg_unlock_context(ctx);
  9533. }
  9534. void
  9535. mg_set_request_handler(struct mg_context *ctx,
  9536. const char *uri,
  9537. mg_request_handler handler,
  9538. void *cbdata)
  9539. {
  9540. mg_set_handler_type(ctx,
  9541. uri,
  9542. REQUEST_HANDLER,
  9543. handler == NULL,
  9544. handler,
  9545. NULL,
  9546. NULL,
  9547. NULL,
  9548. NULL,
  9549. NULL,
  9550. NULL,
  9551. cbdata);
  9552. }
  9553. void
  9554. mg_set_websocket_handler(struct mg_context *ctx,
  9555. const char *uri,
  9556. mg_websocket_connect_handler connect_handler,
  9557. mg_websocket_ready_handler ready_handler,
  9558. mg_websocket_data_handler data_handler,
  9559. mg_websocket_close_handler close_handler,
  9560. void *cbdata)
  9561. {
  9562. mg_set_websocket_handler_with_subprotocols(ctx,
  9563. uri,
  9564. NULL,
  9565. connect_handler,
  9566. ready_handler,
  9567. data_handler,
  9568. close_handler,
  9569. cbdata);
  9570. }
  9571. void
  9572. mg_set_websocket_handler_with_subprotocols(
  9573. struct mg_context *ctx,
  9574. const char *uri,
  9575. struct mg_websocket_subprotocols *subprotocols,
  9576. mg_websocket_connect_handler connect_handler,
  9577. mg_websocket_ready_handler ready_handler,
  9578. mg_websocket_data_handler data_handler,
  9579. mg_websocket_close_handler close_handler,
  9580. void *cbdata)
  9581. {
  9582. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9583. && (data_handler == NULL)
  9584. && (close_handler == NULL);
  9585. mg_set_handler_type(ctx,
  9586. uri,
  9587. WEBSOCKET_HANDLER,
  9588. is_delete_request,
  9589. NULL,
  9590. subprotocols,
  9591. connect_handler,
  9592. ready_handler,
  9593. data_handler,
  9594. close_handler,
  9595. NULL,
  9596. cbdata);
  9597. }
  9598. void
  9599. mg_set_auth_handler(struct mg_context *ctx,
  9600. const char *uri,
  9601. mg_request_handler handler,
  9602. void *cbdata)
  9603. {
  9604. mg_set_handler_type(ctx,
  9605. uri,
  9606. AUTH_HANDLER,
  9607. handler == NULL,
  9608. NULL,
  9609. NULL,
  9610. NULL,
  9611. NULL,
  9612. NULL,
  9613. NULL,
  9614. handler,
  9615. cbdata);
  9616. }
  9617. static int
  9618. get_request_handler(struct mg_connection *conn,
  9619. int handler_type,
  9620. mg_request_handler *handler,
  9621. struct mg_websocket_subprotocols **subprotocols,
  9622. mg_websocket_connect_handler *connect_handler,
  9623. mg_websocket_ready_handler *ready_handler,
  9624. mg_websocket_data_handler *data_handler,
  9625. mg_websocket_close_handler *close_handler,
  9626. mg_authorization_handler *auth_handler,
  9627. void **cbdata)
  9628. {
  9629. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9630. if (request_info) {
  9631. const char *uri = request_info->local_uri;
  9632. size_t urilen = strlen(uri);
  9633. struct mg_handler_info *tmp_rh;
  9634. if (!conn || !conn->ctx) {
  9635. return 0;
  9636. }
  9637. mg_lock_context(conn->ctx);
  9638. /* first try for an exact match */
  9639. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9640. tmp_rh = tmp_rh->next) {
  9641. if (tmp_rh->handler_type == handler_type) {
  9642. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9643. if (handler_type == WEBSOCKET_HANDLER) {
  9644. *subprotocols = tmp_rh->subprotocols;
  9645. *connect_handler = tmp_rh->connect_handler;
  9646. *ready_handler = tmp_rh->ready_handler;
  9647. *data_handler = tmp_rh->data_handler;
  9648. *close_handler = tmp_rh->close_handler;
  9649. } else if (handler_type == REQUEST_HANDLER) {
  9650. *handler = tmp_rh->handler;
  9651. } else { /* AUTH_HANDLER */
  9652. *auth_handler = tmp_rh->auth_handler;
  9653. }
  9654. *cbdata = tmp_rh->cbdata;
  9655. mg_unlock_context(conn->ctx);
  9656. return 1;
  9657. }
  9658. }
  9659. }
  9660. /* next try for a partial match, we will accept uri/something */
  9661. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9662. tmp_rh = tmp_rh->next) {
  9663. if (tmp_rh->handler_type == handler_type) {
  9664. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9665. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9666. if (handler_type == WEBSOCKET_HANDLER) {
  9667. *subprotocols = tmp_rh->subprotocols;
  9668. *connect_handler = tmp_rh->connect_handler;
  9669. *ready_handler = tmp_rh->ready_handler;
  9670. *data_handler = tmp_rh->data_handler;
  9671. *close_handler = tmp_rh->close_handler;
  9672. } else if (handler_type == REQUEST_HANDLER) {
  9673. *handler = tmp_rh->handler;
  9674. } else { /* AUTH_HANDLER */
  9675. *auth_handler = tmp_rh->auth_handler;
  9676. }
  9677. *cbdata = tmp_rh->cbdata;
  9678. mg_unlock_context(conn->ctx);
  9679. return 1;
  9680. }
  9681. }
  9682. }
  9683. /* finally try for pattern match */
  9684. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9685. tmp_rh = tmp_rh->next) {
  9686. if (tmp_rh->handler_type == handler_type) {
  9687. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9688. if (handler_type == WEBSOCKET_HANDLER) {
  9689. *subprotocols = tmp_rh->subprotocols;
  9690. *connect_handler = tmp_rh->connect_handler;
  9691. *ready_handler = tmp_rh->ready_handler;
  9692. *data_handler = tmp_rh->data_handler;
  9693. *close_handler = tmp_rh->close_handler;
  9694. } else if (handler_type == REQUEST_HANDLER) {
  9695. *handler = tmp_rh->handler;
  9696. } else { /* AUTH_HANDLER */
  9697. *auth_handler = tmp_rh->auth_handler;
  9698. }
  9699. *cbdata = tmp_rh->cbdata;
  9700. mg_unlock_context(conn->ctx);
  9701. return 1;
  9702. }
  9703. }
  9704. }
  9705. mg_unlock_context(conn->ctx);
  9706. }
  9707. return 0; /* none found */
  9708. }
  9709. /* Check if the script file is in a path, allowed for script files.
  9710. * This can be used if uploading files is possible not only for the server
  9711. * admin, and the upload mechanism does not check the file extension.
  9712. */
  9713. static int
  9714. is_in_script_path(const struct mg_connection *conn, const char *path)
  9715. {
  9716. /* TODO (Feature): Add config value for allowed script path.
  9717. * Default: All allowed. */
  9718. (void)conn;
  9719. (void)path;
  9720. return 1;
  9721. }
  9722. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9723. static int
  9724. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9725. void *cbdata)
  9726. {
  9727. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9728. if (pcallbacks->websocket_connect) {
  9729. return pcallbacks->websocket_connect(conn);
  9730. }
  9731. /* No handler set - assume "OK" */
  9732. return 0;
  9733. }
  9734. static void
  9735. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9736. {
  9737. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9738. if (pcallbacks->websocket_ready) {
  9739. pcallbacks->websocket_ready(conn);
  9740. }
  9741. }
  9742. static int
  9743. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9744. int bits,
  9745. char *data,
  9746. size_t len,
  9747. void *cbdata)
  9748. {
  9749. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9750. if (pcallbacks->websocket_data) {
  9751. return pcallbacks->websocket_data(conn, bits, data, len);
  9752. }
  9753. /* No handler set - assume "OK" */
  9754. return 1;
  9755. }
  9756. #endif
  9757. /* This is the heart of the Civetweb's logic.
  9758. * This function is called when the request is read, parsed and validated,
  9759. * and Civetweb must decide what action to take: serve a file, or
  9760. * a directory, or call embedded function, etcetera. */
  9761. static void
  9762. handle_request(struct mg_connection *conn)
  9763. {
  9764. struct mg_request_info *ri = &conn->request_info;
  9765. char path[PATH_MAX];
  9766. int uri_len, ssl_index;
  9767. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9768. is_put_or_delete_request = 0, is_callback_resource = 0;
  9769. int i;
  9770. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9771. mg_request_handler callback_handler = NULL;
  9772. struct mg_websocket_subprotocols *subprotocols;
  9773. mg_websocket_connect_handler ws_connect_handler = NULL;
  9774. mg_websocket_ready_handler ws_ready_handler = NULL;
  9775. mg_websocket_data_handler ws_data_handler = NULL;
  9776. mg_websocket_close_handler ws_close_handler = NULL;
  9777. void *callback_data = NULL;
  9778. mg_authorization_handler auth_handler = NULL;
  9779. void *auth_callback_data = NULL;
  9780. #if !defined(NO_FILES)
  9781. time_t curtime = time(NULL);
  9782. char date[64];
  9783. #endif
  9784. path[0] = 0;
  9785. /* 1. get the request url */
  9786. /* 1.1. split into url and query string */
  9787. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9788. != NULL) {
  9789. *((char *)conn->request_info.query_string++) = '\0';
  9790. }
  9791. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9792. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9793. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9794. if (ssl_index >= 0) {
  9795. redirect_to_https_port(conn, ssl_index);
  9796. } else {
  9797. /* A http to https forward port has been specified,
  9798. * but no https port to forward to. */
  9799. mg_send_http_error(conn,
  9800. 503,
  9801. "%s",
  9802. "Error: SSL forward not configured properly");
  9803. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9804. }
  9805. return;
  9806. }
  9807. uri_len = (int)strlen(ri->local_uri);
  9808. /* 1.3. decode url (if config says so) */
  9809. if (should_decode_url(conn)) {
  9810. mg_url_decode(
  9811. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9812. }
  9813. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9814. * not possible */
  9815. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9816. /* step 1. completed, the url is known now */
  9817. uri_len = (int)strlen(ri->local_uri);
  9818. DEBUG_TRACE("URL: %s", ri->local_uri);
  9819. /* 3. if this ip has limited speed, set it for this connection */
  9820. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9821. get_remote_ip(conn),
  9822. ri->local_uri);
  9823. /* 4. call a "handle everything" callback, if registered */
  9824. if (conn->ctx->callbacks.begin_request != NULL) {
  9825. /* Note that since V1.7 the "begin_request" function is called
  9826. * before an authorization check. If an authorization check is
  9827. * required, use a request_handler instead. */
  9828. i = conn->ctx->callbacks.begin_request(conn);
  9829. if (i > 0) {
  9830. /* callback already processed the request. Store the
  9831. return value as a status code for the access log. */
  9832. conn->status_code = i;
  9833. discard_unread_request_data(conn);
  9834. return;
  9835. } else if (i == 0) {
  9836. /* civetweb should process the request */
  9837. } else {
  9838. /* unspecified - may change with the next version */
  9839. return;
  9840. }
  9841. }
  9842. /* request not yet handled by a handler or redirect, so the request
  9843. * is processed here */
  9844. /* 5. interpret the url to find out how the request must be handled
  9845. */
  9846. /* 5.1. first test, if the request targets the regular http(s)://
  9847. * protocol namespace or the websocket ws(s):// protocol namespace.
  9848. */
  9849. is_websocket_request = is_websocket_protocol(conn);
  9850. /* 5.2. check if the request will be handled by a callback */
  9851. if (get_request_handler(conn,
  9852. is_websocket_request ? WEBSOCKET_HANDLER
  9853. : REQUEST_HANDLER,
  9854. &callback_handler,
  9855. &subprotocols,
  9856. &ws_connect_handler,
  9857. &ws_ready_handler,
  9858. &ws_data_handler,
  9859. &ws_close_handler,
  9860. NULL,
  9861. &callback_data)) {
  9862. /* 5.2.1. A callback will handle this request. All requests
  9863. * handled
  9864. * by a callback have to be considered as requests to a script
  9865. * resource. */
  9866. is_callback_resource = 1;
  9867. is_script_resource = 1;
  9868. is_put_or_delete_request = is_put_or_delete_method(conn);
  9869. } else {
  9870. no_callback_resource:
  9871. /* 5.2.2. No callback is responsible for this request. The URI
  9872. * addresses a file based resource (static content or Lua/cgi
  9873. * scripts in the file system). */
  9874. is_callback_resource = 0;
  9875. interpret_uri(conn,
  9876. path,
  9877. sizeof(path),
  9878. &file.stat,
  9879. &is_found,
  9880. &is_script_resource,
  9881. &is_websocket_request,
  9882. &is_put_or_delete_request);
  9883. }
  9884. /* 6. authorization check */
  9885. /* 6.1. a custom authorization handler is installed */
  9886. if (get_request_handler(conn,
  9887. AUTH_HANDLER,
  9888. NULL,
  9889. NULL,
  9890. NULL,
  9891. NULL,
  9892. NULL,
  9893. NULL,
  9894. &auth_handler,
  9895. &auth_callback_data)) {
  9896. if (!auth_handler(conn, auth_callback_data)) {
  9897. return;
  9898. }
  9899. } else if (is_put_or_delete_request && !is_script_resource
  9900. && !is_callback_resource) {
  9901. /* 6.2. this request is a PUT/DELETE to a real file */
  9902. /* 6.2.1. thus, the server must have real files */
  9903. #if defined(NO_FILES)
  9904. if (1) {
  9905. #else
  9906. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9907. #endif
  9908. /* This server does not have any real files, thus the
  9909. * PUT/DELETE methods are not valid. */
  9910. mg_send_http_error(conn,
  9911. 405,
  9912. "%s method not allowed",
  9913. conn->request_info.request_method);
  9914. return;
  9915. }
  9916. #if !defined(NO_FILES)
  9917. /* 6.2.2. Check if put authorization for static files is
  9918. * available.
  9919. */
  9920. if (!is_authorized_for_put(conn)) {
  9921. send_authorization_request(conn);
  9922. return;
  9923. }
  9924. #endif
  9925. } else {
  9926. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9927. * or it is a PUT or DELETE request to a resource that does not
  9928. * correspond to a file. Check authorization. */
  9929. if (!check_authorization(conn, path)) {
  9930. send_authorization_request(conn);
  9931. return;
  9932. }
  9933. }
  9934. /* request is authorized or does not need authorization */
  9935. /* 7. check if there are request handlers for this uri */
  9936. if (is_callback_resource) {
  9937. if (!is_websocket_request) {
  9938. i = callback_handler(conn, callback_data);
  9939. if (i > 0) {
  9940. /* Do nothing, callback has served the request. Store
  9941. * then return value as status code for the log and discard
  9942. * all data from the client not used by the callback. */
  9943. conn->status_code = i;
  9944. discard_unread_request_data(conn);
  9945. } else {
  9946. /* The handler did NOT handle the request. */
  9947. /* Some proper reactions would be:
  9948. * a) close the connections without sending anything
  9949. * b) send a 404 not found
  9950. * c) try if there is a file matching the URI
  9951. * It would be possible to do a, b or c in the callback
  9952. * implementation, and return 1 - we cannot do anything
  9953. * here, that is not possible in the callback.
  9954. *
  9955. * TODO: What would be the best reaction here?
  9956. * (Note: The reaction may change, if there is a better idea.)
  9957. */
  9958. /* For the moment, use option c: We look for a proper file,
  9959. * but since a file request is not always a script resource,
  9960. * the authorization check might be different. */
  9961. interpret_uri(conn,
  9962. path,
  9963. sizeof(path),
  9964. &file.stat,
  9965. &is_found,
  9966. &is_script_resource,
  9967. &is_websocket_request,
  9968. &is_put_or_delete_request);
  9969. callback_handler = NULL;
  9970. /* Here we are at a dead end:
  9971. * According to URI matching, a callback should be
  9972. * responsible for handling the request,
  9973. * we called it, but the callback declared itself
  9974. * not responsible.
  9975. * We use a goto here, to get out of this dead end,
  9976. * and continue with the default handling.
  9977. * A goto here is simpler and better to understand
  9978. * than some curious loop. */
  9979. goto no_callback_resource;
  9980. }
  9981. } else {
  9982. #if defined(USE_WEBSOCKET)
  9983. handle_websocket_request(conn,
  9984. path,
  9985. is_callback_resource,
  9986. subprotocols,
  9987. ws_connect_handler,
  9988. ws_ready_handler,
  9989. ws_data_handler,
  9990. ws_close_handler,
  9991. callback_data);
  9992. #endif
  9993. }
  9994. return;
  9995. }
  9996. /* 8. handle websocket requests */
  9997. #if defined(USE_WEBSOCKET)
  9998. if (is_websocket_request) {
  9999. if (is_script_resource) {
  10000. if (is_in_script_path(conn, path)) {
  10001. /* Websocket Lua script */
  10002. handle_websocket_request(conn,
  10003. path,
  10004. 0 /* Lua Script */,
  10005. NULL,
  10006. NULL,
  10007. NULL,
  10008. NULL,
  10009. NULL,
  10010. &conn->ctx->callbacks);
  10011. } else {
  10012. /* Script was in an illegal path */
  10013. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10014. }
  10015. } else {
  10016. #if defined(MG_LEGACY_INTERFACE)
  10017. handle_websocket_request(
  10018. conn,
  10019. path,
  10020. !is_script_resource /* could be deprecated global callback */,
  10021. NULL,
  10022. deprecated_websocket_connect_wrapper,
  10023. deprecated_websocket_ready_wrapper,
  10024. deprecated_websocket_data_wrapper,
  10025. NULL,
  10026. &conn->ctx->callbacks);
  10027. #else
  10028. mg_send_http_error(conn, 404, "%s", "Not found");
  10029. #endif
  10030. }
  10031. return;
  10032. } else
  10033. #endif
  10034. #if defined(NO_FILES)
  10035. /* 9a. In case the server uses only callbacks, this uri is
  10036. * unknown.
  10037. * Then, all request handling ends here. */
  10038. mg_send_http_error(conn, 404, "%s", "Not Found");
  10039. #else
  10040. /* 9b. This request is either for a static file or resource handled
  10041. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  10042. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10043. mg_send_http_error(conn, 404, "%s", "Not Found");
  10044. return;
  10045. }
  10046. /* 10. Request is handled by a script */
  10047. if (is_script_resource) {
  10048. handle_file_based_request(conn, path, &file);
  10049. return;
  10050. }
  10051. /* 11. Handle put/delete/mkcol requests */
  10052. if (is_put_or_delete_request) {
  10053. /* 11.1. PUT method */
  10054. if (!strcmp(ri->request_method, "PUT")) {
  10055. put_file(conn, path);
  10056. return;
  10057. }
  10058. /* 11.2. DELETE method */
  10059. if (!strcmp(ri->request_method, "DELETE")) {
  10060. delete_file(conn, path);
  10061. return;
  10062. }
  10063. /* 11.3. MKCOL method */
  10064. if (!strcmp(ri->request_method, "MKCOL")) {
  10065. mkcol(conn, path);
  10066. return;
  10067. }
  10068. /* 11.4. PATCH method
  10069. * This method is not supported for static resources,
  10070. * only for scripts (Lua, CGI) and callbacks. */
  10071. mg_send_http_error(conn,
  10072. 405,
  10073. "%s method not allowed",
  10074. conn->request_info.request_method);
  10075. return;
  10076. }
  10077. /* 11. File does not exist, or it was configured that it should be
  10078. * hidden */
  10079. if (!is_found || (must_hide_file(conn, path))) {
  10080. mg_send_http_error(conn, 404, "%s", "Not found");
  10081. return;
  10082. }
  10083. /* 12. Directory uris should end with a slash */
  10084. if (file.stat.is_directory && (uri_len > 0)
  10085. && (ri->local_uri[uri_len - 1] != '/')) {
  10086. gmt_time_string(date, sizeof(date), &curtime);
  10087. mg_printf(conn,
  10088. "HTTP/1.1 301 Moved Permanently\r\n"
  10089. "Location: %s/\r\n"
  10090. "Date: %s\r\n"
  10091. /* "Cache-Control: private\r\n" (= default) */
  10092. "Content-Length: 0\r\n"
  10093. "Connection: %s\r\n",
  10094. ri->request_uri,
  10095. date,
  10096. suggest_connection_header(conn));
  10097. send_additional_header(conn);
  10098. mg_printf(conn, "\r\n");
  10099. return;
  10100. }
  10101. /* 13. Handle other methods than GET/HEAD */
  10102. /* 13.1. Handle PROPFIND */
  10103. if (!strcmp(ri->request_method, "PROPFIND")) {
  10104. handle_propfind(conn, path, &file.stat);
  10105. return;
  10106. }
  10107. /* 13.2. Handle OPTIONS for files */
  10108. if (!strcmp(ri->request_method, "OPTIONS")) {
  10109. /* This standard handler is only used for real files.
  10110. * Scripts should support the OPTIONS method themselves, to allow a
  10111. * maximum flexibility.
  10112. * Lua and CGI scripts may fully support CORS this way (including
  10113. * preflights). */
  10114. send_options(conn);
  10115. return;
  10116. }
  10117. /* 13.3. everything but GET and HEAD (e.g. POST) */
  10118. if (0 != strcmp(ri->request_method, "GET")
  10119. && 0 != strcmp(ri->request_method, "HEAD")) {
  10120. mg_send_http_error(conn,
  10121. 405,
  10122. "%s method not allowed",
  10123. conn->request_info.request_method);
  10124. return;
  10125. }
  10126. /* 14. directories */
  10127. if (file.stat.is_directory) {
  10128. /* Substitute files have already been handled above. */
  10129. /* Here we can either generate and send a directory listing,
  10130. * or send an "access denied" error. */
  10131. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  10132. "yes")) {
  10133. handle_directory_request(conn, path);
  10134. } else {
  10135. mg_send_http_error(conn,
  10136. 403,
  10137. "%s",
  10138. "Error: Directory listing denied");
  10139. }
  10140. return;
  10141. }
  10142. handle_file_based_request(conn, path, &file);
  10143. #endif /* !defined(NO_FILES) */
  10144. #if 0
  10145. /* Perform redirect and auth checks before calling begin_request()
  10146. * handler.
  10147. * Otherwise, begin_request() would need to perform auth checks and
  10148. * redirects. */
  10149. #endif
  10150. }
  10151. static void
  10152. handle_file_based_request(struct mg_connection *conn,
  10153. const char *path,
  10154. struct mg_file *file)
  10155. {
  10156. if (!conn || !conn->ctx) {
  10157. return;
  10158. }
  10159. if (0) {
  10160. #ifdef USE_LUA
  10161. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10162. strlen(
  10163. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10164. path) > 0) {
  10165. if (is_in_script_path(conn, path)) {
  10166. /* Lua server page: an SSI like page containing mostly plain html
  10167. * code
  10168. * plus some tags with server generated contents. */
  10169. handle_lsp_request(conn, path, file, NULL);
  10170. } else {
  10171. /* Script was in an illegal path */
  10172. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10173. }
  10174. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10175. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10176. path) > 0) {
  10177. if (is_in_script_path(conn, path)) {
  10178. /* Lua in-server module script: a CGI like script used to generate
  10179. * the
  10180. * entire reply. */
  10181. mg_exec_lua_script(conn, path, NULL);
  10182. } else {
  10183. /* Script was in an illegal path */
  10184. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10185. }
  10186. #endif
  10187. #if defined(USE_DUKTAPE)
  10188. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10189. strlen(
  10190. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10191. path) > 0) {
  10192. if (is_in_script_path(conn, path)) {
  10193. /* Call duktape to generate the page */
  10194. mg_exec_duktape_script(conn, path);
  10195. } else {
  10196. /* Script was in an illegal path */
  10197. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10198. }
  10199. #endif
  10200. #if !defined(NO_CGI)
  10201. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10202. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10203. path) > 0) {
  10204. if (is_in_script_path(conn, path)) {
  10205. /* CGI scripts may support all HTTP methods */
  10206. handle_cgi_request(conn, path);
  10207. } else {
  10208. /* Script was in an illegal path */
  10209. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10210. }
  10211. #endif /* !NO_CGI */
  10212. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10213. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10214. path) > 0) {
  10215. if (is_in_script_path(conn, path)) {
  10216. handle_ssi_file_request(conn, path, file);
  10217. } else {
  10218. /* Script was in an illegal path */
  10219. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10220. }
  10221. #if !defined(NO_CACHING)
  10222. } else if ((!conn->in_error_handler)
  10223. && is_not_modified(conn, &file->stat)) {
  10224. /* Send 304 "Not Modified" - this must not send any body data */
  10225. handle_not_modified_static_file_request(conn, file);
  10226. #endif /* !NO_CACHING */
  10227. } else {
  10228. handle_static_file_request(conn, path, file, NULL, NULL);
  10229. }
  10230. }
  10231. static void
  10232. close_all_listening_sockets(struct mg_context *ctx)
  10233. {
  10234. unsigned int i;
  10235. if (!ctx) {
  10236. return;
  10237. }
  10238. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10239. closesocket(ctx->listening_sockets[i].sock);
  10240. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10241. }
  10242. mg_free(ctx->listening_sockets);
  10243. ctx->listening_sockets = NULL;
  10244. mg_free(ctx->listening_socket_fds);
  10245. ctx->listening_socket_fds = NULL;
  10246. }
  10247. /* Valid listening port specification is: [ip_address:]port[s]
  10248. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10249. * Examples for IPv6: [::]:80, [::1]:80,
  10250. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10251. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10252. * In order to bind to both, IPv4 and IPv6, you can either add
  10253. * both ports using 8080,[::]:8080, or the short form +8080.
  10254. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10255. * one only accepting IPv4 the other only IPv6. +8080 creates
  10256. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10257. * environment, they might work differently, or might not work
  10258. * at all - it must be tested what options work best in the
  10259. * relevant network environment.
  10260. */
  10261. static int
  10262. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10263. {
  10264. unsigned int a, b, c, d, port;
  10265. int ch, len;
  10266. #if defined(USE_IPV6)
  10267. char buf[100] = {0};
  10268. #endif
  10269. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10270. * Also, all-zeroes in the socket address means binding to all addresses
  10271. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10272. memset(so, 0, sizeof(*so));
  10273. so->lsa.sin.sin_family = AF_INET;
  10274. *ip_version = 0;
  10275. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10276. == 5) {
  10277. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10278. so->lsa.sin.sin_addr.s_addr =
  10279. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10280. so->lsa.sin.sin_port = htons((uint16_t)port);
  10281. *ip_version = 4;
  10282. #if defined(USE_IPV6)
  10283. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10284. && mg_inet_pton(
  10285. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10286. /* IPv6 address, examples: see above */
  10287. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10288. */
  10289. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10290. *ip_version = 6;
  10291. #endif
  10292. } else if ((vec->ptr[0] == '+')
  10293. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10294. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10295. /* Add 1 to len for the + character we skipped before */
  10296. len++;
  10297. #if defined(USE_IPV6)
  10298. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10299. so->lsa.sin6.sin6_family = AF_INET6;
  10300. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10301. *ip_version = 4 + 6;
  10302. #else
  10303. /* Bind to IPv4 only, since IPv6 is not built in. */
  10304. so->lsa.sin.sin_port = htons((uint16_t)port);
  10305. *ip_version = 4;
  10306. #endif
  10307. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10308. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10309. so->lsa.sin.sin_port = htons((uint16_t)port);
  10310. *ip_version = 4;
  10311. } else {
  10312. /* Parsing failure. Make port invalid. */
  10313. port = 0;
  10314. len = 0;
  10315. }
  10316. /* sscanf and the option splitting code ensure the following condition
  10317. */
  10318. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  10319. *ip_version = 0;
  10320. return 0;
  10321. }
  10322. ch = vec->ptr[len]; /* Next character after the port number */
  10323. so->is_ssl = (ch == 's');
  10324. so->ssl_redir = (ch == 'r');
  10325. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  10326. if (is_valid_port(port)
  10327. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  10328. return 1;
  10329. }
  10330. /* Reset ip_version to 0 of there is an error */
  10331. *ip_version = 0;
  10332. return 0;
  10333. }
  10334. static int
  10335. set_ports_option(struct mg_context *ctx)
  10336. {
  10337. const char *list;
  10338. int on = 1;
  10339. #if defined(USE_IPV6)
  10340. int off = 0;
  10341. #endif
  10342. struct vec vec;
  10343. struct socket so, *ptr;
  10344. struct pollfd *pfd;
  10345. union usa usa;
  10346. socklen_t len;
  10347. int ip_version;
  10348. int portsTotal = 0;
  10349. int portsOk = 0;
  10350. if (!ctx) {
  10351. return 0;
  10352. }
  10353. memset(&so, 0, sizeof(so));
  10354. memset(&usa, 0, sizeof(usa));
  10355. len = sizeof(usa);
  10356. list = ctx->config[LISTENING_PORTS];
  10357. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10358. portsTotal++;
  10359. if (!parse_port_string(&vec, &so, &ip_version)) {
  10360. mg_cry(fc(ctx),
  10361. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  10362. (int)vec.len,
  10363. vec.ptr,
  10364. portsTotal,
  10365. "[IP_ADDRESS:]PORT[s|r]");
  10366. continue;
  10367. }
  10368. #if !defined(NO_SSL)
  10369. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10370. mg_cry(fc(ctx),
  10371. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10372. "option set?",
  10373. portsTotal);
  10374. continue;
  10375. }
  10376. #endif
  10377. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10378. == INVALID_SOCKET) {
  10379. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10380. continue;
  10381. }
  10382. #ifdef _WIN32
  10383. /* Windows SO_REUSEADDR lets many procs binds to a
  10384. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10385. * if someone already has the socket -- DTL */
  10386. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10387. * Windows might need a few seconds before
  10388. * the same port can be used again in the
  10389. * same process, so a short Sleep may be
  10390. * required between mg_stop and mg_start.
  10391. */
  10392. if (setsockopt(so.sock,
  10393. SOL_SOCKET,
  10394. SO_EXCLUSIVEADDRUSE,
  10395. (SOCK_OPT_TYPE)&on,
  10396. sizeof(on)) != 0) {
  10397. /* Set reuse option, but don't abort on errors. */
  10398. mg_cry(fc(ctx),
  10399. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10400. portsTotal);
  10401. }
  10402. #else
  10403. if (setsockopt(so.sock,
  10404. SOL_SOCKET,
  10405. SO_REUSEADDR,
  10406. (SOCK_OPT_TYPE)&on,
  10407. sizeof(on)) != 0) {
  10408. /* Set reuse option, but don't abort on errors. */
  10409. mg_cry(fc(ctx),
  10410. "cannot set socket option SO_REUSEADDR (entry %i)",
  10411. portsTotal);
  10412. }
  10413. #endif
  10414. if (ip_version > 4) {
  10415. #if defined(USE_IPV6)
  10416. if (ip_version == 6) {
  10417. if (so.lsa.sa.sa_family == AF_INET6
  10418. && setsockopt(so.sock,
  10419. IPPROTO_IPV6,
  10420. IPV6_V6ONLY,
  10421. (void *)&off,
  10422. sizeof(off)) != 0) {
  10423. /* Set IPv6 only option, but don't abort on errors. */
  10424. mg_cry(fc(ctx),
  10425. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10426. portsTotal);
  10427. }
  10428. }
  10429. #else
  10430. mg_cry(fc(ctx), "IPv6 not available");
  10431. closesocket(so.sock);
  10432. so.sock = INVALID_SOCKET;
  10433. continue;
  10434. #endif
  10435. }
  10436. if (so.lsa.sa.sa_family == AF_INET) {
  10437. len = sizeof(so.lsa.sin);
  10438. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10439. mg_cry(fc(ctx),
  10440. "cannot bind to %.*s: %d (%s)",
  10441. (int)vec.len,
  10442. vec.ptr,
  10443. (int)ERRNO,
  10444. strerror(errno));
  10445. closesocket(so.sock);
  10446. so.sock = INVALID_SOCKET;
  10447. continue;
  10448. }
  10449. }
  10450. #if defined(USE_IPV6)
  10451. else if (so.lsa.sa.sa_family == AF_INET6) {
  10452. len = sizeof(so.lsa.sin6);
  10453. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10454. mg_cry(fc(ctx),
  10455. "cannot bind to IPv6 %.*s: %d (%s)",
  10456. (int)vec.len,
  10457. vec.ptr,
  10458. (int)ERRNO,
  10459. strerror(errno));
  10460. closesocket(so.sock);
  10461. so.sock = INVALID_SOCKET;
  10462. continue;
  10463. }
  10464. }
  10465. #endif
  10466. else {
  10467. mg_cry(fc(ctx),
  10468. "cannot bind: address family not supported (entry %i)",
  10469. portsTotal);
  10470. continue;
  10471. }
  10472. if (listen(so.sock, SOMAXCONN) != 0) {
  10473. mg_cry(fc(ctx),
  10474. "cannot listen to %.*s: %d (%s)",
  10475. (int)vec.len,
  10476. vec.ptr,
  10477. (int)ERRNO,
  10478. strerror(errno));
  10479. closesocket(so.sock);
  10480. so.sock = INVALID_SOCKET;
  10481. continue;
  10482. }
  10483. if (getsockname(so.sock, &(usa.sa), &len) != 0
  10484. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  10485. int err = (int)ERRNO;
  10486. mg_cry(fc(ctx),
  10487. "call to getsockname failed %.*s: %d (%s)",
  10488. (int)vec.len,
  10489. vec.ptr,
  10490. err,
  10491. strerror(errno));
  10492. closesocket(so.sock);
  10493. so.sock = INVALID_SOCKET;
  10494. continue;
  10495. }
  10496. /* Update lsa port in case of random free ports */
  10497. #if defined(USE_IPV6)
  10498. if (so.lsa.sa.sa_family == AF_INET6) {
  10499. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10500. } else
  10501. #endif
  10502. {
  10503. so.lsa.sin.sin_port = usa.sin.sin_port;
  10504. }
  10505. if ((ptr = (struct socket *)
  10506. mg_realloc_ctx(ctx->listening_sockets,
  10507. (ctx->num_listening_sockets + 1)
  10508. * sizeof(ctx->listening_sockets[0]),
  10509. ctx)) == NULL) {
  10510. mg_cry(fc(ctx), "%s", "Out of memory");
  10511. closesocket(so.sock);
  10512. so.sock = INVALID_SOCKET;
  10513. continue;
  10514. }
  10515. if ((pfd = (struct pollfd *)
  10516. mg_realloc_ctx(ctx->listening_socket_fds,
  10517. (ctx->num_listening_sockets + 1)
  10518. * sizeof(ctx->listening_socket_fds[0]),
  10519. ctx)) == NULL) {
  10520. mg_cry(fc(ctx), "%s", "Out of memory");
  10521. closesocket(so.sock);
  10522. so.sock = INVALID_SOCKET;
  10523. mg_free(ptr);
  10524. continue;
  10525. }
  10526. set_close_on_exec(so.sock, fc(ctx));
  10527. ctx->listening_sockets = ptr;
  10528. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10529. ctx->listening_socket_fds = pfd;
  10530. ctx->num_listening_sockets++;
  10531. portsOk++;
  10532. }
  10533. if (portsOk != portsTotal) {
  10534. close_all_listening_sockets(ctx);
  10535. portsOk = 0;
  10536. }
  10537. return portsOk;
  10538. }
  10539. static const char *
  10540. header_val(const struct mg_connection *conn, const char *header)
  10541. {
  10542. const char *header_value;
  10543. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10544. return "-";
  10545. } else {
  10546. return header_value;
  10547. }
  10548. }
  10549. static void
  10550. log_access(const struct mg_connection *conn)
  10551. {
  10552. const struct mg_request_info *ri;
  10553. struct mg_file fi;
  10554. char date[64], src_addr[IP_ADDR_STR_LEN];
  10555. struct tm *tm;
  10556. const char *referer;
  10557. const char *user_agent;
  10558. char buf[4096];
  10559. if (!conn || !conn->ctx) {
  10560. return;
  10561. }
  10562. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10563. if (mg_fopen(conn,
  10564. conn->ctx->config[ACCESS_LOG_FILE],
  10565. MG_FOPEN_MODE_APPEND,
  10566. &fi) == 0) {
  10567. fi.access.fp = NULL;
  10568. }
  10569. } else {
  10570. fi.access.fp = NULL;
  10571. }
  10572. /* Log is written to a file and/or a callback. If both are not set,
  10573. * executing the rest of the function is pointless. */
  10574. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10575. return;
  10576. }
  10577. tm = localtime(&conn->conn_birth_time);
  10578. if (tm != NULL) {
  10579. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10580. } else {
  10581. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10582. date[sizeof(date) - 1] = '\0';
  10583. }
  10584. ri = &conn->request_info;
  10585. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10586. referer = header_val(conn, "Referer");
  10587. user_agent = header_val(conn, "User-Agent");
  10588. mg_snprintf(conn,
  10589. NULL, /* Ignore truncation in access log */
  10590. buf,
  10591. sizeof(buf),
  10592. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10593. src_addr,
  10594. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10595. date,
  10596. ri->request_method ? ri->request_method : "-",
  10597. ri->request_uri ? ri->request_uri : "-",
  10598. ri->query_string ? "?" : "",
  10599. ri->query_string ? ri->query_string : "",
  10600. ri->http_version,
  10601. conn->status_code,
  10602. conn->num_bytes_sent,
  10603. referer,
  10604. user_agent);
  10605. if (conn->ctx->callbacks.log_access) {
  10606. conn->ctx->callbacks.log_access(conn, buf);
  10607. }
  10608. if (fi.access.fp) {
  10609. int ok = 1;
  10610. flockfile(fi.access.fp);
  10611. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10612. ok = 0;
  10613. }
  10614. if (fflush(fi.access.fp) != 0) {
  10615. ok = 0;
  10616. }
  10617. funlockfile(fi.access.fp);
  10618. if (mg_fclose(&fi.access) != 0) {
  10619. ok = 0;
  10620. }
  10621. if (!ok) {
  10622. mg_cry(conn,
  10623. "Error writing log file %s",
  10624. conn->ctx->config[ACCESS_LOG_FILE]);
  10625. }
  10626. }
  10627. }
  10628. /* Verify given socket address against the ACL.
  10629. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10630. */
  10631. static int
  10632. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10633. {
  10634. int allowed, flag;
  10635. uint32_t net, mask;
  10636. struct vec vec;
  10637. if (ctx) {
  10638. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10639. /* If any ACL is set, deny by default */
  10640. allowed = (list == NULL) ? '+' : '-';
  10641. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10642. flag = vec.ptr[0];
  10643. if ((flag != '+' && flag != '-')
  10644. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10645. mg_cry(fc(ctx),
  10646. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10647. __func__);
  10648. return -1;
  10649. }
  10650. if (net == (remote_ip & mask)) {
  10651. allowed = flag;
  10652. }
  10653. }
  10654. return allowed == '+';
  10655. }
  10656. return -1;
  10657. }
  10658. #if !defined(_WIN32)
  10659. static int
  10660. set_uid_option(struct mg_context *ctx)
  10661. {
  10662. struct passwd *pw;
  10663. if (ctx) {
  10664. const char *uid = ctx->config[RUN_AS_USER];
  10665. int success = 0;
  10666. if (uid == NULL) {
  10667. success = 1;
  10668. } else {
  10669. if ((pw = getpwnam(uid)) == NULL) {
  10670. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10671. } else if (setgid(pw->pw_gid) == -1) {
  10672. mg_cry(fc(ctx),
  10673. "%s: setgid(%s): %s",
  10674. __func__,
  10675. uid,
  10676. strerror(errno));
  10677. } else if (setgroups(0, NULL)) {
  10678. mg_cry(fc(ctx),
  10679. "%s: setgroups(): %s",
  10680. __func__,
  10681. strerror(errno));
  10682. } else if (setuid(pw->pw_uid) == -1) {
  10683. mg_cry(fc(ctx),
  10684. "%s: setuid(%s): %s",
  10685. __func__,
  10686. uid,
  10687. strerror(errno));
  10688. } else {
  10689. success = 1;
  10690. }
  10691. }
  10692. return success;
  10693. }
  10694. return 0;
  10695. }
  10696. #endif /* !_WIN32 */
  10697. static void
  10698. tls_dtor(void *key)
  10699. {
  10700. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10701. /* key == pthread_getspecific(sTlsKey); */
  10702. if (tls) {
  10703. if (tls->is_master == 2) {
  10704. tls->is_master = -3; /* Mark memory as dead */
  10705. mg_free(tls);
  10706. }
  10707. }
  10708. pthread_setspecific(sTlsKey, NULL);
  10709. }
  10710. #if !defined(NO_SSL)
  10711. static int
  10712. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  10713. static const char *ssl_error(void);
  10714. static int
  10715. refresh_trust(struct mg_connection *conn)
  10716. {
  10717. static int reload_lock = 0;
  10718. static long int data_check = 0;
  10719. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10720. struct stat cert_buf;
  10721. long int t;
  10722. const char *pem;
  10723. const char *chain;
  10724. int should_verify_peer;
  10725. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10726. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10727. * refresh_trust still can not work. */
  10728. return 0;
  10729. }
  10730. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  10731. if (chain == NULL) {
  10732. chain = pem;
  10733. }
  10734. if ((chain != NULL) && (*chain == 0)) {
  10735. chain = NULL;
  10736. }
  10737. t = data_check;
  10738. if (stat(pem, &cert_buf) != -1) {
  10739. t = (long int)cert_buf.st_mtime;
  10740. }
  10741. if (data_check != t) {
  10742. data_check = t;
  10743. should_verify_peer = 0;
  10744. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  10745. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10746. == 0) {
  10747. should_verify_peer = 1;
  10748. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  10749. "optional") == 0) {
  10750. should_verify_peer = 1;
  10751. }
  10752. }
  10753. if (should_verify_peer) {
  10754. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10755. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10756. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10757. ca_file,
  10758. ca_path) != 1) {
  10759. mg_cry(fc(conn->ctx),
  10760. "SSL_CTX_load_verify_locations error: %s "
  10761. "ssl_verify_peer requires setting "
  10762. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10763. "present in "
  10764. "the .conf file?",
  10765. ssl_error());
  10766. return 0;
  10767. }
  10768. }
  10769. if (1 == mg_atomic_inc(p_reload_lock)) {
  10770. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  10771. return 0;
  10772. }
  10773. *p_reload_lock = 0;
  10774. }
  10775. }
  10776. /* lock while cert is reloading */
  10777. while (*p_reload_lock) {
  10778. sleep(1);
  10779. }
  10780. return 1;
  10781. }
  10782. #ifdef OPENSSL_API_1_1
  10783. #else
  10784. static pthread_mutex_t *ssl_mutexes;
  10785. #endif /* OPENSSL_API_1_1 */
  10786. static int
  10787. sslize(struct mg_connection *conn,
  10788. SSL_CTX *s,
  10789. int (*func)(SSL *),
  10790. volatile int *stop_server)
  10791. {
  10792. int ret, err;
  10793. int short_trust;
  10794. unsigned i;
  10795. if (!conn) {
  10796. return 0;
  10797. }
  10798. short_trust =
  10799. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10800. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10801. if (short_trust) {
  10802. int trust_ret = refresh_trust(conn);
  10803. if (!trust_ret) {
  10804. return trust_ret;
  10805. }
  10806. }
  10807. conn->ssl = SSL_new(s);
  10808. if (conn->ssl == NULL) {
  10809. return 0;
  10810. }
  10811. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10812. if (ret != 1) {
  10813. err = SSL_get_error(conn->ssl, ret);
  10814. (void)err; /* TODO: set some error message */
  10815. SSL_free(conn->ssl);
  10816. conn->ssl = NULL;
  10817. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10818. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10819. #ifndef OPENSSL_API_1_1
  10820. ERR_remove_state(0);
  10821. #endif
  10822. return 0;
  10823. }
  10824. /* SSL functions may fail and require to be called again:
  10825. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10826. * Here "func" could be SSL_connect or SSL_accept. */
  10827. for (i = 16; i <= 1024; i *= 2) {
  10828. ret = func(conn->ssl);
  10829. if (ret != 1) {
  10830. err = SSL_get_error(conn->ssl, ret);
  10831. if ((err == SSL_ERROR_WANT_CONNECT)
  10832. || (err == SSL_ERROR_WANT_ACCEPT)
  10833. || (err == SSL_ERROR_WANT_READ)
  10834. || (err == SSL_ERROR_WANT_WRITE)) {
  10835. /* Need to retry the function call "later".
  10836. * See https://linux.die.net/man/3/ssl_get_error
  10837. * This is typical for non-blocking sockets. */
  10838. if (*stop_server) {
  10839. /* Don't wait if the server is going to be stopped. */
  10840. break;
  10841. }
  10842. mg_sleep(i);
  10843. } else if (err == SSL_ERROR_SYSCALL) {
  10844. /* This is an IO error. Look at errno. */
  10845. err = errno;
  10846. /* TODO: set some error message */
  10847. (void)err;
  10848. break;
  10849. } else {
  10850. /* This is an SSL specific error */
  10851. /* TODO: set some error message */
  10852. break;
  10853. }
  10854. } else {
  10855. /* success */
  10856. break;
  10857. }
  10858. }
  10859. if (ret != 1) {
  10860. SSL_free(conn->ssl);
  10861. conn->ssl = NULL;
  10862. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10863. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10864. #ifndef OPENSSL_API_1_1
  10865. ERR_remove_state(0);
  10866. #endif
  10867. return 0;
  10868. }
  10869. return 1;
  10870. }
  10871. /* Return OpenSSL error message (from CRYPTO lib) */
  10872. static const char *
  10873. ssl_error(void)
  10874. {
  10875. unsigned long err;
  10876. err = ERR_get_error();
  10877. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10878. }
  10879. static int
  10880. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10881. {
  10882. int i;
  10883. const char hexdigit[] = "0123456789abcdef";
  10884. if (memlen <= 0 || buflen <= 0) {
  10885. return 0;
  10886. }
  10887. if (buflen < (3 * memlen)) {
  10888. return 0;
  10889. }
  10890. for (i = 0; i < memlen; i++) {
  10891. if (i > 0) {
  10892. buf[3 * i - 1] = ' ';
  10893. }
  10894. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10895. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10896. }
  10897. buf[3 * memlen - 1] = 0;
  10898. return 1;
  10899. }
  10900. static void
  10901. ssl_get_client_cert_info(struct mg_connection *conn)
  10902. {
  10903. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10904. if (cert) {
  10905. char str_subject[1024];
  10906. char str_issuer[1024];
  10907. char str_finger[1024];
  10908. unsigned char buf[256];
  10909. char *str_serial = NULL;
  10910. unsigned int ulen;
  10911. int ilen;
  10912. unsigned char *tmp_buf;
  10913. unsigned char *tmp_p;
  10914. /* Handle to algorithm used for fingerprint */
  10915. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10916. /* Get Subject and issuer */
  10917. X509_NAME *subj = X509_get_subject_name(cert);
  10918. X509_NAME *iss = X509_get_issuer_name(cert);
  10919. /* Get serial number */
  10920. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10921. /* Translate serial number to a hex string */
  10922. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10923. str_serial = BN_bn2hex(serial_bn);
  10924. BN_free(serial_bn);
  10925. /* Translate subject and issuer to a string */
  10926. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10927. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10928. /* Calculate SHA1 fingerprint and store as a hex string */
  10929. ulen = 0;
  10930. /* ASN1_digest is deprecated. Do the calculation manually,
  10931. * using EVP_Digest. */
  10932. ilen = i2d_X509((void *)cert, NULL);
  10933. tmp_buf =
  10934. (ilen > 0)
  10935. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  10936. : NULL;
  10937. if (tmp_buf) {
  10938. tmp_p = tmp_buf;
  10939. (void)i2d_X509((void *)cert, &tmp_p);
  10940. if (!EVP_Digest(
  10941. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  10942. ulen = 0;
  10943. }
  10944. mg_free(tmp_buf);
  10945. }
  10946. if (!hexdump2string(
  10947. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10948. *str_finger = 0;
  10949. }
  10950. conn->request_info.client_cert =
  10951. (struct client_cert *)mg_malloc_ctx(sizeof(struct client_cert),
  10952. conn->ctx);
  10953. if (conn->request_info.client_cert) {
  10954. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10955. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10956. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10957. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10958. } else {
  10959. /* TODO: write some OOM message */
  10960. }
  10961. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10962. * see https://linux.die.net/man/3/bn_bn2hex */
  10963. OPENSSL_free(str_serial);
  10964. /* Free certificate memory */
  10965. X509_free(cert);
  10966. }
  10967. }
  10968. #ifdef OPENSSL_API_1_1
  10969. #else
  10970. static void
  10971. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10972. {
  10973. (void)line;
  10974. (void)file;
  10975. if (mode & 1) {
  10976. /* 1 is CRYPTO_LOCK */
  10977. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10978. } else {
  10979. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10980. }
  10981. }
  10982. #endif /* OPENSSL_API_1_1 */
  10983. #if !defined(NO_SSL_DL)
  10984. static void *
  10985. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  10986. {
  10987. union {
  10988. void *p;
  10989. void (*fp)(void);
  10990. } u;
  10991. void *dll_handle;
  10992. struct ssl_func *fp;
  10993. int ok;
  10994. int truncated = 0;
  10995. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10996. mg_snprintf(NULL,
  10997. NULL, /* No truncation check for ebuf */
  10998. ebuf,
  10999. ebuf_len,
  11000. "%s: cannot load %s",
  11001. __func__,
  11002. dll_name);
  11003. return NULL;
  11004. }
  11005. ok = 1;
  11006. for (fp = sw; fp->name != NULL; fp++) {
  11007. #ifdef _WIN32
  11008. /* GetProcAddress() returns pointer to function */
  11009. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  11010. #else
  11011. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  11012. * pointers to function pointers. We need to use a union to make a
  11013. * cast. */
  11014. u.p = dlsym(dll_handle, fp->name);
  11015. #endif /* _WIN32 */
  11016. if (u.fp == NULL) {
  11017. if (ok) {
  11018. mg_snprintf(NULL,
  11019. &truncated,
  11020. ebuf,
  11021. ebuf_len,
  11022. "%s: %s: cannot find %s",
  11023. __func__,
  11024. dll_name,
  11025. fp->name);
  11026. ok = 0;
  11027. } else {
  11028. size_t cur_len = strlen(ebuf);
  11029. if (!truncated) {
  11030. mg_snprintf(NULL,
  11031. &truncated,
  11032. ebuf + cur_len,
  11033. ebuf_len - cur_len - 3,
  11034. ", %s",
  11035. fp->name);
  11036. if (truncated) {
  11037. /* If truncated, add "..." */
  11038. strcat(ebuf, "...");
  11039. }
  11040. }
  11041. }
  11042. /* Debug:
  11043. * printf("Missing function: %s\n", fp->name); */
  11044. } else {
  11045. fp->ptr = u.fp;
  11046. }
  11047. }
  11048. if (!ok) {
  11049. (void)dlclose(dll_handle);
  11050. return NULL;
  11051. }
  11052. return dll_handle;
  11053. }
  11054. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  11055. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  11056. #endif /* NO_SSL_DL */
  11057. #if defined(SSL_ALREADY_INITIALIZED)
  11058. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  11059. #else
  11060. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  11061. #endif
  11062. static int
  11063. initialize_ssl(char *ebuf, size_t ebuf_len)
  11064. {
  11065. #ifdef OPENSSL_API_1_1
  11066. if (ebuf_len > 0) {
  11067. ebuf[0] = 0;
  11068. }
  11069. #if !defined(NO_SSL_DL)
  11070. if (!cryptolib_dll_handle) {
  11071. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11072. if (!cryptolib_dll_handle) {
  11073. return 0;
  11074. }
  11075. }
  11076. #endif /* NO_SSL_DL */
  11077. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11078. return 1;
  11079. }
  11080. #else /* not OPENSSL_API_1_1 */
  11081. int i;
  11082. size_t size;
  11083. if (ebuf_len > 0) {
  11084. ebuf[0] = 0;
  11085. }
  11086. #if !defined(NO_SSL_DL)
  11087. if (!cryptolib_dll_handle) {
  11088. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11089. if (!cryptolib_dll_handle) {
  11090. return 0;
  11091. }
  11092. }
  11093. #endif /* NO_SSL_DL */
  11094. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11095. return 1;
  11096. }
  11097. /* Initialize locking callbacks, needed for thread safety.
  11098. * http://www.openssl.org/support/faq.html#PROG1
  11099. */
  11100. i = CRYPTO_num_locks();
  11101. if (i < 0) {
  11102. i = 0;
  11103. }
  11104. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  11105. if (size == 0) {
  11106. ssl_mutexes = NULL;
  11107. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  11108. mg_snprintf(NULL,
  11109. NULL, /* No truncation check for ebuf */
  11110. ebuf,
  11111. ebuf_len,
  11112. "%s: cannot allocate mutexes: %s",
  11113. __func__,
  11114. ssl_error());
  11115. return 0;
  11116. }
  11117. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11118. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  11119. }
  11120. CRYPTO_set_locking_callback(&ssl_locking_callback);
  11121. CRYPTO_set_id_callback(&mg_current_thread_id);
  11122. #endif /* OPENSSL_API_1_1 */
  11123. return 1;
  11124. }
  11125. static int
  11126. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  11127. {
  11128. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  11129. mg_cry(fc(ctx),
  11130. "%s: cannot open certificate file %s: %s",
  11131. __func__,
  11132. pem,
  11133. ssl_error());
  11134. return 0;
  11135. }
  11136. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  11137. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  11138. mg_cry(fc(ctx),
  11139. "%s: cannot open private key file %s: %s",
  11140. __func__,
  11141. pem,
  11142. ssl_error());
  11143. return 0;
  11144. }
  11145. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  11146. mg_cry(fc(ctx),
  11147. "%s: certificate and private key do not match: %s",
  11148. __func__,
  11149. pem);
  11150. return 0;
  11151. }
  11152. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11153. * chain files that contain private keys and certificates in
  11154. * SSL_CTX_use_certificate_chain_file.
  11155. * The CivetWeb-Server used pem-Files that contained both information.
  11156. * In order to make wolfSSL work, it is split in two files.
  11157. * One file that contains key and certificate used by the server and
  11158. * an optional chain file for the ssl stack.
  11159. */
  11160. if (chain) {
  11161. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11162. mg_cry(fc(ctx),
  11163. "%s: cannot use certificate chain file %s: %s",
  11164. __func__,
  11165. pem,
  11166. ssl_error());
  11167. return 0;
  11168. }
  11169. }
  11170. return 1;
  11171. }
  11172. #ifdef OPENSSL_API_1_1
  11173. static unsigned long
  11174. ssl_get_protocol(int version_id)
  11175. {
  11176. long unsigned ret = SSL_OP_ALL;
  11177. if (version_id > 0)
  11178. ret |= SSL_OP_NO_SSLv2;
  11179. if (version_id > 1)
  11180. ret |= SSL_OP_NO_SSLv3;
  11181. if (version_id > 2)
  11182. ret |= SSL_OP_NO_TLSv1;
  11183. if (version_id > 3)
  11184. ret |= SSL_OP_NO_TLSv1_1;
  11185. return ret;
  11186. }
  11187. #else
  11188. static long
  11189. ssl_get_protocol(int version_id)
  11190. {
  11191. long ret = SSL_OP_ALL;
  11192. if (version_id > 0)
  11193. ret |= SSL_OP_NO_SSLv2;
  11194. if (version_id > 1)
  11195. ret |= SSL_OP_NO_SSLv3;
  11196. if (version_id > 2)
  11197. ret |= SSL_OP_NO_TLSv1;
  11198. if (version_id > 3)
  11199. ret |= SSL_OP_NO_TLSv1_1;
  11200. return ret;
  11201. }
  11202. #endif /* OPENSSL_API_1_1 */
  11203. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11204. static int
  11205. set_ssl_option(struct mg_context *ctx)
  11206. {
  11207. const char *pem;
  11208. const char *chain;
  11209. int callback_ret;
  11210. int should_verify_peer;
  11211. int peer_certificate_optional;
  11212. const char *ca_path;
  11213. const char *ca_file;
  11214. int use_default_verify_paths;
  11215. int verify_depth;
  11216. time_t now_rt = time(NULL);
  11217. struct timespec now_mt;
  11218. md5_byte_t ssl_context_id[16];
  11219. md5_state_t md5state;
  11220. int protocol_ver;
  11221. char ebuf[128];
  11222. /* If PEM file is not specified and the init_ssl callback
  11223. * is not specified, skip SSL initialization. */
  11224. if (!ctx) {
  11225. return 0;
  11226. }
  11227. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11228. && ctx->callbacks.init_ssl == NULL) {
  11229. return 1;
  11230. }
  11231. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11232. if (chain == NULL) {
  11233. chain = pem;
  11234. }
  11235. if ((chain != NULL) && (*chain == 0)) {
  11236. chain = NULL;
  11237. }
  11238. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11239. mg_cry(fc(ctx), "%s", ebuf);
  11240. return 0;
  11241. }
  11242. #if !defined(NO_SSL_DL)
  11243. if (!ssllib_dll_handle) {
  11244. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11245. if (!ssllib_dll_handle) {
  11246. mg_cry(fc(ctx), "%s", ebuf);
  11247. return 0;
  11248. }
  11249. }
  11250. #endif /* NO_SSL_DL */
  11251. #ifdef OPENSSL_API_1_1
  11252. /* Initialize SSL library */
  11253. OPENSSL_init_ssl(0, NULL);
  11254. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11255. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11256. NULL);
  11257. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11258. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11259. return 0;
  11260. }
  11261. #else
  11262. /* Initialize SSL library */
  11263. SSL_library_init();
  11264. SSL_load_error_strings();
  11265. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11266. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11267. return 0;
  11268. }
  11269. #endif /* OPENSSL_API_1_1 */
  11270. SSL_CTX_clear_options(ctx->ssl_ctx,
  11271. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11272. | SSL_OP_NO_TLSv1_1);
  11273. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11274. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11275. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11276. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11277. #if !defined(NO_SSL_DL)
  11278. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11279. #endif /* NO_SSL_DL */
  11280. /* If a callback has been specified, call it. */
  11281. callback_ret =
  11282. (ctx->callbacks.init_ssl == NULL)
  11283. ? 0
  11284. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11285. /* If callback returns 0, civetweb sets up the SSL certificate.
  11286. * If it returns 1, civetweb assumes the calback already did this.
  11287. * If it returns -1, initializing ssl fails. */
  11288. if (callback_ret < 0) {
  11289. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11290. return 0;
  11291. }
  11292. if (callback_ret > 0) {
  11293. if (pem != NULL) {
  11294. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11295. }
  11296. return 1;
  11297. }
  11298. /* Use some UID as session context ID. */
  11299. md5_init(&md5state);
  11300. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  11301. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  11302. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  11303. md5_append(&md5state,
  11304. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  11305. strlen(ctx->config[LISTENING_PORTS]));
  11306. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  11307. md5_finish(&md5state, ssl_context_id);
  11308. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  11309. (const unsigned char *)&ssl_context_id,
  11310. sizeof(ssl_context_id));
  11311. if (pem != NULL) {
  11312. if (!ssl_use_pem_file(ctx, pem, chain)) {
  11313. return 0;
  11314. }
  11315. }
  11316. /* Should we support client certificates? */
  11317. /* Default is "no". */
  11318. should_verify_peer = 0;
  11319. peer_certificate_optional = 0;
  11320. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11321. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  11322. /* Yes, they are mandatory */
  11323. should_verify_peer = 1;
  11324. peer_certificate_optional = 0;
  11325. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  11326. == 0) {
  11327. /* Yes, they are optional */
  11328. should_verify_peer = 1;
  11329. peer_certificate_optional = 1;
  11330. }
  11331. }
  11332. use_default_verify_paths =
  11333. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  11334. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  11335. if (should_verify_peer) {
  11336. ca_path = ctx->config[SSL_CA_PATH];
  11337. ca_file = ctx->config[SSL_CA_FILE];
  11338. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  11339. != 1) {
  11340. mg_cry(fc(ctx),
  11341. "SSL_CTX_load_verify_locations error: %s "
  11342. "ssl_verify_peer requires setting "
  11343. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11344. "present in "
  11345. "the .conf file?",
  11346. ssl_error());
  11347. return 0;
  11348. }
  11349. if (peer_certificate_optional) {
  11350. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  11351. } else {
  11352. SSL_CTX_set_verify(ctx->ssl_ctx,
  11353. SSL_VERIFY_PEER
  11354. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11355. NULL);
  11356. }
  11357. if (use_default_verify_paths
  11358. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  11359. mg_cry(fc(ctx),
  11360. "SSL_CTX_set_default_verify_paths error: %s",
  11361. ssl_error());
  11362. return 0;
  11363. }
  11364. if (ctx->config[SSL_VERIFY_DEPTH]) {
  11365. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  11366. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  11367. }
  11368. }
  11369. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  11370. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  11371. != 1) {
  11372. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  11373. }
  11374. }
  11375. return 1;
  11376. }
  11377. static void
  11378. uninitialize_ssl(void)
  11379. {
  11380. #ifdef OPENSSL_API_1_1
  11381. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11382. /* Shutdown according to
  11383. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11384. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11385. */
  11386. CONF_modules_unload(1);
  11387. #else
  11388. int i;
  11389. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11390. /* Shutdown according to
  11391. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11392. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11393. */
  11394. CRYPTO_set_locking_callback(NULL);
  11395. CRYPTO_set_id_callback(NULL);
  11396. ENGINE_cleanup();
  11397. CONF_modules_unload(1);
  11398. ERR_free_strings();
  11399. EVP_cleanup();
  11400. CRYPTO_cleanup_all_ex_data();
  11401. ERR_remove_state(0);
  11402. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11403. pthread_mutex_destroy(&ssl_mutexes[i]);
  11404. }
  11405. mg_free(ssl_mutexes);
  11406. ssl_mutexes = NULL;
  11407. #endif /* OPENSSL_API_1_1 */
  11408. }
  11409. }
  11410. #endif /* !NO_SSL */
  11411. static int
  11412. set_gpass_option(struct mg_context *ctx)
  11413. {
  11414. if (ctx) {
  11415. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11416. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  11417. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  11418. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  11419. return 0;
  11420. }
  11421. return 1;
  11422. }
  11423. return 0;
  11424. }
  11425. static int
  11426. set_acl_option(struct mg_context *ctx)
  11427. {
  11428. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  11429. }
  11430. static void
  11431. reset_per_request_attributes(struct mg_connection *conn)
  11432. {
  11433. if (!conn) {
  11434. return;
  11435. }
  11436. conn->path_info = NULL;
  11437. conn->num_bytes_sent = conn->consumed_content = 0;
  11438. conn->status_code = -1;
  11439. conn->is_chunked = 0;
  11440. conn->must_close = conn->request_len = conn->throttle = 0;
  11441. conn->request_info.content_length = -1;
  11442. conn->request_info.remote_user = NULL;
  11443. conn->request_info.request_method = NULL;
  11444. conn->request_info.request_uri = NULL;
  11445. conn->request_info.local_uri = NULL;
  11446. #if defined(MG_LEGACY_INTERFACE)
  11447. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  11448. * local_uri and request_uri */
  11449. #endif
  11450. conn->request_info.http_version = NULL;
  11451. conn->request_info.num_headers = 0;
  11452. conn->data_len = 0;
  11453. conn->chunk_remainder = 0;
  11454. }
  11455. #if 0
  11456. /* Note: set_sock_timeout is not required for non-blocking sockets.
  11457. * Leave this function here (commented out) for reference until
  11458. * CivetWeb 1.9 is tested, and the tests confirme this function is
  11459. * no longer required.
  11460. */
  11461. static int
  11462. set_sock_timeout(SOCKET sock, int milliseconds)
  11463. {
  11464. int r0 = 0, r1, r2;
  11465. #ifdef _WIN32
  11466. /* Windows specific */
  11467. DWORD tv = (DWORD)milliseconds;
  11468. #else
  11469. /* Linux, ... (not Windows) */
  11470. struct timeval tv;
  11471. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  11472. * max. time waiting for the acknowledged of TCP data before the connection
  11473. * will be forcefully closed and ETIMEDOUT is returned to the application.
  11474. * If this option is not set, the default timeout of 20-30 minutes is used.
  11475. */
  11476. /* #define TCP_USER_TIMEOUT (18) */
  11477. #if defined(TCP_USER_TIMEOUT)
  11478. unsigned int uto = (unsigned int)milliseconds;
  11479. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  11480. #endif
  11481. memset(&tv, 0, sizeof(tv));
  11482. tv.tv_sec = milliseconds / 1000;
  11483. tv.tv_usec = (milliseconds * 1000) % 1000000;
  11484. #endif /* _WIN32 */
  11485. r1 = setsockopt(
  11486. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11487. r2 = setsockopt(
  11488. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11489. return r0 || r1 || r2;
  11490. }
  11491. #endif
  11492. static int
  11493. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11494. {
  11495. if (setsockopt(sock,
  11496. IPPROTO_TCP,
  11497. TCP_NODELAY,
  11498. (SOCK_OPT_TYPE)&nodelay_on,
  11499. sizeof(nodelay_on)) != 0) {
  11500. /* Error */
  11501. return 1;
  11502. }
  11503. /* OK */
  11504. return 0;
  11505. }
  11506. static void
  11507. close_socket_gracefully(struct mg_connection *conn)
  11508. {
  11509. #if defined(_WIN32)
  11510. char buf[MG_BUF_LEN];
  11511. int n;
  11512. #endif
  11513. struct linger linger;
  11514. int error_code = 0;
  11515. int linger_timeout = -2;
  11516. socklen_t opt_len = sizeof(error_code);
  11517. if (!conn) {
  11518. return;
  11519. }
  11520. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  11521. * "Note that enabling a nonzero timeout on a nonblocking socket
  11522. * is not recommended.", so set it to blocking now */
  11523. set_blocking_mode(conn->client.sock, 1);
  11524. /* Send FIN to the client */
  11525. shutdown(conn->client.sock, SHUTDOWN_WR);
  11526. #if defined(_WIN32)
  11527. /* Read and discard pending incoming data. If we do not do that and
  11528. * close
  11529. * the socket, the data in the send buffer may be discarded. This
  11530. * behaviour is seen on Windows, when client keeps sending data
  11531. * when server decides to close the connection; then when client
  11532. * does recv() it gets no data back. */
  11533. do {
  11534. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  11535. } while (n > 0);
  11536. #endif
  11537. if (conn->ctx->config[LINGER_TIMEOUT]) {
  11538. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  11539. }
  11540. /* Set linger option according to configuration */
  11541. if (linger_timeout >= 0) {
  11542. /* Set linger option to avoid socket hanging out after close. This
  11543. * prevent ephemeral port exhaust problem under high QPS. */
  11544. linger.l_onoff = 1;
  11545. #if defined(_MSC_VER)
  11546. #pragma warning(push)
  11547. #pragma warning(disable : 4244)
  11548. #endif
  11549. linger.l_linger = (linger_timeout + 999) / 1000;
  11550. #if defined(_MSC_VER)
  11551. #pragma warning(pop)
  11552. #endif
  11553. } else {
  11554. linger.l_onoff = 0;
  11555. linger.l_linger = 0;
  11556. }
  11557. if (linger_timeout < -1) {
  11558. /* Default: don't configure any linger */
  11559. } else if (getsockopt(conn->client.sock,
  11560. SOL_SOCKET,
  11561. SO_ERROR,
  11562. (char *)&error_code,
  11563. &opt_len) != 0) {
  11564. /* Cannot determine if socket is already closed. This should
  11565. * not occur and never did in a test. Log an error message
  11566. * and continue. */
  11567. mg_cry(conn,
  11568. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  11569. __func__,
  11570. strerror(ERRNO));
  11571. } else if (error_code == ECONNRESET) {
  11572. /* Socket already closed by client/peer, close socket without linger */
  11573. } else {
  11574. /* Set linger timeout */
  11575. if (setsockopt(conn->client.sock,
  11576. SOL_SOCKET,
  11577. SO_LINGER,
  11578. (char *)&linger,
  11579. sizeof(linger)) != 0) {
  11580. mg_cry(conn,
  11581. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  11582. __func__,
  11583. linger.l_onoff,
  11584. linger.l_linger,
  11585. strerror(ERRNO));
  11586. }
  11587. }
  11588. /* Now we know that our FIN is ACK-ed, safe to close */
  11589. closesocket(conn->client.sock);
  11590. conn->client.sock = INVALID_SOCKET;
  11591. }
  11592. static void
  11593. close_connection(struct mg_connection *conn)
  11594. {
  11595. if (!conn || !conn->ctx) {
  11596. return;
  11597. }
  11598. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11599. if (conn->lua_websocket_state) {
  11600. lua_websocket_close(conn, conn->lua_websocket_state);
  11601. conn->lua_websocket_state = NULL;
  11602. }
  11603. #endif
  11604. /* call the connection_close callback if assigned */
  11605. if ((conn->ctx->callbacks.connection_close != NULL)
  11606. && (conn->ctx->context_type == 1)) {
  11607. conn->ctx->callbacks.connection_close(conn);
  11608. }
  11609. mg_lock_connection(conn);
  11610. conn->must_close = 1;
  11611. #ifndef NO_SSL
  11612. if (conn->ssl != NULL) {
  11613. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11614. */
  11615. SSL_shutdown(conn->ssl);
  11616. SSL_free(conn->ssl);
  11617. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11618. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11619. #ifndef OPENSSL_API_1_1
  11620. ERR_remove_state(0);
  11621. #endif
  11622. conn->ssl = NULL;
  11623. }
  11624. #endif
  11625. if (conn->client.sock != INVALID_SOCKET) {
  11626. close_socket_gracefully(conn);
  11627. conn->client.sock = INVALID_SOCKET;
  11628. }
  11629. mg_unlock_connection(conn);
  11630. }
  11631. void
  11632. mg_close_connection(struct mg_connection *conn)
  11633. {
  11634. struct mg_context *client_ctx = NULL;
  11635. if (conn == NULL) {
  11636. return;
  11637. }
  11638. #if defined(USE_WEBSOCKET)
  11639. if (conn->ctx->context_type == 2) {
  11640. unsigned int i;
  11641. /* ws/wss client */
  11642. client_ctx = conn->ctx;
  11643. /* client context: loops must end */
  11644. conn->ctx->stop_flag = 1;
  11645. /* We need to get the client thread out of the select/recv call here. */
  11646. /* Since we use a sleep quantum of some seconds to check for recv
  11647. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11648. /* join worker thread */
  11649. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11650. if (client_ctx->worker_threadids[i] != 0) {
  11651. mg_join_thread(client_ctx->worker_threadids[i]);
  11652. }
  11653. }
  11654. }
  11655. #else
  11656. (void)client_ctx;
  11657. #endif
  11658. close_connection(conn);
  11659. #ifndef NO_SSL
  11660. if (conn->client_ssl_ctx != NULL) {
  11661. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11662. }
  11663. #endif
  11664. if (client_ctx != NULL) {
  11665. /* free context */
  11666. mg_free(client_ctx->worker_threadids);
  11667. mg_free(client_ctx);
  11668. (void)pthread_mutex_destroy(&conn->mutex);
  11669. mg_free(conn);
  11670. } else if (conn->ctx->context_type == 0) { // Client
  11671. mg_free(conn);
  11672. }
  11673. }
  11674. static struct mg_context common_client_context;
  11675. static struct mg_connection *
  11676. mg_connect_client_impl(const struct mg_client_options *client_options,
  11677. int use_ssl,
  11678. char *ebuf,
  11679. size_t ebuf_len)
  11680. {
  11681. struct mg_connection *conn = NULL;
  11682. SOCKET sock;
  11683. union usa sa;
  11684. unsigned max_req_size =
  11685. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  11686. if (!connect_socket(&common_client_context,
  11687. client_options->host,
  11688. client_options->port,
  11689. use_ssl,
  11690. ebuf,
  11691. ebuf_len,
  11692. &sock,
  11693. &sa)) {
  11694. return NULL;
  11695. }
  11696. if ((conn = (struct mg_connection *)mg_calloc_ctx(
  11697. 1, sizeof(*conn) + max_req_size, &common_client_context))
  11698. == NULL) {
  11699. mg_snprintf(NULL,
  11700. NULL, /* No truncation check for ebuf */
  11701. ebuf,
  11702. ebuf_len,
  11703. "calloc(): %s",
  11704. strerror(ERRNO));
  11705. closesocket(sock);
  11706. return NULL;
  11707. }
  11708. #ifndef NO_SSL
  11709. #ifdef OPENSSL_API_1_1
  11710. if (use_ssl
  11711. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  11712. mg_snprintf(NULL,
  11713. NULL, /* No truncation check for ebuf */
  11714. ebuf,
  11715. ebuf_len,
  11716. "SSL_CTX_new error");
  11717. closesocket(sock);
  11718. mg_free(conn);
  11719. return NULL;
  11720. }
  11721. #else
  11722. if (use_ssl
  11723. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11724. == NULL) {
  11725. mg_snprintf(NULL,
  11726. NULL, /* No truncation check for ebuf */
  11727. ebuf,
  11728. ebuf_len,
  11729. "SSL_CTX_new error");
  11730. closesocket(sock);
  11731. mg_free(conn);
  11732. return NULL;
  11733. }
  11734. #endif /* OPENSSL_API_1_1 */
  11735. #endif /* NO_SSL */
  11736. #ifdef USE_IPV6
  11737. socklen_t len = (sa.sa.sa_family == AF_INET)
  11738. ? sizeof(conn->client.rsa.sin)
  11739. : sizeof(conn->client.rsa.sin6);
  11740. struct sockaddr *psa = (sa.sa.sa_family == AF_INET)
  11741. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11742. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11743. #else
  11744. socklen_t len = sizeof(conn->client.rsa.sin);
  11745. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11746. #endif
  11747. conn->buf_size = (int)max_req_size;
  11748. conn->buf = (char *)(conn + 1);
  11749. conn->ctx = &common_client_context;
  11750. conn->client.sock = sock;
  11751. conn->client.lsa = sa;
  11752. if (getsockname(sock, psa, &len) != 0) {
  11753. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  11754. }
  11755. conn->client.is_ssl = use_ssl ? 1 : 0;
  11756. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11757. #ifndef NO_SSL
  11758. if (use_ssl) {
  11759. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  11760. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11761. * SSL_CTX_set_verify call is needed to switch off server
  11762. * certificate checking, which is off by default in OpenSSL and
  11763. * on in yaSSL. */
  11764. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11765. * SSL_VERIFY_PEER, verify_ssl_server); */
  11766. if (client_options->client_cert) {
  11767. if (!ssl_use_pem_file(&common_client_context,
  11768. client_options->client_cert,
  11769. NULL)) {
  11770. mg_snprintf(NULL,
  11771. NULL, /* No truncation check for ebuf */
  11772. ebuf,
  11773. ebuf_len,
  11774. "Can not use SSL client certificate");
  11775. SSL_CTX_free(conn->client_ssl_ctx);
  11776. closesocket(sock);
  11777. mg_free(conn);
  11778. return NULL;
  11779. }
  11780. }
  11781. if (client_options->server_cert) {
  11782. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11783. client_options->server_cert,
  11784. NULL);
  11785. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11786. } else {
  11787. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11788. }
  11789. if (!sslize(conn,
  11790. conn->client_ssl_ctx,
  11791. SSL_connect,
  11792. &(conn->ctx->stop_flag))) {
  11793. mg_snprintf(NULL,
  11794. NULL, /* No truncation check for ebuf */
  11795. ebuf,
  11796. ebuf_len,
  11797. "SSL connection error");
  11798. SSL_CTX_free(conn->client_ssl_ctx);
  11799. closesocket(sock);
  11800. mg_free(conn);
  11801. return NULL;
  11802. }
  11803. }
  11804. #endif
  11805. set_blocking_mode(sock, 0);
  11806. return conn;
  11807. }
  11808. CIVETWEB_API struct mg_connection *
  11809. mg_connect_client_secure(const struct mg_client_options *client_options,
  11810. char *error_buffer,
  11811. size_t error_buffer_size)
  11812. {
  11813. return mg_connect_client_impl(client_options,
  11814. 1,
  11815. error_buffer,
  11816. error_buffer_size);
  11817. }
  11818. struct mg_connection *
  11819. mg_connect_client(const char *host,
  11820. int port,
  11821. int use_ssl,
  11822. char *error_buffer,
  11823. size_t error_buffer_size)
  11824. {
  11825. struct mg_client_options opts;
  11826. memset(&opts, 0, sizeof(opts));
  11827. opts.host = host;
  11828. opts.port = port;
  11829. return mg_connect_client_impl(&opts,
  11830. use_ssl,
  11831. error_buffer,
  11832. error_buffer_size);
  11833. }
  11834. static const struct {
  11835. const char *proto;
  11836. size_t proto_len;
  11837. unsigned default_port;
  11838. } abs_uri_protocols[] = {{"http://", 7, 80},
  11839. {"https://", 8, 443},
  11840. {"ws://", 5, 80},
  11841. {"wss://", 6, 443},
  11842. {NULL, 0, 0}};
  11843. /* Check if the uri is valid.
  11844. * return 0 for invalid uri,
  11845. * return 1 for *,
  11846. * return 2 for relative uri,
  11847. * return 3 for absolute uri without port,
  11848. * return 4 for absolute uri with port */
  11849. static int
  11850. get_uri_type(const char *uri)
  11851. {
  11852. int i;
  11853. const char *hostend, *portbegin;
  11854. char *portend;
  11855. unsigned long port;
  11856. /* According to the HTTP standard
  11857. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11858. * URI can be an asterisk (*) or should start with slash (relative uri),
  11859. * or it should start with the protocol (absolute uri). */
  11860. if (uri[0] == '*' && uri[1] == '\0') {
  11861. /* asterisk */
  11862. return 1;
  11863. }
  11864. /* Valid URIs according to RFC 3986
  11865. * (https://www.ietf.org/rfc/rfc3986.txt)
  11866. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11867. * and unreserved characters A-Z a-z 0-9 and -._~
  11868. * and % encoded symbols.
  11869. */
  11870. for (i = 0; uri[i] != 0; i++) {
  11871. if (uri[i] < 33) {
  11872. /* control characters and spaces are invalid */
  11873. return 0;
  11874. }
  11875. if (uri[i] > 126) {
  11876. /* non-ascii characters must be % encoded */
  11877. return 0;
  11878. } else {
  11879. switch (uri[i]) {
  11880. case '"': /* 34 */
  11881. case '<': /* 60 */
  11882. case '>': /* 62 */
  11883. case '\\': /* 92 */
  11884. case '^': /* 94 */
  11885. case '`': /* 96 */
  11886. case '{': /* 123 */
  11887. case '|': /* 124 */
  11888. case '}': /* 125 */
  11889. return 0;
  11890. default:
  11891. /* character is ok */
  11892. break;
  11893. }
  11894. }
  11895. }
  11896. /* A relative uri starts with a / character */
  11897. if (uri[0] == '/') {
  11898. /* relative uri */
  11899. return 2;
  11900. }
  11901. /* It could be an absolute uri: */
  11902. /* This function only checks if the uri is valid, not if it is
  11903. * addressing the current server. So civetweb can also be used
  11904. * as a proxy server. */
  11905. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11906. if (mg_strncasecmp(uri,
  11907. abs_uri_protocols[i].proto,
  11908. abs_uri_protocols[i].proto_len) == 0) {
  11909. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11910. if (!hostend) {
  11911. return 0;
  11912. }
  11913. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11914. if (!portbegin) {
  11915. return 3;
  11916. }
  11917. port = strtoul(portbegin + 1, &portend, 10);
  11918. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11919. return 0;
  11920. }
  11921. return 4;
  11922. }
  11923. }
  11924. return 0;
  11925. }
  11926. /* Return NULL or the relative uri at the current server */
  11927. static const char *
  11928. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11929. {
  11930. const char *server_domain;
  11931. size_t server_domain_len;
  11932. size_t request_domain_len = 0;
  11933. unsigned long port = 0;
  11934. int i, auth_domain_check_enabled;
  11935. const char *hostbegin = NULL;
  11936. const char *hostend = NULL;
  11937. const char *portbegin;
  11938. char *portend;
  11939. auth_domain_check_enabled =
  11940. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  11941. if (!auth_domain_check_enabled) {
  11942. return 0;
  11943. }
  11944. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11945. if (!server_domain) {
  11946. return 0;
  11947. }
  11948. server_domain_len = strlen(server_domain);
  11949. if (!server_domain_len) {
  11950. return 0;
  11951. }
  11952. /* DNS is case insensitive, so use case insensitive string compare here
  11953. */
  11954. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11955. if (mg_strncasecmp(uri,
  11956. abs_uri_protocols[i].proto,
  11957. abs_uri_protocols[i].proto_len) == 0) {
  11958. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11959. hostend = strchr(hostbegin, '/');
  11960. if (!hostend) {
  11961. return 0;
  11962. }
  11963. portbegin = strchr(hostbegin, ':');
  11964. if ((!portbegin) || (portbegin > hostend)) {
  11965. port = abs_uri_protocols[i].default_port;
  11966. request_domain_len = (size_t)(hostend - hostbegin);
  11967. } else {
  11968. port = strtoul(portbegin + 1, &portend, 10);
  11969. if ((portend != hostend) || (port <= 0)
  11970. || !is_valid_port(port)) {
  11971. return 0;
  11972. }
  11973. request_domain_len = (size_t)(portbegin - hostbegin);
  11974. }
  11975. /* protocol found, port set */
  11976. break;
  11977. }
  11978. }
  11979. if (!port) {
  11980. /* port remains 0 if the protocol is not found */
  11981. return 0;
  11982. }
  11983. /* Check if the request is directed to a different server. */
  11984. /* First check if the port is the same (IPv4 and IPv6). */
  11985. #if defined(USE_IPV6)
  11986. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11987. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11988. /* Request is directed to a different port */
  11989. return 0;
  11990. }
  11991. } else
  11992. #endif
  11993. {
  11994. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11995. /* Request is directed to a different port */
  11996. return 0;
  11997. }
  11998. }
  11999. /* Finally check if the server corresponds to the authentication
  12000. * domain of the server (the server domain).
  12001. * Allow full matches (like http://mydomain.com/path/file.ext), and
  12002. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  12003. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  12004. * or http://mydomain.com.fake/path/file.ext).
  12005. */
  12006. if (auth_domain_check_enabled) {
  12007. if ((request_domain_len == server_domain_len)
  12008. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  12009. /* Request is directed to this server - full name match. */
  12010. } else {
  12011. if (request_domain_len < (server_domain_len + 2)) {
  12012. /* Request is directed to another server: The server name is
  12013. * longer
  12014. * than
  12015. * the request name. Drop this case here to avoid overflows in
  12016. * the
  12017. * following checks. */
  12018. return 0;
  12019. }
  12020. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  12021. /* Request is directed to another server: It could be a
  12022. * substring
  12023. * like notmyserver.com */
  12024. return 0;
  12025. }
  12026. if (0 != memcmp(server_domain,
  12027. hostbegin + request_domain_len - server_domain_len,
  12028. server_domain_len)) {
  12029. /* Request is directed to another server:
  12030. * The server name is different. */
  12031. return 0;
  12032. }
  12033. }
  12034. }
  12035. return hostend;
  12036. }
  12037. static int
  12038. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12039. {
  12040. const char *cl;
  12041. if (ebuf_len > 0) {
  12042. ebuf[0] = '\0';
  12043. }
  12044. *err = 0;
  12045. reset_per_request_attributes(conn);
  12046. if (!conn) {
  12047. mg_snprintf(conn,
  12048. NULL, /* No truncation check for ebuf */
  12049. ebuf,
  12050. ebuf_len,
  12051. "%s",
  12052. "Internal error");
  12053. *err = 500;
  12054. return 0;
  12055. }
  12056. /* Set the time the request was received. This value should be used for
  12057. * timeouts. */
  12058. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  12059. conn->request_len =
  12060. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  12061. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  12062. */
  12063. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  12064. mg_snprintf(conn,
  12065. NULL, /* No truncation check for ebuf */
  12066. ebuf,
  12067. ebuf_len,
  12068. "%s",
  12069. "Invalid request size");
  12070. *err = 500;
  12071. return 0;
  12072. }
  12073. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  12074. mg_snprintf(conn,
  12075. NULL, /* No truncation check for ebuf */
  12076. ebuf,
  12077. ebuf_len,
  12078. "%s",
  12079. "Request Too Large");
  12080. *err = 413;
  12081. return 0;
  12082. } else if (conn->request_len <= 0) {
  12083. if (conn->data_len > 0) {
  12084. mg_snprintf(conn,
  12085. NULL, /* No truncation check for ebuf */
  12086. ebuf,
  12087. ebuf_len,
  12088. "%s",
  12089. "Client sent malformed request");
  12090. *err = 400;
  12091. } else {
  12092. /* Server did not recv anything -> just close the connection */
  12093. conn->must_close = 1;
  12094. mg_snprintf(conn,
  12095. NULL, /* No truncation check for ebuf */
  12096. ebuf,
  12097. ebuf_len,
  12098. "%s",
  12099. "Client did not send a request");
  12100. *err = 0;
  12101. }
  12102. return 0;
  12103. } else if (parse_http_message(conn->buf,
  12104. conn->buf_size,
  12105. &conn->request_info) <= 0) {
  12106. mg_snprintf(conn,
  12107. NULL, /* No truncation check for ebuf */
  12108. ebuf,
  12109. ebuf_len,
  12110. "%s",
  12111. "Bad Request");
  12112. *err = 400;
  12113. return 0;
  12114. } else {
  12115. /* Message is a valid request or response */
  12116. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  12117. /* Request/response has content length set */
  12118. char *endptr = NULL;
  12119. conn->content_len = strtoll(cl, &endptr, 10);
  12120. if (endptr == cl) {
  12121. mg_snprintf(conn,
  12122. NULL, /* No truncation check for ebuf */
  12123. ebuf,
  12124. ebuf_len,
  12125. "%s",
  12126. "Bad Request");
  12127. *err = 411;
  12128. return 0;
  12129. }
  12130. /* Publish the content length back to the request info. */
  12131. conn->request_info.content_length = conn->content_len;
  12132. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  12133. != NULL
  12134. && !mg_strcasecmp(cl, "chunked")) {
  12135. conn->is_chunked = 1;
  12136. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  12137. || !mg_strcasecmp(conn->request_info.request_method,
  12138. "PUT")) {
  12139. /* POST or PUT request without content length set */
  12140. conn->content_len = -1;
  12141. } else if (!mg_strncasecmp(conn->request_info.request_method,
  12142. "HTTP/",
  12143. 5)) {
  12144. /* Response without content length set */
  12145. conn->content_len = -1;
  12146. } else {
  12147. /* Other request */
  12148. conn->content_len = 0;
  12149. }
  12150. }
  12151. return 1;
  12152. }
  12153. int
  12154. mg_get_response(struct mg_connection *conn,
  12155. char *ebuf,
  12156. size_t ebuf_len,
  12157. int timeout)
  12158. {
  12159. if (conn) {
  12160. /* Implementation of API function for HTTP clients */
  12161. int err, ret;
  12162. struct mg_context *octx = conn->ctx;
  12163. struct mg_context rctx = *(conn->ctx);
  12164. char txt[32]; /* will not overflow */
  12165. if (timeout >= 0) {
  12166. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  12167. rctx.config[REQUEST_TIMEOUT] = txt;
  12168. /* Not required for non-blocking sockets.
  12169. set_sock_timeout(conn->client.sock, timeout);
  12170. */
  12171. } else {
  12172. rctx.config[REQUEST_TIMEOUT] = NULL;
  12173. }
  12174. conn->ctx = &rctx;
  12175. ret = getreq(conn, ebuf, ebuf_len, &err);
  12176. conn->ctx = octx;
  12177. #if defined(MG_LEGACY_INTERFACE)
  12178. /* TODO: 1) uri is deprecated;
  12179. * 2) here, ri.uri is the http response code */
  12180. conn->request_info.uri = conn->request_info.request_uri;
  12181. #endif
  12182. conn->request_info.local_uri = conn->request_info.request_uri;
  12183. /* TODO (mid): Define proper return values - maybe return length?
  12184. * For the first test use <0 for error and >0 for OK */
  12185. return (ret == 0) ? -1 : +1;
  12186. }
  12187. return -1;
  12188. }
  12189. struct mg_connection *
  12190. mg_download(const char *host,
  12191. int port,
  12192. int use_ssl,
  12193. char *ebuf,
  12194. size_t ebuf_len,
  12195. const char *fmt,
  12196. ...)
  12197. {
  12198. struct mg_connection *conn;
  12199. va_list ap;
  12200. int i;
  12201. int reqerr;
  12202. va_start(ap, fmt);
  12203. ebuf[0] = '\0';
  12204. /* open a connection */
  12205. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  12206. if (conn != NULL) {
  12207. i = mg_vprintf(conn, fmt, ap);
  12208. if (i <= 0) {
  12209. mg_snprintf(conn,
  12210. NULL, /* No truncation check for ebuf */
  12211. ebuf,
  12212. ebuf_len,
  12213. "%s",
  12214. "Error sending request");
  12215. } else {
  12216. getreq(conn, ebuf, ebuf_len, &reqerr);
  12217. #if defined(MG_LEGACY_INTERFACE)
  12218. /* TODO: 1) uri is deprecated;
  12219. * 2) here, ri.uri is the http response code */
  12220. conn->request_info.uri = conn->request_info.request_uri;
  12221. #endif
  12222. conn->request_info.local_uri = conn->request_info.request_uri;
  12223. }
  12224. }
  12225. /* if an error occured, close the connection */
  12226. if (ebuf[0] != '\0' && conn != NULL) {
  12227. mg_close_connection(conn);
  12228. conn = NULL;
  12229. }
  12230. va_end(ap);
  12231. return conn;
  12232. }
  12233. struct websocket_client_thread_data {
  12234. struct mg_connection *conn;
  12235. mg_websocket_data_handler data_handler;
  12236. mg_websocket_close_handler close_handler;
  12237. void *callback_data;
  12238. };
  12239. #if defined(USE_WEBSOCKET)
  12240. #ifdef _WIN32
  12241. static unsigned __stdcall websocket_client_thread(void *data)
  12242. #else
  12243. static void *
  12244. websocket_client_thread(void *data)
  12245. #endif
  12246. {
  12247. struct websocket_client_thread_data *cdata =
  12248. (struct websocket_client_thread_data *)data;
  12249. mg_set_thread_name("ws-clnt");
  12250. if (cdata->conn->ctx) {
  12251. if (cdata->conn->ctx->callbacks.init_thread) {
  12252. /* 3 indicates a websocket client thread */
  12253. /* TODO: check if conn->ctx can be set */
  12254. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  12255. }
  12256. }
  12257. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  12258. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  12259. if (cdata->close_handler != NULL) {
  12260. cdata->close_handler(cdata->conn, cdata->callback_data);
  12261. }
  12262. /* The websocket_client context has only this thread. If it runs out,
  12263. set the stop_flag to 2 (= "stopped"). */
  12264. cdata->conn->ctx->stop_flag = 2;
  12265. mg_free((void *)cdata);
  12266. #ifdef _WIN32
  12267. return 0;
  12268. #else
  12269. return NULL;
  12270. #endif
  12271. }
  12272. #endif
  12273. struct mg_connection *
  12274. mg_connect_websocket_client(const char *host,
  12275. int port,
  12276. int use_ssl,
  12277. char *error_buffer,
  12278. size_t error_buffer_size,
  12279. const char *path,
  12280. const char *origin,
  12281. mg_websocket_data_handler data_func,
  12282. mg_websocket_close_handler close_func,
  12283. void *user_data)
  12284. {
  12285. struct mg_connection *conn = NULL;
  12286. #if defined(USE_WEBSOCKET)
  12287. struct mg_context *newctx = NULL;
  12288. struct websocket_client_thread_data *thread_data;
  12289. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  12290. static const char *handshake_req;
  12291. if (origin != NULL) {
  12292. handshake_req = "GET %s HTTP/1.1\r\n"
  12293. "Host: %s\r\n"
  12294. "Upgrade: websocket\r\n"
  12295. "Connection: Upgrade\r\n"
  12296. "Sec-WebSocket-Key: %s\r\n"
  12297. "Sec-WebSocket-Version: 13\r\n"
  12298. "Origin: %s\r\n"
  12299. "\r\n";
  12300. } else {
  12301. handshake_req = "GET %s HTTP/1.1\r\n"
  12302. "Host: %s\r\n"
  12303. "Upgrade: websocket\r\n"
  12304. "Connection: Upgrade\r\n"
  12305. "Sec-WebSocket-Key: %s\r\n"
  12306. "Sec-WebSocket-Version: 13\r\n"
  12307. "\r\n";
  12308. }
  12309. /* Establish the client connection and request upgrade */
  12310. conn = mg_download(host,
  12311. port,
  12312. use_ssl,
  12313. error_buffer,
  12314. error_buffer_size,
  12315. handshake_req,
  12316. path,
  12317. host,
  12318. magic,
  12319. origin);
  12320. /* Connection object will be null if something goes wrong */
  12321. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  12322. if (!*error_buffer) {
  12323. /* if there is a connection, but it did not return 101,
  12324. * error_buffer is not yet set */
  12325. mg_snprintf(conn,
  12326. NULL, /* No truncation check for ebuf */
  12327. error_buffer,
  12328. error_buffer_size,
  12329. "Unexpected server reply");
  12330. }
  12331. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  12332. if (conn != NULL) {
  12333. mg_free(conn);
  12334. conn = NULL;
  12335. }
  12336. return conn;
  12337. }
  12338. /* For client connections, mg_context is fake. Since we need to set a
  12339. * callback function, we need to create a copy and modify it. */
  12340. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  12341. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  12342. newctx->user_data = user_data;
  12343. newctx->context_type = 2; /* ws/wss client context type */
  12344. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  12345. newctx->worker_threadids =
  12346. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  12347. sizeof(pthread_t),
  12348. newctx);
  12349. conn->ctx = newctx;
  12350. thread_data = (struct websocket_client_thread_data *)
  12351. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  12352. thread_data->conn = conn;
  12353. thread_data->data_handler = data_func;
  12354. thread_data->close_handler = close_func;
  12355. thread_data->callback_data = user_data;
  12356. /* Start a thread to read the websocket client connection
  12357. * This thread will automatically stop when mg_disconnect is
  12358. * called on the client connection */
  12359. if (mg_start_thread_with_id(websocket_client_thread,
  12360. (void *)thread_data,
  12361. newctx->worker_threadids) != 0) {
  12362. mg_free((void *)thread_data);
  12363. mg_free((void *)newctx->worker_threadids);
  12364. mg_free((void *)newctx);
  12365. mg_free((void *)conn);
  12366. conn = NULL;
  12367. DEBUG_TRACE("%s",
  12368. "Websocket client connect thread could not be started\r\n");
  12369. }
  12370. #else
  12371. /* Appease "unused parameter" warnings */
  12372. (void)host;
  12373. (void)port;
  12374. (void)use_ssl;
  12375. (void)error_buffer;
  12376. (void)error_buffer_size;
  12377. (void)path;
  12378. (void)origin;
  12379. (void)user_data;
  12380. (void)data_func;
  12381. (void)close_func;
  12382. #endif
  12383. return conn;
  12384. }
  12385. static void
  12386. process_new_connection(struct mg_connection *conn)
  12387. {
  12388. if (conn && conn->ctx) {
  12389. struct mg_request_info *ri = &conn->request_info;
  12390. int keep_alive_enabled, keep_alive, discard_len;
  12391. char ebuf[100];
  12392. const char *hostend;
  12393. int reqerr, uri_type;
  12394. #if defined(USE_SERVER_STATS)
  12395. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  12396. mg_atomic_add(&(conn->ctx->total_connections), 1);
  12397. if (mcon > (conn->ctx->max_connections)) {
  12398. /* could use atomic compare exchange, but this
  12399. * seems overkill for statistics data */
  12400. conn->ctx->max_connections = mcon;
  12401. }
  12402. #endif
  12403. keep_alive_enabled =
  12404. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  12405. /* Important: on new connection, reset the receiving buffer. Credit
  12406. * goes to crule42. */
  12407. conn->data_len = 0;
  12408. conn->handled_requests = 0;
  12409. do {
  12410. DEBUG_TRACE("calling getreq (%i times for this connection)",
  12411. conn->handled_requests + 1);
  12412. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  12413. /* The request sent by the client could not be understood by
  12414. * the server, or it was incomplete or a timeout. Send an
  12415. * error message and close the connection. */
  12416. if (reqerr > 0) {
  12417. /*assert(ebuf[0] != '\0');*/
  12418. mg_send_http_error(conn, reqerr, "%s", ebuf);
  12419. }
  12420. } else if (strcmp(ri->http_version, "1.0")
  12421. && strcmp(ri->http_version, "1.1")) {
  12422. mg_snprintf(conn,
  12423. NULL, /* No truncation check for ebuf */
  12424. ebuf,
  12425. sizeof(ebuf),
  12426. "Bad HTTP version: [%s]",
  12427. ri->http_version);
  12428. mg_send_http_error(conn, 505, "%s", ebuf);
  12429. }
  12430. if (ebuf[0] == '\0') {
  12431. uri_type = get_uri_type(conn->request_info.request_uri);
  12432. switch (uri_type) {
  12433. case 1:
  12434. /* Asterisk */
  12435. conn->request_info.local_uri = NULL;
  12436. break;
  12437. case 2:
  12438. /* relative uri */
  12439. conn->request_info.local_uri =
  12440. conn->request_info.request_uri;
  12441. break;
  12442. case 3:
  12443. case 4:
  12444. /* absolute uri (with/without port) */
  12445. hostend = get_rel_url_at_current_server(
  12446. conn->request_info.request_uri, conn);
  12447. if (hostend) {
  12448. conn->request_info.local_uri = hostend;
  12449. } else {
  12450. conn->request_info.local_uri = NULL;
  12451. }
  12452. break;
  12453. default:
  12454. mg_snprintf(conn,
  12455. NULL, /* No truncation check for ebuf */
  12456. ebuf,
  12457. sizeof(ebuf),
  12458. "Invalid URI");
  12459. mg_send_http_error(conn, 400, "%s", ebuf);
  12460. conn->request_info.local_uri = NULL;
  12461. break;
  12462. }
  12463. #if defined(MG_LEGACY_INTERFACE)
  12464. /* TODO: cleanup uri, local_uri and request_uri */
  12465. conn->request_info.uri = conn->request_info.local_uri;
  12466. #endif
  12467. }
  12468. DEBUG_TRACE("http: %s, error: %s",
  12469. (ri->http_version ? ri->http_version : "none"),
  12470. (ebuf[0] ? ebuf : "none"));
  12471. if (ebuf[0] == '\0') {
  12472. if (conn->request_info.local_uri) {
  12473. /* handle request to local server */
  12474. handle_request(conn);
  12475. DEBUG_TRACE("%s", "handle_request done");
  12476. if (conn->ctx->callbacks.end_request != NULL) {
  12477. conn->ctx->callbacks.end_request(conn,
  12478. conn->status_code);
  12479. DEBUG_TRACE("%s", "end_request callback done");
  12480. }
  12481. log_access(conn);
  12482. } else {
  12483. /* TODO: handle non-local request (PROXY) */
  12484. conn->must_close = 1;
  12485. }
  12486. } else {
  12487. conn->must_close = 1;
  12488. }
  12489. if (ri->remote_user != NULL) {
  12490. mg_free((void *)ri->remote_user);
  12491. /* Important! When having connections with and without auth
  12492. * would cause double free and then crash */
  12493. ri->remote_user = NULL;
  12494. }
  12495. /* NOTE(lsm): order is important here. should_keep_alive() call
  12496. * is
  12497. * using parsed request, which will be invalid after memmove's
  12498. * below.
  12499. * Therefore, memorize should_keep_alive() result now for later
  12500. * use
  12501. * in loop exit condition. */
  12502. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  12503. && (conn->content_len >= 0) && should_keep_alive(conn);
  12504. /* Discard all buffered data for this request */
  12505. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  12506. && ((conn->request_len + conn->content_len)
  12507. < (int64_t)conn->data_len))
  12508. ? (int)(conn->request_len + conn->content_len)
  12509. : conn->data_len;
  12510. /*assert(discard_len >= 0);*/
  12511. if (discard_len < 0) {
  12512. DEBUG_TRACE("internal error: discard_len = %li",
  12513. (long int)discard_len);
  12514. break;
  12515. }
  12516. conn->data_len -= discard_len;
  12517. if (conn->data_len > 0) {
  12518. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  12519. memmove(conn->buf,
  12520. conn->buf + discard_len,
  12521. (size_t)conn->data_len);
  12522. }
  12523. /* assert(conn->data_len >= 0); */
  12524. /* assert(conn->data_len <= conn->buf_size); */
  12525. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  12526. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  12527. (long int)conn->data_len,
  12528. (long int)conn->buf_size);
  12529. break;
  12530. }
  12531. conn->handled_requests++;
  12532. } while (keep_alive);
  12533. #if defined(USE_SERVER_STATS)
  12534. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  12535. mg_atomic_dec(&(conn->ctx->active_connections));
  12536. #endif
  12537. }
  12538. }
  12539. #if defined(ALTERNATIVE_QUEUE)
  12540. static void
  12541. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12542. {
  12543. unsigned int i;
  12544. for (;;) {
  12545. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12546. /* find a free worker slot and signal it */
  12547. if (ctx->client_socks[i].in_use == 0) {
  12548. ctx->client_socks[i] = *sp;
  12549. ctx->client_socks[i].in_use = 1;
  12550. event_signal(ctx->client_wait_events[i]);
  12551. return;
  12552. }
  12553. }
  12554. /* queue is full */
  12555. mg_sleep(1);
  12556. }
  12557. }
  12558. static int
  12559. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12560. {
  12561. DEBUG_TRACE("%s", "going idle");
  12562. ctx->client_socks[thread_index].in_use = 0;
  12563. event_wait(ctx->client_wait_events[thread_index]);
  12564. *sp = ctx->client_socks[thread_index];
  12565. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12566. return !ctx->stop_flag;
  12567. }
  12568. #else /* ALTERNATIVE_QUEUE */
  12569. /* Worker threads take accepted socket from the queue */
  12570. static int
  12571. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12572. {
  12573. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12574. (void)thread_index;
  12575. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12576. DEBUG_TRACE("%s", "going idle");
  12577. /* If the queue is empty, wait. We're idle at this point. */
  12578. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  12579. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  12580. }
  12581. /* If we're stopping, sq_head may be equal to sq_tail. */
  12582. if (ctx->sq_head > ctx->sq_tail) {
  12583. /* Copy socket from the queue and increment tail */
  12584. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  12585. ctx->sq_tail++;
  12586. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12587. /* Wrap pointers if needed */
  12588. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  12589. ctx->sq_tail -= QUEUE_SIZE(ctx);
  12590. ctx->sq_head -= QUEUE_SIZE(ctx);
  12591. }
  12592. }
  12593. (void)pthread_cond_signal(&ctx->sq_empty);
  12594. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12595. return !ctx->stop_flag;
  12596. #undef QUEUE_SIZE
  12597. }
  12598. /* Master thread adds accepted socket to a queue */
  12599. static void
  12600. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12601. {
  12602. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12603. if (!ctx) {
  12604. return;
  12605. }
  12606. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12607. /* If the queue is full, wait */
  12608. while (ctx->stop_flag == 0
  12609. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  12610. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  12611. }
  12612. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  12613. /* Copy socket to the queue and increment head */
  12614. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  12615. ctx->sq_head++;
  12616. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12617. }
  12618. (void)pthread_cond_signal(&ctx->sq_full);
  12619. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12620. #undef QUEUE_SIZE
  12621. }
  12622. #endif /* ALTERNATIVE_QUEUE */
  12623. struct worker_thread_args {
  12624. struct mg_context *ctx;
  12625. int index;
  12626. };
  12627. static void *
  12628. worker_thread_run(struct worker_thread_args *thread_args)
  12629. {
  12630. struct mg_context *ctx = thread_args->ctx;
  12631. struct mg_connection *conn;
  12632. struct mg_workerTLS tls;
  12633. #if defined(MG_LEGACY_INTERFACE)
  12634. uint32_t addr;
  12635. #endif
  12636. mg_set_thread_name("worker");
  12637. tls.is_master = 0;
  12638. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12639. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12640. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12641. #endif
  12642. /* Initialize thread local storage before calling any callback */
  12643. pthread_setspecific(sTlsKey, &tls);
  12644. if (ctx->callbacks.init_thread) {
  12645. /* call init_thread for a worker thread (type 1) */
  12646. ctx->callbacks.init_thread(ctx, 1);
  12647. }
  12648. /* Connection structure has been pre-allocated */
  12649. if (((int)thread_args->index < 0)
  12650. || ((unsigned)thread_args->index
  12651. >= (unsigned)ctx->cfg_worker_threads)) {
  12652. mg_cry(fc(ctx),
  12653. "Internal error: Invalid worker index %i",
  12654. (int)thread_args->index);
  12655. return NULL;
  12656. }
  12657. conn = ctx->worker_connections + thread_args->index;
  12658. /* Request buffers are not pre-allocated. They are private to the
  12659. * request and do not contain any state information that might be
  12660. * of interest to anyone observing a server status. */
  12661. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->ctx);
  12662. if (conn->buf == NULL) {
  12663. mg_cry(fc(ctx),
  12664. "Out of memory: Cannot allocate buffer for worker %i",
  12665. (int)thread_args->index);
  12666. return NULL;
  12667. }
  12668. conn->buf_size = (int)ctx->max_request_size;
  12669. conn->ctx = ctx;
  12670. conn->thread_index = thread_args->index;
  12671. conn->request_info.user_data = ctx->user_data;
  12672. /* Allocate a mutex for this connection to allow communication both
  12673. * within the request handler and from elsewhere in the application
  12674. */
  12675. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12676. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12677. * signal sq_empty condvar to wake up the master waiting in
  12678. * produce_socket() */
  12679. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12680. conn->conn_birth_time = time(NULL);
  12681. /* Fill in IP, port info early so even if SSL setup below fails,
  12682. * error handler would have the corresponding info.
  12683. * Thanks to Johannes Winkelmann for the patch.
  12684. */
  12685. #if defined(USE_IPV6)
  12686. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12687. conn->request_info.remote_port =
  12688. ntohs(conn->client.rsa.sin6.sin6_port);
  12689. } else
  12690. #endif
  12691. {
  12692. conn->request_info.remote_port =
  12693. ntohs(conn->client.rsa.sin.sin_port);
  12694. }
  12695. sockaddr_to_string(conn->request_info.remote_addr,
  12696. sizeof(conn->request_info.remote_addr),
  12697. &conn->client.rsa);
  12698. DEBUG_TRACE("Start processing connection from %s",
  12699. conn->request_info.remote_addr);
  12700. #if defined(MG_LEGACY_INTERFACE)
  12701. /* This legacy interface only works for the IPv4 case */
  12702. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12703. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12704. #endif
  12705. conn->request_info.is_ssl = conn->client.is_ssl;
  12706. if (conn->client.is_ssl) {
  12707. #ifndef NO_SSL
  12708. /* HTTPS connection */
  12709. if (sslize(conn,
  12710. conn->ctx->ssl_ctx,
  12711. SSL_accept,
  12712. &(conn->ctx->stop_flag))) {
  12713. /* Get SSL client certificate information (if set) */
  12714. ssl_get_client_cert_info(conn);
  12715. /* process HTTPS connection */
  12716. process_new_connection(conn);
  12717. /* Free client certificate info */
  12718. if (conn->request_info.client_cert) {
  12719. mg_free((void *)(conn->request_info.client_cert->subject));
  12720. mg_free((void *)(conn->request_info.client_cert->issuer));
  12721. mg_free((void *)(conn->request_info.client_cert->serial));
  12722. mg_free((void *)(conn->request_info.client_cert->finger));
  12723. conn->request_info.client_cert->subject = 0;
  12724. conn->request_info.client_cert->issuer = 0;
  12725. conn->request_info.client_cert->serial = 0;
  12726. conn->request_info.client_cert->finger = 0;
  12727. mg_free(conn->request_info.client_cert);
  12728. conn->request_info.client_cert = 0;
  12729. }
  12730. }
  12731. #endif
  12732. } else {
  12733. /* process HTTP connection */
  12734. process_new_connection(conn);
  12735. }
  12736. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12737. conn->request_info.remote_addr,
  12738. difftime(time(NULL), conn->conn_birth_time));
  12739. close_connection(conn);
  12740. DEBUG_TRACE("%s", "Connection closed");
  12741. }
  12742. pthread_setspecific(sTlsKey, NULL);
  12743. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12744. CloseHandle(tls.pthread_cond_helper_mutex);
  12745. #endif
  12746. pthread_mutex_destroy(&conn->mutex);
  12747. /* Free the request buffer. */
  12748. conn->buf_size = 0;
  12749. mg_free(conn->buf);
  12750. conn->buf = NULL;
  12751. DEBUG_TRACE("%s", "exiting");
  12752. return NULL;
  12753. }
  12754. /* Threads have different return types on Windows and Unix. */
  12755. #ifdef _WIN32
  12756. static unsigned __stdcall worker_thread(void *thread_func_param)
  12757. {
  12758. struct worker_thread_args *pwta =
  12759. (struct worker_thread_args *)thread_func_param;
  12760. worker_thread_run(pwta);
  12761. mg_free(thread_func_param);
  12762. return 0;
  12763. }
  12764. #else
  12765. static void *
  12766. worker_thread(void *thread_func_param)
  12767. {
  12768. struct worker_thread_args *pwta =
  12769. (struct worker_thread_args *)thread_func_param;
  12770. worker_thread_run(pwta);
  12771. mg_free(thread_func_param);
  12772. return NULL;
  12773. }
  12774. #endif /* _WIN32 */
  12775. static void
  12776. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12777. {
  12778. struct socket so;
  12779. char src_addr[IP_ADDR_STR_LEN];
  12780. socklen_t len = sizeof(so.rsa);
  12781. int on = 1;
  12782. if (!listener) {
  12783. return;
  12784. }
  12785. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12786. == INVALID_SOCKET) {
  12787. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12788. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12789. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12790. closesocket(so.sock);
  12791. so.sock = INVALID_SOCKET;
  12792. } else {
  12793. /* Put so socket structure into the queue */
  12794. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12795. set_close_on_exec(so.sock, fc(ctx));
  12796. so.is_ssl = listener->is_ssl;
  12797. so.ssl_redir = listener->ssl_redir;
  12798. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12799. mg_cry(fc(ctx),
  12800. "%s: getsockname() failed: %s",
  12801. __func__,
  12802. strerror(ERRNO));
  12803. }
  12804. /* Set TCP keep-alive. This is needed because if HTTP-level
  12805. * keep-alive
  12806. * is enabled, and client resets the connection, server won't get
  12807. * TCP FIN or RST and will keep the connection open forever. With
  12808. * TCP keep-alive, next keep-alive handshake will figure out that
  12809. * the client is down and will close the server end.
  12810. * Thanks to Igor Klopov who suggested the patch. */
  12811. if (setsockopt(so.sock,
  12812. SOL_SOCKET,
  12813. SO_KEEPALIVE,
  12814. (SOCK_OPT_TYPE)&on,
  12815. sizeof(on)) != 0) {
  12816. mg_cry(fc(ctx),
  12817. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12818. __func__,
  12819. strerror(ERRNO));
  12820. }
  12821. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12822. * to effectively fill up the underlying IP packet payload and
  12823. * reduce the overhead of sending lots of small buffers. However
  12824. * this hurts the server's throughput (ie. operations per second)
  12825. * when HTTP 1.1 persistent connections are used and the responses
  12826. * are relatively small (eg. less than 1400 bytes).
  12827. */
  12828. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12829. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12830. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12831. mg_cry(fc(ctx),
  12832. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12833. __func__,
  12834. strerror(ERRNO));
  12835. }
  12836. }
  12837. /* We are using non-blocking sockets. Thus, the
  12838. * set_sock_timeout(so.sock, timeout);
  12839. * call is no longer required. */
  12840. set_blocking_mode(so.sock, 0);
  12841. produce_socket(ctx, &so);
  12842. }
  12843. }
  12844. static void
  12845. master_thread_run(void *thread_func_param)
  12846. {
  12847. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12848. struct mg_workerTLS tls;
  12849. struct pollfd *pfd;
  12850. unsigned int i;
  12851. unsigned int workerthreadcount;
  12852. if (!ctx) {
  12853. return;
  12854. }
  12855. mg_set_thread_name("master");
  12856. /* Increase priority of the master thread */
  12857. #if defined(_WIN32)
  12858. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12859. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12860. int min_prio = sched_get_priority_min(SCHED_RR);
  12861. int max_prio = sched_get_priority_max(SCHED_RR);
  12862. if ((min_prio >= 0) && (max_prio >= 0)
  12863. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12864. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12865. struct sched_param sched_param = {0};
  12866. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12867. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12868. }
  12869. #endif
  12870. /* Initialize thread local storage */
  12871. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12872. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12873. #endif
  12874. tls.is_master = 1;
  12875. pthread_setspecific(sTlsKey, &tls);
  12876. if (ctx->callbacks.init_thread) {
  12877. /* Callback for the master thread (type 0) */
  12878. ctx->callbacks.init_thread(ctx, 0);
  12879. }
  12880. /* Server starts *now* */
  12881. ctx->start_time = time(NULL);
  12882. /* Start the server */
  12883. pfd = ctx->listening_socket_fds;
  12884. while (ctx->stop_flag == 0) {
  12885. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12886. pfd[i].fd = ctx->listening_sockets[i].sock;
  12887. pfd[i].events = POLLIN;
  12888. }
  12889. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12890. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12891. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12892. * successful poll, and POLLIN is defined as
  12893. * (POLLRDNORM | POLLRDBAND)
  12894. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12895. * pfd[i].revents == POLLIN. */
  12896. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12897. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12898. }
  12899. }
  12900. }
  12901. }
  12902. /* Here stop_flag is 1 - Initiate shutdown. */
  12903. DEBUG_TRACE("%s", "stopping workers");
  12904. /* Stop signal received: somebody called mg_stop. Quit. */
  12905. close_all_listening_sockets(ctx);
  12906. /* Wakeup workers that are waiting for connections to handle. */
  12907. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12908. #if defined(ALTERNATIVE_QUEUE)
  12909. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12910. event_signal(ctx->client_wait_events[i]);
  12911. /* Since we know all sockets, we can shutdown the connections. */
  12912. if (ctx->client_socks[i].in_use) {
  12913. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12914. }
  12915. }
  12916. #else
  12917. pthread_cond_broadcast(&ctx->sq_full);
  12918. #endif
  12919. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12920. /* Join all worker threads to avoid leaking threads. */
  12921. workerthreadcount = ctx->cfg_worker_threads;
  12922. for (i = 0; i < workerthreadcount; i++) {
  12923. if (ctx->worker_threadids[i] != 0) {
  12924. mg_join_thread(ctx->worker_threadids[i]);
  12925. }
  12926. }
  12927. #if defined(USE_LUA)
  12928. /* Free Lua state of lua background task */
  12929. if (ctx->lua_background_state) {
  12930. lua_close((lua_State *)ctx->lua_background_state);
  12931. ctx->lua_background_state = 0;
  12932. }
  12933. #endif
  12934. #if !defined(NO_SSL)
  12935. if (ctx->ssl_ctx != NULL) {
  12936. uninitialize_ssl();
  12937. }
  12938. #endif
  12939. DEBUG_TRACE("%s", "exiting");
  12940. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12941. CloseHandle(tls.pthread_cond_helper_mutex);
  12942. #endif
  12943. pthread_setspecific(sTlsKey, NULL);
  12944. /* Signal mg_stop() that we're done.
  12945. * WARNING: This must be the very last thing this
  12946. * thread does, as ctx becomes invalid after this line. */
  12947. ctx->stop_flag = 2;
  12948. }
  12949. /* Threads have different return types on Windows and Unix. */
  12950. #ifdef _WIN32
  12951. static unsigned __stdcall master_thread(void *thread_func_param)
  12952. {
  12953. master_thread_run(thread_func_param);
  12954. return 0;
  12955. }
  12956. #else
  12957. static void *
  12958. master_thread(void *thread_func_param)
  12959. {
  12960. master_thread_run(thread_func_param);
  12961. return NULL;
  12962. }
  12963. #endif /* _WIN32 */
  12964. static void
  12965. free_context(struct mg_context *ctx)
  12966. {
  12967. int i;
  12968. struct mg_handler_info *tmp_rh;
  12969. if (ctx == NULL) {
  12970. return;
  12971. }
  12972. if (ctx->callbacks.exit_context) {
  12973. ctx->callbacks.exit_context(ctx);
  12974. }
  12975. /* All threads exited, no sync is needed. Destroy thread mutex and
  12976. * condvars
  12977. */
  12978. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12979. #if defined(ALTERNATIVE_QUEUE)
  12980. mg_free(ctx->client_socks);
  12981. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12982. event_destroy(ctx->client_wait_events[i]);
  12983. }
  12984. mg_free(ctx->client_wait_events);
  12985. #else
  12986. (void)pthread_cond_destroy(&ctx->sq_empty);
  12987. (void)pthread_cond_destroy(&ctx->sq_full);
  12988. #endif
  12989. /* Destroy other context global data structures mutex */
  12990. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12991. #if defined(USE_TIMERS)
  12992. timers_exit(ctx);
  12993. #endif
  12994. /* Deallocate config parameters */
  12995. for (i = 0; i < NUM_OPTIONS; i++) {
  12996. if (ctx->config[i] != NULL) {
  12997. #if defined(_MSC_VER)
  12998. #pragma warning(suppress : 6001)
  12999. #endif
  13000. mg_free(ctx->config[i]);
  13001. }
  13002. }
  13003. /* Deallocate request handlers */
  13004. while (ctx->handlers) {
  13005. tmp_rh = ctx->handlers;
  13006. ctx->handlers = tmp_rh->next;
  13007. mg_free(tmp_rh->uri);
  13008. mg_free(tmp_rh);
  13009. }
  13010. #ifndef NO_SSL
  13011. /* Deallocate SSL context */
  13012. if (ctx->ssl_ctx != NULL) {
  13013. SSL_CTX_free(ctx->ssl_ctx);
  13014. }
  13015. #endif /* !NO_SSL */
  13016. /* Deallocate worker thread ID array */
  13017. if (ctx->worker_threadids != NULL) {
  13018. mg_free(ctx->worker_threadids);
  13019. }
  13020. /* Deallocate worker thread ID array */
  13021. if (ctx->worker_connections != NULL) {
  13022. mg_free(ctx->worker_connections);
  13023. }
  13024. /* Deallocate the tls variable */
  13025. if (mg_atomic_dec(&sTlsInit) == 0) {
  13026. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13027. DeleteCriticalSection(&global_log_file_lock);
  13028. #endif /* _WIN32 && !__SYMBIAN32__ */
  13029. #if !defined(_WIN32)
  13030. pthread_mutexattr_destroy(&pthread_mutex_attr);
  13031. #endif
  13032. pthread_key_delete(sTlsKey);
  13033. #if defined(USE_LUA)
  13034. lua_exit_optional_libraries();
  13035. #endif
  13036. }
  13037. /* deallocate system name string */
  13038. mg_free(ctx->systemName);
  13039. /* Deallocate context itself */
  13040. mg_free(ctx);
  13041. }
  13042. void
  13043. mg_stop(struct mg_context *ctx)
  13044. {
  13045. pthread_t mt;
  13046. if (!ctx) {
  13047. return;
  13048. }
  13049. /* We don't use a lock here. Calling mg_stop with the same ctx from
  13050. * two threads is not allowed. */
  13051. mt = ctx->masterthreadid;
  13052. if (mt == 0) {
  13053. return;
  13054. }
  13055. ctx->masterthreadid = 0;
  13056. /* Set stop flag, so all threads know they have to exit. */
  13057. ctx->stop_flag = 1;
  13058. /* Wait until everything has stopped. */
  13059. while (ctx->stop_flag != 2) {
  13060. (void)mg_sleep(10);
  13061. }
  13062. mg_join_thread(mt);
  13063. free_context(ctx);
  13064. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13065. (void)WSACleanup();
  13066. #endif /* _WIN32 && !__SYMBIAN32__ */
  13067. }
  13068. static void
  13069. get_system_name(char **sysName)
  13070. {
  13071. #if defined(_WIN32)
  13072. #if !defined(__SYMBIAN32__)
  13073. #if defined(_WIN32_WCE)
  13074. *sysName = mg_strdup("WinCE");
  13075. #else
  13076. char name[128];
  13077. DWORD dwVersion = 0;
  13078. DWORD dwMajorVersion = 0;
  13079. DWORD dwMinorVersion = 0;
  13080. DWORD dwBuild = 0;
  13081. BOOL wowRet, isWoW = FALSE;
  13082. #ifdef _MSC_VER
  13083. #pragma warning(push)
  13084. /* GetVersion was declared deprecated */
  13085. #pragma warning(disable : 4996)
  13086. #endif
  13087. dwVersion = GetVersion();
  13088. #ifdef _MSC_VER
  13089. #pragma warning(pop)
  13090. #endif
  13091. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13092. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13093. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  13094. (void)dwBuild;
  13095. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  13096. sprintf(name,
  13097. "Windows %u.%u%s",
  13098. (unsigned)dwMajorVersion,
  13099. (unsigned)dwMinorVersion,
  13100. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  13101. *sysName = mg_strdup(name);
  13102. #endif
  13103. #else
  13104. *sysName = mg_strdup("Symbian");
  13105. #endif
  13106. #else
  13107. struct utsname name;
  13108. memset(&name, 0, sizeof(name));
  13109. uname(&name);
  13110. *sysName = mg_strdup(name.sysname);
  13111. #endif
  13112. }
  13113. struct mg_context *
  13114. mg_start(const struct mg_callbacks *callbacks,
  13115. void *user_data,
  13116. const char **options)
  13117. {
  13118. struct mg_context *ctx;
  13119. const char *name, *value, *default_value;
  13120. int idx, ok, workerthreadcount;
  13121. unsigned int i;
  13122. int itmp;
  13123. void (*exit_callback)(const struct mg_context *ctx) = 0;
  13124. struct mg_workerTLS tls;
  13125. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13126. WSADATA data;
  13127. WSAStartup(MAKEWORD(2, 2), &data);
  13128. #endif /* _WIN32 && !__SYMBIAN32__ */
  13129. /* Allocate context and initialize reasonable general case defaults. */
  13130. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  13131. return NULL;
  13132. }
  13133. /* Random number generator will initialize at the first call */
  13134. ctx->auth_nonce_mask =
  13135. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  13136. if (mg_atomic_inc(&sTlsInit) == 1) {
  13137. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13138. InitializeCriticalSection(&global_log_file_lock);
  13139. #endif /* _WIN32 && !__SYMBIAN32__ */
  13140. #if !defined(_WIN32)
  13141. pthread_mutexattr_init(&pthread_mutex_attr);
  13142. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  13143. #endif
  13144. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  13145. /* Fatal error - abort start. However, this situation should
  13146. * never occur in practice. */
  13147. mg_atomic_dec(&sTlsInit);
  13148. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  13149. mg_free(ctx);
  13150. return NULL;
  13151. }
  13152. #if defined(USE_LUA)
  13153. lua_init_optional_libraries();
  13154. #endif
  13155. } else {
  13156. /* TODO (low): instead of sleeping, check if sTlsKey is already
  13157. * initialized. */
  13158. mg_sleep(1);
  13159. }
  13160. tls.is_master = -1;
  13161. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13162. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13163. tls.pthread_cond_helper_mutex = NULL;
  13164. #endif
  13165. pthread_setspecific(sTlsKey, &tls);
  13166. /* Dummy use this function - in some #ifdef combinations it's used,
  13167. * while it's not used in others, but GCC seems to stupid to understand
  13168. * #pragma GCC diagnostic ignored "-Wunused-function"
  13169. * in cases the function is unused, and it also complains on
  13170. * __attribute((unused))__ in cases it is used.
  13171. * So dummy use it, to have our peace. */
  13172. (void)mg_current_thread_id();
  13173. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  13174. #if !defined(ALTERNATIVE_QUEUE)
  13175. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  13176. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  13177. #endif
  13178. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  13179. if (!ok) {
  13180. /* Fatal error - abort start. However, this situation should never
  13181. * occur in practice. */
  13182. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  13183. mg_free(ctx);
  13184. pthread_setspecific(sTlsKey, NULL);
  13185. return NULL;
  13186. }
  13187. if (callbacks) {
  13188. ctx->callbacks = *callbacks;
  13189. exit_callback = callbacks->exit_context;
  13190. ctx->callbacks.exit_context = 0;
  13191. }
  13192. ctx->user_data = user_data;
  13193. ctx->handlers = NULL;
  13194. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13195. ctx->shared_lua_websockets = 0;
  13196. #endif
  13197. while (options && (name = *options++) != NULL) {
  13198. if ((idx = get_option_index(name)) == -1) {
  13199. mg_cry(fc(ctx), "Invalid option: %s", name);
  13200. free_context(ctx);
  13201. pthread_setspecific(sTlsKey, NULL);
  13202. return NULL;
  13203. } else if ((value = *options++) == NULL) {
  13204. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  13205. free_context(ctx);
  13206. pthread_setspecific(sTlsKey, NULL);
  13207. return NULL;
  13208. }
  13209. if (ctx->config[idx] != NULL) {
  13210. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  13211. mg_free(ctx->config[idx]);
  13212. }
  13213. ctx->config[idx] = mg_strdup(value);
  13214. DEBUG_TRACE("[%s] -> [%s]", name, value);
  13215. }
  13216. /* Set default value if needed */
  13217. for (i = 0; config_options[i].name != NULL; i++) {
  13218. default_value = config_options[i].default_value;
  13219. if (ctx->config[i] == NULL && default_value != NULL) {
  13220. ctx->config[i] = mg_strdup(default_value);
  13221. }
  13222. }
  13223. itmp = atoi(ctx->config[MAX_REQUEST_SIZE]);
  13224. if (itmp < 1024) {
  13225. mg_cry(fc(ctx), "max_request_size too small");
  13226. free_context(ctx);
  13227. pthread_setspecific(sTlsKey, NULL);
  13228. return NULL;
  13229. }
  13230. ctx->max_request_size = (unsigned)itmp;
  13231. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  13232. if (workerthreadcount > MAX_WORKER_THREADS) {
  13233. mg_cry(fc(ctx), "Too many worker threads");
  13234. free_context(ctx);
  13235. pthread_setspecific(sTlsKey, NULL);
  13236. return NULL;
  13237. }
  13238. if (workerthreadcount <= 0) {
  13239. mg_cry(fc(ctx), "Invalid number of worker threads");
  13240. free_context(ctx);
  13241. pthread_setspecific(sTlsKey, NULL);
  13242. return NULL;
  13243. }
  13244. #if defined(NO_FILES)
  13245. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  13246. mg_cry(fc(ctx), "%s", "Document root must not be set");
  13247. free_context(ctx);
  13248. pthread_setspecific(sTlsKey, NULL);
  13249. return NULL;
  13250. }
  13251. #endif
  13252. get_system_name(&ctx->systemName);
  13253. #if defined(USE_LUA)
  13254. /* If a Lua background script has been configured, start it. */
  13255. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  13256. char ebuf[256];
  13257. void *state = (void *)mg_prepare_lua_context_script(
  13258. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  13259. if (!state) {
  13260. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  13261. free_context(ctx);
  13262. pthread_setspecific(sTlsKey, NULL);
  13263. return NULL;
  13264. }
  13265. ctx->lua_background_state = state;
  13266. } else {
  13267. ctx->lua_background_state = 0;
  13268. }
  13269. #endif
  13270. /* NOTE(lsm): order is important here. SSL certificates must
  13271. * be initialized before listening ports. UID must be set last. */
  13272. if (!set_gpass_option(ctx) ||
  13273. #if !defined(NO_SSL)
  13274. !set_ssl_option(ctx) ||
  13275. #endif
  13276. !set_ports_option(ctx) ||
  13277. #if !defined(_WIN32)
  13278. !set_uid_option(ctx) ||
  13279. #endif
  13280. !set_acl_option(ctx)) {
  13281. free_context(ctx);
  13282. pthread_setspecific(sTlsKey, NULL);
  13283. return NULL;
  13284. }
  13285. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  13286. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  13287. * won't kill the whole process. */
  13288. (void)signal(SIGPIPE, SIG_IGN);
  13289. #endif /* !_WIN32 && !__SYMBIAN32__ */
  13290. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  13291. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13292. sizeof(pthread_t),
  13293. ctx);
  13294. if (ctx->worker_threadids == NULL) {
  13295. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  13296. free_context(ctx);
  13297. pthread_setspecific(sTlsKey, NULL);
  13298. return NULL;
  13299. }
  13300. ctx->worker_connections =
  13301. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  13302. sizeof(struct mg_connection),
  13303. ctx);
  13304. if (ctx->worker_connections == NULL) {
  13305. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  13306. free_context(ctx);
  13307. pthread_setspecific(sTlsKey, NULL);
  13308. return NULL;
  13309. }
  13310. #if defined(ALTERNATIVE_QUEUE)
  13311. ctx->client_wait_events = mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  13312. ctx->cfg_worker_threads,
  13313. ctx);
  13314. if (ctx->client_wait_events == NULL) {
  13315. mg_cry(fc(ctx), "Not enough memory for worker event array");
  13316. mg_free(ctx->worker_threadids);
  13317. free_context(ctx);
  13318. pthread_setspecific(sTlsKey, NULL);
  13319. return NULL;
  13320. }
  13321. ctx->client_socks = mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  13322. ctx->cfg_worker_threads,
  13323. ctx);
  13324. if (ctx->client_wait_events == NULL) {
  13325. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  13326. mg_free(ctx->client_socks);
  13327. mg_free(ctx->worker_threadids);
  13328. free_context(ctx);
  13329. pthread_setspecific(sTlsKey, NULL);
  13330. return NULL;
  13331. }
  13332. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13333. ctx->client_wait_events[i] = event_create();
  13334. if (ctx->client_wait_events[i] == 0) {
  13335. mg_cry(fc(ctx), "Error creating worker event %i", i);
  13336. while (i > 0) {
  13337. i--;
  13338. event_destroy(ctx->client_wait_events[i]);
  13339. }
  13340. mg_free(ctx->client_socks);
  13341. mg_free(ctx->worker_threadids);
  13342. free_context(ctx);
  13343. pthread_setspecific(sTlsKey, NULL);
  13344. return NULL;
  13345. }
  13346. }
  13347. #endif
  13348. #if defined(USE_TIMERS)
  13349. if (timers_init(ctx) != 0) {
  13350. mg_cry(fc(ctx), "Error creating timers");
  13351. free_context(ctx);
  13352. pthread_setspecific(sTlsKey, NULL);
  13353. return NULL;
  13354. }
  13355. #endif
  13356. /* Context has been created - init user libraries */
  13357. if (ctx->callbacks.init_context) {
  13358. ctx->callbacks.init_context(ctx);
  13359. }
  13360. ctx->callbacks.exit_context = exit_callback;
  13361. ctx->context_type = 1; /* server context */
  13362. /* Start master (listening) thread */
  13363. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  13364. /* Start worker threads */
  13365. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13366. struct worker_thread_args *wta = (struct worker_thread_args *)
  13367. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  13368. if (wta) {
  13369. wta->ctx = ctx;
  13370. wta->index = (int)i;
  13371. }
  13372. if ((wta == NULL)
  13373. || (mg_start_thread_with_id(worker_thread,
  13374. wta,
  13375. &ctx->worker_threadids[i]) != 0)) {
  13376. /* thread was not created */
  13377. if (wta != NULL) {
  13378. mg_free(wta);
  13379. }
  13380. if (i > 0) {
  13381. mg_cry(fc(ctx),
  13382. "Cannot start worker thread %i: error %ld",
  13383. i + 1,
  13384. (long)ERRNO);
  13385. } else {
  13386. mg_cry(fc(ctx),
  13387. "Cannot create threads: error %ld",
  13388. (long)ERRNO);
  13389. free_context(ctx);
  13390. pthread_setspecific(sTlsKey, NULL);
  13391. return NULL;
  13392. }
  13393. break;
  13394. }
  13395. }
  13396. pthread_setspecific(sTlsKey, NULL);
  13397. return ctx;
  13398. }
  13399. /* Feature check API function */
  13400. unsigned
  13401. mg_check_feature(unsigned feature)
  13402. {
  13403. static const unsigned feature_set = 0
  13404. /* Set bits for available features according to API documentation.
  13405. * This bit mask is created at compile time, according to the active
  13406. * preprocessor defines. It is a single const value at runtime. */
  13407. #if !defined(NO_FILES)
  13408. | 0x0001u
  13409. #endif
  13410. #if !defined(NO_SSL)
  13411. | 0x0002u
  13412. #endif
  13413. #if !defined(NO_CGI)
  13414. | 0x0004u
  13415. #endif
  13416. #if defined(USE_IPV6)
  13417. | 0x0008u
  13418. #endif
  13419. #if defined(USE_WEBSOCKET)
  13420. | 0x0010u
  13421. #endif
  13422. #if defined(USE_LUA)
  13423. | 0x0020u
  13424. #endif
  13425. #if defined(USE_DUKTAPE)
  13426. | 0x0040u
  13427. #endif
  13428. #if !defined(NO_CACHING)
  13429. | 0x0080u
  13430. #endif
  13431. #if defined(USE_SERVER_STATS)
  13432. | 0x0100u
  13433. #endif
  13434. /* Set some extra bits not defined in the API documentation.
  13435. * These bits may change without further notice. */
  13436. #if defined(MG_LEGACY_INTERFACE)
  13437. | 0x8000u
  13438. #endif
  13439. #if defined(MEMORY_DEBUGGING)
  13440. | 0x0100u
  13441. #endif
  13442. #if defined(USE_TIMERS)
  13443. | 0x0200u
  13444. #endif
  13445. #if !defined(NO_NONCE_CHECK)
  13446. | 0x0400u
  13447. #endif
  13448. #if !defined(NO_POPEN)
  13449. | 0x0800u
  13450. #endif
  13451. ;
  13452. return (feature & feature_set);
  13453. }
  13454. /* Get system information. It can be printed or stored by the caller.
  13455. * Return the size of available information. */
  13456. static int
  13457. mg_get_system_info_impl(char *buffer, int buflen)
  13458. {
  13459. char block[256];
  13460. int system_info_length = 0;
  13461. #if defined(_WIN32)
  13462. const char *eol = "\r\n";
  13463. #else
  13464. const char *eol = "\n";
  13465. #endif
  13466. if (buffer == NULL) {
  13467. /* Avoid some warning (although, if some dillweed supplies
  13468. * buffer==NULL combined with buflen>0, he deserves a crash).
  13469. */
  13470. buflen = 0;
  13471. }
  13472. /* Server version */
  13473. {
  13474. const char *version = mg_version();
  13475. mg_snprintf(NULL,
  13476. NULL,
  13477. block,
  13478. sizeof(block),
  13479. "Server Version: %s%s",
  13480. version,
  13481. eol);
  13482. system_info_length += (int)strlen(block);
  13483. if (system_info_length < buflen) {
  13484. strcat(buffer, block);
  13485. }
  13486. }
  13487. /* System info */
  13488. {
  13489. #if defined(_WIN32)
  13490. #if !defined(__SYMBIAN32__)
  13491. DWORD dwVersion = 0;
  13492. DWORD dwMajorVersion = 0;
  13493. DWORD dwMinorVersion = 0;
  13494. SYSTEM_INFO si;
  13495. GetSystemInfo(&si);
  13496. #ifdef _MSC_VER
  13497. #pragma warning(push)
  13498. /* GetVersion was declared deprecated */
  13499. #pragma warning(disable : 4996)
  13500. #endif
  13501. dwVersion = GetVersion();
  13502. #ifdef _MSC_VER
  13503. #pragma warning(pop)
  13504. #endif
  13505. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13506. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13507. mg_snprintf(NULL,
  13508. NULL,
  13509. block,
  13510. sizeof(block),
  13511. "Windows %u.%u%s",
  13512. (unsigned)dwMajorVersion,
  13513. (unsigned)dwMinorVersion,
  13514. eol);
  13515. system_info_length += (int)strlen(block);
  13516. if (system_info_length < buflen) {
  13517. strcat(buffer, block);
  13518. }
  13519. mg_snprintf(NULL,
  13520. NULL,
  13521. block,
  13522. sizeof(block),
  13523. "CPU: type %u, cores %u, mask %x%s",
  13524. (unsigned)si.wProcessorArchitecture,
  13525. (unsigned)si.dwNumberOfProcessors,
  13526. (unsigned)si.dwActiveProcessorMask,
  13527. eol);
  13528. system_info_length += (int)strlen(block);
  13529. if (system_info_length < buflen) {
  13530. strcat(buffer, block);
  13531. }
  13532. #else
  13533. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  13534. system_info_length += (int)strlen(block);
  13535. if (system_info_length < buflen) {
  13536. strcat(buffer, block);
  13537. }
  13538. #endif
  13539. #else
  13540. struct utsname name;
  13541. memset(&name, 0, sizeof(name));
  13542. uname(&name);
  13543. mg_snprintf(NULL,
  13544. NULL,
  13545. block,
  13546. sizeof(block),
  13547. "%s %s (%s) - %s%s",
  13548. name.sysname,
  13549. name.version,
  13550. name.release,
  13551. name.machine,
  13552. eol);
  13553. system_info_length += (int)strlen(block);
  13554. if (system_info_length < buflen) {
  13555. strcat(buffer, block);
  13556. }
  13557. #endif
  13558. }
  13559. /* Features */
  13560. {
  13561. mg_snprintf(NULL,
  13562. NULL,
  13563. block,
  13564. sizeof(block),
  13565. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  13566. mg_check_feature(0xFFFFFFFFu),
  13567. eol,
  13568. mg_check_feature(1) ? " Files" : "",
  13569. mg_check_feature(2) ? " HTTPS" : "",
  13570. mg_check_feature(4) ? " CGI" : "",
  13571. mg_check_feature(8) ? " IPv6" : "",
  13572. mg_check_feature(16) ? " WebSockets" : "",
  13573. mg_check_feature(32) ? " Lua" : "",
  13574. mg_check_feature(64) ? " JavaScript" : "",
  13575. mg_check_feature(128) ? " Cache" : "",
  13576. eol);
  13577. system_info_length += (int)strlen(block);
  13578. if (system_info_length < buflen) {
  13579. strcat(buffer, block);
  13580. }
  13581. #ifdef USE_LUA
  13582. mg_snprintf(NULL,
  13583. NULL,
  13584. block,
  13585. sizeof(block),
  13586. "Lua Version: %u (%s)%s",
  13587. (unsigned)LUA_VERSION_NUM,
  13588. LUA_RELEASE,
  13589. eol);
  13590. system_info_length += (int)strlen(block);
  13591. if (system_info_length < buflen) {
  13592. strcat(buffer, block);
  13593. }
  13594. #endif
  13595. #if defined(USE_DUKTAPE)
  13596. mg_snprintf(NULL,
  13597. NULL,
  13598. block,
  13599. sizeof(block),
  13600. "JavaScript: Duktape %u.%u.%u%s",
  13601. (unsigned)DUK_VERSION / 10000,
  13602. ((unsigned)DUK_VERSION / 100) % 100,
  13603. (unsigned)DUK_VERSION % 100,
  13604. eol);
  13605. system_info_length += (int)strlen(block);
  13606. if (system_info_length < buflen) {
  13607. strcat(buffer, block);
  13608. }
  13609. #endif
  13610. }
  13611. /* Build date */
  13612. {
  13613. mg_snprintf(
  13614. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  13615. system_info_length += (int)strlen(block);
  13616. if (system_info_length < buflen) {
  13617. strcat(buffer, block);
  13618. }
  13619. }
  13620. /* Compiler information */
  13621. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  13622. {
  13623. #if defined(_MSC_VER)
  13624. mg_snprintf(NULL,
  13625. NULL,
  13626. block,
  13627. sizeof(block),
  13628. "MSC: %u (%u)%s",
  13629. (unsigned)_MSC_VER,
  13630. (unsigned)_MSC_FULL_VER,
  13631. eol);
  13632. system_info_length += (int)strlen(block);
  13633. if (system_info_length < buflen) {
  13634. strcat(buffer, block);
  13635. }
  13636. #elif defined(__MINGW64__)
  13637. mg_snprintf(NULL,
  13638. NULL,
  13639. block,
  13640. sizeof(block),
  13641. "MinGW64: %u.%u%s",
  13642. (unsigned)__MINGW64_VERSION_MAJOR,
  13643. (unsigned)__MINGW64_VERSION_MINOR,
  13644. eol);
  13645. system_info_length += (int)strlen(block);
  13646. if (system_info_length < buflen) {
  13647. strcat(buffer, block);
  13648. }
  13649. mg_snprintf(NULL,
  13650. NULL,
  13651. block,
  13652. sizeof(block),
  13653. "MinGW32: %u.%u%s",
  13654. (unsigned)__MINGW32_MAJOR_VERSION,
  13655. (unsigned)__MINGW32_MINOR_VERSION,
  13656. eol);
  13657. system_info_length += (int)strlen(block);
  13658. if (system_info_length < buflen) {
  13659. strcat(buffer, block);
  13660. }
  13661. #elif defined(__MINGW32__)
  13662. mg_snprintf(NULL,
  13663. NULL,
  13664. block,
  13665. sizeof(block),
  13666. "MinGW32: %u.%u%s",
  13667. (unsigned)__MINGW32_MAJOR_VERSION,
  13668. (unsigned)__MINGW32_MINOR_VERSION,
  13669. eol);
  13670. system_info_length += (int)strlen(block);
  13671. if (system_info_length < buflen) {
  13672. strcat(buffer, block);
  13673. }
  13674. #elif defined(__clang__)
  13675. mg_snprintf(NULL,
  13676. NULL,
  13677. block,
  13678. sizeof(block),
  13679. "clang: %u.%u.%u (%s)%s",
  13680. __clang_major__,
  13681. __clang_minor__,
  13682. __clang_patchlevel__,
  13683. __clang_version__,
  13684. eol);
  13685. system_info_length += (int)strlen(block);
  13686. if (system_info_length < buflen) {
  13687. strcat(buffer, block);
  13688. }
  13689. #elif defined(__GNUC__)
  13690. mg_snprintf(NULL,
  13691. NULL,
  13692. block,
  13693. sizeof(block),
  13694. "gcc: %u.%u.%u%s",
  13695. (unsigned)__GNUC__,
  13696. (unsigned)__GNUC_MINOR__,
  13697. (unsigned)__GNUC_PATCHLEVEL__,
  13698. eol);
  13699. system_info_length += (int)strlen(block);
  13700. if (system_info_length < buflen) {
  13701. strcat(buffer, block);
  13702. }
  13703. #elif defined(__INTEL_COMPILER)
  13704. mg_snprintf(NULL,
  13705. NULL,
  13706. block,
  13707. sizeof(block),
  13708. "Intel C/C++: %u%s",
  13709. (unsigned)__INTEL_COMPILER,
  13710. eol);
  13711. system_info_length += (int)strlen(block);
  13712. if (system_info_length < buflen) {
  13713. strcat(buffer, block);
  13714. }
  13715. #elif defined(__BORLANDC__)
  13716. mg_snprintf(NULL,
  13717. NULL,
  13718. block,
  13719. sizeof(block),
  13720. "Borland C: 0x%x%s",
  13721. (unsigned)__BORLANDC__,
  13722. eol);
  13723. system_info_length += (int)strlen(block);
  13724. if (system_info_length < buflen) {
  13725. strcat(buffer, block);
  13726. }
  13727. #elif defined(__SUNPRO_C)
  13728. mg_snprintf(NULL,
  13729. NULL,
  13730. block,
  13731. sizeof(block),
  13732. "Solaris: 0x%x%s",
  13733. (unsigned)__SUNPRO_C,
  13734. eol);
  13735. system_info_length += (int)strlen(block);
  13736. if (system_info_length < buflen) {
  13737. strcat(buffer, block);
  13738. }
  13739. #else
  13740. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13741. system_info_length += (int)strlen(block);
  13742. if (system_info_length < buflen) {
  13743. strcat(buffer, block);
  13744. }
  13745. #endif
  13746. }
  13747. /* Determine 32/64 bit data mode.
  13748. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13749. {
  13750. mg_snprintf(NULL,
  13751. NULL,
  13752. block,
  13753. sizeof(block),
  13754. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13755. "ptr:%u, size:%u, time:%u%s",
  13756. (unsigned)sizeof(short),
  13757. (unsigned)sizeof(int),
  13758. (unsigned)sizeof(long),
  13759. (unsigned)sizeof(long long),
  13760. (unsigned)sizeof(float),
  13761. (unsigned)sizeof(double),
  13762. (unsigned)sizeof(long double),
  13763. (unsigned)sizeof(char),
  13764. (unsigned)sizeof(wchar_t),
  13765. (unsigned)sizeof(void *),
  13766. (unsigned)sizeof(size_t),
  13767. (unsigned)sizeof(time_t),
  13768. eol);
  13769. system_info_length += (int)strlen(block);
  13770. if (system_info_length < buflen) {
  13771. strcat(buffer, block);
  13772. }
  13773. }
  13774. return system_info_length;
  13775. }
  13776. #if defined(USE_SERVER_STATS)
  13777. /* Get context information. It can be printed or stored by the caller.
  13778. * Return the size of available information. */
  13779. static int
  13780. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  13781. {
  13782. char block[256];
  13783. int context_info_length = 0;
  13784. #if defined(_WIN32)
  13785. const char *eol = "\r\n";
  13786. #else
  13787. const char *eol = "\n";
  13788. #endif
  13789. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  13790. const char *eoobj = "}";
  13791. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  13792. if ((buffer == NULL) || (buflen < 10)) {
  13793. buflen = 0;
  13794. }
  13795. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  13796. context_info_length += (int)strlen(block);
  13797. if (context_info_length < buflen) {
  13798. strcat(buffer, block);
  13799. }
  13800. /* Memory information */
  13801. if (ms) {
  13802. mg_snprintf(NULL,
  13803. NULL,
  13804. block,
  13805. sizeof(block),
  13806. "\"memory\" : {%s"
  13807. "\"blocks\" : %i,%s"
  13808. "\"used\" : %" INT64_FMT ",%s"
  13809. "\"maxUsed\" : %" INT64_FMT "%s"
  13810. "}%s%s",
  13811. eol,
  13812. ms->blockCount,
  13813. eol,
  13814. ms->totalMemUsed,
  13815. eol,
  13816. ms->maxMemUsed,
  13817. eol,
  13818. (ctx ? "," : ""),
  13819. eol);
  13820. context_info_length += (int)strlen(block);
  13821. if (context_info_length + reserved_len < buflen) {
  13822. strcat(buffer, block);
  13823. }
  13824. }
  13825. /* Connections information */
  13826. if (ctx) {
  13827. mg_snprintf(NULL,
  13828. NULL,
  13829. block,
  13830. sizeof(block),
  13831. "\"connections\" : {%s"
  13832. "\"active\" : %i,%s"
  13833. "\"maxActive\" : %i,%s"
  13834. "\"total\" : %" INT64_FMT "%s"
  13835. "},%s",
  13836. eol,
  13837. ctx->active_connections,
  13838. eol,
  13839. ctx->max_connections,
  13840. eol,
  13841. ctx->total_connections,
  13842. eol,
  13843. eol);
  13844. context_info_length += (int)strlen(block);
  13845. if (context_info_length + reserved_len < buflen) {
  13846. strcat(buffer, block);
  13847. }
  13848. }
  13849. /* Requests information */
  13850. if (ctx) {
  13851. mg_snprintf(NULL,
  13852. NULL,
  13853. block,
  13854. sizeof(block),
  13855. "\"requests\" : {%s"
  13856. "\"total\" : %" INT64_FMT "%s"
  13857. "}%s",
  13858. eol,
  13859. ctx->total_requests,
  13860. eol,
  13861. eol);
  13862. context_info_length += (int)strlen(block);
  13863. if (context_info_length + reserved_len < buflen) {
  13864. strcat(buffer, block);
  13865. }
  13866. }
  13867. if ((buflen > 0) && buffer && buffer[0]) {
  13868. if (context_info_length < buflen) {
  13869. strcat(buffer, eoobj);
  13870. strcat(buffer, eol);
  13871. context_info_length += reserved_len;
  13872. }
  13873. }
  13874. return context_info_length;
  13875. }
  13876. #endif
  13877. /* Get system information. It can be printed or stored by the caller.
  13878. * Return the size of available information. */
  13879. int
  13880. mg_get_system_info(char *buffer, int buflen)
  13881. {
  13882. if ((buffer == NULL) || (buflen < 1)) {
  13883. return mg_get_system_info_impl(NULL, 0);
  13884. } else {
  13885. /* Reset buffer, so we can always use strcat. */
  13886. buffer[0] = 0;
  13887. return mg_get_system_info_impl(buffer, buflen);
  13888. }
  13889. }
  13890. /* Get context information. It can be printed or stored by the caller.
  13891. * Return the size of available information. */
  13892. int
  13893. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  13894. {
  13895. #if defined(USE_SERVER_STATS)
  13896. if ((buffer == NULL) || (buflen < 1)) {
  13897. return mg_get_context_info_impl(ctx, NULL, 0);
  13898. } else {
  13899. /* Reset buffer, so we can always use strcat. */
  13900. buffer[0] = 0;
  13901. return mg_get_context_info_impl(ctx, buffer, buflen);
  13902. }
  13903. #else
  13904. (void)ctx;
  13905. if ((buffer != NULL) && (buflen > 0)) {
  13906. buffer[0] = 0;
  13907. }
  13908. return 0;
  13909. #endif
  13910. }
  13911. /* mg_init_library counter */
  13912. static int mg_init_library_called = 0;
  13913. #if !defined(NO_SSL)
  13914. static int mg_ssl_initialized = 0;
  13915. #endif
  13916. /* Initialize this library. This function does not need to be thread safe. */
  13917. unsigned
  13918. mg_init_library(unsigned features)
  13919. {
  13920. #if !defined(NO_SSL)
  13921. char ebuf[128];
  13922. #endif
  13923. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  13924. unsigned features_inited = features_to_init;
  13925. #if !defined(NO_SSL)
  13926. if (features_to_init & 2) {
  13927. if (!mg_ssl_initialized) {
  13928. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  13929. mg_ssl_initialized = 1;
  13930. } else {
  13931. (void)ebuf;
  13932. /* TODO: print error */
  13933. features_inited &= ~(2u);
  13934. }
  13935. } else {
  13936. /* ssl already initialized */
  13937. }
  13938. }
  13939. #endif
  13940. /* Start Windows. */
  13941. if (mg_init_library_called <= 0) {
  13942. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13943. WSADATA data;
  13944. WSAStartup(MAKEWORD(2, 2), &data);
  13945. #endif /* _WIN32 && !__SYMBIAN32__ */
  13946. mg_init_library_called = 1;
  13947. } else {
  13948. mg_init_library_called++;
  13949. }
  13950. return features_inited;
  13951. }
  13952. /* Un-initialize this library. */
  13953. unsigned
  13954. mg_exit_library(void)
  13955. {
  13956. if (mg_init_library_called <= 0) {
  13957. return 0;
  13958. }
  13959. mg_init_library_called--;
  13960. if (mg_init_library_called == 0) {
  13961. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13962. (void)WSACleanup();
  13963. #endif /* _WIN32 && !__SYMBIAN32__ */
  13964. #if !defined(NO_SSL)
  13965. if (mg_ssl_initialized) {
  13966. uninitialize_ssl();
  13967. mg_ssl_initialized = 0;
  13968. }
  13969. #endif
  13970. }
  13971. return 1;
  13972. }
  13973. /* End of civetweb.c */