civetweb.c 485 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385
  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. /* Alternative queue is well tested and should be the new default */
  92. #ifdef NO_ALTERNATIVE_QUEUE
  93. #ifdef ALTERNATIVE_QUEUE
  94. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  95. #endif
  96. #else
  97. #define ALTERNATIVE_QUEUE
  98. #endif
  99. /* DTL -- including winsock2.h works better if lean and mean */
  100. #ifndef WIN32_LEAN_AND_MEAN
  101. #define WIN32_LEAN_AND_MEAN
  102. #endif
  103. #if defined(__SYMBIAN32__)
  104. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  105. * Symbian is no longer maintained since 2014-01-01.
  106. * Recent versions of CivetWeb are no longer tested for Symbian.
  107. * It makes no sense, to support an abandoned operating system.
  108. * All remaining "#ifdef __SYMBIAN__" cases will be droped from
  109. * the code sooner or later.
  110. */
  111. #pragma message \
  112. "Symbian is no longer maintained. CivetWeb will drop Symbian support."
  113. #define NO_SSL /* SSL is not supported */
  114. #define NO_CGI /* CGI is not supported */
  115. #define PATH_MAX FILENAME_MAX
  116. #endif /* __SYMBIAN32__ */
  117. #ifndef CIVETWEB_HEADER_INCLUDED
  118. /* Include the header file here, so the CivetWeb interface is defined for the
  119. * entire implementation, including the following forward definitions. */
  120. #include "civetweb.h"
  121. #endif
  122. #ifndef IGNORE_UNUSED_RESULT
  123. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  124. #endif
  125. #if defined(__GNUC__) || defined(__MINGW32__)
  126. /* GCC unused function attribute seems fundamentally broken.
  127. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  128. * OR UNUSED" for individual functions failed.
  129. * Either the compiler creates an "unused-function" warning if a
  130. * function is not marked with __attribute__((unused)).
  131. * On the other hand, if the function is marked with this attribute,
  132. * but is used, the compiler raises a completely idiotic
  133. * "used-but-marked-unused" warning - and
  134. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  135. * raises error: unknown option after "#pragma GCC diagnostic".
  136. * Disable this warning completely, until the GCC guys sober up
  137. * again.
  138. */
  139. #pragma GCC diagnostic ignored "-Wunused-function"
  140. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  141. #else
  142. #define FUNCTION_MAY_BE_UNUSED
  143. #endif
  144. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  145. #include <sys/types.h>
  146. #include <sys/stat.h>
  147. #include <errno.h>
  148. #include <signal.h>
  149. #include <fcntl.h>
  150. #endif /* !_WIN32_WCE */
  151. #ifdef __clang__
  152. /* When using -Weverything, clang does not accept it's own headers
  153. * in a release build configuration. Disable what is too much in
  154. * -Weverything. */
  155. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  156. #endif
  157. #if defined(__GNUC__) || defined(__MINGW32__)
  158. /* Who on earth came to the conclusion, using __DATE__ should rise
  159. * an "expansion of date or time macro is not reproducible"
  160. * warning. That's exactly what was intended by using this macro.
  161. * Just disable this nonsense warning. */
  162. /* And disabling them does not work either:
  163. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  164. * #pragma clang diagnostic ignored "-Wdate-time"
  165. * So we just have to disable ALL warnings for some lines
  166. * of code.
  167. * This seems to be a known GCC bug, not resolved since 2012:
  168. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  169. */
  170. #endif
  171. #ifdef __MACH__ /* Apple OSX section */
  172. #ifdef __clang__
  173. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  174. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  175. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  176. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  177. #endif
  178. #endif
  179. #define CLOCK_MONOTONIC (1)
  180. #define CLOCK_REALTIME (2)
  181. #include <sys/errno.h>
  182. #include <sys/time.h>
  183. #include <mach/clock.h>
  184. #include <mach/mach.h>
  185. #include <mach/mach_time.h>
  186. #include <assert.h>
  187. /* clock_gettime is not implemented on OSX prior to 10.12 */
  188. static int
  189. _civet_clock_gettime(int clk_id, struct timespec *t)
  190. {
  191. memset(t, 0, sizeof(*t));
  192. if (clk_id == CLOCK_REALTIME) {
  193. struct timeval now;
  194. int rv = gettimeofday(&now, NULL);
  195. if (rv) {
  196. return rv;
  197. }
  198. t->tv_sec = now.tv_sec;
  199. t->tv_nsec = now.tv_usec * 1000;
  200. return 0;
  201. } else if (clk_id == CLOCK_MONOTONIC) {
  202. static uint64_t clock_start_time = 0;
  203. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  204. uint64_t now = mach_absolute_time();
  205. if (clock_start_time == 0) {
  206. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  207. #if defined(DEBUG)
  208. assert(mach_status == KERN_SUCCESS);
  209. #else
  210. /* appease "unused variable" warning for release builds */
  211. (void)mach_status;
  212. #endif
  213. clock_start_time = now;
  214. }
  215. now = (uint64_t)((double)(now - clock_start_time)
  216. * (double)timebase_ifo.numer
  217. / (double)timebase_ifo.denom);
  218. t->tv_sec = now / 1000000000;
  219. t->tv_nsec = now % 1000000000;
  220. return 0;
  221. }
  222. return -1; /* EINVAL - Clock ID is unknown */
  223. }
  224. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  225. #ifdef __CLOCK_AVAILABILITY
  226. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  227. * declared but it may be NULL at runtime. So we need to check before using
  228. * it. */
  229. static int
  230. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  231. {
  232. if (clock_gettime) {
  233. return clock_gettime(clk_id, t);
  234. }
  235. return _civet_clock_gettime(clk_id, t);
  236. }
  237. #define clock_gettime _civet_safe_clock_gettime
  238. #else
  239. #define clock_gettime _civet_clock_gettime
  240. #endif
  241. #endif
  242. #include <time.h>
  243. #include <stdlib.h>
  244. #include <stdarg.h>
  245. #include <assert.h>
  246. #include <string.h>
  247. #include <ctype.h>
  248. #include <limits.h>
  249. #include <stddef.h>
  250. #include <stdio.h>
  251. #include <stdint.h>
  252. #ifndef INT64_MAX
  253. #define INT64_MAX (9223372036854775807)
  254. #endif
  255. #ifndef MAX_WORKER_THREADS
  256. #define MAX_WORKER_THREADS (1024 * 64)
  257. #endif
  258. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  259. #define SOCKET_TIMEOUT_QUANTUM (2000)
  260. #endif
  261. #define SHUTDOWN_RD (0)
  262. #define SHUTDOWN_WR (1)
  263. #define SHUTDOWN_BOTH (2)
  264. mg_static_assert(MAX_WORKER_THREADS >= 1,
  265. "worker threads must be a positive number");
  266. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  267. "size_t data type size check");
  268. #if defined(_WIN32) \
  269. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  270. #include <windows.h>
  271. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  272. #include <ws2tcpip.h>
  273. typedef const char *SOCK_OPT_TYPE;
  274. #if !defined(PATH_MAX)
  275. #define PATH_MAX (MAX_PATH)
  276. #endif
  277. #if !defined(PATH_MAX)
  278. #define PATH_MAX (4096)
  279. #endif
  280. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  281. #ifndef _IN_PORT_T
  282. #ifndef in_port_t
  283. #define in_port_t u_short
  284. #endif
  285. #endif
  286. #ifndef _WIN32_WCE
  287. #include <process.h>
  288. #include <direct.h>
  289. #include <io.h>
  290. #else /* _WIN32_WCE */
  291. #define NO_CGI /* WinCE has no pipes */
  292. #define NO_POPEN /* WinCE has no popen */
  293. typedef long off_t;
  294. #define errno ((int)(GetLastError()))
  295. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  296. #endif /* _WIN32_WCE */
  297. #define MAKEUQUAD(lo, hi) \
  298. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  299. #define RATE_DIFF (10000000) /* 100 nsecs */
  300. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  301. #define SYS2UNIX_TIME(lo, hi) \
  302. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  303. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  304. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  305. * Also use _strtoui64 on modern M$ compilers */
  306. #if defined(_MSC_VER)
  307. #if (_MSC_VER < 1300)
  308. #define STRX(x) #x
  309. #define STR(x) STRX(x)
  310. #define __func__ __FILE__ ":" STR(__LINE__)
  311. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  312. #define strtoll(x, y, z) (_atoi64(x))
  313. #else
  314. #define __func__ __FUNCTION__
  315. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  316. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  317. #endif
  318. #endif /* _MSC_VER */
  319. #define ERRNO ((int)(GetLastError()))
  320. #define NO_SOCKLEN_T
  321. #if defined(_WIN64) || defined(__MINGW64__)
  322. #define SSL_LIB "ssleay64.dll"
  323. #define CRYPTO_LIB "libeay64.dll"
  324. #else
  325. #define SSL_LIB "ssleay32.dll"
  326. #define CRYPTO_LIB "libeay32.dll"
  327. #endif
  328. #define O_NONBLOCK (0)
  329. #ifndef W_OK
  330. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  331. #endif
  332. #if !defined(EWOULDBLOCK)
  333. #define EWOULDBLOCK WSAEWOULDBLOCK
  334. #endif /* !EWOULDBLOCK */
  335. #define _POSIX_
  336. #define INT64_FMT "I64d"
  337. #define UINT64_FMT "I64u"
  338. #define WINCDECL __cdecl
  339. #define vsnprintf_impl _vsnprintf
  340. #define access _access
  341. #define mg_sleep(x) (Sleep(x))
  342. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  343. #ifndef popen
  344. #define popen(x, y) (_popen(x, y))
  345. #endif
  346. #ifndef pclose
  347. #define pclose(x) (_pclose(x))
  348. #endif
  349. #define close(x) (_close(x))
  350. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  351. #define RTLD_LAZY (0)
  352. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  353. #define fdopen(x, y) (_fdopen((x), (y)))
  354. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  355. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  356. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  357. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  358. #define sleep(x) (Sleep((x)*1000))
  359. #define rmdir(x) (_rmdir(x))
  360. #define timegm(x) (_mkgmtime(x))
  361. #if !defined(fileno)
  362. #define fileno(x) (_fileno(x))
  363. #endif /* !fileno MINGW #defines fileno */
  364. typedef HANDLE pthread_mutex_t;
  365. typedef DWORD pthread_key_t;
  366. typedef HANDLE pthread_t;
  367. typedef struct {
  368. CRITICAL_SECTION threadIdSec;
  369. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  370. } pthread_cond_t;
  371. #ifndef __clockid_t_defined
  372. typedef DWORD clockid_t;
  373. #endif
  374. #ifndef CLOCK_MONOTONIC
  375. #define CLOCK_MONOTONIC (1)
  376. #endif
  377. #ifndef CLOCK_REALTIME
  378. #define CLOCK_REALTIME (2)
  379. #endif
  380. #ifndef CLOCK_THREAD
  381. #define CLOCK_THREAD (3)
  382. #endif
  383. #ifndef CLOCK_PROCESS
  384. #define CLOCK_PROCESS (4)
  385. #endif
  386. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  387. #define _TIMESPEC_DEFINED
  388. #endif
  389. #ifndef _TIMESPEC_DEFINED
  390. struct timespec {
  391. time_t tv_sec; /* seconds */
  392. long tv_nsec; /* nanoseconds */
  393. };
  394. #endif
  395. #if !defined(WIN_PTHREADS_TIME_H)
  396. #define MUST_IMPLEMENT_CLOCK_GETTIME
  397. #endif
  398. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  399. #define clock_gettime mg_clock_gettime
  400. static int
  401. clock_gettime(clockid_t clk_id, struct timespec *tp)
  402. {
  403. FILETIME ft;
  404. ULARGE_INTEGER li, li2;
  405. BOOL ok = FALSE;
  406. double d;
  407. static double perfcnt_per_sec = 0.0;
  408. if (tp) {
  409. memset(tp, 0, sizeof(*tp));
  410. if (clk_id == CLOCK_REALTIME) {
  411. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  412. GetSystemTimeAsFileTime(&ft);
  413. li.LowPart = ft.dwLowDateTime;
  414. li.HighPart = ft.dwHighDateTime;
  415. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  416. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  417. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  418. ok = TRUE;
  419. /* END: CLOCK_REALTIME */
  420. } else if (clk_id == CLOCK_MONOTONIC) {
  421. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  422. if (perfcnt_per_sec == 0.0) {
  423. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  424. perfcnt_per_sec = 1.0 / li.QuadPart;
  425. }
  426. if (perfcnt_per_sec != 0.0) {
  427. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  428. d = li.QuadPart * perfcnt_per_sec;
  429. tp->tv_sec = (time_t)d;
  430. d -= tp->tv_sec;
  431. tp->tv_nsec = (long)(d * 1.0E9);
  432. ok = TRUE;
  433. }
  434. /* END: CLOCK_MONOTONIC */
  435. } else if (clk_id == CLOCK_THREAD) {
  436. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  437. FILETIME t_create, t_exit, t_kernel, t_user;
  438. if (GetThreadTimes(GetCurrentThread(),
  439. &t_create,
  440. &t_exit,
  441. &t_kernel,
  442. &t_user)) {
  443. li.LowPart = t_user.dwLowDateTime;
  444. li.HighPart = t_user.dwHighDateTime;
  445. li2.LowPart = t_kernel.dwLowDateTime;
  446. li2.HighPart = t_kernel.dwHighDateTime;
  447. li.QuadPart += li2.QuadPart;
  448. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  449. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  450. ok = TRUE;
  451. }
  452. /* END: CLOCK_THREAD */
  453. } else if (clk_id == CLOCK_PROCESS) {
  454. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  455. FILETIME t_create, t_exit, t_kernel, t_user;
  456. if (GetProcessTimes(GetCurrentProcess(),
  457. &t_create,
  458. &t_exit,
  459. &t_kernel,
  460. &t_user)) {
  461. li.LowPart = t_user.dwLowDateTime;
  462. li.HighPart = t_user.dwHighDateTime;
  463. li2.LowPart = t_kernel.dwLowDateTime;
  464. li2.HighPart = t_kernel.dwHighDateTime;
  465. li.QuadPart += li2.QuadPart;
  466. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  467. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  468. ok = TRUE;
  469. }
  470. /* END: CLOCK_PROCESS */
  471. } else {
  472. /* BEGIN: unknown clock */
  473. /* ok = FALSE; already set by init */
  474. /* END: unknown clock */
  475. }
  476. }
  477. return ok ? 0 : -1;
  478. }
  479. #endif
  480. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  481. static int pthread_mutex_lock(pthread_mutex_t *);
  482. static int pthread_mutex_unlock(pthread_mutex_t *);
  483. static void path_to_unicode(const struct mg_connection *conn,
  484. const char *path,
  485. wchar_t *wbuf,
  486. size_t wbuf_len);
  487. /* All file operations need to be rewritten to solve #246. */
  488. #include "file_ops.inl"
  489. struct mg_file;
  490. static const char *
  491. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  492. /* POSIX dirent interface */
  493. struct dirent {
  494. char d_name[PATH_MAX];
  495. };
  496. typedef struct DIR {
  497. HANDLE handle;
  498. WIN32_FIND_DATAW info;
  499. struct dirent result;
  500. } DIR;
  501. #if defined(_WIN32) && !defined(POLLIN)
  502. #ifndef HAVE_POLL
  503. struct pollfd {
  504. SOCKET fd;
  505. short events;
  506. short revents;
  507. };
  508. #define POLLIN (0x0300)
  509. #endif
  510. #endif
  511. /* Mark required libraries */
  512. #if defined(_MSC_VER)
  513. #pragma comment(lib, "Ws2_32.lib")
  514. #endif
  515. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  516. WINDOWS / UNIX include block */
  517. #include <sys/wait.h>
  518. #include <sys/socket.h>
  519. #include <sys/poll.h>
  520. #include <netinet/in.h>
  521. #include <arpa/inet.h>
  522. #include <sys/time.h>
  523. #include <sys/utsname.h>
  524. #include <stdint.h>
  525. #include <inttypes.h>
  526. #include <netdb.h>
  527. #include <netinet/tcp.h>
  528. typedef const void *SOCK_OPT_TYPE;
  529. #if defined(ANDROID)
  530. typedef unsigned short int in_port_t;
  531. #endif
  532. #include <pwd.h>
  533. #include <unistd.h>
  534. #include <grp.h>
  535. #include <dirent.h>
  536. #define vsnprintf_impl vsnprintf
  537. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  538. #include <dlfcn.h>
  539. #endif
  540. #include <pthread.h>
  541. #if defined(__MACH__)
  542. #define SSL_LIB "libssl.dylib"
  543. #define CRYPTO_LIB "libcrypto.dylib"
  544. #else
  545. #if !defined(SSL_LIB)
  546. #define SSL_LIB "libssl.so"
  547. #endif
  548. #if !defined(CRYPTO_LIB)
  549. #define CRYPTO_LIB "libcrypto.so"
  550. #endif
  551. #endif
  552. #ifndef O_BINARY
  553. #define O_BINARY (0)
  554. #endif /* O_BINARY */
  555. #define closesocket(a) (close(a))
  556. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  557. #define mg_remove(conn, x) (remove(x))
  558. #define mg_sleep(x) (usleep((x)*1000))
  559. #define mg_opendir(conn, x) (opendir(x))
  560. #define mg_closedir(x) (closedir(x))
  561. #define mg_readdir(x) (readdir(x))
  562. #define ERRNO (errno)
  563. #define INVALID_SOCKET (-1)
  564. #define INT64_FMT PRId64
  565. #define UINT64_FMT PRIu64
  566. typedef int SOCKET;
  567. #define WINCDECL
  568. #if defined(__hpux)
  569. /* HPUX 11 does not have monotonic, fall back to realtime */
  570. #ifndef CLOCK_MONOTONIC
  571. #define CLOCK_MONOTONIC CLOCK_REALTIME
  572. #endif
  573. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  574. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  575. * the prototypes use int* rather than socklen_t* which matches the
  576. * actual library expectation. When called with the wrong size arg
  577. * accept() returns a zero client inet addr and check_acl() always
  578. * fails. Since socklen_t is widely used below, just force replace
  579. * their typedef with int. - DTL
  580. */
  581. #define socklen_t int
  582. #endif /* hpux */
  583. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  584. WINDOWS / UNIX include block */
  585. /* va_copy should always be a macro, C99 and C++11 - DTL */
  586. #ifndef va_copy
  587. #define va_copy(x, y) ((x) = (y))
  588. #endif
  589. #ifdef _WIN32
  590. /* Create substitutes for POSIX functions in Win32. */
  591. #if defined(__MINGW32__)
  592. /* Show no warning in case system functions are not used. */
  593. #pragma GCC diagnostic push
  594. #pragma GCC diagnostic ignored "-Wunused-function"
  595. #endif
  596. static CRITICAL_SECTION global_log_file_lock;
  597. FUNCTION_MAY_BE_UNUSED
  598. static DWORD
  599. pthread_self(void)
  600. {
  601. return GetCurrentThreadId();
  602. }
  603. FUNCTION_MAY_BE_UNUSED
  604. static int
  605. pthread_key_create(
  606. pthread_key_t *key,
  607. void (*_ignored)(void *) /* destructor not supported for Windows */
  608. )
  609. {
  610. (void)_ignored;
  611. if ((key != 0)) {
  612. *key = TlsAlloc();
  613. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  614. }
  615. return -2;
  616. }
  617. FUNCTION_MAY_BE_UNUSED
  618. static int
  619. pthread_key_delete(pthread_key_t key)
  620. {
  621. return TlsFree(key) ? 0 : 1;
  622. }
  623. FUNCTION_MAY_BE_UNUSED
  624. static int
  625. pthread_setspecific(pthread_key_t key, void *value)
  626. {
  627. return TlsSetValue(key, value) ? 0 : 1;
  628. }
  629. FUNCTION_MAY_BE_UNUSED
  630. static void *
  631. pthread_getspecific(pthread_key_t key)
  632. {
  633. return TlsGetValue(key);
  634. }
  635. #if defined(__MINGW32__)
  636. /* Enable unused function warning again */
  637. #pragma GCC diagnostic pop
  638. #endif
  639. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  640. #else
  641. static pthread_mutexattr_t pthread_mutex_attr;
  642. #endif /* _WIN32 */
  643. #define PASSWORDS_FILE_NAME ".htpasswd"
  644. #define CGI_ENVIRONMENT_SIZE (4096)
  645. #define MAX_CGI_ENVIR_VARS (256)
  646. #define MG_BUF_LEN (8192)
  647. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  648. #if defined(_WIN32_WCE)
  649. /* Create substitutes for POSIX functions in Win32. */
  650. #if defined(__MINGW32__)
  651. /* Show no warning in case system functions are not used. */
  652. #pragma GCC diagnostic push
  653. #pragma GCC diagnostic ignored "-Wunused-function"
  654. #endif
  655. FUNCTION_MAY_BE_UNUSED
  656. static time_t
  657. time(time_t *ptime)
  658. {
  659. time_t t;
  660. SYSTEMTIME st;
  661. FILETIME ft;
  662. GetSystemTime(&st);
  663. SystemTimeToFileTime(&st, &ft);
  664. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  665. if (ptime != NULL) {
  666. *ptime = t;
  667. }
  668. return t;
  669. }
  670. FUNCTION_MAY_BE_UNUSED
  671. static struct tm *
  672. localtime_s(const time_t *ptime, struct tm *ptm)
  673. {
  674. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  675. FILETIME ft, lft;
  676. SYSTEMTIME st;
  677. TIME_ZONE_INFORMATION tzinfo;
  678. if (ptm == NULL) {
  679. return NULL;
  680. }
  681. *(int64_t *)&ft = t;
  682. FileTimeToLocalFileTime(&ft, &lft);
  683. FileTimeToSystemTime(&lft, &st);
  684. ptm->tm_year = st.wYear - 1900;
  685. ptm->tm_mon = st.wMonth - 1;
  686. ptm->tm_wday = st.wDayOfWeek;
  687. ptm->tm_mday = st.wDay;
  688. ptm->tm_hour = st.wHour;
  689. ptm->tm_min = st.wMinute;
  690. ptm->tm_sec = st.wSecond;
  691. ptm->tm_yday = 0; /* hope nobody uses this */
  692. ptm->tm_isdst =
  693. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  694. return ptm;
  695. }
  696. FUNCTION_MAY_BE_UNUSED
  697. static struct tm *
  698. gmtime_s(const time_t *ptime, struct tm *ptm)
  699. {
  700. /* FIXME(lsm): fix this. */
  701. return localtime_s(ptime, ptm);
  702. }
  703. static int mg_atomic_inc(volatile int *addr);
  704. static struct tm tm_array[MAX_WORKER_THREADS];
  705. static int tm_index = 0;
  706. FUNCTION_MAY_BE_UNUSED
  707. static struct tm *
  708. localtime(const time_t *ptime)
  709. {
  710. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  711. return localtime_s(ptime, tm_array + i);
  712. }
  713. FUNCTION_MAY_BE_UNUSED
  714. static struct tm *
  715. gmtime(const time_t *ptime)
  716. {
  717. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  718. return gmtime_s(ptime, tm_array + i);
  719. }
  720. FUNCTION_MAY_BE_UNUSED
  721. static size_t
  722. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  723. {
  724. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  725. * for WinCE"); */
  726. return 0;
  727. }
  728. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  729. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  730. #define remove(f) mg_remove(NULL, f)
  731. FUNCTION_MAY_BE_UNUSED
  732. static int
  733. rename(const char *a, const char *b)
  734. {
  735. wchar_t wa[PATH_MAX];
  736. wchar_t wb[PATH_MAX];
  737. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  738. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  739. return MoveFileW(wa, wb) ? 0 : -1;
  740. }
  741. struct stat {
  742. int64_t st_size;
  743. time_t st_mtime;
  744. };
  745. FUNCTION_MAY_BE_UNUSED
  746. static int
  747. stat(const char *name, struct stat *st)
  748. {
  749. wchar_t wbuf[PATH_MAX];
  750. WIN32_FILE_ATTRIBUTE_DATA attr;
  751. time_t creation_time, write_time;
  752. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  753. memset(&attr, 0, sizeof(attr));
  754. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  755. st->st_size =
  756. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  757. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  758. attr.ftLastWriteTime.dwHighDateTime);
  759. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  760. attr.ftCreationTime.dwHighDateTime);
  761. if (creation_time > write_time) {
  762. st->st_mtime = creation_time;
  763. } else {
  764. st->st_mtime = write_time;
  765. }
  766. return 0;
  767. }
  768. #define access(x, a) 1 /* not required anyway */
  769. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  770. /* Values from errno.h in Windows SDK (Visual Studio). */
  771. #define EEXIST 17
  772. #define EACCES 13
  773. #define ENOENT 2
  774. #if defined(__MINGW32__)
  775. /* Enable unused function warning again */
  776. #pragma GCC diagnostic pop
  777. #endif
  778. #endif /* defined(_WIN32_WCE) */
  779. #if defined(__GNUC__) || defined(__MINGW32__)
  780. /* Show no warning in case system functions are not used. */
  781. #define GCC_VERSION \
  782. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  783. #if GCC_VERSION >= 40500
  784. #pragma GCC diagnostic push
  785. #pragma GCC diagnostic ignored "-Wunused-function"
  786. #endif /* GCC_VERSION >= 40500 */
  787. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  788. #if defined(__clang__)
  789. /* Show no warning in case system functions are not used. */
  790. #pragma clang diagnostic push
  791. #pragma clang diagnostic ignored "-Wunused-function"
  792. #endif
  793. static pthread_mutex_t global_lock_mutex;
  794. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  795. /* Forward declaration for Windows */
  796. FUNCTION_MAY_BE_UNUSED
  797. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  798. FUNCTION_MAY_BE_UNUSED
  799. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  800. #endif
  801. FUNCTION_MAY_BE_UNUSED
  802. static void
  803. mg_global_lock(void)
  804. {
  805. (void)pthread_mutex_lock(&global_lock_mutex);
  806. }
  807. FUNCTION_MAY_BE_UNUSED
  808. static void
  809. mg_global_unlock(void)
  810. {
  811. (void)pthread_mutex_unlock(&global_lock_mutex);
  812. }
  813. FUNCTION_MAY_BE_UNUSED
  814. static int
  815. mg_atomic_inc(volatile int *addr)
  816. {
  817. int ret;
  818. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  819. /* Depending on the SDK, this function uses either
  820. * (volatile unsigned int *) or (volatile LONG *),
  821. * so whatever you use, the other SDK is likely to raise a warning. */
  822. ret = InterlockedIncrement((volatile long *)addr);
  823. #elif defined(__GNUC__) \
  824. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  825. && !defined(NO_ATOMICS)
  826. ret = __sync_add_and_fetch(addr, 1);
  827. #else
  828. mg_global_lock();
  829. ret = (++(*addr));
  830. mg_global_unlock();
  831. #endif
  832. return ret;
  833. }
  834. FUNCTION_MAY_BE_UNUSED
  835. static int
  836. mg_atomic_dec(volatile int *addr)
  837. {
  838. int ret;
  839. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  840. /* Depending on the SDK, this function uses either
  841. * (volatile unsigned int *) or (volatile LONG *),
  842. * so whatever you use, the other SDK is likely to raise a warning. */
  843. ret = InterlockedDecrement((volatile long *)addr);
  844. #elif defined(__GNUC__) \
  845. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  846. && !defined(NO_ATOMICS)
  847. ret = __sync_sub_and_fetch(addr, 1);
  848. #else
  849. mg_global_lock();
  850. ret = (--(*addr));
  851. mg_global_unlock();
  852. #endif
  853. return ret;
  854. }
  855. #if defined(USE_SERVER_STATS)
  856. static int64_t
  857. mg_atomic_add(volatile int64_t *addr, int64_t value)
  858. {
  859. int64_t ret;
  860. #if defined(_WIN64) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  861. ret = InterlockedAdd64(addr, value);
  862. #elif defined(__GNUC__) \
  863. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  864. && !defined(NO_ATOMICS)
  865. ret = __sync_add_and_fetch(addr, value);
  866. #else
  867. mg_global_lock();
  868. *addr += value;
  869. ret = (*addr);
  870. mg_global_unlock();
  871. #endif
  872. return ret;
  873. }
  874. #endif
  875. #if defined(__GNUC__)
  876. /* Show no warning in case system functions are not used. */
  877. #if GCC_VERSION >= 40500
  878. #pragma GCC diagnostic pop
  879. #endif /* GCC_VERSION >= 40500 */
  880. #endif /* defined(__GNUC__) */
  881. #if defined(__clang__)
  882. /* Show no warning in case system functions are not used. */
  883. #pragma clang diagnostic pop
  884. #endif
  885. #if defined(USE_SERVER_STATS)
  886. struct mg_memory_stat {
  887. volatile int64_t totalMemUsed;
  888. volatile int64_t maxMemUsed;
  889. volatile int blockCount;
  890. };
  891. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  892. static void *
  893. mg_malloc_ex(size_t size,
  894. struct mg_context *ctx,
  895. const char *file,
  896. unsigned line)
  897. {
  898. void *data = malloc(size + 2 * sizeof(uintptr_t));
  899. void *memory = 0;
  900. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  901. #if defined(MEMORY_DEBUGGING)
  902. char mallocStr[256];
  903. #else
  904. (void)file;
  905. (void)line;
  906. #endif
  907. if (data) {
  908. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  909. if (mmem > mstat->maxMemUsed) {
  910. /* could use atomic compare exchange, but this
  911. * seems overkill for statistics data */
  912. mstat->maxMemUsed = mmem;
  913. }
  914. mg_atomic_inc(&mstat->blockCount);
  915. ((uintptr_t *)data)[0] = size;
  916. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  917. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  918. }
  919. #if defined(MEMORY_DEBUGGING)
  920. sprintf(mallocStr,
  921. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  922. memory,
  923. (unsigned long)size,
  924. (unsigned long)mstat->totalMemUsed,
  925. (unsigned long)mstat->blockCount,
  926. file,
  927. line);
  928. #if defined(_WIN32)
  929. OutputDebugStringA(mallocStr);
  930. #else
  931. DEBUG_TRACE("%s", mallocStr);
  932. #endif
  933. #endif
  934. return memory;
  935. }
  936. static void *
  937. mg_calloc_ex(size_t count,
  938. size_t size,
  939. struct mg_context *ctx,
  940. const char *file,
  941. unsigned line)
  942. {
  943. void *data = mg_malloc_ex(size * count, ctx, file, line);
  944. if (data) {
  945. memset(data, 0, size * count);
  946. }
  947. return data;
  948. }
  949. static void
  950. mg_free_ex(void *memory, const char *file, unsigned line)
  951. {
  952. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  953. #if defined(MEMORY_DEBUGGING)
  954. char mallocStr[256];
  955. #else
  956. (void)file;
  957. (void)line;
  958. #endif
  959. if (memory) {
  960. uintptr_t size = ((uintptr_t *)data)[0];
  961. struct mg_memory_stat *mstat =
  962. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  963. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  964. mg_atomic_dec(&mstat->blockCount);
  965. #if defined(MEMORY_DEBUGGING)
  966. sprintf(mallocStr,
  967. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  968. memory,
  969. (unsigned long)size,
  970. (unsigned long)mstat->totalMemUsed,
  971. (unsigned long)mstat->blockCount,
  972. file,
  973. line);
  974. #if defined(_WIN32)
  975. OutputDebugStringA(mallocStr);
  976. #else
  977. DEBUG_TRACE("%s", mallocStr);
  978. #endif
  979. #endif
  980. free(data);
  981. }
  982. }
  983. static void *
  984. mg_realloc_ex(void *memory,
  985. size_t newsize,
  986. struct mg_context *ctx,
  987. const char *file,
  988. unsigned line)
  989. {
  990. void *data;
  991. void *_realloc;
  992. uintptr_t oldsize;
  993. #if defined(MEMORY_DEBUGGING)
  994. char mallocStr[256];
  995. #else
  996. (void)file;
  997. (void)line;
  998. #endif
  999. if (newsize) {
  1000. if (memory) {
  1001. /* Reallocate existing block */
  1002. struct mg_memory_stat *mstat;
  1003. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1004. oldsize = ((uintptr_t *)data)[0];
  1005. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1006. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1007. if (_realloc) {
  1008. data = _realloc;
  1009. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1010. #if defined(MEMORY_DEBUGGING)
  1011. sprintf(mallocStr,
  1012. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1013. memory,
  1014. (unsigned long)oldsize,
  1015. (unsigned long)mstat->totalMemUsed,
  1016. (unsigned long)mstat->blockCount,
  1017. file,
  1018. line);
  1019. #if defined(_WIN32)
  1020. OutputDebugStringA(mallocStr);
  1021. #else
  1022. DEBUG_TRACE("%s", mallocStr);
  1023. #endif
  1024. #endif
  1025. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1026. #if defined(MEMORY_DEBUGGING)
  1027. sprintf(mallocStr,
  1028. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1029. memory,
  1030. (unsigned long)newsize,
  1031. (unsigned long)mstat->totalMemUsed,
  1032. (unsigned long)mstat->blockCount,
  1033. file,
  1034. line);
  1035. #if defined(_WIN32)
  1036. OutputDebugStringA(mallocStr);
  1037. #else
  1038. DEBUG_TRACE("%s", mallocStr);
  1039. #endif
  1040. #endif
  1041. *(uintptr_t *)data = newsize;
  1042. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1043. } else {
  1044. #if defined(MEMORY_DEBUGGING)
  1045. #if defined(_WIN32)
  1046. OutputDebugStringA("MEM: realloc failed\n");
  1047. #else
  1048. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1049. #endif
  1050. #endif
  1051. return _realloc;
  1052. }
  1053. } else {
  1054. /* Allocate new block */
  1055. data = mg_malloc_ex(newsize, ctx, file, line);
  1056. }
  1057. } else {
  1058. /* Free existing block */
  1059. data = 0;
  1060. mg_free_ex(memory, file, line);
  1061. }
  1062. return data;
  1063. }
  1064. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1065. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1066. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1067. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1068. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1069. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1070. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1071. #else /* USE_SERVER_STATS */
  1072. static __inline void *
  1073. mg_malloc(size_t a)
  1074. {
  1075. return malloc(a);
  1076. }
  1077. static __inline void *
  1078. mg_calloc(size_t a, size_t b)
  1079. {
  1080. return calloc(a, b);
  1081. }
  1082. static __inline void *
  1083. mg_realloc(void *a, size_t b)
  1084. {
  1085. return realloc(a, b);
  1086. }
  1087. static __inline void
  1088. mg_free(void *a)
  1089. {
  1090. free(a);
  1091. }
  1092. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1093. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1094. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1095. #define mg_free_ctx(a, c) mg_free(a)
  1096. #endif /* USE_SERVER_STATS */
  1097. static void mg_vsnprintf(const struct mg_connection *conn,
  1098. int *truncated,
  1099. char *buf,
  1100. size_t buflen,
  1101. const char *fmt,
  1102. va_list ap);
  1103. static void mg_snprintf(const struct mg_connection *conn,
  1104. int *truncated,
  1105. char *buf,
  1106. size_t buflen,
  1107. PRINTF_FORMAT_STRING(const char *fmt),
  1108. ...) PRINTF_ARGS(5, 6);
  1109. /* This following lines are just meant as a reminder to use the mg-functions
  1110. * for memory management */
  1111. #ifdef malloc
  1112. #undef malloc
  1113. #endif
  1114. #ifdef calloc
  1115. #undef calloc
  1116. #endif
  1117. #ifdef realloc
  1118. #undef realloc
  1119. #endif
  1120. #ifdef free
  1121. #undef free
  1122. #endif
  1123. #ifdef snprintf
  1124. #undef snprintf
  1125. #endif
  1126. #ifdef vsnprintf
  1127. #undef vsnprintf
  1128. #endif
  1129. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1130. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1131. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1132. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1133. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1134. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  1135. * but this define only works well for Windows. */
  1136. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1137. #endif
  1138. /* mg_init_library counter */
  1139. static int mg_init_library_called = 0;
  1140. #if !defined(NO_SSL)
  1141. static int mg_ssl_initialized = 0;
  1142. #endif
  1143. static pthread_key_t sTlsKey; /* Thread local storage index */
  1144. static int thread_idx_max = 0;
  1145. struct mg_workerTLS {
  1146. int is_master;
  1147. unsigned long thread_idx;
  1148. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1149. HANDLE pthread_cond_helper_mutex;
  1150. struct mg_workerTLS *next_waiting_thread;
  1151. #endif
  1152. };
  1153. #if defined(__GNUC__) || defined(__MINGW32__)
  1154. /* Show no warning in case system functions are not used. */
  1155. #if GCC_VERSION >= 40500
  1156. #pragma GCC diagnostic push
  1157. #pragma GCC diagnostic ignored "-Wunused-function"
  1158. #endif /* GCC_VERSION >= 40500 */
  1159. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1160. #if defined(__clang__)
  1161. /* Show no warning in case system functions are not used. */
  1162. #pragma clang diagnostic push
  1163. #pragma clang diagnostic ignored "-Wunused-function"
  1164. #endif
  1165. /* Get a unique thread ID as unsigned long, independent from the data type
  1166. * of thread IDs defined by the operating system API.
  1167. * If two calls to mg_current_thread_id return the same value, they calls
  1168. * are done from the same thread. If they return different values, they are
  1169. * done from different threads. (Provided this function is used in the same
  1170. * process context and threads are not repeatedly created and deleted, but
  1171. * CivetWeb does not do that).
  1172. * This function must match the signature required for SSL id callbacks:
  1173. * CRYPTO_set_id_callback
  1174. */
  1175. FUNCTION_MAY_BE_UNUSED
  1176. static unsigned long
  1177. mg_current_thread_id(void)
  1178. {
  1179. #ifdef _WIN32
  1180. return GetCurrentThreadId();
  1181. #else
  1182. #ifdef __clang__
  1183. #pragma clang diagnostic push
  1184. #pragma clang diagnostic ignored "-Wunreachable-code"
  1185. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1186. * or not, so one of the two conditions will be unreachable by construction.
  1187. * Unfortunately the C standard does not define a way to check this at
  1188. * compile time, since the #if preprocessor conditions can not use the sizeof
  1189. * operator as an argument. */
  1190. #endif
  1191. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1192. /* This is the problematic case for CRYPTO_set_id_callback:
  1193. * The OS pthread_t can not be cast to unsigned long. */
  1194. struct mg_workerTLS *tls =
  1195. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1196. if (tls == NULL) {
  1197. /* SSL called from an unknown thread: Create some thread index.
  1198. */
  1199. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1200. tls->is_master = -2; /* -2 means "3rd party thread" */
  1201. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1202. pthread_setspecific(sTlsKey, tls);
  1203. }
  1204. return tls->thread_idx;
  1205. } else {
  1206. /* pthread_t may be any data type, so a simple cast to unsigned long
  1207. * can rise a warning/error, depending on the platform.
  1208. * Here memcpy is used as an anything-to-anything cast. */
  1209. unsigned long ret = 0;
  1210. pthread_t t = pthread_self();
  1211. memcpy(&ret, &t, sizeof(pthread_t));
  1212. return ret;
  1213. }
  1214. #ifdef __clang__
  1215. #pragma clang diagnostic pop
  1216. #endif
  1217. #endif
  1218. }
  1219. FUNCTION_MAY_BE_UNUSED
  1220. static uint64_t
  1221. mg_get_current_time_ns(void)
  1222. {
  1223. struct timespec tsnow;
  1224. clock_gettime(CLOCK_REALTIME, &tsnow);
  1225. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1226. }
  1227. #if defined(__GNUC__)
  1228. /* Show no warning in case system functions are not used. */
  1229. #if GCC_VERSION >= 40500
  1230. #pragma GCC diagnostic pop
  1231. #endif /* GCC_VERSION >= 40500 */
  1232. #endif /* defined(__GNUC__) */
  1233. #if defined(__clang__)
  1234. /* Show no warning in case system functions are not used. */
  1235. #pragma clang diagnostic pop
  1236. #endif
  1237. #if !defined(DEBUG_TRACE)
  1238. #if defined(DEBUG)
  1239. static void DEBUG_TRACE_FUNC(const char *func,
  1240. unsigned line,
  1241. PRINTF_FORMAT_STRING(const char *fmt),
  1242. ...) PRINTF_ARGS(3, 4);
  1243. static void
  1244. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1245. {
  1246. va_list args;
  1247. uint64_t nsnow;
  1248. static uint64_t nslast;
  1249. struct timespec tsnow;
  1250. /* Get some operating system independent thread id */
  1251. unsigned long thread_id = mg_current_thread_id();
  1252. clock_gettime(CLOCK_REALTIME, &tsnow);
  1253. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1254. + ((uint64_t)tsnow.tv_nsec);
  1255. if (!nslast) {
  1256. nslast = nsnow;
  1257. }
  1258. flockfile(stdout);
  1259. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1260. (unsigned long)tsnow.tv_sec,
  1261. (unsigned long)tsnow.tv_nsec,
  1262. nsnow - nslast,
  1263. thread_id,
  1264. func,
  1265. line);
  1266. va_start(args, fmt);
  1267. vprintf(fmt, args);
  1268. va_end(args);
  1269. putchar('\n');
  1270. fflush(stdout);
  1271. funlockfile(stdout);
  1272. nslast = nsnow;
  1273. }
  1274. #define DEBUG_TRACE(fmt, ...) \
  1275. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1276. #else
  1277. #define DEBUG_TRACE(fmt, ...) \
  1278. do { \
  1279. } while (0)
  1280. #endif /* DEBUG */
  1281. #endif /* DEBUG_TRACE */
  1282. #define MD5_STATIC static
  1283. #include "md5.inl"
  1284. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1285. #ifdef NO_SOCKLEN_T
  1286. typedef int socklen_t;
  1287. #endif /* NO_SOCKLEN_T */
  1288. #define _DARWIN_UNLIMITED_SELECT
  1289. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1290. #if !defined(MSG_NOSIGNAL)
  1291. #define MSG_NOSIGNAL (0)
  1292. #endif
  1293. #if !defined(SOMAXCONN)
  1294. #define SOMAXCONN (100)
  1295. #endif
  1296. /* Size of the accepted socket queue */
  1297. #if !defined(MGSQLEN)
  1298. #define MGSQLEN (20)
  1299. #endif
  1300. #if defined(NO_SSL)
  1301. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1302. typedef struct SSL_CTX SSL_CTX;
  1303. #else
  1304. #if defined(NO_SSL_DL)
  1305. #include <openssl/ssl.h>
  1306. #include <openssl/err.h>
  1307. #include <openssl/crypto.h>
  1308. #include <openssl/x509.h>
  1309. #include <openssl/pem.h>
  1310. #include <openssl/engine.h>
  1311. #include <openssl/conf.h>
  1312. #include <openssl/dh.h>
  1313. #include <openssl/bn.h>
  1314. #include <openssl/opensslv.h>
  1315. #else
  1316. /* SSL loaded dynamically from DLL.
  1317. * I put the prototypes here to be independent from OpenSSL source
  1318. * installation. */
  1319. typedef struct ssl_st SSL;
  1320. typedef struct ssl_method_st SSL_METHOD;
  1321. typedef struct ssl_ctx_st SSL_CTX;
  1322. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1323. typedef struct x509_name X509_NAME;
  1324. typedef struct asn1_integer ASN1_INTEGER;
  1325. typedef struct bignum BIGNUM;
  1326. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1327. typedef struct evp_md EVP_MD;
  1328. typedef struct x509 X509;
  1329. #define SSL_CTRL_OPTIONS (32)
  1330. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1331. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1332. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1333. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1334. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1335. #define SSL_VERIFY_NONE (0)
  1336. #define SSL_VERIFY_PEER (1)
  1337. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1338. #define SSL_VERIFY_CLIENT_ONCE (4)
  1339. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1340. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1341. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1342. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1343. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1344. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1345. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1346. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1347. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1348. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1349. #define SSL_CB_HANDSHAKE_START (0x10)
  1350. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1351. #define SSL_ERROR_NONE (0)
  1352. #define SSL_ERROR_SSL (1)
  1353. #define SSL_ERROR_WANT_READ (2)
  1354. #define SSL_ERROR_WANT_WRITE (3)
  1355. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1356. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1357. #define SSL_ERROR_ZERO_RETURN (6)
  1358. #define SSL_ERROR_WANT_CONNECT (7)
  1359. #define SSL_ERROR_WANT_ACCEPT (8)
  1360. #define TLSEXT_TYPE_server_name (0)
  1361. #define TLSEXT_NAMETYPE_host_name (0)
  1362. #define SSL_TLSEXT_ERR_OK (0)
  1363. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1364. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1365. #define SSL_TLSEXT_ERR_NOACK (3)
  1366. struct ssl_func {
  1367. const char *name; /* SSL function name */
  1368. void (*ptr)(void); /* Function pointer */
  1369. };
  1370. #ifdef OPENSSL_API_1_1
  1371. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1372. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1373. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1374. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1375. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1376. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1377. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1378. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1379. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1380. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1381. #define OPENSSL_init_ssl \
  1382. (*(int (*)(uint64_t opts, \
  1383. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1384. #define SSL_CTX_use_PrivateKey_file \
  1385. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1386. #define SSL_CTX_use_certificate_file \
  1387. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1388. #define SSL_CTX_set_default_passwd_cb \
  1389. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1390. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1391. #define SSL_CTX_use_certificate_chain_file \
  1392. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1393. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1394. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1395. #define SSL_CTX_set_verify \
  1396. (*(void (*)(SSL_CTX *, \
  1397. int, \
  1398. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1399. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1400. #define SSL_CTX_load_verify_locations \
  1401. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1402. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1403. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1404. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1405. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1406. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1407. #define SSL_CIPHER_get_name \
  1408. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1409. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1410. #define SSL_CTX_set_session_id_context \
  1411. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1412. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1413. #define SSL_CTX_set_cipher_list \
  1414. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1415. #define SSL_CTX_set_options \
  1416. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1417. #define SSL_CTX_set_info_callback \
  1418. (*(void (*)(SSL_CTX * ctx, \
  1419. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1420. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1421. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1422. #define SSL_CTX_callback_ctrl \
  1423. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1424. #define SSL_get_servername \
  1425. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1426. #define SSL_CTX_clear_options(ctx, op) \
  1427. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1428. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1429. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1430. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1431. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1432. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1433. SSL_CTX_callback_ctrl(ctx, \
  1434. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1435. (void (*)(void))cb)
  1436. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1437. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1438. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1439. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1440. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1441. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1442. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1443. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1444. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1445. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1446. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1447. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1448. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1449. #define X509_NAME_oneline \
  1450. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1451. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1452. #define EVP_get_digestbyname \
  1453. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1454. #define EVP_Digest \
  1455. (*(int (*)( \
  1456. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1457. crypto_sw[10].ptr)
  1458. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1459. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1460. #define ASN1_INTEGER_to_BN \
  1461. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1462. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1463. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1464. #define OPENSSL_free(a) CRYPTO_free(a)
  1465. /* init_ssl_ctx() function updates this array.
  1466. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1467. * of respective functions. The macros above (like SSL_connect()) are really
  1468. * just calling these functions indirectly via the pointer. */
  1469. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1470. {"SSL_accept", NULL},
  1471. {"SSL_connect", NULL},
  1472. {"SSL_read", NULL},
  1473. {"SSL_write", NULL},
  1474. {"SSL_get_error", NULL},
  1475. {"SSL_set_fd", NULL},
  1476. {"SSL_new", NULL},
  1477. {"SSL_CTX_new", NULL},
  1478. {"TLS_server_method", NULL},
  1479. {"OPENSSL_init_ssl", NULL},
  1480. {"SSL_CTX_use_PrivateKey_file", NULL},
  1481. {"SSL_CTX_use_certificate_file", NULL},
  1482. {"SSL_CTX_set_default_passwd_cb", NULL},
  1483. {"SSL_CTX_free", NULL},
  1484. {"SSL_CTX_use_certificate_chain_file", NULL},
  1485. {"TLS_client_method", NULL},
  1486. {"SSL_pending", NULL},
  1487. {"SSL_CTX_set_verify", NULL},
  1488. {"SSL_shutdown", NULL},
  1489. {"SSL_CTX_load_verify_locations", NULL},
  1490. {"SSL_CTX_set_default_verify_paths", NULL},
  1491. {"SSL_CTX_set_verify_depth", NULL},
  1492. {"SSL_get_peer_certificate", NULL},
  1493. {"SSL_get_version", NULL},
  1494. {"SSL_get_current_cipher", NULL},
  1495. {"SSL_CIPHER_get_name", NULL},
  1496. {"SSL_CTX_check_private_key", NULL},
  1497. {"SSL_CTX_set_session_id_context", NULL},
  1498. {"SSL_CTX_ctrl", NULL},
  1499. {"SSL_CTX_set_cipher_list", NULL},
  1500. {"SSL_CTX_set_options", NULL},
  1501. {"SSL_CTX_set_info_callback", NULL},
  1502. {"SSL_get_ex_data", NULL},
  1503. {"SSL_set_ex_data", NULL},
  1504. {"SSL_CTX_callback_ctrl", NULL},
  1505. {"SSL_get_servername", NULL},
  1506. {NULL, NULL}};
  1507. /* Similar array as ssl_sw. These functions could be located in different
  1508. * lib. */
  1509. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1510. {"ERR_error_string", NULL},
  1511. {"ERR_remove_state", NULL},
  1512. {"CONF_modules_unload", NULL},
  1513. {"X509_free", NULL},
  1514. {"X509_get_subject_name", NULL},
  1515. {"X509_get_issuer_name", NULL},
  1516. {"X509_NAME_oneline", NULL},
  1517. {"X509_get_serialNumber", NULL},
  1518. {"EVP_get_digestbyname", NULL},
  1519. {"EVP_Digest", NULL},
  1520. {"i2d_X509", NULL},
  1521. {"BN_bn2hex", NULL},
  1522. {"ASN1_INTEGER_to_BN", NULL},
  1523. {"BN_free", NULL},
  1524. {"CRYPTO_free", NULL},
  1525. {NULL, NULL}};
  1526. #else
  1527. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1528. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1529. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1530. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1531. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1532. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1533. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1534. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1535. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1536. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1537. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1538. #define SSL_CTX_use_PrivateKey_file \
  1539. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1540. #define SSL_CTX_use_certificate_file \
  1541. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1542. #define SSL_CTX_set_default_passwd_cb \
  1543. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1544. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1545. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1546. #define SSL_CTX_use_certificate_chain_file \
  1547. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1548. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1549. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1550. #define SSL_CTX_set_verify \
  1551. (*(void (*)(SSL_CTX *, \
  1552. int, \
  1553. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1554. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1555. #define SSL_CTX_load_verify_locations \
  1556. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1557. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1558. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1559. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1560. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1561. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1562. #define SSL_CIPHER_get_name \
  1563. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1564. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1565. #define SSL_CTX_set_session_id_context \
  1566. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1567. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1568. #define SSL_CTX_set_cipher_list \
  1569. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1570. #define SSL_CTX_set_info_callback \
  1571. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1572. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1573. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1574. #define SSL_CTX_callback_ctrl \
  1575. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1576. #define SSL_get_servername \
  1577. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1578. #define SSL_CTX_set_options(ctx, op) \
  1579. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1580. #define SSL_CTX_clear_options(ctx, op) \
  1581. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1582. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1583. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1584. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1585. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1586. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1587. SSL_CTX_callback_ctrl(ctx, \
  1588. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1589. (void (*)(void))cb)
  1590. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1591. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1592. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1593. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1594. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1595. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1596. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1597. #define CRYPTO_set_locking_callback \
  1598. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1599. #define CRYPTO_set_id_callback \
  1600. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1601. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1602. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1603. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1604. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1605. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1606. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1607. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1608. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1609. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1610. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1611. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1612. #define X509_NAME_oneline \
  1613. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1614. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1615. #define i2c_ASN1_INTEGER \
  1616. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1617. #define EVP_get_digestbyname \
  1618. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1619. #define EVP_Digest \
  1620. (*(int (*)( \
  1621. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1622. crypto_sw[18].ptr)
  1623. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1624. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1625. #define ASN1_INTEGER_to_BN \
  1626. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1627. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1628. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1629. #define OPENSSL_free(a) CRYPTO_free(a)
  1630. /* init_ssl_ctx() function updates this array.
  1631. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1632. * of respective functions. The macros above (like SSL_connect()) are really
  1633. * just calling these functions indirectly via the pointer. */
  1634. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1635. {"SSL_accept", NULL},
  1636. {"SSL_connect", NULL},
  1637. {"SSL_read", NULL},
  1638. {"SSL_write", NULL},
  1639. {"SSL_get_error", NULL},
  1640. {"SSL_set_fd", NULL},
  1641. {"SSL_new", NULL},
  1642. {"SSL_CTX_new", NULL},
  1643. {"SSLv23_server_method", NULL},
  1644. {"SSL_library_init", NULL},
  1645. {"SSL_CTX_use_PrivateKey_file", NULL},
  1646. {"SSL_CTX_use_certificate_file", NULL},
  1647. {"SSL_CTX_set_default_passwd_cb", NULL},
  1648. {"SSL_CTX_free", NULL},
  1649. {"SSL_load_error_strings", NULL},
  1650. {"SSL_CTX_use_certificate_chain_file", NULL},
  1651. {"SSLv23_client_method", NULL},
  1652. {"SSL_pending", NULL},
  1653. {"SSL_CTX_set_verify", NULL},
  1654. {"SSL_shutdown", NULL},
  1655. {"SSL_CTX_load_verify_locations", NULL},
  1656. {"SSL_CTX_set_default_verify_paths", NULL},
  1657. {"SSL_CTX_set_verify_depth", NULL},
  1658. {"SSL_get_peer_certificate", NULL},
  1659. {"SSL_get_version", NULL},
  1660. {"SSL_get_current_cipher", NULL},
  1661. {"SSL_CIPHER_get_name", NULL},
  1662. {"SSL_CTX_check_private_key", NULL},
  1663. {"SSL_CTX_set_session_id_context", NULL},
  1664. {"SSL_CTX_ctrl", NULL},
  1665. {"SSL_CTX_set_cipher_list", NULL},
  1666. {"SSL_CTX_set_info_callback", NULL},
  1667. {"SSL_get_ex_data", NULL},
  1668. {"SSL_set_ex_data", NULL},
  1669. {"SSL_CTX_callback_ctrl", NULL},
  1670. {"SSL_get_servername", NULL},
  1671. {NULL, NULL}};
  1672. /* Similar array as ssl_sw. These functions could be located in different
  1673. * lib. */
  1674. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1675. {"CRYPTO_set_locking_callback", NULL},
  1676. {"CRYPTO_set_id_callback", NULL},
  1677. {"ERR_get_error", NULL},
  1678. {"ERR_error_string", NULL},
  1679. {"ERR_remove_state", NULL},
  1680. {"ERR_free_strings", NULL},
  1681. {"ENGINE_cleanup", NULL},
  1682. {"CONF_modules_unload", NULL},
  1683. {"CRYPTO_cleanup_all_ex_data", NULL},
  1684. {"EVP_cleanup", NULL},
  1685. {"X509_free", NULL},
  1686. {"X509_get_subject_name", NULL},
  1687. {"X509_get_issuer_name", NULL},
  1688. {"X509_NAME_oneline", NULL},
  1689. {"X509_get_serialNumber", NULL},
  1690. {"i2c_ASN1_INTEGER", NULL},
  1691. {"EVP_get_digestbyname", NULL},
  1692. {"EVP_Digest", NULL},
  1693. {"i2d_X509", NULL},
  1694. {"BN_bn2hex", NULL},
  1695. {"ASN1_INTEGER_to_BN", NULL},
  1696. {"BN_free", NULL},
  1697. {"CRYPTO_free", NULL},
  1698. {NULL, NULL}};
  1699. #endif /* OPENSSL_API_1_1 */
  1700. #endif /* NO_SSL_DL */
  1701. #endif /* NO_SSL */
  1702. #if !defined(NO_CACHING)
  1703. static const char *month_names[] = {"Jan",
  1704. "Feb",
  1705. "Mar",
  1706. "Apr",
  1707. "May",
  1708. "Jun",
  1709. "Jul",
  1710. "Aug",
  1711. "Sep",
  1712. "Oct",
  1713. "Nov",
  1714. "Dec"};
  1715. #endif /* !NO_CACHING */
  1716. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1717. * the
  1718. * union u. */
  1719. union usa {
  1720. struct sockaddr sa;
  1721. struct sockaddr_in sin;
  1722. #if defined(USE_IPV6)
  1723. struct sockaddr_in6 sin6;
  1724. #endif
  1725. };
  1726. /* Describes a string (chunk of memory). */
  1727. struct vec {
  1728. const char *ptr;
  1729. size_t len;
  1730. };
  1731. struct mg_file_stat {
  1732. /* File properties filled by mg_stat: */
  1733. uint64_t size;
  1734. time_t last_modified;
  1735. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1736. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1737. * case we need a "Content-Eencoding: gzip" header */
  1738. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1739. };
  1740. struct mg_file_in_memory {
  1741. char *p;
  1742. uint32_t pos;
  1743. char mode;
  1744. };
  1745. struct mg_file_access {
  1746. /* File properties filled by mg_fopen: */
  1747. FILE *fp;
  1748. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1749. * support library. Use some struct mg_file_in_memory *mf; instead of
  1750. * membuf char pointer. */
  1751. const char *membuf;
  1752. };
  1753. struct mg_file {
  1754. struct mg_file_stat stat;
  1755. struct mg_file_access access;
  1756. };
  1757. #define STRUCT_FILE_INITIALIZER \
  1758. { \
  1759. { \
  1760. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1761. } \
  1762. , \
  1763. { \
  1764. (FILE *) NULL, (const char *)NULL \
  1765. } \
  1766. }
  1767. /* Describes listening socket, or socket which was accept()-ed by the master
  1768. * thread and queued for future handling by the worker thread. */
  1769. struct socket {
  1770. SOCKET sock; /* Listening socket */
  1771. union usa lsa; /* Local socket address */
  1772. union usa rsa; /* Remote socket address */
  1773. unsigned char is_ssl; /* Is port SSL-ed */
  1774. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1775. * port */
  1776. unsigned char in_use; /* Is valid */
  1777. };
  1778. /* Enum const for all options must be in sync with
  1779. * static struct mg_option config_options[]
  1780. * This is tested in the unit test (test/private.c)
  1781. * "Private Config Options"
  1782. */
  1783. enum {
  1784. LISTENING_PORTS,
  1785. NUM_THREADS,
  1786. RUN_AS_USER,
  1787. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1788. * socket option typedef TCP_NODELAY. */
  1789. MAX_REQUEST_SIZE,
  1790. LINGER_TIMEOUT,
  1791. #if defined(__linux__)
  1792. ALLOW_SENDFILE_CALL,
  1793. #endif
  1794. #if defined(_WIN32)
  1795. CASE_SENSITIVE_FILES,
  1796. #endif
  1797. THROTTLE,
  1798. ACCESS_LOG_FILE,
  1799. ERROR_LOG_FILE,
  1800. ENABLE_KEEP_ALIVE,
  1801. REQUEST_TIMEOUT,
  1802. KEEP_ALIVE_TIMEOUT,
  1803. #if defined(USE_WEBSOCKET)
  1804. WEBSOCKET_TIMEOUT,
  1805. #endif
  1806. DECODE_URL,
  1807. #if defined(USE_LUA)
  1808. LUA_BACKGROUND_SCRIPT,
  1809. LUA_BACKGROUND_SCRIPT_PARAMS,
  1810. #endif
  1811. DOCUMENT_ROOT,
  1812. CGI_EXTENSIONS,
  1813. CGI_ENVIRONMENT,
  1814. PUT_DELETE_PASSWORDS_FILE,
  1815. CGI_INTERPRETER,
  1816. PROTECT_URI,
  1817. AUTHENTICATION_DOMAIN,
  1818. ENABLE_AUTH_DOMAIN_CHECK,
  1819. SSI_EXTENSIONS,
  1820. ENABLE_DIRECTORY_LISTING,
  1821. GLOBAL_PASSWORDS_FILE,
  1822. INDEX_FILES,
  1823. ACCESS_CONTROL_LIST,
  1824. EXTRA_MIME_TYPES,
  1825. SSL_CERTIFICATE,
  1826. SSL_CERTIFICATE_CHAIN,
  1827. URL_REWRITE_PATTERN,
  1828. HIDE_FILES,
  1829. SSL_DO_VERIFY_PEER,
  1830. SSL_CA_PATH,
  1831. SSL_CA_FILE,
  1832. SSL_VERIFY_DEPTH,
  1833. SSL_DEFAULT_VERIFY_PATHS,
  1834. SSL_CIPHER_LIST,
  1835. SSL_PROTOCOL_VERSION,
  1836. SSL_SHORT_TRUST,
  1837. #if defined(USE_LUA)
  1838. LUA_PRELOAD_FILE,
  1839. LUA_SCRIPT_EXTENSIONS,
  1840. LUA_SERVER_PAGE_EXTENSIONS,
  1841. #endif
  1842. #if defined(USE_DUKTAPE)
  1843. DUKTAPE_SCRIPT_EXTENSIONS,
  1844. #endif
  1845. #if defined(USE_WEBSOCKET)
  1846. WEBSOCKET_ROOT,
  1847. #endif
  1848. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1849. LUA_WEBSOCKET_EXTENSIONS,
  1850. #endif
  1851. ACCESS_CONTROL_ALLOW_ORIGIN,
  1852. ACCESS_CONTROL_ALLOW_METHODS,
  1853. ACCESS_CONTROL_ALLOW_HEADERS,
  1854. ERROR_PAGES,
  1855. #if !defined(NO_CACHING)
  1856. STATIC_FILE_MAX_AGE,
  1857. #endif
  1858. #if !defined(NO_SSL)
  1859. STRICT_HTTPS_MAX_AGE,
  1860. #endif
  1861. ADDITIONAL_HEADER,
  1862. ALLOW_INDEX_SCRIPT_SUB_RES,
  1863. NUM_OPTIONS
  1864. };
  1865. /* Config option name, config types, default value.
  1866. * Must be in the same order as the enum const above.
  1867. */
  1868. static struct mg_option config_options[] = {
  1869. /* Once for each server */
  1870. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1871. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1872. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1873. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1874. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1875. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1876. #if defined(__linux__)
  1877. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1878. #endif
  1879. #if defined(_WIN32)
  1880. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1881. #endif
  1882. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1883. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1884. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1885. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1886. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1887. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1888. #if defined(USE_WEBSOCKET)
  1889. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1890. #endif
  1891. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1892. #if defined(USE_LUA)
  1893. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1894. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1895. #endif
  1896. /* Once for each domain */
  1897. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1898. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1899. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1900. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1901. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1902. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1903. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1904. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1905. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1906. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1907. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1908. {"index_files",
  1909. MG_CONFIG_TYPE_STRING_LIST,
  1910. #ifdef USE_LUA
  1911. "index.xhtml,index.html,index.htm,"
  1912. "index.lp,index.lsp,index.lua,index.cgi,"
  1913. "index.shtml,index.php"},
  1914. #else
  1915. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1916. #endif
  1917. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1918. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1919. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1920. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1921. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1922. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1923. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1924. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1925. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1926. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1927. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1928. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1929. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  1930. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1931. #if defined(USE_LUA)
  1932. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1933. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1934. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1935. #endif
  1936. #if defined(USE_DUKTAPE)
  1937. /* The support for duktape is still in alpha version state.
  1938. * The name of this config option might change. */
  1939. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1940. #endif
  1941. #if defined(USE_WEBSOCKET)
  1942. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1943. #endif
  1944. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1945. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1946. #endif
  1947. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1948. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1949. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1950. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1951. #if !defined(NO_CACHING)
  1952. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1953. #endif
  1954. #if !defined(NO_SSL)
  1955. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1956. #endif
  1957. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1958. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1959. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1960. /* Check if the config_options and the corresponding enum have compatible
  1961. * sizes. */
  1962. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1963. == (NUM_OPTIONS + 1),
  1964. "config_options and enum not sync");
  1965. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1966. struct mg_handler_info {
  1967. /* Name/Pattern of the URI. */
  1968. char *uri;
  1969. size_t uri_len;
  1970. /* handler type */
  1971. int handler_type;
  1972. /* Handler for http/https or authorization requests. */
  1973. mg_request_handler handler;
  1974. /* Handler for ws/wss (websocket) requests. */
  1975. mg_websocket_connect_handler connect_handler;
  1976. mg_websocket_ready_handler ready_handler;
  1977. mg_websocket_data_handler data_handler;
  1978. mg_websocket_close_handler close_handler;
  1979. /* accepted subprotocols for ws/wss requests. */
  1980. struct mg_websocket_subprotocols *subprotocols;
  1981. /* Handler for authorization requests */
  1982. mg_authorization_handler auth_handler;
  1983. /* User supplied argument for the handler function. */
  1984. void *cbdata;
  1985. /* next handler in a linked list */
  1986. struct mg_handler_info *next;
  1987. };
  1988. enum {
  1989. CONTEXT_INVALID,
  1990. CONTEXT_SERVER,
  1991. CONTEXT_HTTP_CLIENT,
  1992. CONTEXT_WS_CLIENT
  1993. };
  1994. struct mg_domain_context {
  1995. SSL_CTX *ssl_ctx; /* SSL context */
  1996. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1997. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1998. /* Server nonce */
  1999. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2000. unsigned long nonce_count; /* Used nonces, used for authentication */
  2001. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2002. /* linked list of shared lua websockets */
  2003. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2004. #endif
  2005. };
  2006. struct mg_context {
  2007. /* Part 1 - Physical context:
  2008. * This holds threads, ports, timeouts, ...
  2009. * set for the entire server, independent from the
  2010. * addressed hostname.
  2011. */
  2012. /* Connection related */
  2013. int context_type; /* See CONTEXT_* above */
  2014. struct socket *listening_sockets;
  2015. struct pollfd *listening_socket_fds;
  2016. unsigned int num_listening_sockets;
  2017. struct mg_connection *worker_connections; /* The connection struct, pre-
  2018. * allocated for each worker */
  2019. #if defined(USE_SERVER_STATS)
  2020. int active_connections;
  2021. int max_connections;
  2022. int64_t total_connections;
  2023. int64_t total_requests;
  2024. int64_t total_data_read;
  2025. int64_t total_data_written;
  2026. #endif
  2027. /* Thread related */
  2028. volatile int stop_flag; /* Should we stop event loop */
  2029. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2030. pthread_t masterthreadid; /* The master thread ID */
  2031. unsigned int
  2032. cfg_worker_threads; /* The number of configured worker threads. */
  2033. pthread_t *worker_threadids; /* The worker thread IDs */
  2034. /* Connection to thread dispatching */
  2035. #ifdef ALTERNATIVE_QUEUE
  2036. struct socket *client_socks;
  2037. void **client_wait_events;
  2038. #else
  2039. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2040. volatile int sq_head; /* Head of the socket queue */
  2041. volatile int sq_tail; /* Tail of the socket queue */
  2042. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2043. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2044. #endif
  2045. /* Memory related */
  2046. unsigned int max_request_size; /* The max request size */
  2047. #if defined(USE_SERVER_STATS)
  2048. struct mg_memory_stat ctx_memory;
  2049. #endif
  2050. /* Operating system related */
  2051. char *systemName; /* What operating system is running */
  2052. time_t start_time; /* Server start time, used for authentication
  2053. * and for diagnstics. */
  2054. #if defined(USE_TIMERS)
  2055. struct ttimers *timers;
  2056. #endif
  2057. /* Lua specific: Background operations and shared websockets */
  2058. #if defined(USE_LUA)
  2059. void *lua_background_state;
  2060. #endif
  2061. /* Server nonce */
  2062. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2063. /* Server callbacks */
  2064. struct mg_callbacks callbacks; /* User-defined callback function */
  2065. void *user_data; /* User-defined data */
  2066. /* Part 2 - Logical domain:
  2067. * This holds hostname, TLS certificate, document root, ...
  2068. * set for a domain hosted at the server.
  2069. * There may be multiple domains hosted at one physical server.
  2070. */
  2071. struct mg_domain_context dd; /* default domain */
  2072. struct mg_domain_context *add_domains;
  2073. unsigned int num_add_domains;
  2074. };
  2075. #if defined(USE_SERVER_STATS)
  2076. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2077. static struct mg_memory_stat *
  2078. get_memory_stat(struct mg_context *ctx)
  2079. {
  2080. if (ctx) {
  2081. return &(ctx->ctx_memory);
  2082. }
  2083. return &mg_common_memory;
  2084. }
  2085. #endif
  2086. enum {
  2087. CONNECTION_TYPE_INVALID,
  2088. CONNECTION_TYPE_REQUEST,
  2089. CONNECTION_TYPE_RESPONSE
  2090. };
  2091. struct mg_connection {
  2092. int connection_type; /* see CONNECTION_TYPE_* above */
  2093. struct mg_request_info request_info;
  2094. struct mg_response_info response_info;
  2095. struct mg_context *phys_ctx;
  2096. struct mg_domain_context *dom_ctx;
  2097. #if defined(USE_SERVER_STATS)
  2098. int conn_state; /* 0 = undef, numerical value may change in different
  2099. * versions. For the current definition, see
  2100. * mg_get_connection_info_impl */
  2101. #endif
  2102. SSL *ssl; /* SSL descriptor */
  2103. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2104. struct socket client; /* Connected client */
  2105. time_t conn_birth_time; /* Time (wall clock) when connection was
  2106. * established */
  2107. struct timespec req_time; /* Time (since system start) when the request
  2108. * was received */
  2109. int64_t num_bytes_sent; /* Total bytes sent to client */
  2110. int64_t content_len; /* Content-Length header value */
  2111. int64_t consumed_content; /* How many bytes of content have been read */
  2112. int is_chunked; /* Transfer-Encoding is chunked:
  2113. * 0 = not chunked,
  2114. * 1 = chunked, do data read yet,
  2115. * 2 = chunked, some data read,
  2116. * 3 = chunked, all data read
  2117. */
  2118. size_t chunk_remainder; /* Unread data from the last chunk */
  2119. char *buf; /* Buffer for received data */
  2120. char *path_info; /* PATH_INFO part of the URL */
  2121. int must_close; /* 1 if connection must be closed */
  2122. int accept_gzip; /* 1 if gzip encoding is accepted */
  2123. int in_error_handler; /* 1 if in handler for user defined error
  2124. * pages */
  2125. #if defined(USE_WEBSOCKET)
  2126. int in_websocket_handling; /* 1 if in read_websocket */
  2127. #endif
  2128. int handled_requests; /* Number of requests handled by this connection
  2129. */
  2130. int buf_size; /* Buffer size */
  2131. int request_len; /* Size of the request + headers in a buffer */
  2132. int data_len; /* Total size of data in a buffer */
  2133. int status_code; /* HTTP reply status code, e.g. 200 */
  2134. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2135. * throttle */
  2136. time_t last_throttle_time; /* Last time throttled data was sent */
  2137. int64_t last_throttle_bytes; /* Bytes sent this second */
  2138. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2139. * atomic transmissions for websockets */
  2140. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2141. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2142. #endif
  2143. int thread_index; /* Thread index within ctx */
  2144. };
  2145. /* Directory entry */
  2146. struct de {
  2147. struct mg_connection *conn;
  2148. char *file_name;
  2149. struct mg_file_stat file;
  2150. };
  2151. #if defined(USE_WEBSOCKET)
  2152. static int is_websocket_protocol(const struct mg_connection *conn);
  2153. #else
  2154. #define is_websocket_protocol(conn) (0)
  2155. #endif
  2156. #if !defined(NO_THREAD_NAME)
  2157. #if defined(_WIN32) && defined(_MSC_VER)
  2158. /* Set the thread name for debugging purposes in Visual Studio
  2159. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2160. */
  2161. #pragma pack(push, 8)
  2162. typedef struct tagTHREADNAME_INFO {
  2163. DWORD dwType; /* Must be 0x1000. */
  2164. LPCSTR szName; /* Pointer to name (in user addr space). */
  2165. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2166. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2167. } THREADNAME_INFO;
  2168. #pragma pack(pop)
  2169. #elif defined(__linux__)
  2170. #include <sys/prctl.h>
  2171. #include <sys/sendfile.h>
  2172. #ifdef ALTERNATIVE_QUEUE
  2173. #include <sys/eventfd.h>
  2174. #endif /* ALTERNATIVE_QUEUE */
  2175. #if defined(ALTERNATIVE_QUEUE)
  2176. #ifdef __clang__
  2177. #pragma clang diagnostic push
  2178. #pragma clang diagnostic ignored "-Wunreachable-code"
  2179. /* For every system, "(sizeof(int) == sizeof(void *))" is either always
  2180. * true or always false. One of the two branches is unreachable in any case.
  2181. * Unfortunately the C standard does not define a way to check this at
  2182. * compile time, since the #if preprocessor conditions can not use the sizeof
  2183. * operator as an argument. */
  2184. #endif
  2185. #if defined(__GNUC__) || defined(__MINGW32__)
  2186. /* GCC does not realize one branch is unreachable, so it raises some
  2187. * pointer cast warning within the unreachable branch.
  2188. */
  2189. #pragma GCC diagnostic push
  2190. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
  2191. #pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
  2192. #endif
  2193. static void *
  2194. event_create(void)
  2195. {
  2196. int evhdl = eventfd(0, EFD_CLOEXEC);
  2197. int *ret;
  2198. if (evhdl == -1) {
  2199. /* Linux uses -1 on error, Windows NULL. */
  2200. /* However, Linux does not return 0 on success either. */
  2201. return 0;
  2202. }
  2203. if (sizeof(int) == sizeof(void *)) {
  2204. ret = (void *)evhdl;
  2205. } else {
  2206. ret = (int *)mg_malloc(sizeof(int));
  2207. if (ret) {
  2208. *ret = evhdl;
  2209. } else {
  2210. (void)close(evhdl);
  2211. }
  2212. }
  2213. return (void *)ret;
  2214. }
  2215. static int
  2216. event_wait(void *eventhdl)
  2217. {
  2218. uint64_t u;
  2219. int evhdl, s;
  2220. if (sizeof(int) == sizeof(void *)) {
  2221. evhdl = (int)eventhdl;
  2222. } else {
  2223. if (!eventhdl) {
  2224. /* error */
  2225. return 0;
  2226. }
  2227. evhdl = *(int *)eventhdl;
  2228. }
  2229. s = (int)read(evhdl, &u, sizeof(u));
  2230. if (s != sizeof(uint64_t)) {
  2231. /* error */
  2232. return 0;
  2233. }
  2234. (void)u; /* the value is not required */
  2235. return 1;
  2236. }
  2237. static int
  2238. event_signal(void *eventhdl)
  2239. {
  2240. uint64_t u = 1;
  2241. int evhdl, s;
  2242. if (sizeof(int) == sizeof(void *)) {
  2243. evhdl = (int)eventhdl;
  2244. } else {
  2245. if (!eventhdl) {
  2246. /* error */
  2247. return 0;
  2248. }
  2249. evhdl = *(int *)eventhdl;
  2250. }
  2251. s = (int)write(evhdl, &u, sizeof(u));
  2252. if (s != sizeof(uint64_t)) {
  2253. /* error */
  2254. return 0;
  2255. }
  2256. return 1;
  2257. }
  2258. static void
  2259. event_destroy(void *eventhdl)
  2260. {
  2261. int evhdl;
  2262. if (sizeof(int) == sizeof(void *)) {
  2263. evhdl = (int)eventhdl;
  2264. close(evhdl);
  2265. } else {
  2266. if (!eventhdl) {
  2267. /* error */
  2268. return;
  2269. }
  2270. evhdl = *(int *)eventhdl;
  2271. close(evhdl);
  2272. mg_free(eventhdl);
  2273. }
  2274. }
  2275. #if defined(__GNUC__) || defined(__MINGW32__)
  2276. #pragma GCC diagnostic pop
  2277. #endif
  2278. #ifdef __clang__
  2279. #pragma clang diagnostic pop
  2280. #endif
  2281. #endif
  2282. #endif
  2283. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2284. struct posix_event {
  2285. pthread_mutex_t mutex;
  2286. pthread_cond_t cond;
  2287. };
  2288. static void *
  2289. event_create(void)
  2290. {
  2291. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2292. if (ret == 0) {
  2293. /* out of memory */
  2294. return 0;
  2295. }
  2296. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2297. /* pthread mutex not available */
  2298. mg_free(ret);
  2299. return 0;
  2300. }
  2301. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2302. /* pthread cond not available */
  2303. pthread_mutex_destroy(&(ret->mutex));
  2304. mg_free(ret);
  2305. return 0;
  2306. }
  2307. return (void *)ret;
  2308. }
  2309. static int
  2310. event_wait(void *eventhdl)
  2311. {
  2312. struct posix_event *ev = (struct posix_event *)eventhdl;
  2313. pthread_mutex_lock(&(ev->mutex));
  2314. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2315. pthread_mutex_unlock(&(ev->mutex));
  2316. return 1;
  2317. }
  2318. static int
  2319. event_signal(void *eventhdl)
  2320. {
  2321. struct posix_event *ev = (struct posix_event *)eventhdl;
  2322. pthread_mutex_lock(&(ev->mutex));
  2323. pthread_cond_signal(&(ev->cond));
  2324. pthread_mutex_unlock(&(ev->mutex));
  2325. return 1;
  2326. }
  2327. static void
  2328. event_destroy(void *eventhdl)
  2329. {
  2330. struct posix_event *ev = (struct posix_event *)eventhdl;
  2331. pthread_cond_destroy(&(ev->cond));
  2332. pthread_mutex_destroy(&(ev->mutex));
  2333. mg_free(ev);
  2334. }
  2335. #endif
  2336. static void
  2337. mg_set_thread_name(const char *name)
  2338. {
  2339. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2340. mg_snprintf(
  2341. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2342. #if defined(_WIN32)
  2343. #if defined(_MSC_VER)
  2344. /* Windows and Visual Studio Compiler */
  2345. __try
  2346. {
  2347. THREADNAME_INFO info;
  2348. info.dwType = 0x1000;
  2349. info.szName = threadName;
  2350. info.dwThreadID = ~0U;
  2351. info.dwFlags = 0;
  2352. RaiseException(0x406D1388,
  2353. 0,
  2354. sizeof(info) / sizeof(ULONG_PTR),
  2355. (ULONG_PTR *)&info);
  2356. }
  2357. __except(EXCEPTION_EXECUTE_HANDLER)
  2358. {
  2359. }
  2360. #elif defined(__MINGW32__)
  2361. /* No option known to set thread name for MinGW */
  2362. #endif
  2363. #elif defined(__GLIBC__) \
  2364. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2365. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2366. (void)pthread_setname_np(pthread_self(), threadName);
  2367. #elif defined(__linux__)
  2368. /* on linux we can use the old prctl function */
  2369. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2370. #endif
  2371. }
  2372. #else /* !defined(NO_THREAD_NAME) */
  2373. void
  2374. mg_set_thread_name(const char *threadName)
  2375. {
  2376. }
  2377. #endif
  2378. #if defined(MG_LEGACY_INTERFACE)
  2379. const char **
  2380. mg_get_valid_option_names(void)
  2381. {
  2382. /* This function is deprecated. Use mg_get_valid_options instead. */
  2383. static const char *
  2384. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2385. int i;
  2386. for (i = 0; config_options[i].name != NULL; i++) {
  2387. data[i * 2] = config_options[i].name;
  2388. data[i * 2 + 1] = config_options[i].default_value;
  2389. }
  2390. return data;
  2391. }
  2392. #endif
  2393. const struct mg_option *
  2394. mg_get_valid_options(void)
  2395. {
  2396. return config_options;
  2397. }
  2398. /* Do not open file (used in is_file_in_memory) */
  2399. #define MG_FOPEN_MODE_NONE (0)
  2400. /* Open file for read only access */
  2401. #define MG_FOPEN_MODE_READ (1)
  2402. /* Open file for writing, create and overwrite */
  2403. #define MG_FOPEN_MODE_WRITE (2)
  2404. /* Open file for writing, create and append */
  2405. #define MG_FOPEN_MODE_APPEND (4)
  2406. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2407. * output filep and return 1, otherwise return 0 and don't modify anything.
  2408. */
  2409. static int
  2410. open_file_in_memory(const struct mg_connection *conn,
  2411. const char *path,
  2412. struct mg_file *filep,
  2413. int mode)
  2414. {
  2415. #if defined(MG_USE_OPEN_FILE)
  2416. size_t size = 0;
  2417. const char *buf = NULL;
  2418. if (!conn) {
  2419. return 0;
  2420. }
  2421. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2422. return 0;
  2423. }
  2424. if (conn->phys_ctx->callbacks.open_file) {
  2425. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2426. if (buf != NULL) {
  2427. if (filep == NULL) {
  2428. /* This is a file in memory, but we cannot store the
  2429. * properties
  2430. * now.
  2431. * Called from "is_file_in_memory" function. */
  2432. return 1;
  2433. }
  2434. /* NOTE: override filep->size only on success. Otherwise, it
  2435. * might
  2436. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2437. filep->access.membuf = buf;
  2438. filep->access.fp = NULL;
  2439. /* Size was set by the callback */
  2440. filep->stat.size = size;
  2441. /* Assume the data may change during runtime by setting
  2442. * last_modified = now */
  2443. filep->stat.last_modified = time(NULL);
  2444. filep->stat.is_directory = 0;
  2445. filep->stat.is_gzipped = 0;
  2446. }
  2447. }
  2448. return (buf != NULL);
  2449. #else
  2450. (void)conn;
  2451. (void)path;
  2452. (void)filep;
  2453. (void)mode;
  2454. return 0;
  2455. #endif
  2456. }
  2457. static int
  2458. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2459. {
  2460. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2461. }
  2462. static int
  2463. is_file_opened(const struct mg_file_access *fileacc)
  2464. {
  2465. if (!fileacc) {
  2466. return 0;
  2467. }
  2468. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2469. }
  2470. static int mg_stat(const struct mg_connection *conn,
  2471. const char *path,
  2472. struct mg_file_stat *filep);
  2473. /* mg_fopen will open a file either in memory or on the disk.
  2474. * The input parameter path is a string in UTF-8 encoding.
  2475. * The input parameter mode is MG_FOPEN_MODE_*
  2476. * On success, either fp or membuf will be set in the output
  2477. * struct file. All status members will also be set.
  2478. * The function returns 1 on success, 0 on error. */
  2479. static int
  2480. mg_fopen(const struct mg_connection *conn,
  2481. const char *path,
  2482. int mode,
  2483. struct mg_file *filep)
  2484. {
  2485. int found;
  2486. if (!filep) {
  2487. return 0;
  2488. }
  2489. filep->access.fp = NULL;
  2490. filep->access.membuf = NULL;
  2491. if (!is_file_in_memory(conn, path)) {
  2492. /* filep is initialized in mg_stat: all fields with memset to,
  2493. * some fields like size and modification date with values */
  2494. found = mg_stat(conn, path, &(filep->stat));
  2495. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2496. /* file does not exist and will not be created */
  2497. return 0;
  2498. }
  2499. #ifdef _WIN32
  2500. {
  2501. wchar_t wbuf[PATH_MAX];
  2502. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2503. switch (mode) {
  2504. case MG_FOPEN_MODE_READ:
  2505. filep->access.fp = _wfopen(wbuf, L"rb");
  2506. break;
  2507. case MG_FOPEN_MODE_WRITE:
  2508. filep->access.fp = _wfopen(wbuf, L"wb");
  2509. break;
  2510. case MG_FOPEN_MODE_APPEND:
  2511. filep->access.fp = _wfopen(wbuf, L"ab");
  2512. break;
  2513. }
  2514. }
  2515. #else
  2516. /* Linux et al already use unicode. No need to convert. */
  2517. switch (mode) {
  2518. case MG_FOPEN_MODE_READ:
  2519. filep->access.fp = fopen(path, "r");
  2520. break;
  2521. case MG_FOPEN_MODE_WRITE:
  2522. filep->access.fp = fopen(path, "w");
  2523. break;
  2524. case MG_FOPEN_MODE_APPEND:
  2525. filep->access.fp = fopen(path, "a");
  2526. break;
  2527. }
  2528. #endif
  2529. if (!found) {
  2530. /* File did not exist before fopen was called.
  2531. * Maybe it has been created now. Get stat info
  2532. * like creation time now. */
  2533. found = mg_stat(conn, path, &(filep->stat));
  2534. (void)found;
  2535. }
  2536. /* file is on disk */
  2537. return (filep->access.fp != NULL);
  2538. } else {
  2539. /* is_file_in_memory returned true */
  2540. if (open_file_in_memory(conn, path, filep, mode)) {
  2541. /* file is in memory */
  2542. return (filep->access.membuf != NULL);
  2543. }
  2544. }
  2545. /* Open failed */
  2546. return 0;
  2547. }
  2548. /* return 0 on success, just like fclose */
  2549. static int
  2550. mg_fclose(struct mg_file_access *fileacc)
  2551. {
  2552. int ret = -1;
  2553. if (fileacc != NULL) {
  2554. if (fileacc->fp != NULL) {
  2555. ret = fclose(fileacc->fp);
  2556. } else if (fileacc->membuf != NULL) {
  2557. ret = 0;
  2558. }
  2559. /* reset all members of fileacc */
  2560. memset(fileacc, 0, sizeof(*fileacc));
  2561. }
  2562. return ret;
  2563. }
  2564. static void
  2565. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2566. {
  2567. for (; *src != '\0' && n > 1; n--) {
  2568. *dst++ = *src++;
  2569. }
  2570. *dst = '\0';
  2571. }
  2572. static int
  2573. lowercase(const char *s)
  2574. {
  2575. return tolower(*(const unsigned char *)s);
  2576. }
  2577. int
  2578. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2579. {
  2580. int diff = 0;
  2581. if (len > 0) {
  2582. do {
  2583. diff = lowercase(s1++) - lowercase(s2++);
  2584. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2585. }
  2586. return diff;
  2587. }
  2588. int
  2589. mg_strcasecmp(const char *s1, const char *s2)
  2590. {
  2591. int diff;
  2592. do {
  2593. diff = lowercase(s1++) - lowercase(s2++);
  2594. } while (diff == 0 && s1[-1] != '\0');
  2595. return diff;
  2596. }
  2597. static char *
  2598. mg_strndup(const char *ptr, size_t len)
  2599. {
  2600. char *p;
  2601. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2602. mg_strlcpy(p, ptr, len + 1);
  2603. }
  2604. return p;
  2605. }
  2606. static char *
  2607. mg_strdup(const char *str)
  2608. {
  2609. return mg_strndup(str, strlen(str));
  2610. }
  2611. static const char *
  2612. mg_strcasestr(const char *big_str, const char *small_str)
  2613. {
  2614. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2615. if (big_len >= small_len) {
  2616. for (i = 0; i <= (big_len - small_len); i++) {
  2617. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2618. return big_str + i;
  2619. }
  2620. }
  2621. }
  2622. return NULL;
  2623. }
  2624. /* Return null terminated string of given maximum length.
  2625. * Report errors if length is exceeded. */
  2626. static void
  2627. mg_vsnprintf(const struct mg_connection *conn,
  2628. int *truncated,
  2629. char *buf,
  2630. size_t buflen,
  2631. const char *fmt,
  2632. va_list ap)
  2633. {
  2634. int n, ok;
  2635. if (buflen == 0) {
  2636. if (truncated) {
  2637. *truncated = 1;
  2638. }
  2639. return;
  2640. }
  2641. #ifdef __clang__
  2642. #pragma clang diagnostic push
  2643. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2644. /* Using fmt as a non-literal is intended here, since it is mostly called
  2645. * indirectly by mg_snprintf */
  2646. #endif
  2647. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2648. ok = (n >= 0) && ((size_t)n < buflen);
  2649. #ifdef __clang__
  2650. #pragma clang diagnostic pop
  2651. #endif
  2652. if (ok) {
  2653. if (truncated) {
  2654. *truncated = 0;
  2655. }
  2656. } else {
  2657. if (truncated) {
  2658. *truncated = 1;
  2659. }
  2660. mg_cry(conn,
  2661. "truncating vsnprintf buffer: [%.*s]",
  2662. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2663. buf);
  2664. n = (int)buflen - 1;
  2665. }
  2666. buf[n] = '\0';
  2667. }
  2668. static void
  2669. mg_snprintf(const struct mg_connection *conn,
  2670. int *truncated,
  2671. char *buf,
  2672. size_t buflen,
  2673. const char *fmt,
  2674. ...)
  2675. {
  2676. va_list ap;
  2677. va_start(ap, fmt);
  2678. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2679. va_end(ap);
  2680. }
  2681. static int
  2682. get_option_index(const char *name)
  2683. {
  2684. int i;
  2685. for (i = 0; config_options[i].name != NULL; i++) {
  2686. if (strcmp(config_options[i].name, name) == 0) {
  2687. return i;
  2688. }
  2689. }
  2690. return -1;
  2691. }
  2692. const char *
  2693. mg_get_option(const struct mg_context *ctx, const char *name)
  2694. {
  2695. int i;
  2696. if ((i = get_option_index(name)) == -1) {
  2697. return NULL;
  2698. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2699. return "";
  2700. } else {
  2701. return ctx->dd.config[i];
  2702. }
  2703. }
  2704. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2705. struct mg_context *
  2706. mg_get_context(const struct mg_connection *conn)
  2707. {
  2708. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2709. }
  2710. void *
  2711. mg_get_user_data(const struct mg_context *ctx)
  2712. {
  2713. return (ctx == NULL) ? NULL : ctx->user_data;
  2714. }
  2715. void
  2716. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2717. {
  2718. if (conn != NULL) {
  2719. conn->request_info.conn_data = data;
  2720. }
  2721. }
  2722. void *
  2723. mg_get_user_connection_data(const struct mg_connection *conn)
  2724. {
  2725. if (conn != NULL) {
  2726. return conn->request_info.conn_data;
  2727. }
  2728. return NULL;
  2729. }
  2730. #if defined(MG_LEGACY_INTERFACE)
  2731. /* Deprecated: Use mg_get_server_ports instead. */
  2732. size_t
  2733. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2734. {
  2735. size_t i;
  2736. if (!ctx) {
  2737. return 0;
  2738. }
  2739. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2740. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2741. ports[i] =
  2742. #if defined(USE_IPV6)
  2743. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2744. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2745. :
  2746. #endif
  2747. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2748. }
  2749. return i;
  2750. }
  2751. #endif
  2752. int
  2753. mg_get_server_ports(const struct mg_context *ctx,
  2754. int size,
  2755. struct mg_server_ports *ports)
  2756. {
  2757. int i, cnt = 0;
  2758. if (size <= 0) {
  2759. return -1;
  2760. }
  2761. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2762. if (!ctx) {
  2763. return -1;
  2764. }
  2765. if (!ctx->listening_sockets) {
  2766. return -1;
  2767. }
  2768. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2769. ports[cnt].port =
  2770. #if defined(USE_IPV6)
  2771. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2772. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2773. :
  2774. #endif
  2775. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2776. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2777. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2778. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2779. /* IPv4 */
  2780. ports[cnt].protocol = 1;
  2781. cnt++;
  2782. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2783. /* IPv6 */
  2784. ports[cnt].protocol = 3;
  2785. cnt++;
  2786. }
  2787. }
  2788. return cnt;
  2789. }
  2790. static void
  2791. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2792. {
  2793. buf[0] = '\0';
  2794. if (!usa) {
  2795. return;
  2796. }
  2797. if (usa->sa.sa_family == AF_INET) {
  2798. getnameinfo(&usa->sa,
  2799. sizeof(usa->sin),
  2800. buf,
  2801. (unsigned)len,
  2802. NULL,
  2803. 0,
  2804. NI_NUMERICHOST);
  2805. }
  2806. #if defined(USE_IPV6)
  2807. else if (usa->sa.sa_family == AF_INET6) {
  2808. getnameinfo(&usa->sa,
  2809. sizeof(usa->sin6),
  2810. buf,
  2811. (unsigned)len,
  2812. NULL,
  2813. 0,
  2814. NI_NUMERICHOST);
  2815. }
  2816. #endif
  2817. }
  2818. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2819. * included in all responses other than 100, 101, 5xx. */
  2820. static void
  2821. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2822. {
  2823. struct tm *tm;
  2824. tm = ((t != NULL) ? gmtime(t) : NULL);
  2825. if (tm != NULL) {
  2826. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2827. } else {
  2828. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2829. buf[buf_len - 1] = '\0';
  2830. }
  2831. }
  2832. /* difftime for struct timespec. Return value is in seconds. */
  2833. static double
  2834. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2835. {
  2836. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2837. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2838. }
  2839. /* Print error message to the opened error log stream. */
  2840. void
  2841. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2842. {
  2843. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2844. va_list ap;
  2845. struct mg_file fi;
  2846. time_t timestamp;
  2847. va_start(ap, fmt);
  2848. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2849. va_end(ap);
  2850. buf[sizeof(buf) - 1] = 0;
  2851. DEBUG_TRACE("mg_cry: %s", buf);
  2852. if (!conn) {
  2853. puts(buf);
  2854. return;
  2855. }
  2856. /* Do not lock when getting the callback value, here and below.
  2857. * I suppose this is fine, since function cannot disappear in the
  2858. * same way string option can. */
  2859. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2860. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2861. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2862. if (mg_fopen(conn,
  2863. conn->dom_ctx->config[ERROR_LOG_FILE],
  2864. MG_FOPEN_MODE_APPEND,
  2865. &fi) == 0) {
  2866. fi.access.fp = NULL;
  2867. }
  2868. } else {
  2869. fi.access.fp = NULL;
  2870. }
  2871. if (fi.access.fp != NULL) {
  2872. flockfile(fi.access.fp);
  2873. timestamp = time(NULL);
  2874. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2875. fprintf(fi.access.fp,
  2876. "[%010lu] [error] [client %s] ",
  2877. (unsigned long)timestamp,
  2878. src_addr);
  2879. if (conn->request_info.request_method != NULL) {
  2880. fprintf(fi.access.fp,
  2881. "%s %s: ",
  2882. conn->request_info.request_method,
  2883. conn->request_info.request_uri
  2884. ? conn->request_info.request_uri
  2885. : "");
  2886. }
  2887. fprintf(fi.access.fp, "%s", buf);
  2888. fputc('\n', fi.access.fp);
  2889. fflush(fi.access.fp);
  2890. funlockfile(fi.access.fp);
  2891. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2892. * mg_cry here anyway ;-) */
  2893. }
  2894. }
  2895. }
  2896. /* Return fake connection structure. Used for logging, if connection
  2897. * is not applicable at the moment of logging. */
  2898. static struct mg_connection *
  2899. fc(struct mg_context *ctx)
  2900. {
  2901. static struct mg_connection fake_connection;
  2902. fake_connection.phys_ctx = ctx;
  2903. fake_connection.dom_ctx = &(ctx->dd);
  2904. return &fake_connection;
  2905. }
  2906. const char *
  2907. mg_version(void)
  2908. {
  2909. return CIVETWEB_VERSION;
  2910. }
  2911. const struct mg_request_info *
  2912. mg_get_request_info(const struct mg_connection *conn)
  2913. {
  2914. if (!conn) {
  2915. return NULL;
  2916. }
  2917. #if 1 /* TODO: deal with legacy */
  2918. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2919. static char txt[16];
  2920. sprintf(txt, "%03i", conn->response_info.status_code);
  2921. ((struct mg_connection *)conn)->request_info.local_uri =
  2922. ((struct mg_connection *)conn)->request_info.request_uri =
  2923. txt; /* TODO: not thread safe */
  2924. ((struct mg_connection *)conn)->request_info.num_headers =
  2925. conn->response_info.num_headers;
  2926. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2927. conn->response_info.http_headers,
  2928. sizeof(conn->response_info.http_headers));
  2929. } else
  2930. #endif
  2931. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2932. return NULL;
  2933. }
  2934. return &conn->request_info;
  2935. }
  2936. const struct mg_response_info *
  2937. mg_get_response_info(const struct mg_connection *conn)
  2938. {
  2939. if (!conn) {
  2940. return NULL;
  2941. }
  2942. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2943. return NULL;
  2944. }
  2945. return &conn->response_info;
  2946. }
  2947. static const char *
  2948. get_proto_name(const struct mg_connection *conn)
  2949. {
  2950. #ifdef __clang__
  2951. #pragma clang diagnostic push
  2952. #pragma clang diagnostic ignored "-Wunreachable-code"
  2953. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2954. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2955. * unreachable, but splitting into four different #ifdef clauses here is more
  2956. * complicated.
  2957. */
  2958. #endif
  2959. const struct mg_request_info *ri = &conn->request_info;
  2960. const char *proto =
  2961. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2962. : (ri->is_ssl ? "https" : "http"));
  2963. return proto;
  2964. #ifdef __clang__
  2965. #pragma clang diagnostic pop
  2966. #endif
  2967. }
  2968. int
  2969. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2970. {
  2971. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2972. return -1;
  2973. } else {
  2974. int truncated = 0;
  2975. const struct mg_request_info *ri = &conn->request_info;
  2976. const char *proto = get_proto_name(conn);
  2977. if (ri->local_uri == NULL) {
  2978. return -1;
  2979. }
  2980. if ((ri->request_uri != NULL)
  2981. && strcmp(ri->local_uri, ri->request_uri)) {
  2982. mg_snprintf(conn,
  2983. &truncated,
  2984. buf,
  2985. buflen,
  2986. "%s://%s",
  2987. proto,
  2988. ri->request_uri);
  2989. if (truncated) {
  2990. return -1;
  2991. }
  2992. return 0;
  2993. } else {
  2994. #if defined(USE_IPV6)
  2995. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2996. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2997. : htons(conn->client.lsa.sin.sin_port);
  2998. #else
  2999. int port = htons(conn->client.lsa.sin.sin_port);
  3000. #endif
  3001. int def_port = ri->is_ssl ? 443 : 80;
  3002. int auth_domain_check_enabled =
  3003. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3004. && (!mg_strcasecmp(
  3005. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  3006. "yes"));
  3007. const char *server_domain =
  3008. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3009. char portstr[16];
  3010. char server_ip[48];
  3011. if (port != def_port) {
  3012. sprintf(portstr, ":%u", (unsigned)port);
  3013. } else {
  3014. portstr[0] = 0;
  3015. }
  3016. if (!auth_domain_check_enabled || !server_domain) {
  3017. sockaddr_to_string(server_ip,
  3018. sizeof(server_ip),
  3019. &conn->client.lsa);
  3020. server_domain = server_ip;
  3021. }
  3022. mg_snprintf(conn,
  3023. &truncated,
  3024. buf,
  3025. buflen,
  3026. "%s://%s%s%s",
  3027. proto,
  3028. server_domain,
  3029. portstr,
  3030. ri->local_uri);
  3031. if (truncated) {
  3032. return -1;
  3033. }
  3034. return 0;
  3035. }
  3036. }
  3037. }
  3038. /* Skip the characters until one of the delimiters characters found.
  3039. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3040. * Advance pointer to buffer to the next word. Return found 0-terminated
  3041. * word.
  3042. * Delimiters can be quoted with quotechar. */
  3043. static char *
  3044. skip_quoted(char **buf,
  3045. const char *delimiters,
  3046. const char *whitespace,
  3047. char quotechar)
  3048. {
  3049. char *p, *begin_word, *end_word, *end_whitespace;
  3050. begin_word = *buf;
  3051. end_word = begin_word + strcspn(begin_word, delimiters);
  3052. /* Check for quotechar */
  3053. if (end_word > begin_word) {
  3054. p = end_word - 1;
  3055. while (*p == quotechar) {
  3056. /* While the delimiter is quoted, look for the next delimiter.
  3057. */
  3058. /* This happens, e.g., in calls from parse_auth_header,
  3059. * if the user name contains a " character. */
  3060. /* If there is anything beyond end_word, copy it. */
  3061. if (*end_word != '\0') {
  3062. size_t end_off = strcspn(end_word + 1, delimiters);
  3063. memmove(p, end_word, end_off + 1);
  3064. p += end_off; /* p must correspond to end_word - 1 */
  3065. end_word += end_off + 1;
  3066. } else {
  3067. *p = '\0';
  3068. break;
  3069. }
  3070. }
  3071. for (p++; p < end_word; p++) {
  3072. *p = '\0';
  3073. }
  3074. }
  3075. if (*end_word == '\0') {
  3076. *buf = end_word;
  3077. } else {
  3078. #if defined(__GNUC__) || defined(__MINGW32__)
  3079. /* Disable spurious conversion warning for GCC */
  3080. #if GCC_VERSION >= 40500
  3081. #pragma GCC diagnostic push
  3082. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3083. #endif /* GCC_VERSION >= 40500 */
  3084. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3085. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3086. #if defined(__GNUC__) || defined(__MINGW32__)
  3087. #if GCC_VERSION >= 40500
  3088. #pragma GCC diagnostic pop
  3089. #endif /* GCC_VERSION >= 40500 */
  3090. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3091. for (p = end_word; p < end_whitespace; p++) {
  3092. *p = '\0';
  3093. }
  3094. *buf = end_whitespace;
  3095. }
  3096. return begin_word;
  3097. }
  3098. /* Return HTTP header value, or NULL if not found. */
  3099. static const char *
  3100. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3101. {
  3102. int i;
  3103. for (i = 0; i < num_hdr; i++) {
  3104. if (!mg_strcasecmp(name, hdr[i].name)) {
  3105. return hdr[i].value;
  3106. }
  3107. }
  3108. return NULL;
  3109. }
  3110. #if defined(USE_WEBSOCKET)
  3111. /* Retrieve requested HTTP header multiple values, and return the number of
  3112. * found occurences */
  3113. static int
  3114. get_req_headers(const struct mg_request_info *ri,
  3115. const char *name,
  3116. const char **output,
  3117. int output_max_size)
  3118. {
  3119. int i;
  3120. int cnt = 0;
  3121. if (ri) {
  3122. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3123. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3124. output[cnt++] = ri->http_headers[i].value;
  3125. }
  3126. }
  3127. }
  3128. return cnt;
  3129. }
  3130. #endif
  3131. const char *
  3132. mg_get_header(const struct mg_connection *conn, const char *name)
  3133. {
  3134. if (!conn) {
  3135. return NULL;
  3136. }
  3137. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3138. return get_header(conn->request_info.http_headers,
  3139. conn->request_info.num_headers,
  3140. name);
  3141. }
  3142. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3143. return get_header(conn->response_info.http_headers,
  3144. conn->response_info.num_headers,
  3145. name);
  3146. }
  3147. return NULL;
  3148. }
  3149. static const char *
  3150. get_http_version(const struct mg_connection *conn)
  3151. {
  3152. if (!conn) {
  3153. return NULL;
  3154. }
  3155. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3156. return conn->request_info.http_version;
  3157. }
  3158. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3159. return conn->response_info.http_version;
  3160. }
  3161. return NULL;
  3162. }
  3163. /* A helper function for traversing a comma separated list of values.
  3164. * It returns a list pointer shifted to the next value, or NULL if the end
  3165. * of the list found.
  3166. * Value is stored in val vector. If value has form "x=y", then eq_val
  3167. * vector is initialized to point to the "y" part, and val vector length
  3168. * is adjusted to point only to "x". */
  3169. static const char *
  3170. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3171. {
  3172. int end;
  3173. reparse:
  3174. if (val == NULL || list == NULL || *list == '\0') {
  3175. /* End of the list */
  3176. return NULL;
  3177. }
  3178. /* Skip over leading LWS */
  3179. while (*list == ' ' || *list == '\t')
  3180. list++;
  3181. val->ptr = list;
  3182. if ((list = strchr(val->ptr, ',')) != NULL) {
  3183. /* Comma found. Store length and shift the list ptr */
  3184. val->len = ((size_t)(list - val->ptr));
  3185. list++;
  3186. } else {
  3187. /* This value is the last one */
  3188. list = val->ptr + strlen(val->ptr);
  3189. val->len = ((size_t)(list - val->ptr));
  3190. }
  3191. /* Adjust length for trailing LWS */
  3192. end = (int)val->len - 1;
  3193. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3194. end--;
  3195. val->len = (size_t)(end + 1);
  3196. if (val->len == 0) {
  3197. /* Ignore any empty entries. */
  3198. goto reparse;
  3199. }
  3200. if (eq_val != NULL) {
  3201. /* Value has form "x=y", adjust pointers and lengths
  3202. * so that val points to "x", and eq_val points to "y". */
  3203. eq_val->len = 0;
  3204. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3205. if (eq_val->ptr != NULL) {
  3206. eq_val->ptr++; /* Skip over '=' character */
  3207. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3208. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3209. }
  3210. }
  3211. return list;
  3212. }
  3213. /* A helper function for checking if a comma separated list of values
  3214. * contains
  3215. * the given option (case insensitvely).
  3216. * 'header' can be NULL, in which case false is returned. */
  3217. static int
  3218. header_has_option(const char *header, const char *option)
  3219. {
  3220. struct vec opt_vec;
  3221. struct vec eq_vec;
  3222. /*
  3223. assert(option != NULL);
  3224. assert(option[0] != '\0');
  3225. */
  3226. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3227. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3228. return 1;
  3229. }
  3230. return 0;
  3231. }
  3232. /* Perform case-insensitive match of string against pattern */
  3233. static int
  3234. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3235. {
  3236. const char *or_str;
  3237. size_t i;
  3238. int j, len, res;
  3239. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3240. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3241. return (res > 0) ? res : match_prefix(or_str + 1,
  3242. (size_t)((pattern + pattern_len)
  3243. - (or_str + 1)),
  3244. str);
  3245. }
  3246. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  3247. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3248. continue;
  3249. } else if (pattern[i] == '$') {
  3250. return (str[j] == '\0') ? j : -1;
  3251. } else if (pattern[i] == '*') {
  3252. i++;
  3253. if (pattern[i] == '*') {
  3254. i++;
  3255. len = (int)strlen(str + j);
  3256. } else {
  3257. len = (int)strcspn(str + j, "/");
  3258. }
  3259. if (i == pattern_len) {
  3260. return j + len;
  3261. }
  3262. do {
  3263. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3264. } while (res == -1 && len-- > 0);
  3265. return (res == -1) ? -1 : j + res + len;
  3266. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3267. return -1;
  3268. }
  3269. }
  3270. return j;
  3271. }
  3272. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3273. * This function must tolerate situations when connection info is not
  3274. * set up, for example if request parsing failed. */
  3275. static int
  3276. should_keep_alive(const struct mg_connection *conn)
  3277. {
  3278. const char *http_version;
  3279. const char *header;
  3280. /* First satisfy needs of the server */
  3281. if ((conn == NULL) || conn->must_close) {
  3282. /* Close, if civetweb framework needs to close */
  3283. return 0;
  3284. }
  3285. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3286. /* Close, if keep alive is not enabled */
  3287. return 0;
  3288. }
  3289. /* Check explicit wish of the client */
  3290. header = mg_get_header(conn, "Connection");
  3291. if (header) {
  3292. /* If there is a connection header from the client, obey */
  3293. if (header_has_option(header, "keep-alive")) {
  3294. return 1;
  3295. }
  3296. return 0;
  3297. }
  3298. /* Use default of the standard */
  3299. http_version = get_http_version(conn);
  3300. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3301. /* HTTP 1.1 default is keep alive */
  3302. return 1;
  3303. }
  3304. /* HTTP 1.0 (and earlier) default is to close the connection */
  3305. return 0;
  3306. }
  3307. static int
  3308. should_decode_url(const struct mg_connection *conn)
  3309. {
  3310. if (!conn || !conn->dom_ctx) {
  3311. return 0;
  3312. }
  3313. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3314. }
  3315. static const char *
  3316. suggest_connection_header(const struct mg_connection *conn)
  3317. {
  3318. return should_keep_alive(conn) ? "keep-alive" : "close";
  3319. }
  3320. static int
  3321. send_no_cache_header(struct mg_connection *conn)
  3322. {
  3323. /* Send all current and obsolete cache opt-out directives. */
  3324. return mg_printf(conn,
  3325. "Cache-Control: no-cache, no-store, "
  3326. "must-revalidate, private, max-age=0\r\n"
  3327. "Pragma: no-cache\r\n"
  3328. "Expires: 0\r\n");
  3329. }
  3330. static int
  3331. send_static_cache_header(struct mg_connection *conn)
  3332. {
  3333. #if !defined(NO_CACHING)
  3334. /* Read the server config to check how long a file may be cached.
  3335. * The configuration is in seconds. */
  3336. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3337. if (max_age <= 0) {
  3338. /* 0 means "do not cache". All values <0 are reserved
  3339. * and may be used differently in the future. */
  3340. /* If a file should not be cached, do not only send
  3341. * max-age=0, but also pragmas and Expires headers. */
  3342. return send_no_cache_header(conn);
  3343. }
  3344. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3345. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3346. /* See also https://www.mnot.net/cache_docs/ */
  3347. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3348. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3349. * leap
  3350. * year to 31622400 seconds. For the moment, we just send whatever has
  3351. * been configured, still the behavior for >1 year should be considered
  3352. * as undefined. */
  3353. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3354. #else /* NO_CACHING */
  3355. return send_no_cache_header(conn);
  3356. #endif /* !NO_CACHING */
  3357. }
  3358. static int
  3359. send_additional_header(struct mg_connection *conn)
  3360. {
  3361. int i = 0;
  3362. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3363. #if !defined(NO_SSL)
  3364. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3365. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3366. if (max_age >= 0) {
  3367. i += mg_printf(conn,
  3368. "Strict-Transport-Security: max-age=%u\r\n",
  3369. (unsigned)max_age);
  3370. }
  3371. }
  3372. #endif
  3373. if (header && header[0]) {
  3374. i += mg_printf(conn, "%s\r\n", header);
  3375. }
  3376. return i;
  3377. }
  3378. static void handle_file_based_request(struct mg_connection *conn,
  3379. const char *path,
  3380. struct mg_file *filep);
  3381. const char *
  3382. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3383. {
  3384. /* See IANA HTTP status code assignment:
  3385. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3386. */
  3387. switch (response_code) {
  3388. /* RFC2616 Section 10.1 - Informational 1xx */
  3389. case 100:
  3390. return "Continue"; /* RFC2616 Section 10.1.1 */
  3391. case 101:
  3392. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3393. case 102:
  3394. return "Processing"; /* RFC2518 Section 10.1 */
  3395. /* RFC2616 Section 10.2 - Successful 2xx */
  3396. case 200:
  3397. return "OK"; /* RFC2616 Section 10.2.1 */
  3398. case 201:
  3399. return "Created"; /* RFC2616 Section 10.2.2 */
  3400. case 202:
  3401. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3402. case 203:
  3403. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3404. case 204:
  3405. return "No Content"; /* RFC2616 Section 10.2.5 */
  3406. case 205:
  3407. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3408. case 206:
  3409. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3410. case 207:
  3411. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3412. */
  3413. case 208:
  3414. return "Already Reported"; /* RFC5842 Section 7.1 */
  3415. case 226:
  3416. return "IM used"; /* RFC3229 Section 10.4.1 */
  3417. /* RFC2616 Section 10.3 - Redirection 3xx */
  3418. case 300:
  3419. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3420. case 301:
  3421. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3422. case 302:
  3423. return "Found"; /* RFC2616 Section 10.3.3 */
  3424. case 303:
  3425. return "See Other"; /* RFC2616 Section 10.3.4 */
  3426. case 304:
  3427. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3428. case 305:
  3429. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3430. case 307:
  3431. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3432. case 308:
  3433. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3434. /* RFC2616 Section 10.4 - Client Error 4xx */
  3435. case 400:
  3436. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3437. case 401:
  3438. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3439. case 402:
  3440. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3441. case 403:
  3442. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3443. case 404:
  3444. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3445. case 405:
  3446. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3447. case 406:
  3448. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3449. case 407:
  3450. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3451. case 408:
  3452. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3453. case 409:
  3454. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3455. case 410:
  3456. return "Gone"; /* RFC2616 Section 10.4.11 */
  3457. case 411:
  3458. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3459. case 412:
  3460. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3461. case 413:
  3462. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3463. case 414:
  3464. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3465. case 415:
  3466. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3467. case 416:
  3468. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3469. */
  3470. case 417:
  3471. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3472. case 421:
  3473. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3474. case 422:
  3475. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3476. * Section 11.2 */
  3477. case 423:
  3478. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3479. case 424:
  3480. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3481. * Section 11.4 */
  3482. case 426:
  3483. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3484. case 428:
  3485. return "Precondition Required"; /* RFC 6585, Section 3 */
  3486. case 429:
  3487. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3488. case 431:
  3489. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3490. case 451:
  3491. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3492. * Section 3 */
  3493. /* RFC2616 Section 10.5 - Server Error 5xx */
  3494. case 500:
  3495. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3496. case 501:
  3497. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3498. case 502:
  3499. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3500. case 503:
  3501. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3502. case 504:
  3503. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3504. case 505:
  3505. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3506. case 506:
  3507. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3508. case 507:
  3509. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3510. * Section 11.5 */
  3511. case 508:
  3512. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3513. case 510:
  3514. return "Not Extended"; /* RFC 2774, Section 7 */
  3515. case 511:
  3516. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3517. /* Other status codes, not shown in the IANA HTTP status code
  3518. * assignment.
  3519. * E.g., "de facto" standards due to common use, ... */
  3520. case 418:
  3521. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3522. case 419:
  3523. return "Authentication Timeout"; /* common use */
  3524. case 420:
  3525. return "Enhance Your Calm"; /* common use */
  3526. case 440:
  3527. return "Login Timeout"; /* common use */
  3528. case 509:
  3529. return "Bandwidth Limit Exceeded"; /* common use */
  3530. default:
  3531. /* This error code is unknown. This should not happen. */
  3532. if (conn) {
  3533. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3534. }
  3535. /* Return at least a category according to RFC 2616 Section 10. */
  3536. if (response_code >= 100 && response_code < 200) {
  3537. /* Unknown informational status code */
  3538. return "Information";
  3539. }
  3540. if (response_code >= 200 && response_code < 300) {
  3541. /* Unknown success code */
  3542. return "Success";
  3543. }
  3544. if (response_code >= 300 && response_code < 400) {
  3545. /* Unknown redirection code */
  3546. return "Redirection";
  3547. }
  3548. if (response_code >= 400 && response_code < 500) {
  3549. /* Unknown request error code */
  3550. return "Client Error";
  3551. }
  3552. if (response_code >= 500 && response_code < 600) {
  3553. /* Unknown server error code */
  3554. return "Server Error";
  3555. }
  3556. /* Response code not even within reasonable range */
  3557. return "";
  3558. }
  3559. }
  3560. void
  3561. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3562. {
  3563. char buf[MG_BUF_LEN];
  3564. va_list ap;
  3565. int len, i, page_handler_found, scope, truncated, has_body;
  3566. char date[64];
  3567. time_t curtime = time(NULL);
  3568. const char *error_handler = NULL;
  3569. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3570. const char *error_page_file_ext, *tstr;
  3571. const char *status_text = mg_get_response_code_text(conn, status);
  3572. if (conn == NULL) {
  3573. return;
  3574. }
  3575. conn->status_code = status;
  3576. if (conn->in_error_handler || (conn->phys_ctx->callbacks.http_error == NULL)
  3577. || conn->phys_ctx->callbacks.http_error(conn, status)) {
  3578. /* Check for recursion */
  3579. if (conn->in_error_handler) {
  3580. DEBUG_TRACE(
  3581. "Recursion when handling error %u - fall back to default",
  3582. status);
  3583. } else {
  3584. /* Send user defined error pages, if defined */
  3585. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3586. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3587. page_handler_found = 0;
  3588. if (error_handler != NULL) {
  3589. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3590. switch (scope) {
  3591. case 1: /* Handler for specific error, e.g. 404 error */
  3592. mg_snprintf(conn,
  3593. &truncated,
  3594. buf,
  3595. sizeof(buf) - 32,
  3596. "%serror%03u.",
  3597. error_handler,
  3598. status);
  3599. break;
  3600. case 2: /* Handler for error group, e.g., 5xx error
  3601. * handler
  3602. * for all server errors (500-599) */
  3603. mg_snprintf(conn,
  3604. &truncated,
  3605. buf,
  3606. sizeof(buf) - 32,
  3607. "%serror%01uxx.",
  3608. error_handler,
  3609. status / 100);
  3610. break;
  3611. default: /* Handler for all errors */
  3612. mg_snprintf(conn,
  3613. &truncated,
  3614. buf,
  3615. sizeof(buf) - 32,
  3616. "%serror.",
  3617. error_handler);
  3618. break;
  3619. }
  3620. /* String truncation in buf may only occur if
  3621. * error_handler is too long. This string is
  3622. * from the config, not from a client. */
  3623. (void)truncated;
  3624. len = (int)strlen(buf);
  3625. tstr = strchr(error_page_file_ext, '.');
  3626. while (tstr) {
  3627. for (i = 1;
  3628. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3629. i++)
  3630. buf[len + i - 1] = tstr[i];
  3631. buf[len + i - 1] = 0;
  3632. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3633. DEBUG_TRACE("Check error page %s - found", buf);
  3634. page_handler_found = 1;
  3635. break;
  3636. }
  3637. DEBUG_TRACE("Check error page %s - not found", buf);
  3638. tstr = strchr(tstr + i, '.');
  3639. }
  3640. }
  3641. }
  3642. if (page_handler_found) {
  3643. conn->in_error_handler = 1;
  3644. handle_file_based_request(conn, buf, &error_page_file);
  3645. conn->in_error_handler = 0;
  3646. return;
  3647. }
  3648. }
  3649. /* No custom error page. Send default error page. */
  3650. gmt_time_string(date, sizeof(date), &curtime);
  3651. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3652. has_body = ((status > 199) && (status != 204) && (status != 304));
  3653. conn->must_close = 1;
  3654. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3655. send_no_cache_header(conn);
  3656. send_additional_header(conn);
  3657. if (has_body) {
  3658. mg_printf(conn,
  3659. "%s",
  3660. "Content-Type: text/plain; charset=utf-8\r\n");
  3661. }
  3662. mg_printf(conn,
  3663. "Date: %s\r\n"
  3664. "Connection: close\r\n\r\n",
  3665. date);
  3666. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3667. if (has_body) {
  3668. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3669. if (fmt != NULL) {
  3670. va_start(ap, fmt);
  3671. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3672. va_end(ap);
  3673. mg_write(conn, buf, strlen(buf));
  3674. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3675. }
  3676. } else {
  3677. /* No body allowed. Close the connection. */
  3678. DEBUG_TRACE("Error %i", status);
  3679. }
  3680. }
  3681. }
  3682. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3683. /* Create substitutes for POSIX functions in Win32. */
  3684. #if defined(__MINGW32__)
  3685. /* Show no warning in case system functions are not used. */
  3686. #pragma GCC diagnostic push
  3687. #pragma GCC diagnostic ignored "-Wunused-function"
  3688. #endif
  3689. FUNCTION_MAY_BE_UNUSED
  3690. static int
  3691. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3692. {
  3693. (void)unused;
  3694. *mutex = CreateMutex(NULL, FALSE, NULL);
  3695. return (*mutex == NULL) ? -1 : 0;
  3696. }
  3697. FUNCTION_MAY_BE_UNUSED
  3698. static int
  3699. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3700. {
  3701. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3702. }
  3703. FUNCTION_MAY_BE_UNUSED
  3704. static int
  3705. pthread_mutex_lock(pthread_mutex_t *mutex)
  3706. {
  3707. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  3708. : -1;
  3709. }
  3710. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3711. FUNCTION_MAY_BE_UNUSED
  3712. static int
  3713. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3714. {
  3715. switch (WaitForSingleObject(*mutex, 0)) {
  3716. case WAIT_OBJECT_0:
  3717. return 0;
  3718. case WAIT_TIMEOUT:
  3719. return -2; /* EBUSY */
  3720. }
  3721. return -1;
  3722. }
  3723. #endif
  3724. FUNCTION_MAY_BE_UNUSED
  3725. static int
  3726. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3727. {
  3728. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3729. }
  3730. FUNCTION_MAY_BE_UNUSED
  3731. static int
  3732. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3733. {
  3734. (void)unused;
  3735. InitializeCriticalSection(&cv->threadIdSec);
  3736. cv->waiting_thread = NULL;
  3737. return 0;
  3738. }
  3739. FUNCTION_MAY_BE_UNUSED
  3740. static int
  3741. pthread_cond_timedwait(pthread_cond_t *cv,
  3742. pthread_mutex_t *mutex,
  3743. const struct timespec *abstime)
  3744. {
  3745. struct mg_workerTLS **ptls,
  3746. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3747. int ok;
  3748. int64_t nsnow, nswaitabs, nswaitrel;
  3749. DWORD mswaitrel;
  3750. EnterCriticalSection(&cv->threadIdSec);
  3751. /* Add this thread to cv's waiting list */
  3752. ptls = &cv->waiting_thread;
  3753. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3754. ;
  3755. tls->next_waiting_thread = NULL;
  3756. *ptls = tls;
  3757. LeaveCriticalSection(&cv->threadIdSec);
  3758. if (abstime) {
  3759. nsnow = mg_get_current_time_ns();
  3760. nswaitabs =
  3761. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3762. nswaitrel = nswaitabs - nsnow;
  3763. if (nswaitrel < 0) {
  3764. nswaitrel = 0;
  3765. }
  3766. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3767. } else {
  3768. mswaitrel = (DWORD)INFINITE;
  3769. }
  3770. pthread_mutex_unlock(mutex);
  3771. ok = (WAIT_OBJECT_0
  3772. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3773. if (!ok) {
  3774. ok = 1;
  3775. EnterCriticalSection(&cv->threadIdSec);
  3776. ptls = &cv->waiting_thread;
  3777. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3778. if (*ptls == tls) {
  3779. *ptls = tls->next_waiting_thread;
  3780. ok = 0;
  3781. break;
  3782. }
  3783. }
  3784. LeaveCriticalSection(&cv->threadIdSec);
  3785. if (ok) {
  3786. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  3787. (DWORD)INFINITE);
  3788. }
  3789. }
  3790. /* This thread has been removed from cv's waiting list */
  3791. pthread_mutex_lock(mutex);
  3792. return ok ? 0 : -1;
  3793. }
  3794. FUNCTION_MAY_BE_UNUSED
  3795. static int
  3796. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3797. {
  3798. return pthread_cond_timedwait(cv, mutex, NULL);
  3799. }
  3800. FUNCTION_MAY_BE_UNUSED
  3801. static int
  3802. pthread_cond_signal(pthread_cond_t *cv)
  3803. {
  3804. HANDLE wkup = NULL;
  3805. BOOL ok = FALSE;
  3806. EnterCriticalSection(&cv->threadIdSec);
  3807. if (cv->waiting_thread) {
  3808. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3809. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3810. ok = SetEvent(wkup);
  3811. assert(ok);
  3812. }
  3813. LeaveCriticalSection(&cv->threadIdSec);
  3814. return ok ? 0 : 1;
  3815. }
  3816. FUNCTION_MAY_BE_UNUSED
  3817. static int
  3818. pthread_cond_broadcast(pthread_cond_t *cv)
  3819. {
  3820. EnterCriticalSection(&cv->threadIdSec);
  3821. while (cv->waiting_thread) {
  3822. pthread_cond_signal(cv);
  3823. }
  3824. LeaveCriticalSection(&cv->threadIdSec);
  3825. return 0;
  3826. }
  3827. FUNCTION_MAY_BE_UNUSED
  3828. static int
  3829. pthread_cond_destroy(pthread_cond_t *cv)
  3830. {
  3831. EnterCriticalSection(&cv->threadIdSec);
  3832. assert(cv->waiting_thread == NULL);
  3833. LeaveCriticalSection(&cv->threadIdSec);
  3834. DeleteCriticalSection(&cv->threadIdSec);
  3835. return 0;
  3836. }
  3837. #ifdef ALTERNATIVE_QUEUE
  3838. FUNCTION_MAY_BE_UNUSED
  3839. static void *
  3840. event_create(void)
  3841. {
  3842. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3843. }
  3844. FUNCTION_MAY_BE_UNUSED
  3845. static int
  3846. event_wait(void *eventhdl)
  3847. {
  3848. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  3849. return (res == WAIT_OBJECT_0);
  3850. }
  3851. FUNCTION_MAY_BE_UNUSED
  3852. static int
  3853. event_signal(void *eventhdl)
  3854. {
  3855. return (int)SetEvent((HANDLE)eventhdl);
  3856. }
  3857. FUNCTION_MAY_BE_UNUSED
  3858. static void
  3859. event_destroy(void *eventhdl)
  3860. {
  3861. CloseHandle((HANDLE)eventhdl);
  3862. }
  3863. #endif
  3864. #if defined(__MINGW32__)
  3865. /* Enable unused function warning again */
  3866. #pragma GCC diagnostic pop
  3867. #endif
  3868. /* For Windows, change all slashes to backslashes in path names. */
  3869. static void
  3870. change_slashes_to_backslashes(char *path)
  3871. {
  3872. int i;
  3873. for (i = 0; path[i] != '\0'; i++) {
  3874. if (path[i] == '/') {
  3875. path[i] = '\\';
  3876. }
  3877. /* remove double backslash (check i > 0 to preserve UNC paths,
  3878. * like \\server\file.txt) */
  3879. if ((path[i] == '\\') && (i > 0)) {
  3880. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3881. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3882. }
  3883. }
  3884. }
  3885. }
  3886. static int
  3887. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3888. {
  3889. int diff;
  3890. do {
  3891. diff = tolower(*s1) - tolower(*s2);
  3892. s1++;
  3893. s2++;
  3894. } while ((diff == 0) && (s1[-1] != '\0'));
  3895. return diff;
  3896. }
  3897. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3898. * wbuf and wbuf_len is a target buffer and its length. */
  3899. static void
  3900. path_to_unicode(const struct mg_connection *conn,
  3901. const char *path,
  3902. wchar_t *wbuf,
  3903. size_t wbuf_len)
  3904. {
  3905. char buf[PATH_MAX], buf2[PATH_MAX];
  3906. wchar_t wbuf2[MAX_PATH + 1];
  3907. DWORD long_len, err;
  3908. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3909. mg_strlcpy(buf, path, sizeof(buf));
  3910. change_slashes_to_backslashes(buf);
  3911. /* Convert to Unicode and back. If doubly-converted string does not
  3912. * match the original, something is fishy, reject. */
  3913. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3914. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3915. WideCharToMultiByte(
  3916. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3917. if (strcmp(buf, buf2) != 0) {
  3918. wbuf[0] = L'\0';
  3919. }
  3920. /* Windows file systems are not case sensitive, but you can still use
  3921. * uppercase and lowercase letters (on all modern file systems).
  3922. * The server can check if the URI uses the same upper/lowercase
  3923. * letters an the file system, effectively making Windows servers
  3924. * case sensitive (like Linux servers are). It is still not possible
  3925. * to use two files with the same name in different cases on Windows
  3926. * (like /a and /A) - this would be possible in Linux.
  3927. * As a default, Windows is not case sensitive, but the case sensitive
  3928. * file name check can be activated by an additional configuration. */
  3929. if (conn) {
  3930. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  3931. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  3932. "yes")) {
  3933. /* Use case sensitive compare function */
  3934. fcompare = wcscmp;
  3935. }
  3936. }
  3937. (void)conn; /* conn is currently unused */
  3938. #if !defined(_WIN32_WCE)
  3939. /* Only accept a full file path, not a Windows short (8.3) path. */
  3940. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3941. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3942. if (long_len == 0) {
  3943. err = GetLastError();
  3944. if (err == ERROR_FILE_NOT_FOUND) {
  3945. /* File does not exist. This is not always a problem here. */
  3946. return;
  3947. }
  3948. }
  3949. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3950. /* Short name is used. */
  3951. wbuf[0] = L'\0';
  3952. }
  3953. #else
  3954. (void)long_len;
  3955. (void)wbuf2;
  3956. (void)err;
  3957. if (strchr(path, '~')) {
  3958. wbuf[0] = L'\0';
  3959. }
  3960. #endif
  3961. }
  3962. /* Windows happily opens files with some garbage at the end of file name.
  3963. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3964. * "a.cgi", despite one would expect an error back.
  3965. * This function returns non-0 if path ends with some garbage. */
  3966. static int
  3967. path_cannot_disclose_cgi(const char *path)
  3968. {
  3969. static const char *allowed_last_characters = "_-";
  3970. int last = path[strlen(path) - 1];
  3971. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3972. }
  3973. static int
  3974. mg_stat(const struct mg_connection *conn,
  3975. const char *path,
  3976. struct mg_file_stat *filep)
  3977. {
  3978. wchar_t wbuf[PATH_MAX];
  3979. WIN32_FILE_ATTRIBUTE_DATA info;
  3980. time_t creation_time;
  3981. if (!filep) {
  3982. return 0;
  3983. }
  3984. memset(filep, 0, sizeof(*filep));
  3985. if (conn && is_file_in_memory(conn, path)) {
  3986. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3987. * memset */
  3988. /* Quick fix (for 1.9.x): */
  3989. /* mg_stat must fill all fields, also for files in memory */
  3990. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3991. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3992. filep->size = tmp_file.stat.size;
  3993. filep->location = 2;
  3994. /* TODO: for 1.10: restructure how files in memory are handled */
  3995. /* The "file in memory" feature is a candidate for deletion.
  3996. * Please join the discussion at
  3997. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3998. */
  3999. filep->last_modified = time(NULL); /* TODO */
  4000. /* last_modified = now ... assumes the file may change during
  4001. * runtime,
  4002. * so every mg_fopen call may return different data */
  4003. /* last_modified = conn->phys_ctx.start_time;
  4004. * May be used it the data does not change during runtime. This
  4005. * allows
  4006. * browser caching. Since we do not know, we have to assume the file
  4007. * in memory may change. */
  4008. return 1;
  4009. }
  4010. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4011. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4012. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4013. filep->last_modified =
  4014. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4015. info.ftLastWriteTime.dwHighDateTime);
  4016. /* On Windows, the file creation time can be higher than the
  4017. * modification time, e.g. when a file is copied.
  4018. * Since the Last-Modified timestamp is used for caching
  4019. * it should be based on the most recent timestamp. */
  4020. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4021. info.ftCreationTime.dwHighDateTime);
  4022. if (creation_time > filep->last_modified) {
  4023. filep->last_modified = creation_time;
  4024. }
  4025. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4026. /* If file name is fishy, reset the file structure and return
  4027. * error.
  4028. * Note it is important to reset, not just return the error, cause
  4029. * functions like is_file_opened() check the struct. */
  4030. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4031. memset(filep, 0, sizeof(*filep));
  4032. return 0;
  4033. }
  4034. return 1;
  4035. }
  4036. return 0;
  4037. }
  4038. static int
  4039. mg_remove(const struct mg_connection *conn, const char *path)
  4040. {
  4041. wchar_t wbuf[PATH_MAX];
  4042. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4043. return DeleteFileW(wbuf) ? 0 : -1;
  4044. }
  4045. static int
  4046. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4047. {
  4048. wchar_t wbuf[PATH_MAX];
  4049. (void)mode;
  4050. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4051. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4052. }
  4053. /* Create substitutes for POSIX functions in Win32. */
  4054. #if defined(__MINGW32__)
  4055. /* Show no warning in case system functions are not used. */
  4056. #pragma GCC diagnostic push
  4057. #pragma GCC diagnostic ignored "-Wunused-function"
  4058. #endif
  4059. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4060. FUNCTION_MAY_BE_UNUSED
  4061. static DIR *
  4062. mg_opendir(const struct mg_connection *conn, const char *name)
  4063. {
  4064. DIR *dir = NULL;
  4065. wchar_t wpath[PATH_MAX];
  4066. DWORD attrs;
  4067. if (name == NULL) {
  4068. SetLastError(ERROR_BAD_ARGUMENTS);
  4069. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4070. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4071. } else {
  4072. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4073. attrs = GetFileAttributesW(wpath);
  4074. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  4075. == FILE_ATTRIBUTE_DIRECTORY)) {
  4076. (void)wcscat(wpath, L"\\*");
  4077. dir->handle = FindFirstFileW(wpath, &dir->info);
  4078. dir->result.d_name[0] = '\0';
  4079. } else {
  4080. mg_free(dir);
  4081. dir = NULL;
  4082. }
  4083. }
  4084. return dir;
  4085. }
  4086. FUNCTION_MAY_BE_UNUSED
  4087. static int
  4088. mg_closedir(DIR *dir)
  4089. {
  4090. int result = 0;
  4091. if (dir != NULL) {
  4092. if (dir->handle != INVALID_HANDLE_VALUE)
  4093. result = FindClose(dir->handle) ? 0 : -1;
  4094. mg_free(dir);
  4095. } else {
  4096. result = -1;
  4097. SetLastError(ERROR_BAD_ARGUMENTS);
  4098. }
  4099. return result;
  4100. }
  4101. FUNCTION_MAY_BE_UNUSED
  4102. static struct dirent *
  4103. mg_readdir(DIR *dir)
  4104. {
  4105. struct dirent *result = 0;
  4106. if (dir) {
  4107. if (dir->handle != INVALID_HANDLE_VALUE) {
  4108. result = &dir->result;
  4109. (void)WideCharToMultiByte(CP_UTF8,
  4110. 0,
  4111. dir->info.cFileName,
  4112. -1,
  4113. result->d_name,
  4114. sizeof(result->d_name),
  4115. NULL,
  4116. NULL);
  4117. if (!FindNextFileW(dir->handle, &dir->info)) {
  4118. (void)FindClose(dir->handle);
  4119. dir->handle = INVALID_HANDLE_VALUE;
  4120. }
  4121. } else {
  4122. SetLastError(ERROR_FILE_NOT_FOUND);
  4123. }
  4124. } else {
  4125. SetLastError(ERROR_BAD_ARGUMENTS);
  4126. }
  4127. return result;
  4128. }
  4129. #ifndef HAVE_POLL
  4130. FUNCTION_MAY_BE_UNUSED
  4131. static int
  4132. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4133. {
  4134. struct timeval tv;
  4135. fd_set set;
  4136. unsigned int i;
  4137. int result;
  4138. SOCKET maxfd = 0;
  4139. memset(&tv, 0, sizeof(tv));
  4140. tv.tv_sec = milliseconds / 1000;
  4141. tv.tv_usec = (milliseconds % 1000) * 1000;
  4142. FD_ZERO(&set);
  4143. for (i = 0; i < n; i++) {
  4144. FD_SET((SOCKET)pfd[i].fd, &set);
  4145. pfd[i].revents = 0;
  4146. if (pfd[i].fd > maxfd) {
  4147. maxfd = pfd[i].fd;
  4148. }
  4149. }
  4150. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4151. for (i = 0; i < n; i++) {
  4152. if (FD_ISSET(pfd[i].fd, &set)) {
  4153. pfd[i].revents = POLLIN;
  4154. }
  4155. }
  4156. }
  4157. /* We should subtract the time used in select from remaining
  4158. * "milliseconds", in particular if called from mg_poll with a
  4159. * timeout quantum.
  4160. * Unfortunately, the remaining time is not stored in "tv" in all
  4161. * implementations, so the result in "tv" must be considered undefined.
  4162. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4163. return result;
  4164. }
  4165. #endif /* HAVE_POLL */
  4166. #if defined(__MINGW32__)
  4167. /* Enable unused function warning again */
  4168. #pragma GCC diagnostic pop
  4169. #endif
  4170. static void
  4171. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4172. {
  4173. (void)conn; /* Unused. */
  4174. #if defined(_WIN32_WCE)
  4175. (void)sock;
  4176. #else
  4177. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4178. #endif
  4179. }
  4180. int
  4181. mg_start_thread(mg_thread_func_t f, void *p)
  4182. {
  4183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4184. /* Compile-time option to control stack size, e.g.
  4185. * -DUSE_STACK_SIZE=16384
  4186. */
  4187. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4188. == ((uintptr_t)(-1L)))
  4189. ? -1
  4190. : 0);
  4191. #else
  4192. return (
  4193. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4194. ? -1
  4195. : 0);
  4196. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4197. }
  4198. /* Start a thread storing the thread context. */
  4199. static int
  4200. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4201. void *p,
  4202. pthread_t *threadidptr)
  4203. {
  4204. uintptr_t uip;
  4205. HANDLE threadhandle;
  4206. int result = -1;
  4207. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4208. threadhandle = (HANDLE)uip;
  4209. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4210. *threadidptr = threadhandle;
  4211. result = 0;
  4212. }
  4213. return result;
  4214. }
  4215. /* Wait for a thread to finish. */
  4216. static int
  4217. mg_join_thread(pthread_t threadid)
  4218. {
  4219. int result;
  4220. DWORD dwevent;
  4221. result = -1;
  4222. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4223. if (dwevent == WAIT_FAILED) {
  4224. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4225. } else {
  4226. if (dwevent == WAIT_OBJECT_0) {
  4227. CloseHandle(threadid);
  4228. result = 0;
  4229. }
  4230. }
  4231. return result;
  4232. }
  4233. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4234. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4235. /* Create substitutes for POSIX functions in Win32. */
  4236. #if defined(__MINGW32__)
  4237. /* Show no warning in case system functions are not used. */
  4238. #pragma GCC diagnostic push
  4239. #pragma GCC diagnostic ignored "-Wunused-function"
  4240. #endif
  4241. FUNCTION_MAY_BE_UNUSED
  4242. static HANDLE
  4243. dlopen(const char *dll_name, int flags)
  4244. {
  4245. wchar_t wbuf[PATH_MAX];
  4246. (void)flags;
  4247. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4248. return LoadLibraryW(wbuf);
  4249. }
  4250. FUNCTION_MAY_BE_UNUSED
  4251. static int
  4252. dlclose(void *handle)
  4253. {
  4254. int result;
  4255. if (FreeLibrary((HMODULE)handle) != 0) {
  4256. result = 0;
  4257. } else {
  4258. result = -1;
  4259. }
  4260. return result;
  4261. }
  4262. #if defined(__MINGW32__)
  4263. /* Enable unused function warning again */
  4264. #pragma GCC diagnostic pop
  4265. #endif
  4266. #endif
  4267. #if !defined(NO_CGI)
  4268. #define SIGKILL (0)
  4269. static int
  4270. kill(pid_t pid, int sig_num)
  4271. {
  4272. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4273. (void)CloseHandle((HANDLE)pid);
  4274. return 0;
  4275. }
  4276. static void
  4277. trim_trailing_whitespaces(char *s)
  4278. {
  4279. char *e = s + strlen(s) - 1;
  4280. while ((e > s) && isspace(*(unsigned char *)e)) {
  4281. *e-- = '\0';
  4282. }
  4283. }
  4284. static pid_t
  4285. spawn_process(struct mg_connection *conn,
  4286. const char *prog,
  4287. char *envblk,
  4288. char *envp[],
  4289. int fdin[2],
  4290. int fdout[2],
  4291. int fderr[2],
  4292. const char *dir)
  4293. {
  4294. HANDLE me;
  4295. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4296. cmdline[PATH_MAX], buf[PATH_MAX];
  4297. int truncated;
  4298. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4299. STARTUPINFOA si;
  4300. PROCESS_INFORMATION pi = {0};
  4301. (void)envp;
  4302. memset(&si, 0, sizeof(si));
  4303. si.cb = sizeof(si);
  4304. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4305. si.wShowWindow = SW_HIDE;
  4306. me = GetCurrentProcess();
  4307. DuplicateHandle(me,
  4308. (HANDLE)_get_osfhandle(fdin[0]),
  4309. me,
  4310. &si.hStdInput,
  4311. 0,
  4312. TRUE,
  4313. DUPLICATE_SAME_ACCESS);
  4314. DuplicateHandle(me,
  4315. (HANDLE)_get_osfhandle(fdout[1]),
  4316. me,
  4317. &si.hStdOutput,
  4318. 0,
  4319. TRUE,
  4320. DUPLICATE_SAME_ACCESS);
  4321. DuplicateHandle(me,
  4322. (HANDLE)_get_osfhandle(fderr[1]),
  4323. me,
  4324. &si.hStdError,
  4325. 0,
  4326. TRUE,
  4327. DUPLICATE_SAME_ACCESS);
  4328. /* Mark handles that should not be inherited. See
  4329. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4330. */
  4331. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4332. HANDLE_FLAG_INHERIT,
  4333. 0);
  4334. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4335. HANDLE_FLAG_INHERIT,
  4336. 0);
  4337. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4338. HANDLE_FLAG_INHERIT,
  4339. 0);
  4340. /* If CGI file is a script, try to read the interpreter line */
  4341. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4342. if (interp == NULL) {
  4343. buf[0] = buf[1] = '\0';
  4344. /* Read the first line of the script into the buffer */
  4345. mg_snprintf(
  4346. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4347. if (truncated) {
  4348. pi.hProcess = (pid_t)-1;
  4349. goto spawn_cleanup;
  4350. }
  4351. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4352. p = (char *)file.access.membuf;
  4353. mg_fgets(buf, sizeof(buf), &file, &p);
  4354. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4355. buf[sizeof(buf) - 1] = '\0';
  4356. }
  4357. if ((buf[0] == '#') && (buf[1] == '!')) {
  4358. trim_trailing_whitespaces(buf + 2);
  4359. } else {
  4360. buf[2] = '\0';
  4361. }
  4362. interp = buf + 2;
  4363. }
  4364. if (interp[0] != '\0') {
  4365. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4366. interp = full_interp;
  4367. }
  4368. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4369. if (interp[0] != '\0') {
  4370. mg_snprintf(conn,
  4371. &truncated,
  4372. cmdline,
  4373. sizeof(cmdline),
  4374. "\"%s\" \"%s\\%s\"",
  4375. interp,
  4376. full_dir,
  4377. prog);
  4378. } else {
  4379. mg_snprintf(conn,
  4380. &truncated,
  4381. cmdline,
  4382. sizeof(cmdline),
  4383. "\"%s\\%s\"",
  4384. full_dir,
  4385. prog);
  4386. }
  4387. if (truncated) {
  4388. pi.hProcess = (pid_t)-1;
  4389. goto spawn_cleanup;
  4390. }
  4391. DEBUG_TRACE("Running [%s]", cmdline);
  4392. if (CreateProcessA(NULL,
  4393. cmdline,
  4394. NULL,
  4395. NULL,
  4396. TRUE,
  4397. CREATE_NEW_PROCESS_GROUP,
  4398. envblk,
  4399. NULL,
  4400. &si,
  4401. &pi) == 0) {
  4402. mg_cry(
  4403. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4404. pi.hProcess = (pid_t)-1;
  4405. /* goto spawn_cleanup; */
  4406. }
  4407. spawn_cleanup:
  4408. (void)CloseHandle(si.hStdOutput);
  4409. (void)CloseHandle(si.hStdError);
  4410. (void)CloseHandle(si.hStdInput);
  4411. if (pi.hThread != NULL) {
  4412. (void)CloseHandle(pi.hThread);
  4413. }
  4414. return (pid_t)pi.hProcess;
  4415. }
  4416. #endif /* !NO_CGI */
  4417. static int
  4418. set_blocking_mode(SOCKET sock)
  4419. {
  4420. unsigned long non_blocking = 0;
  4421. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4422. }
  4423. static int
  4424. set_non_blocking_mode(SOCKET sock)
  4425. {
  4426. unsigned long non_blocking = 1;
  4427. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4428. }
  4429. #else
  4430. static int
  4431. mg_stat(const struct mg_connection *conn,
  4432. const char *path,
  4433. struct mg_file_stat *filep)
  4434. {
  4435. struct stat st;
  4436. if (!filep) {
  4437. return 0;
  4438. }
  4439. memset(filep, 0, sizeof(*filep));
  4440. if (conn && is_file_in_memory(conn, path)) {
  4441. /* Quick fix (for 1.9.x): */
  4442. /* mg_stat must fill all fields, also for files in memory */
  4443. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4444. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4445. filep->size = tmp_file.stat.size;
  4446. filep->last_modified = time(NULL);
  4447. filep->location = 2;
  4448. /* TODO: for 1.10: restructure how files in memory are handled */
  4449. return 1;
  4450. }
  4451. if (0 == stat(path, &st)) {
  4452. filep->size = (uint64_t)(st.st_size);
  4453. filep->last_modified = st.st_mtime;
  4454. filep->is_directory = S_ISDIR(st.st_mode);
  4455. return 1;
  4456. }
  4457. return 0;
  4458. }
  4459. static void
  4460. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4461. {
  4462. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4463. if (conn) {
  4464. mg_cry(conn,
  4465. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4466. __func__,
  4467. strerror(ERRNO));
  4468. }
  4469. }
  4470. }
  4471. int
  4472. mg_start_thread(mg_thread_func_t func, void *param)
  4473. {
  4474. pthread_t thread_id;
  4475. pthread_attr_t attr;
  4476. int result;
  4477. (void)pthread_attr_init(&attr);
  4478. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4479. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4480. /* Compile-time option to control stack size,
  4481. * e.g. -DUSE_STACK_SIZE=16384 */
  4482. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4483. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4484. result = pthread_create(&thread_id, &attr, func, param);
  4485. pthread_attr_destroy(&attr);
  4486. return result;
  4487. }
  4488. /* Start a thread storing the thread context. */
  4489. static int
  4490. mg_start_thread_with_id(mg_thread_func_t func,
  4491. void *param,
  4492. pthread_t *threadidptr)
  4493. {
  4494. pthread_t thread_id;
  4495. pthread_attr_t attr;
  4496. int result;
  4497. (void)pthread_attr_init(&attr);
  4498. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4499. /* Compile-time option to control stack size,
  4500. * e.g. -DUSE_STACK_SIZE=16384 */
  4501. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4502. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4503. result = pthread_create(&thread_id, &attr, func, param);
  4504. pthread_attr_destroy(&attr);
  4505. if ((result == 0) && (threadidptr != NULL)) {
  4506. *threadidptr = thread_id;
  4507. }
  4508. return result;
  4509. }
  4510. /* Wait for a thread to finish. */
  4511. static int
  4512. mg_join_thread(pthread_t threadid)
  4513. {
  4514. int result;
  4515. result = pthread_join(threadid, NULL);
  4516. return result;
  4517. }
  4518. #ifndef NO_CGI
  4519. static pid_t
  4520. spawn_process(struct mg_connection *conn,
  4521. const char *prog,
  4522. char *envblk,
  4523. char *envp[],
  4524. int fdin[2],
  4525. int fdout[2],
  4526. int fderr[2],
  4527. const char *dir)
  4528. {
  4529. pid_t pid;
  4530. const char *interp;
  4531. (void)envblk;
  4532. if (conn == NULL) {
  4533. return 0;
  4534. }
  4535. if ((pid = fork()) == -1) {
  4536. /* Parent */
  4537. mg_send_http_error(conn,
  4538. 500,
  4539. "Error: Creating CGI process\nfork(): %s",
  4540. strerror(ERRNO));
  4541. } else if (pid == 0) {
  4542. /* Child */
  4543. if (chdir(dir) != 0) {
  4544. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4545. } else if (dup2(fdin[0], 0) == -1) {
  4546. mg_cry(conn,
  4547. "%s: dup2(%d, 0): %s",
  4548. __func__,
  4549. fdin[0],
  4550. strerror(ERRNO));
  4551. } else if (dup2(fdout[1], 1) == -1) {
  4552. mg_cry(conn,
  4553. "%s: dup2(%d, 1): %s",
  4554. __func__,
  4555. fdout[1],
  4556. strerror(ERRNO));
  4557. } else if (dup2(fderr[1], 2) == -1) {
  4558. mg_cry(conn,
  4559. "%s: dup2(%d, 2): %s",
  4560. __func__,
  4561. fderr[1],
  4562. strerror(ERRNO));
  4563. } else {
  4564. /* Keep stderr and stdout in two different pipes.
  4565. * Stdout will be sent back to the client,
  4566. * stderr should go into a server error log. */
  4567. (void)close(fdin[0]);
  4568. (void)close(fdout[1]);
  4569. (void)close(fderr[1]);
  4570. /* Close write end fdin and read end fdout and fderr */
  4571. (void)close(fdin[1]);
  4572. (void)close(fdout[0]);
  4573. (void)close(fderr[0]);
  4574. /* After exec, all signal handlers are restored to their default
  4575. * values, with one exception of SIGCHLD. According to
  4576. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4577. * leave unchanged after exec if it was set to be ignored. Restore
  4578. * it to default action. */
  4579. signal(SIGCHLD, SIG_DFL);
  4580. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4581. if (interp == NULL) {
  4582. (void)execle(prog, prog, NULL, envp);
  4583. mg_cry(conn,
  4584. "%s: execle(%s): %s",
  4585. __func__,
  4586. prog,
  4587. strerror(ERRNO));
  4588. } else {
  4589. (void)execle(interp, interp, prog, NULL, envp);
  4590. mg_cry(conn,
  4591. "%s: execle(%s %s): %s",
  4592. __func__,
  4593. interp,
  4594. prog,
  4595. strerror(ERRNO));
  4596. }
  4597. }
  4598. exit(EXIT_FAILURE);
  4599. }
  4600. return pid;
  4601. }
  4602. #endif /* !NO_CGI */
  4603. static int
  4604. set_non_blocking_mode(SOCKET sock)
  4605. {
  4606. int flags = fcntl(sock, F_GETFL, 0);
  4607. if (flags < 0) {
  4608. return -1;
  4609. }
  4610. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4611. return -1;
  4612. }
  4613. return 0;
  4614. }
  4615. static int
  4616. set_blocking_mode(SOCKET sock)
  4617. {
  4618. int flags = fcntl(sock, F_GETFL, 0);
  4619. if (flags < 0) {
  4620. return -1;
  4621. }
  4622. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4623. return -1;
  4624. }
  4625. return 0;
  4626. }
  4627. #endif /* _WIN32 / else */
  4628. /* End of initial operating system specific define block. */
  4629. /* Get a random number (independent of C rand function) */
  4630. static uint64_t
  4631. get_random(void)
  4632. {
  4633. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4634. static uint64_t lcg = 0; /* Linear congruential generator */
  4635. uint64_t now = mg_get_current_time_ns();
  4636. if (lfsr == 0) {
  4637. /* lfsr will be only 0 if has not been initialized,
  4638. * so this code is called only once. */
  4639. lfsr = mg_get_current_time_ns();
  4640. lcg = mg_get_current_time_ns();
  4641. } else {
  4642. /* Get the next step of both random number generators. */
  4643. lfsr = (lfsr >> 1)
  4644. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4645. << 63);
  4646. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4647. }
  4648. /* Combining two pseudo-random number generators and a high resolution
  4649. * part
  4650. * of the current server time will make it hard (impossible?) to guess
  4651. * the
  4652. * next number. */
  4653. return (lfsr ^ lcg ^ now);
  4654. }
  4655. static int
  4656. mg_poll(struct pollfd *pfd,
  4657. unsigned int n,
  4658. int milliseconds,
  4659. volatile int *stop_server)
  4660. {
  4661. /* Call poll, but only for a maximum time of a few seconds.
  4662. * This will allow to stop the server after some seconds, instead
  4663. * of having to wait for a long socket timeout. */
  4664. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4665. do {
  4666. int result;
  4667. if (*stop_server) {
  4668. /* Shut down signal */
  4669. return -2;
  4670. }
  4671. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4672. ms_now = milliseconds;
  4673. }
  4674. result = poll(pfd, n, ms_now);
  4675. if (result != 0) {
  4676. /* Poll returned either success (1) or error (-1).
  4677. * Forward both to the caller. */
  4678. return result;
  4679. }
  4680. /* Poll returned timeout (0). */
  4681. if (milliseconds > 0) {
  4682. milliseconds -= ms_now;
  4683. }
  4684. } while (milliseconds != 0);
  4685. /* timeout: return 0 */
  4686. return 0;
  4687. }
  4688. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4689. * descriptor.
  4690. * Return value:
  4691. * >=0 .. number of bytes successfully written
  4692. * -1 .. timeout
  4693. * -2 .. error
  4694. */
  4695. static int
  4696. push_inner(struct mg_context *ctx,
  4697. FILE *fp,
  4698. SOCKET sock,
  4699. SSL *ssl,
  4700. const char *buf,
  4701. int len,
  4702. double timeout)
  4703. {
  4704. uint64_t start = 0, now = 0, timeout_ns = 0;
  4705. int n, err;
  4706. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4707. #ifdef _WIN32
  4708. typedef int len_t;
  4709. #else
  4710. typedef size_t len_t;
  4711. #endif
  4712. if (timeout > 0) {
  4713. now = mg_get_current_time_ns();
  4714. start = now;
  4715. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4716. }
  4717. if (ctx == NULL) {
  4718. return -2;
  4719. }
  4720. #ifdef NO_SSL
  4721. if (ssl) {
  4722. return -2;
  4723. }
  4724. #endif
  4725. /* Try to read until it succeeds, fails, times out, or the server
  4726. * shuts down. */
  4727. for (;;) {
  4728. #ifndef NO_SSL
  4729. if (ssl != NULL) {
  4730. n = SSL_write(ssl, buf, len);
  4731. if (n <= 0) {
  4732. err = SSL_get_error(ssl, n);
  4733. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4734. err = ERRNO;
  4735. } else if ((err == SSL_ERROR_WANT_READ)
  4736. || (err == SSL_ERROR_WANT_WRITE)) {
  4737. n = 0;
  4738. } else {
  4739. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4740. return -2;
  4741. }
  4742. } else {
  4743. err = 0;
  4744. }
  4745. } else
  4746. #endif
  4747. if (fp != NULL) {
  4748. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4749. if (ferror(fp)) {
  4750. n = -1;
  4751. err = ERRNO;
  4752. } else {
  4753. err = 0;
  4754. }
  4755. } else {
  4756. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4757. err = (n < 0) ? ERRNO : 0;
  4758. #ifdef _WIN32
  4759. if (err == WSAEWOULDBLOCK) {
  4760. err = 0;
  4761. n = 0;
  4762. }
  4763. #else
  4764. if (err == EWOULDBLOCK) {
  4765. err = 0;
  4766. n = 0;
  4767. }
  4768. #endif
  4769. if (n < 0) {
  4770. /* shutdown of the socket at client side */
  4771. return -2;
  4772. }
  4773. }
  4774. if (ctx->stop_flag) {
  4775. return -2;
  4776. }
  4777. if ((n > 0) || ((n == 0) && (len == 0))) {
  4778. /* some data has been read, or no data was requested */
  4779. return n;
  4780. }
  4781. if (n < 0) {
  4782. /* socket error - check errno */
  4783. DEBUG_TRACE("send() failed, error %d", err);
  4784. /* TODO (mid): error handling depending on the error code.
  4785. * These codes are different between Windows and Linux.
  4786. * Currently there is no problem with failing send calls,
  4787. * if there is a reproducible situation, it should be
  4788. * investigated in detail.
  4789. */
  4790. return -2;
  4791. }
  4792. /* Only in case n=0 (timeout), repeat calling the write function */
  4793. /* If send failed, wait before retry */
  4794. if (fp != NULL) {
  4795. /* For files, just wait a fixed time,
  4796. * maybe an average disk seek time. */
  4797. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4798. } else {
  4799. /* For sockets, wait for the socket using select */
  4800. fd_set wfds;
  4801. struct timeval tv;
  4802. int sret;
  4803. #if defined(__GNUC__) || defined(__MINGW32__)
  4804. /* GCC seems to have a flaw with it's own socket macros:
  4805. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4806. */
  4807. #pragma GCC diagnostic push
  4808. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4809. #endif
  4810. FD_ZERO(&wfds);
  4811. FD_SET(sock, &wfds);
  4812. tv.tv_sec = (time_t)(ms_wait / 1000);
  4813. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4814. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4815. #if defined(__GNUC__) || defined(__MINGW32__)
  4816. #pragma GCC diagnostic pop
  4817. #endif
  4818. if (sret > 0) {
  4819. /* We got ready to write. Don't check the timeout
  4820. * but directly go back to write again. */
  4821. continue;
  4822. }
  4823. }
  4824. if (timeout > 0) {
  4825. now = mg_get_current_time_ns();
  4826. if ((now - start) > timeout_ns) {
  4827. /* Timeout */
  4828. break;
  4829. }
  4830. }
  4831. }
  4832. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4833. used */
  4834. return -1;
  4835. }
  4836. static int64_t
  4837. push_all(struct mg_context *ctx,
  4838. FILE *fp,
  4839. SOCKET sock,
  4840. SSL *ssl,
  4841. const char *buf,
  4842. int64_t len)
  4843. {
  4844. double timeout = -1.0;
  4845. int64_t n, nwritten = 0;
  4846. if (ctx == NULL) {
  4847. return -1;
  4848. }
  4849. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  4850. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  4851. }
  4852. while ((len > 0) && (ctx->stop_flag == 0)) {
  4853. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4854. if (n < 0) {
  4855. if (nwritten == 0) {
  4856. nwritten = n; /* Propagate the error */
  4857. }
  4858. break;
  4859. } else if (n == 0) {
  4860. break; /* No more data to write */
  4861. } else {
  4862. nwritten += n;
  4863. len -= n;
  4864. }
  4865. }
  4866. return nwritten;
  4867. }
  4868. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4869. * Return value:
  4870. * >=0 .. number of bytes successfully read
  4871. * -1 .. timeout
  4872. * -2 .. error
  4873. */
  4874. static int
  4875. pull_inner(FILE *fp,
  4876. struct mg_connection *conn,
  4877. char *buf,
  4878. int len,
  4879. double timeout)
  4880. {
  4881. int nread, err = 0;
  4882. #ifdef _WIN32
  4883. typedef int len_t;
  4884. #else
  4885. typedef size_t len_t;
  4886. #endif
  4887. #ifndef NO_SSL
  4888. int ssl_pending;
  4889. #endif
  4890. /* We need an additional wait loop around this, because in some cases
  4891. * with TLSwe may get data from the socket but not from SSL_read.
  4892. * In this case we need to repeat at least once.
  4893. */
  4894. if (fp != NULL) {
  4895. #if !defined(_WIN32_WCE)
  4896. /* Use read() instead of fread(), because if we're reading from the
  4897. * CGI pipe, fread() may block until IO buffer is filled up. We
  4898. * cannot afford to block and must pass all read bytes immediately
  4899. * to the client. */
  4900. nread = (int)read(fileno(fp), buf, (size_t)len);
  4901. #else
  4902. /* WinCE does not support CGI pipes */
  4903. nread = (int)fread(buf, 1, (size_t)len, fp);
  4904. #endif
  4905. err = (nread < 0) ? ERRNO : 0;
  4906. if ((nread == 0) && (len > 0)) {
  4907. /* Should get data, but got EOL */
  4908. return -2;
  4909. }
  4910. #ifndef NO_SSL
  4911. } else if ((conn->ssl != NULL)
  4912. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4913. /* We already know there is no more data buffered in conn->buf
  4914. * but there is more available in the SSL layer. So don't poll
  4915. * conn->client.sock yet. */
  4916. if (ssl_pending > len) {
  4917. ssl_pending = len;
  4918. }
  4919. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4920. if (nread <= 0) {
  4921. err = SSL_get_error(conn->ssl, nread);
  4922. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4923. err = ERRNO;
  4924. } else if ((err == SSL_ERROR_WANT_READ)
  4925. || (err == SSL_ERROR_WANT_WRITE)) {
  4926. nread = 0;
  4927. } else {
  4928. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4929. return -1;
  4930. }
  4931. } else {
  4932. err = 0;
  4933. }
  4934. } else if (conn->ssl != NULL) {
  4935. struct pollfd pfd[1];
  4936. int pollres;
  4937. pfd[0].fd = conn->client.sock;
  4938. pfd[0].events = POLLIN;
  4939. pollres = mg_poll(pfd,
  4940. 1,
  4941. (int)(timeout * 1000.0),
  4942. &(conn->phys_ctx->stop_flag));
  4943. if (conn->phys_ctx->stop_flag) {
  4944. return -2;
  4945. }
  4946. if (pollres > 0) {
  4947. nread = SSL_read(conn->ssl, buf, len);
  4948. if (nread <= 0) {
  4949. err = SSL_get_error(conn->ssl, nread);
  4950. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4951. err = ERRNO;
  4952. } else if ((err == SSL_ERROR_WANT_READ)
  4953. || (err == SSL_ERROR_WANT_WRITE)) {
  4954. nread = 0;
  4955. } else {
  4956. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4957. return -2;
  4958. }
  4959. } else {
  4960. err = 0;
  4961. }
  4962. } else if (pollres < 0) {
  4963. /* Error */
  4964. return -2;
  4965. } else {
  4966. /* pollres = 0 means timeout */
  4967. nread = 0;
  4968. }
  4969. #endif
  4970. } else {
  4971. struct pollfd pfd[1];
  4972. int pollres;
  4973. pfd[0].fd = conn->client.sock;
  4974. pfd[0].events = POLLIN;
  4975. pollres = mg_poll(pfd,
  4976. 1,
  4977. (int)(timeout * 1000.0),
  4978. &(conn->phys_ctx->stop_flag));
  4979. if (conn->phys_ctx->stop_flag) {
  4980. return -2;
  4981. }
  4982. if (pollres > 0) {
  4983. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4984. err = (nread < 0) ? ERRNO : 0;
  4985. if (nread <= 0) {
  4986. /* shutdown of the socket at client side */
  4987. return -2;
  4988. }
  4989. } else if (pollres < 0) {
  4990. /* error callint poll */
  4991. return -2;
  4992. } else {
  4993. /* pollres = 0 means timeout */
  4994. nread = 0;
  4995. }
  4996. }
  4997. if (conn->phys_ctx->stop_flag) {
  4998. return -2;
  4999. }
  5000. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5001. /* some data has been read, or no data was requested */
  5002. return nread;
  5003. }
  5004. if (nread < 0) {
  5005. /* socket error - check errno */
  5006. #ifdef _WIN32
  5007. if (err == WSAEWOULDBLOCK) {
  5008. /* TODO (low): check if this is still required */
  5009. /* standard case if called from close_socket_gracefully */
  5010. return -2;
  5011. } else if (err == WSAETIMEDOUT) {
  5012. /* TODO (low): check if this is still required */
  5013. /* timeout is handled by the while loop */
  5014. return 0;
  5015. } else if (err == WSAECONNABORTED) {
  5016. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5017. return -2;
  5018. } else {
  5019. DEBUG_TRACE("recv() failed, error %d", err);
  5020. return -2;
  5021. }
  5022. #else
  5023. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5024. * if the timeout is reached and if the socket was set to non-
  5025. * blocking in close_socket_gracefully, so we can not distinguish
  5026. * here. We have to wait for the timeout in both cases for now.
  5027. */
  5028. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5029. /* TODO (low): check if this is still required */
  5030. /* EAGAIN/EWOULDBLOCK:
  5031. * standard case if called from close_socket_gracefully
  5032. * => should return -1 */
  5033. /* or timeout occured
  5034. * => the code must stay in the while loop */
  5035. /* EINTR can be generated on a socket with a timeout set even
  5036. * when SA_RESTART is effective for all relevant signals
  5037. * (see signal(7)).
  5038. * => stay in the while loop */
  5039. } else {
  5040. DEBUG_TRACE("recv() failed, error %d", err);
  5041. return -2;
  5042. }
  5043. #endif
  5044. }
  5045. /* Timeout occured, but no data available. */
  5046. return -1;
  5047. }
  5048. static int
  5049. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5050. {
  5051. int n, nread = 0;
  5052. double timeout = -1.0;
  5053. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5054. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5055. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5056. }
  5057. if (timeout >= 0.0) {
  5058. start_time = mg_get_current_time_ns();
  5059. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5060. }
  5061. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5062. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5063. if (n == -2) {
  5064. if (nread == 0) {
  5065. nread = -1; /* Propagate the error */
  5066. }
  5067. break;
  5068. } else if (n == -1) {
  5069. /* timeout */
  5070. if (timeout >= 0.0) {
  5071. now = mg_get_current_time_ns();
  5072. if ((now - start_time) <= timeout_ns) {
  5073. continue;
  5074. }
  5075. }
  5076. break;
  5077. } else if (n == 0) {
  5078. break; /* No more data to read */
  5079. } else {
  5080. conn->consumed_content += n;
  5081. nread += n;
  5082. len -= n;
  5083. }
  5084. }
  5085. return nread;
  5086. }
  5087. static void
  5088. discard_unread_request_data(struct mg_connection *conn)
  5089. {
  5090. char buf[MG_BUF_LEN];
  5091. size_t to_read;
  5092. int nread;
  5093. if (conn == NULL) {
  5094. return;
  5095. }
  5096. to_read = sizeof(buf);
  5097. if (conn->is_chunked) {
  5098. /* Chunked encoding: 3=chunk read completely
  5099. * completely */
  5100. while (conn->is_chunked != 3) {
  5101. nread = mg_read(conn, buf, to_read);
  5102. if (nread <= 0) {
  5103. break;
  5104. }
  5105. }
  5106. } else {
  5107. /* Not chunked: content length is known */
  5108. while (conn->consumed_content < conn->content_len) {
  5109. if (to_read
  5110. > (size_t)(conn->content_len - conn->consumed_content)) {
  5111. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5112. }
  5113. nread = mg_read(conn, buf, to_read);
  5114. if (nread <= 0) {
  5115. break;
  5116. }
  5117. }
  5118. }
  5119. }
  5120. static int
  5121. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5122. {
  5123. int64_t n, buffered_len, nread;
  5124. int64_t len64 =
  5125. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5126. * int, we may not read more
  5127. * bytes */
  5128. const char *body;
  5129. if (conn == NULL) {
  5130. return 0;
  5131. }
  5132. /* If Content-Length is not set for a request with body data
  5133. * (e.g., a PUT or POST request), we do not know in advance
  5134. * how much data should be read. */
  5135. if (conn->consumed_content == 0) {
  5136. if (conn->is_chunked == 1) {
  5137. conn->content_len = len64;
  5138. conn->is_chunked = 2;
  5139. } else if (conn->content_len == -1) {
  5140. /* The body data is completed when the connection
  5141. * is closed. */
  5142. conn->content_len = INT64_MAX;
  5143. conn->must_close = 1;
  5144. }
  5145. }
  5146. nread = 0;
  5147. if (conn->consumed_content < conn->content_len) {
  5148. /* Adjust number of bytes to read. */
  5149. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5150. if (left_to_read < len64) {
  5151. /* Do not read more than the total content length of the
  5152. * request.
  5153. */
  5154. len64 = left_to_read;
  5155. }
  5156. /* Return buffered data */
  5157. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5158. - conn->consumed_content;
  5159. if (buffered_len > 0) {
  5160. if (len64 < buffered_len) {
  5161. buffered_len = len64;
  5162. }
  5163. body = conn->buf + conn->request_len + conn->consumed_content;
  5164. memcpy(buf, body, (size_t)buffered_len);
  5165. len64 -= buffered_len;
  5166. conn->consumed_content += buffered_len;
  5167. nread += buffered_len;
  5168. buf = (char *)buf + buffered_len;
  5169. }
  5170. /* We have returned all buffered data. Read new data from the remote
  5171. * socket.
  5172. */
  5173. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5174. nread += n;
  5175. } else {
  5176. nread = ((nread > 0) ? nread : n);
  5177. }
  5178. }
  5179. return (int)nread;
  5180. }
  5181. static char
  5182. mg_getc(struct mg_connection *conn)
  5183. {
  5184. char c;
  5185. if (conn == NULL) {
  5186. return 0;
  5187. }
  5188. if (mg_read_inner(conn, &c, 1) <= 0) {
  5189. return (char)0;
  5190. }
  5191. return c;
  5192. }
  5193. int
  5194. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5195. {
  5196. if (len > INT_MAX) {
  5197. len = INT_MAX;
  5198. }
  5199. if (conn == NULL) {
  5200. return 0;
  5201. }
  5202. if (conn->is_chunked) {
  5203. size_t all_read = 0;
  5204. while (len > 0) {
  5205. if (conn->is_chunked == 3) {
  5206. /* No more data left to read */
  5207. return 0;
  5208. }
  5209. if (conn->chunk_remainder) {
  5210. /* copy from the remainder of the last received chunk */
  5211. long read_ret;
  5212. size_t read_now =
  5213. ((conn->chunk_remainder > len) ? (len)
  5214. : (conn->chunk_remainder));
  5215. conn->content_len += (int)read_now;
  5216. read_ret =
  5217. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5218. if (read_ret < 1) {
  5219. /* read error */
  5220. return -1;
  5221. }
  5222. all_read += (size_t)read_ret;
  5223. conn->chunk_remainder -= (size_t)read_ret;
  5224. len -= (size_t)read_ret;
  5225. if (conn->chunk_remainder == 0) {
  5226. /* Add data bytes in the current chunk have been read,
  5227. * so we are expecting \r\n now. */
  5228. char x1, x2;
  5229. conn->content_len += 2;
  5230. x1 = mg_getc(conn);
  5231. x2 = mg_getc(conn);
  5232. if ((x1 != '\r') || (x2 != '\n')) {
  5233. /* Protocol violation */
  5234. return -1;
  5235. }
  5236. }
  5237. } else {
  5238. /* fetch a new chunk */
  5239. int i = 0;
  5240. char lenbuf[64];
  5241. char *end = 0;
  5242. unsigned long chunkSize = 0;
  5243. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5244. conn->content_len++;
  5245. lenbuf[i] = mg_getc(conn);
  5246. if ((i > 0) && (lenbuf[i] == '\r')
  5247. && (lenbuf[i - 1] != '\r')) {
  5248. continue;
  5249. }
  5250. if ((i > 1) && (lenbuf[i] == '\n')
  5251. && (lenbuf[i - 1] == '\r')) {
  5252. lenbuf[i + 1] = 0;
  5253. chunkSize = strtoul(lenbuf, &end, 16);
  5254. if (chunkSize == 0) {
  5255. /* regular end of content */
  5256. conn->is_chunked = 3;
  5257. }
  5258. break;
  5259. }
  5260. if (!isxdigit(lenbuf[i])) {
  5261. /* illegal character for chunk length */
  5262. return -1;
  5263. }
  5264. }
  5265. if ((end == NULL) || (*end != '\r')) {
  5266. /* chunksize not set correctly */
  5267. return -1;
  5268. }
  5269. if (chunkSize == 0) {
  5270. break;
  5271. }
  5272. conn->chunk_remainder = chunkSize;
  5273. }
  5274. }
  5275. return (int)all_read;
  5276. }
  5277. return mg_read_inner(conn, buf, len);
  5278. }
  5279. int
  5280. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5281. {
  5282. time_t now;
  5283. int64_t n, total, allowed;
  5284. if (conn == NULL) {
  5285. return 0;
  5286. }
  5287. if (conn->throttle > 0) {
  5288. if ((now = time(NULL)) != conn->last_throttle_time) {
  5289. conn->last_throttle_time = now;
  5290. conn->last_throttle_bytes = 0;
  5291. }
  5292. allowed = conn->throttle - conn->last_throttle_bytes;
  5293. if (allowed > (int64_t)len) {
  5294. allowed = (int64_t)len;
  5295. }
  5296. if ((total = push_all(conn->phys_ctx,
  5297. NULL,
  5298. conn->client.sock,
  5299. conn->ssl,
  5300. (const char *)buf,
  5301. (int64_t)allowed)) == allowed) {
  5302. buf = (const char *)buf + total;
  5303. conn->last_throttle_bytes += total;
  5304. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5305. allowed = (conn->throttle > ((int64_t)len - total))
  5306. ? (int64_t)len - total
  5307. : conn->throttle;
  5308. if ((n = push_all(conn->phys_ctx,
  5309. NULL,
  5310. conn->client.sock,
  5311. conn->ssl,
  5312. (const char *)buf,
  5313. (int64_t)allowed)) != allowed) {
  5314. break;
  5315. }
  5316. sleep(1);
  5317. conn->last_throttle_bytes = allowed;
  5318. conn->last_throttle_time = time(NULL);
  5319. buf = (const char *)buf + n;
  5320. total += n;
  5321. }
  5322. }
  5323. } else {
  5324. total = push_all(conn->phys_ctx,
  5325. NULL,
  5326. conn->client.sock,
  5327. conn->ssl,
  5328. (const char *)buf,
  5329. (int64_t)len);
  5330. }
  5331. if (total > 0) {
  5332. conn->num_bytes_sent += total;
  5333. }
  5334. return (int)total;
  5335. }
  5336. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5337. int
  5338. mg_send_chunk(struct mg_connection *conn,
  5339. const char *chunk,
  5340. unsigned int chunk_len)
  5341. {
  5342. char lenbuf[16];
  5343. size_t lenbuf_len;
  5344. int ret;
  5345. int t;
  5346. /* First store the length information in a text buffer. */
  5347. sprintf(lenbuf, "%x\r\n", chunk_len);
  5348. lenbuf_len = strlen(lenbuf);
  5349. /* Then send length information, chunk and terminating \r\n. */
  5350. ret = mg_write(conn, lenbuf, lenbuf_len);
  5351. if (ret != (int)lenbuf_len) {
  5352. return -1;
  5353. }
  5354. t = ret;
  5355. ret = mg_write(conn, chunk, chunk_len);
  5356. if (ret != (int)chunk_len) {
  5357. return -1;
  5358. }
  5359. t += ret;
  5360. ret = mg_write(conn, "\r\n", 2);
  5361. if (ret != 2) {
  5362. return -1;
  5363. }
  5364. t += ret;
  5365. return t;
  5366. }
  5367. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5368. static int
  5369. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5370. {
  5371. va_list ap_copy;
  5372. size_t size = MG_BUF_LEN / 4;
  5373. int len = -1;
  5374. *buf = NULL;
  5375. while (len < 0) {
  5376. if (*buf) {
  5377. mg_free(*buf);
  5378. }
  5379. size *= 4;
  5380. *buf = (char *)mg_malloc(size);
  5381. if (!*buf) {
  5382. break;
  5383. }
  5384. va_copy(ap_copy, ap);
  5385. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5386. va_end(ap_copy);
  5387. (*buf)[size - 1] = 0;
  5388. }
  5389. return len;
  5390. }
  5391. /* Print message to buffer. If buffer is large enough to hold the message,
  5392. * return buffer. If buffer is to small, allocate large enough buffer on
  5393. * heap,
  5394. * and return allocated buffer. */
  5395. static int
  5396. alloc_vprintf(char **out_buf,
  5397. char *prealloc_buf,
  5398. size_t prealloc_size,
  5399. const char *fmt,
  5400. va_list ap)
  5401. {
  5402. va_list ap_copy;
  5403. int len;
  5404. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5405. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5406. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5407. * Therefore, we make two passes: on first pass, get required message
  5408. * length.
  5409. * On second pass, actually print the message. */
  5410. va_copy(ap_copy, ap);
  5411. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5412. va_end(ap_copy);
  5413. if (len < 0) {
  5414. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5415. * Switch to alternative code path that uses incremental
  5416. * allocations.
  5417. */
  5418. va_copy(ap_copy, ap);
  5419. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5420. va_end(ap_copy);
  5421. } else if ((size_t)(len) >= prealloc_size) {
  5422. /* The pre-allocated buffer not large enough. */
  5423. /* Allocate a new buffer. */
  5424. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5425. if (!*out_buf) {
  5426. /* Allocation failed. Return -1 as "out of memory" error. */
  5427. return -1;
  5428. }
  5429. /* Buffer allocation successful. Store the string there. */
  5430. va_copy(ap_copy, ap);
  5431. IGNORE_UNUSED_RESULT(
  5432. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5433. va_end(ap_copy);
  5434. } else {
  5435. /* The pre-allocated buffer is large enough.
  5436. * Use it to store the string and return the address. */
  5437. va_copy(ap_copy, ap);
  5438. IGNORE_UNUSED_RESULT(
  5439. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5440. va_end(ap_copy);
  5441. *out_buf = prealloc_buf;
  5442. }
  5443. return len;
  5444. }
  5445. static int
  5446. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5447. {
  5448. char mem[MG_BUF_LEN];
  5449. char *buf = NULL;
  5450. int len;
  5451. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5452. len = mg_write(conn, buf, (size_t)len);
  5453. }
  5454. if ((buf != mem) && (buf != NULL)) {
  5455. mg_free(buf);
  5456. }
  5457. return len;
  5458. }
  5459. int
  5460. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5461. {
  5462. va_list ap;
  5463. int result;
  5464. va_start(ap, fmt);
  5465. result = mg_vprintf(conn, fmt, ap);
  5466. va_end(ap);
  5467. return result;
  5468. }
  5469. int
  5470. mg_url_decode(const char *src,
  5471. int src_len,
  5472. char *dst,
  5473. int dst_len,
  5474. int is_form_url_encoded)
  5475. {
  5476. int i, j, a, b;
  5477. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5478. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5479. if ((i < src_len - 2) && (src[i] == '%')
  5480. && isxdigit(*(const unsigned char *)(src + i + 1))
  5481. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5482. a = tolower(*(const unsigned char *)(src + i + 1));
  5483. b = tolower(*(const unsigned char *)(src + i + 2));
  5484. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5485. i += 2;
  5486. } else if (is_form_url_encoded && (src[i] == '+')) {
  5487. dst[j] = ' ';
  5488. } else {
  5489. dst[j] = src[i];
  5490. }
  5491. }
  5492. dst[j] = '\0'; /* Null-terminate the destination */
  5493. return (i >= src_len) ? j : -1;
  5494. }
  5495. int
  5496. mg_get_var(const char *data,
  5497. size_t data_len,
  5498. const char *name,
  5499. char *dst,
  5500. size_t dst_len)
  5501. {
  5502. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5503. }
  5504. int
  5505. mg_get_var2(const char *data,
  5506. size_t data_len,
  5507. const char *name,
  5508. char *dst,
  5509. size_t dst_len,
  5510. size_t occurrence)
  5511. {
  5512. const char *p, *e, *s;
  5513. size_t name_len;
  5514. int len;
  5515. if ((dst == NULL) || (dst_len == 0)) {
  5516. len = -2;
  5517. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5518. len = -1;
  5519. dst[0] = '\0';
  5520. } else {
  5521. name_len = strlen(name);
  5522. e = data + data_len;
  5523. len = -1;
  5524. dst[0] = '\0';
  5525. /* data is "var1=val1&var2=val2...". Find variable first */
  5526. for (p = data; p + name_len < e; p++) {
  5527. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5528. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5529. /* Point p to variable value */
  5530. p += name_len + 1;
  5531. /* Point s to the end of the value */
  5532. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5533. if (s == NULL) {
  5534. s = e;
  5535. }
  5536. /* assert(s >= p); */
  5537. if (s < p) {
  5538. return -3;
  5539. }
  5540. /* Decode variable into destination buffer */
  5541. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5542. /* Redirect error code from -1 to -2 (destination buffer too
  5543. * small). */
  5544. if (len == -1) {
  5545. len = -2;
  5546. }
  5547. break;
  5548. }
  5549. }
  5550. }
  5551. return len;
  5552. }
  5553. /* HCP24: some changes to compare hole var_name */
  5554. int
  5555. mg_get_cookie(const char *cookie_header,
  5556. const char *var_name,
  5557. char *dst,
  5558. size_t dst_size)
  5559. {
  5560. const char *s, *p, *end;
  5561. int name_len, len = -1;
  5562. if ((dst == NULL) || (dst_size == 0)) {
  5563. return -2;
  5564. }
  5565. dst[0] = '\0';
  5566. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5567. return -1;
  5568. }
  5569. name_len = (int)strlen(var_name);
  5570. end = s + strlen(s);
  5571. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5572. if (s[name_len] == '=') {
  5573. /* HCP24: now check is it a substring or a full cookie name */
  5574. if ((s == cookie_header) || (s[-1] == ' ')) {
  5575. s += name_len + 1;
  5576. if ((p = strchr(s, ' ')) == NULL) {
  5577. p = end;
  5578. }
  5579. if (p[-1] == ';') {
  5580. p--;
  5581. }
  5582. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5583. s++;
  5584. p--;
  5585. }
  5586. if ((size_t)(p - s) < dst_size) {
  5587. len = (int)(p - s);
  5588. mg_strlcpy(dst, s, (size_t)len + 1);
  5589. } else {
  5590. len = -3;
  5591. }
  5592. break;
  5593. }
  5594. }
  5595. }
  5596. return len;
  5597. }
  5598. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5599. static void
  5600. base64_encode(const unsigned char *src, int src_len, char *dst)
  5601. {
  5602. static const char *b64 =
  5603. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5604. int i, j, a, b, c;
  5605. for (i = j = 0; i < src_len; i += 3) {
  5606. a = src[i];
  5607. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5608. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5609. dst[j++] = b64[a >> 2];
  5610. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5611. if (i + 1 < src_len) {
  5612. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5613. }
  5614. if (i + 2 < src_len) {
  5615. dst[j++] = b64[c & 63];
  5616. }
  5617. }
  5618. while (j % 4 != 0) {
  5619. dst[j++] = '=';
  5620. }
  5621. dst[j++] = '\0';
  5622. }
  5623. #endif
  5624. #if defined(USE_LUA)
  5625. static unsigned char
  5626. b64reverse(char letter)
  5627. {
  5628. if ((letter >= 'A') && (letter <= 'Z')) {
  5629. return letter - 'A';
  5630. }
  5631. if ((letter >= 'a') && (letter <= 'z')) {
  5632. return letter - 'a' + 26;
  5633. }
  5634. if ((letter >= '0') && (letter <= '9')) {
  5635. return letter - '0' + 52;
  5636. }
  5637. if (letter == '+') {
  5638. return 62;
  5639. }
  5640. if (letter == '/') {
  5641. return 63;
  5642. }
  5643. if (letter == '=') {
  5644. return 255; /* normal end */
  5645. }
  5646. return 254; /* error */
  5647. }
  5648. static int
  5649. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5650. {
  5651. int i;
  5652. unsigned char a, b, c, d;
  5653. *dst_len = 0;
  5654. for (i = 0; i < src_len; i += 4) {
  5655. a = b64reverse(src[i]);
  5656. if (a >= 254) {
  5657. return i;
  5658. }
  5659. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5660. if (b >= 254) {
  5661. return i + 1;
  5662. }
  5663. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5664. if (c == 254) {
  5665. return i + 2;
  5666. }
  5667. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5668. if (d == 254) {
  5669. return i + 3;
  5670. }
  5671. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5672. if (c != 255) {
  5673. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5674. if (d != 255) {
  5675. dst[(*dst_len)++] = (c << 6) + d;
  5676. }
  5677. }
  5678. }
  5679. return -1;
  5680. }
  5681. #endif
  5682. static int
  5683. is_put_or_delete_method(const struct mg_connection *conn)
  5684. {
  5685. if (conn) {
  5686. const char *s = conn->request_info.request_method;
  5687. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5688. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5689. }
  5690. return 0;
  5691. }
  5692. #if !defined(NO_FILES)
  5693. static int
  5694. extention_matches_script(
  5695. struct mg_connection *conn, /* in: request (must be valid) */
  5696. const char *filename /* in: filename (must be valid) */
  5697. )
  5698. {
  5699. #if !defined(NO_CGI)
  5700. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  5701. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  5702. filename) > 0) {
  5703. return 1;
  5704. }
  5705. #endif
  5706. #if defined(USE_LUA)
  5707. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  5708. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5709. filename) > 0) {
  5710. return 1;
  5711. }
  5712. #endif
  5713. #if defined(USE_DUKTAPE)
  5714. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5715. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5716. filename) > 0) {
  5717. return 1;
  5718. }
  5719. #endif
  5720. /* filename and conn could be unused, if all preocessor conditions
  5721. * are false (no script language supported). */
  5722. (void)filename;
  5723. (void)conn;
  5724. return 0;
  5725. }
  5726. /* For given directory path, substitute it to valid index file.
  5727. * Return 1 if index file has been found, 0 if not found.
  5728. * If the file is found, it's stats is returned in stp. */
  5729. static int
  5730. substitute_index_file(struct mg_connection *conn,
  5731. char *path,
  5732. size_t path_len,
  5733. struct mg_file_stat *filestat)
  5734. {
  5735. const char *list = conn->dom_ctx->config[INDEX_FILES];
  5736. struct vec filename_vec;
  5737. size_t n = strlen(path);
  5738. int found = 0;
  5739. /* The 'path' given to us points to the directory. Remove all trailing
  5740. * directory separator characters from the end of the path, and
  5741. * then append single directory separator character. */
  5742. while ((n > 0) && (path[n - 1] == '/')) {
  5743. n--;
  5744. }
  5745. path[n] = '/';
  5746. /* Traverse index files list. For each entry, append it to the given
  5747. * path and see if the file exists. If it exists, break the loop */
  5748. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5749. /* Ignore too long entries that may overflow path buffer */
  5750. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  5751. continue;
  5752. }
  5753. /* Prepare full path to the index file */
  5754. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5755. /* Does it exist? */
  5756. if (mg_stat(conn, path, filestat)) {
  5757. /* Yes it does, break the loop */
  5758. found = 1;
  5759. break;
  5760. }
  5761. }
  5762. /* If no index file exists, restore directory path */
  5763. if (!found) {
  5764. path[n] = '\0';
  5765. }
  5766. return found;
  5767. }
  5768. #endif
  5769. static void
  5770. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  5771. char *filename, /* out: filename */
  5772. size_t filename_buf_len, /* in: size of filename buffer */
  5773. struct mg_file_stat *filestat, /* out: file status structure */
  5774. int *is_found, /* out: file found (directly) */
  5775. int *is_script_resource, /* out: handled by a script? */
  5776. int *is_websocket_request, /* out: websocket connetion? */
  5777. int *is_put_or_delete_request /* out: put/delete a file? */
  5778. )
  5779. {
  5780. char const *accept_encoding;
  5781. #if !defined(NO_FILES)
  5782. const char *uri = conn->request_info.local_uri;
  5783. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  5784. const char *rewrite;
  5785. struct vec a, b;
  5786. int match_len;
  5787. char gz_path[PATH_MAX];
  5788. int truncated;
  5789. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5790. char *tmp_str;
  5791. size_t tmp_str_len, sep_pos;
  5792. int allow_substitute_script_subresources;
  5793. #endif
  5794. #else
  5795. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5796. #endif
  5797. /* Step 1: Set all initially unknown outputs to zero */
  5798. memset(filestat, 0, sizeof(*filestat));
  5799. *filename = 0;
  5800. *is_found = 0;
  5801. *is_script_resource = 0;
  5802. /* Step 2: Check if the request attempts to modify the file system */
  5803. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5804. /* Step 3: Check if it is a websocket request, and modify the document
  5805. * root if required */
  5806. #if defined(USE_WEBSOCKET)
  5807. *is_websocket_request = is_websocket_protocol(conn);
  5808. #if !defined(NO_FILES)
  5809. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  5810. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  5811. }
  5812. #endif /* !NO_FILES */
  5813. #else /* USE_WEBSOCKET */
  5814. *is_websocket_request = 0;
  5815. #endif /* USE_WEBSOCKET */
  5816. /* Step 4: Check if gzip encoded response is allowed */
  5817. conn->accept_gzip = 0;
  5818. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5819. if (strstr(accept_encoding, "gzip") != NULL) {
  5820. conn->accept_gzip = 1;
  5821. }
  5822. }
  5823. #if !defined(NO_FILES)
  5824. /* Step 5: If there is no root directory, don't look for files. */
  5825. /* Note that root == NULL is a regular use case here. This occurs,
  5826. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5827. * config is not required. */
  5828. if (root == NULL) {
  5829. /* all file related outputs have already been set to 0, just return
  5830. */
  5831. return;
  5832. }
  5833. /* Step 6: Determine the local file path from the root path and the
  5834. * request uri. */
  5835. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5836. * part of the path one byte on the right. */
  5837. mg_snprintf(
  5838. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5839. if (truncated) {
  5840. goto interpret_cleanup;
  5841. }
  5842. /* Step 7: URI rewriting */
  5843. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  5844. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5845. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5846. mg_snprintf(conn,
  5847. &truncated,
  5848. filename,
  5849. filename_buf_len - 1,
  5850. "%.*s%s",
  5851. (int)b.len,
  5852. b.ptr,
  5853. uri + match_len);
  5854. break;
  5855. }
  5856. }
  5857. if (truncated) {
  5858. goto interpret_cleanup;
  5859. }
  5860. /* Step 8: Check if the file exists at the server */
  5861. /* Local file path and name, corresponding to requested URI
  5862. * is now stored in "filename" variable. */
  5863. if (mg_stat(conn, filename, filestat)) {
  5864. /* 8.1: File exists. */
  5865. *is_found = 1;
  5866. /* 8.2: Check if it is a script type. */
  5867. if (extention_matches_script(conn, filename)) {
  5868. /* The request addresses a CGI resource, Lua script or
  5869. * server-side javascript.
  5870. * The URI corresponds to the script itself (like
  5871. * /path/script.cgi), and there is no additional resource
  5872. * path (like /path/script.cgi/something).
  5873. * Requests that modify (replace or delete) a resource, like
  5874. * PUT and DELETE requests, should replace/delete the script
  5875. * file.
  5876. * Requests that read or write from/to a resource, like GET and
  5877. * POST requests, should call the script and return the
  5878. * generated response. */
  5879. *is_script_resource = (!*is_put_or_delete_request);
  5880. }
  5881. /* 8.3: If the request target is a directory, there could be
  5882. * a substitute file (index.html, index.cgi, ...). */
  5883. if (filestat->is_directory) {
  5884. /* Use a local copy here, since substitute_index_file will
  5885. * change the content of the file status */
  5886. struct mg_file_stat tmp_filestat;
  5887. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5888. if (substitute_index_file(
  5889. conn, filename, filename_buf_len, &tmp_filestat)) {
  5890. /* Substitute file found. Copy stat to the output, then
  5891. * check if the file is a script file */
  5892. *filestat = tmp_filestat;
  5893. if (extention_matches_script(conn, filename)) {
  5894. /* Substitute file is a script file */
  5895. *is_script_resource = 1;
  5896. } else {
  5897. /* Substitute file is a regular file */
  5898. *is_script_resource = 0;
  5899. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5900. }
  5901. }
  5902. /* If there is no substitute file, the server could return
  5903. * a directory listing in a later step */
  5904. }
  5905. return;
  5906. }
  5907. /* Step 9: Check for zipped files: */
  5908. /* If we can't find the actual file, look for the file
  5909. * with the same name but a .gz extension. If we find it,
  5910. * use that and set the gzipped flag in the file struct
  5911. * to indicate that the response need to have the content-
  5912. * encoding: gzip header.
  5913. * We can only do this if the browser declares support. */
  5914. if (conn->accept_gzip) {
  5915. mg_snprintf(
  5916. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5917. if (truncated) {
  5918. goto interpret_cleanup;
  5919. }
  5920. if (mg_stat(conn, gz_path, filestat)) {
  5921. if (filestat) {
  5922. filestat->is_gzipped = 1;
  5923. *is_found = 1;
  5924. }
  5925. /* Currently gz files can not be scripts. */
  5926. return;
  5927. }
  5928. }
  5929. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5930. /* Step 10: Script resources may handle sub-resources */
  5931. /* Support PATH_INFO for CGI scripts. */
  5932. tmp_str_len = strlen(filename);
  5933. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  5934. if (!tmp_str) {
  5935. /* Out of memory */
  5936. goto interpret_cleanup;
  5937. }
  5938. memcpy(tmp_str, filename, tmp_str_len + 1);
  5939. /* Check config, if index scripts may have sub-resources */
  5940. allow_substitute_script_subresources =
  5941. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  5942. "yes");
  5943. sep_pos = tmp_str_len;
  5944. while (sep_pos > 0) {
  5945. sep_pos--;
  5946. if (tmp_str[sep_pos] == '/') {
  5947. int is_script = 0, does_exist = 0;
  5948. tmp_str[sep_pos] = 0;
  5949. if (tmp_str[0]) {
  5950. is_script = extention_matches_script(conn, tmp_str);
  5951. does_exist = mg_stat(conn, tmp_str, filestat);
  5952. }
  5953. if (does_exist && is_script) {
  5954. filename[sep_pos] = 0;
  5955. memmove(filename + sep_pos + 2,
  5956. filename + sep_pos + 1,
  5957. strlen(filename + sep_pos + 1) + 1);
  5958. conn->path_info = filename + sep_pos + 1;
  5959. filename[sep_pos + 1] = '/';
  5960. *is_script_resource = 1;
  5961. *is_found = 1;
  5962. break;
  5963. }
  5964. if (allow_substitute_script_subresources) {
  5965. if (substitute_index_file(
  5966. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5967. /* some intermediate directory has an index file */
  5968. if (extention_matches_script(conn, tmp_str)) {
  5969. char *tmp_str2;
  5970. DEBUG_TRACE("Substitute script %s serving path %s",
  5971. tmp_str,
  5972. filename);
  5973. /* this index file is a script */
  5974. tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5975. mg_snprintf(conn,
  5976. &truncated,
  5977. filename,
  5978. filename_buf_len,
  5979. "%s//%s",
  5980. tmp_str,
  5981. tmp_str2);
  5982. mg_free(tmp_str2);
  5983. if (truncated) {
  5984. mg_free(tmp_str);
  5985. goto interpret_cleanup;
  5986. }
  5987. sep_pos = strlen(tmp_str);
  5988. filename[sep_pos] = 0;
  5989. conn->path_info = filename + sep_pos + 1;
  5990. *is_script_resource = 1;
  5991. *is_found = 1;
  5992. break;
  5993. } else {
  5994. DEBUG_TRACE("Substitute file %s serving path %s",
  5995. tmp_str,
  5996. filename);
  5997. /* non-script files will not have sub-resources */
  5998. filename[sep_pos] = 0;
  5999. conn->path_info = 0;
  6000. *is_script_resource = 0;
  6001. *is_found = 0;
  6002. break;
  6003. }
  6004. }
  6005. }
  6006. tmp_str[sep_pos] = '/';
  6007. }
  6008. }
  6009. mg_free(tmp_str);
  6010. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6011. #endif /* !defined(NO_FILES) */
  6012. return;
  6013. #if !defined(NO_FILES)
  6014. /* Reset all outputs */
  6015. interpret_cleanup:
  6016. memset(filestat, 0, sizeof(*filestat));
  6017. *filename = 0;
  6018. *is_found = 0;
  6019. *is_script_resource = 0;
  6020. *is_websocket_request = 0;
  6021. *is_put_or_delete_request = 0;
  6022. #endif /* !defined(NO_FILES) */
  6023. }
  6024. /* Check whether full request is buffered. Return:
  6025. * -1 if request or response is malformed
  6026. * 0 if request or response is not yet fully buffered
  6027. * >0 actual request length, including last \r\n\r\n */
  6028. static int
  6029. get_http_header_len(const char *buf, int buflen)
  6030. {
  6031. int i;
  6032. for (i = 0; i < buflen; i++) {
  6033. /* Do an unsigned comparison in some conditions below */
  6034. const unsigned char c = ((const unsigned char *)buf)[i];
  6035. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6036. && !isprint(c)) {
  6037. /* abort scan as soon as one malformed character is found */
  6038. return -1;
  6039. }
  6040. if (i < buflen - 1) {
  6041. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6042. /* Two newline, no carriage return - not standard compliant,
  6043. * but
  6044. * it
  6045. * should be accepted */
  6046. return i + 2;
  6047. }
  6048. }
  6049. if (i < buflen - 3) {
  6050. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6051. && (buf[i + 3] == '\n')) {
  6052. /* Two \r\n - standard compliant */
  6053. return i + 4;
  6054. }
  6055. }
  6056. }
  6057. return 0;
  6058. }
  6059. #if !defined(NO_CACHING)
  6060. /* Convert month to the month number. Return -1 on error, or month number */
  6061. static int
  6062. get_month_index(const char *s)
  6063. {
  6064. size_t i;
  6065. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6066. if (!strcmp(s, month_names[i])) {
  6067. return (int)i;
  6068. }
  6069. }
  6070. return -1;
  6071. }
  6072. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6073. static time_t
  6074. parse_date_string(const char *datetime)
  6075. {
  6076. char month_str[32] = {0};
  6077. int second, minute, hour, day, month, year;
  6078. time_t result = (time_t)0;
  6079. struct tm tm;
  6080. if ((sscanf(datetime,
  6081. "%d/%3s/%d %d:%d:%d",
  6082. &day,
  6083. month_str,
  6084. &year,
  6085. &hour,
  6086. &minute,
  6087. &second) == 6) || (sscanf(datetime,
  6088. "%d %3s %d %d:%d:%d",
  6089. &day,
  6090. month_str,
  6091. &year,
  6092. &hour,
  6093. &minute,
  6094. &second) == 6)
  6095. || (sscanf(datetime,
  6096. "%*3s, %d %3s %d %d:%d:%d",
  6097. &day,
  6098. month_str,
  6099. &year,
  6100. &hour,
  6101. &minute,
  6102. &second) == 6) || (sscanf(datetime,
  6103. "%d-%3s-%d %d:%d:%d",
  6104. &day,
  6105. month_str,
  6106. &year,
  6107. &hour,
  6108. &minute,
  6109. &second) == 6)) {
  6110. month = get_month_index(month_str);
  6111. if ((month >= 0) && (year >= 1970)) {
  6112. memset(&tm, 0, sizeof(tm));
  6113. tm.tm_year = year - 1900;
  6114. tm.tm_mon = month;
  6115. tm.tm_mday = day;
  6116. tm.tm_hour = hour;
  6117. tm.tm_min = minute;
  6118. tm.tm_sec = second;
  6119. result = timegm(&tm);
  6120. }
  6121. }
  6122. return result;
  6123. }
  6124. #endif /* !NO_CACHING */
  6125. /* Protect against directory disclosure attack by removing '..',
  6126. * excessive '/' and '\' characters */
  6127. static void
  6128. remove_double_dots_and_double_slashes(char *s)
  6129. {
  6130. char *p = s;
  6131. while ((s[0] == '.') && (s[1] == '.')) {
  6132. s++;
  6133. }
  6134. while (*s != '\0') {
  6135. *p++ = *s++;
  6136. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6137. /* Skip all following slashes, backslashes and double-dots */
  6138. while (s[0] != '\0') {
  6139. if ((s[0] == '/') || (s[0] == '\\')) {
  6140. s++;
  6141. } else if ((s[0] == '.') && (s[1] == '.')) {
  6142. s += 2;
  6143. } else {
  6144. break;
  6145. }
  6146. }
  6147. }
  6148. }
  6149. *p = '\0';
  6150. }
  6151. static const struct {
  6152. const char *extension;
  6153. size_t ext_len;
  6154. const char *mime_type;
  6155. } builtin_mime_types[] = {
  6156. /* IANA registered MIME types
  6157. * (http://www.iana.org/assignments/media-types)
  6158. * application types */
  6159. {".doc", 4, "application/msword"},
  6160. {".eps", 4, "application/postscript"},
  6161. {".exe", 4, "application/octet-stream"},
  6162. {".js", 3, "application/javascript"},
  6163. {".json", 5, "application/json"},
  6164. {".pdf", 4, "application/pdf"},
  6165. {".ps", 3, "application/postscript"},
  6166. {".rtf", 4, "application/rtf"},
  6167. {".xhtml", 6, "application/xhtml+xml"},
  6168. {".xsl", 4, "application/xml"},
  6169. {".xslt", 5, "application/xml"},
  6170. /* fonts */
  6171. {".ttf", 4, "application/font-sfnt"},
  6172. {".cff", 4, "application/font-sfnt"},
  6173. {".otf", 4, "application/font-sfnt"},
  6174. {".aat", 4, "application/font-sfnt"},
  6175. {".sil", 4, "application/font-sfnt"},
  6176. {".pfr", 4, "application/font-tdpfr"},
  6177. {".woff", 5, "application/font-woff"},
  6178. /* audio */
  6179. {".mp3", 4, "audio/mpeg"},
  6180. {".oga", 4, "audio/ogg"},
  6181. {".ogg", 4, "audio/ogg"},
  6182. /* image */
  6183. {".gif", 4, "image/gif"},
  6184. {".ief", 4, "image/ief"},
  6185. {".jpeg", 5, "image/jpeg"},
  6186. {".jpg", 4, "image/jpeg"},
  6187. {".jpm", 4, "image/jpm"},
  6188. {".jpx", 4, "image/jpx"},
  6189. {".png", 4, "image/png"},
  6190. {".svg", 4, "image/svg+xml"},
  6191. {".tif", 4, "image/tiff"},
  6192. {".tiff", 5, "image/tiff"},
  6193. /* model */
  6194. {".wrl", 4, "model/vrml"},
  6195. /* text */
  6196. {".css", 4, "text/css"},
  6197. {".csv", 4, "text/csv"},
  6198. {".htm", 4, "text/html"},
  6199. {".html", 5, "text/html"},
  6200. {".sgm", 4, "text/sgml"},
  6201. {".shtm", 5, "text/html"},
  6202. {".shtml", 6, "text/html"},
  6203. {".txt", 4, "text/plain"},
  6204. {".xml", 4, "text/xml"},
  6205. /* video */
  6206. {".mov", 4, "video/quicktime"},
  6207. {".mp4", 4, "video/mp4"},
  6208. {".mpeg", 5, "video/mpeg"},
  6209. {".mpg", 4, "video/mpeg"},
  6210. {".ogv", 4, "video/ogg"},
  6211. {".qt", 3, "video/quicktime"},
  6212. /* not registered types
  6213. * (http://reference.sitepoint.com/html/mime-types-full,
  6214. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6215. {".arj", 4, "application/x-arj-compressed"},
  6216. {".gz", 3, "application/x-gunzip"},
  6217. {".rar", 4, "application/x-arj-compressed"},
  6218. {".swf", 4, "application/x-shockwave-flash"},
  6219. {".tar", 4, "application/x-tar"},
  6220. {".tgz", 4, "application/x-tar-gz"},
  6221. {".torrent", 8, "application/x-bittorrent"},
  6222. {".ppt", 4, "application/x-mspowerpoint"},
  6223. {".xls", 4, "application/x-msexcel"},
  6224. {".zip", 4, "application/x-zip-compressed"},
  6225. {".aac",
  6226. 4,
  6227. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6228. {".aif", 4, "audio/x-aif"},
  6229. {".m3u", 4, "audio/x-mpegurl"},
  6230. {".mid", 4, "audio/x-midi"},
  6231. {".ra", 3, "audio/x-pn-realaudio"},
  6232. {".ram", 4, "audio/x-pn-realaudio"},
  6233. {".wav", 4, "audio/x-wav"},
  6234. {".bmp", 4, "image/bmp"},
  6235. {".ico", 4, "image/x-icon"},
  6236. {".pct", 4, "image/x-pct"},
  6237. {".pict", 5, "image/pict"},
  6238. {".rgb", 4, "image/x-rgb"},
  6239. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6240. {".asf", 4, "video/x-ms-asf"},
  6241. {".avi", 4, "video/x-msvideo"},
  6242. {".m4v", 4, "video/x-m4v"},
  6243. {NULL, 0, NULL}};
  6244. const char *
  6245. mg_get_builtin_mime_type(const char *path)
  6246. {
  6247. const char *ext;
  6248. size_t i, path_len;
  6249. path_len = strlen(path);
  6250. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6251. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6252. if ((path_len > builtin_mime_types[i].ext_len)
  6253. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6254. return builtin_mime_types[i].mime_type;
  6255. }
  6256. }
  6257. return "text/plain";
  6258. }
  6259. /* Look at the "path" extension and figure what mime type it has.
  6260. * Store mime type in the vector. */
  6261. static void
  6262. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6263. {
  6264. struct vec ext_vec, mime_vec;
  6265. const char *list, *ext;
  6266. size_t path_len;
  6267. path_len = strlen(path);
  6268. if ((conn == NULL) || (vec == NULL)) {
  6269. if (vec != NULL) {
  6270. memset(vec, '\0', sizeof(struct vec));
  6271. }
  6272. return;
  6273. }
  6274. /* Scan user-defined mime types first, in case user wants to
  6275. * override default mime types. */
  6276. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6277. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6278. /* ext now points to the path suffix */
  6279. ext = path + path_len - ext_vec.len;
  6280. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6281. *vec = mime_vec;
  6282. return;
  6283. }
  6284. }
  6285. vec->ptr = mg_get_builtin_mime_type(path);
  6286. vec->len = strlen(vec->ptr);
  6287. }
  6288. /* Stringify binary data. Output buffer must be twice as big as input,
  6289. * because each byte takes 2 bytes in string representation */
  6290. static void
  6291. bin2str(char *to, const unsigned char *p, size_t len)
  6292. {
  6293. static const char *hex = "0123456789abcdef";
  6294. for (; len--; p++) {
  6295. *to++ = hex[p[0] >> 4];
  6296. *to++ = hex[p[0] & 0x0f];
  6297. }
  6298. *to = '\0';
  6299. }
  6300. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6301. */
  6302. char *
  6303. mg_md5(char buf[33], ...)
  6304. {
  6305. md5_byte_t hash[16];
  6306. const char *p;
  6307. va_list ap;
  6308. md5_state_t ctx;
  6309. md5_init(&ctx);
  6310. va_start(ap, buf);
  6311. while ((p = va_arg(ap, const char *)) != NULL) {
  6312. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6313. }
  6314. va_end(ap);
  6315. md5_finish(&ctx, hash);
  6316. bin2str(buf, hash, sizeof(hash));
  6317. return buf;
  6318. }
  6319. /* Check the user's password, return 1 if OK */
  6320. static int
  6321. check_password(const char *method,
  6322. const char *ha1,
  6323. const char *uri,
  6324. const char *nonce,
  6325. const char *nc,
  6326. const char *cnonce,
  6327. const char *qop,
  6328. const char *response)
  6329. {
  6330. char ha2[32 + 1], expected_response[32 + 1];
  6331. /* Some of the parameters may be NULL */
  6332. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6333. || (qop == NULL) || (response == NULL)) {
  6334. return 0;
  6335. }
  6336. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6337. if (strlen(response) != 32) {
  6338. return 0;
  6339. }
  6340. mg_md5(ha2, method, ":", uri, NULL);
  6341. mg_md5(expected_response,
  6342. ha1,
  6343. ":",
  6344. nonce,
  6345. ":",
  6346. nc,
  6347. ":",
  6348. cnonce,
  6349. ":",
  6350. qop,
  6351. ":",
  6352. ha2,
  6353. NULL);
  6354. return mg_strcasecmp(response, expected_response) == 0;
  6355. }
  6356. /* Use the global passwords file, if specified by auth_gpass option,
  6357. * or search for .htpasswd in the requested directory. */
  6358. static void
  6359. open_auth_file(struct mg_connection *conn,
  6360. const char *path,
  6361. struct mg_file *filep)
  6362. {
  6363. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6364. char name[PATH_MAX];
  6365. const char *p, *e,
  6366. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6367. int truncated;
  6368. if (gpass != NULL) {
  6369. /* Use global passwords file */
  6370. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6371. #ifdef DEBUG
  6372. /* Use mg_cry here, since gpass has been configured. */
  6373. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6374. #endif
  6375. }
  6376. /* Important: using local struct mg_file to test path for
  6377. * is_directory flag. If filep is used, mg_stat() makes it
  6378. * appear as if auth file was opened.
  6379. * TODO(mid): Check if this is still required after rewriting
  6380. * mg_stat */
  6381. } else if (mg_stat(conn, path, &filep->stat)
  6382. && filep->stat.is_directory) {
  6383. mg_snprintf(conn,
  6384. &truncated,
  6385. name,
  6386. sizeof(name),
  6387. "%s/%s",
  6388. path,
  6389. PASSWORDS_FILE_NAME);
  6390. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6391. #ifdef DEBUG
  6392. /* Don't use mg_cry here, but only a trace, since this is
  6393. * a typical case. It will occur for every directory
  6394. * without a password file. */
  6395. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6396. #endif
  6397. }
  6398. } else {
  6399. /* Try to find .htpasswd in requested directory. */
  6400. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6401. if (e[0] == '/') {
  6402. break;
  6403. }
  6404. }
  6405. mg_snprintf(conn,
  6406. &truncated,
  6407. name,
  6408. sizeof(name),
  6409. "%.*s/%s",
  6410. (int)(e - p),
  6411. p,
  6412. PASSWORDS_FILE_NAME);
  6413. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6414. #ifdef DEBUG
  6415. /* Don't use mg_cry here, but only a trace, since this is
  6416. * a typical case. It will occur for every directory
  6417. * without a password file. */
  6418. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6419. #endif
  6420. }
  6421. }
  6422. }
  6423. }
  6424. /* Parsed Authorization header */
  6425. struct ah {
  6426. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6427. };
  6428. /* Return 1 on success. Always initializes the ah structure. */
  6429. static int
  6430. parse_auth_header(struct mg_connection *conn,
  6431. char *buf,
  6432. size_t buf_size,
  6433. struct ah *ah)
  6434. {
  6435. char *name, *value, *s;
  6436. const char *auth_header;
  6437. uint64_t nonce;
  6438. if (!ah || !conn) {
  6439. return 0;
  6440. }
  6441. (void)memset(ah, 0, sizeof(*ah));
  6442. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6443. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6444. return 0;
  6445. }
  6446. /* Make modifiable copy of the auth header */
  6447. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6448. s = buf;
  6449. /* Parse authorization header */
  6450. for (;;) {
  6451. /* Gobble initial spaces */
  6452. while (isspace(*(unsigned char *)s)) {
  6453. s++;
  6454. }
  6455. name = skip_quoted(&s, "=", " ", 0);
  6456. /* Value is either quote-delimited, or ends at first comma or space.
  6457. */
  6458. if (s[0] == '\"') {
  6459. s++;
  6460. value = skip_quoted(&s, "\"", " ", '\\');
  6461. if (s[0] == ',') {
  6462. s++;
  6463. }
  6464. } else {
  6465. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6466. * spaces */
  6467. }
  6468. if (*name == '\0') {
  6469. break;
  6470. }
  6471. if (!strcmp(name, "username")) {
  6472. ah->user = value;
  6473. } else if (!strcmp(name, "cnonce")) {
  6474. ah->cnonce = value;
  6475. } else if (!strcmp(name, "response")) {
  6476. ah->response = value;
  6477. } else if (!strcmp(name, "uri")) {
  6478. ah->uri = value;
  6479. } else if (!strcmp(name, "qop")) {
  6480. ah->qop = value;
  6481. } else if (!strcmp(name, "nc")) {
  6482. ah->nc = value;
  6483. } else if (!strcmp(name, "nonce")) {
  6484. ah->nonce = value;
  6485. }
  6486. }
  6487. #ifndef NO_NONCE_CHECK
  6488. /* Read the nonce from the response. */
  6489. if (ah->nonce == NULL) {
  6490. return 0;
  6491. }
  6492. s = NULL;
  6493. nonce = strtoull(ah->nonce, &s, 10);
  6494. if ((s == NULL) || (*s != 0)) {
  6495. return 0;
  6496. }
  6497. /* Convert the nonce from the client to a number. */
  6498. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6499. /* The converted number corresponds to the time the nounce has been
  6500. * created. This should not be earlier than the server start. */
  6501. /* Server side nonce check is valuable in all situations but one:
  6502. * if the server restarts frequently, but the client should not see
  6503. * that, so the server should accept nonces from previous starts. */
  6504. /* However, the reasonable default is to not accept a nonce from a
  6505. * previous start, so if anyone changed the access rights between
  6506. * two restarts, a new login is required. */
  6507. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6508. /* nonce is from a previous start of the server and no longer valid
  6509. * (replay attack?) */
  6510. return 0;
  6511. }
  6512. /* Check if the nonce is too high, so it has not (yet) been used by the
  6513. * server. */
  6514. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6515. + conn->dom_ctx->nonce_count)) {
  6516. return 0;
  6517. }
  6518. #else
  6519. (void)nonce;
  6520. #endif
  6521. /* CGI needs it as REMOTE_USER */
  6522. if (ah->user != NULL) {
  6523. conn->request_info.remote_user = mg_strdup(ah->user);
  6524. } else {
  6525. return 0;
  6526. }
  6527. return 1;
  6528. }
  6529. static const char *
  6530. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6531. {
  6532. const char *eof;
  6533. size_t len;
  6534. const char *memend;
  6535. if (!filep) {
  6536. return NULL;
  6537. }
  6538. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6539. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6540. /* Search for \n from p till the end of stream */
  6541. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6542. if (eof != NULL) {
  6543. eof += 1; /* Include \n */
  6544. } else {
  6545. eof = memend; /* Copy remaining data */
  6546. }
  6547. len =
  6548. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6549. memcpy(buf, *p, len);
  6550. buf[len] = '\0';
  6551. *p += len;
  6552. return len ? eof : NULL;
  6553. } else if (filep->access.fp != NULL) {
  6554. return fgets(buf, (int)size, filep->access.fp);
  6555. } else {
  6556. return NULL;
  6557. }
  6558. }
  6559. /* Define the initial recursion depth for procesesing htpasswd files that
  6560. * include other htpasswd
  6561. * (or even the same) files. It is not difficult to provide a file or files
  6562. * s.t. they force civetweb
  6563. * to infinitely recurse and then crash.
  6564. */
  6565. #define INITIAL_DEPTH 9
  6566. #if INITIAL_DEPTH <= 0
  6567. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6568. #endif
  6569. struct read_auth_file_struct {
  6570. struct mg_connection *conn;
  6571. struct ah ah;
  6572. const char *domain;
  6573. char buf[256 + 256 + 40];
  6574. const char *f_user;
  6575. const char *f_domain;
  6576. const char *f_ha1;
  6577. };
  6578. static int
  6579. read_auth_file(struct mg_file *filep,
  6580. struct read_auth_file_struct *workdata,
  6581. int depth)
  6582. {
  6583. char *p;
  6584. int is_authorized = 0;
  6585. struct mg_file fp;
  6586. size_t l;
  6587. if (!filep || !workdata || (0 == depth)) {
  6588. return 0;
  6589. }
  6590. /* Loop over passwords file */
  6591. p = (char *)filep->access.membuf;
  6592. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6593. l = strlen(workdata->buf);
  6594. while (l > 0) {
  6595. if (isspace(workdata->buf[l - 1])
  6596. || iscntrl(workdata->buf[l - 1])) {
  6597. l--;
  6598. workdata->buf[l] = 0;
  6599. } else
  6600. break;
  6601. }
  6602. if (l < 1) {
  6603. continue;
  6604. }
  6605. workdata->f_user = workdata->buf;
  6606. if (workdata->f_user[0] == ':') {
  6607. /* user names may not contain a ':' and may not be empty,
  6608. * so lines starting with ':' may be used for a special purpose
  6609. */
  6610. if (workdata->f_user[1] == '#') {
  6611. /* :# is a comment */
  6612. continue;
  6613. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6614. if (mg_fopen(workdata->conn,
  6615. workdata->f_user + 9,
  6616. MG_FOPEN_MODE_READ,
  6617. &fp)) {
  6618. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6619. (void)mg_fclose(
  6620. &fp.access); /* ignore error on read only file */
  6621. /* No need to continue processing files once we have a
  6622. * match, since nothing will reset it back
  6623. * to 0.
  6624. */
  6625. if (is_authorized) {
  6626. return is_authorized;
  6627. }
  6628. } else {
  6629. mg_cry(workdata->conn,
  6630. "%s: cannot open authorization file: %s",
  6631. __func__,
  6632. workdata->buf);
  6633. }
  6634. continue;
  6635. }
  6636. /* everything is invalid for the moment (might change in the
  6637. * future) */
  6638. mg_cry(workdata->conn,
  6639. "%s: syntax error in authorization file: %s",
  6640. __func__,
  6641. workdata->buf);
  6642. continue;
  6643. }
  6644. workdata->f_domain = strchr(workdata->f_user, ':');
  6645. if (workdata->f_domain == NULL) {
  6646. mg_cry(workdata->conn,
  6647. "%s: syntax error in authorization file: %s",
  6648. __func__,
  6649. workdata->buf);
  6650. continue;
  6651. }
  6652. *(char *)(workdata->f_domain) = 0;
  6653. (workdata->f_domain)++;
  6654. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6655. if (workdata->f_ha1 == NULL) {
  6656. mg_cry(workdata->conn,
  6657. "%s: syntax error in authorization file: %s",
  6658. __func__,
  6659. workdata->buf);
  6660. continue;
  6661. }
  6662. *(char *)(workdata->f_ha1) = 0;
  6663. (workdata->f_ha1)++;
  6664. if (!strcmp(workdata->ah.user, workdata->f_user)
  6665. && !strcmp(workdata->domain, workdata->f_domain)) {
  6666. return check_password(workdata->conn->request_info.request_method,
  6667. workdata->f_ha1,
  6668. workdata->ah.uri,
  6669. workdata->ah.nonce,
  6670. workdata->ah.nc,
  6671. workdata->ah.cnonce,
  6672. workdata->ah.qop,
  6673. workdata->ah.response);
  6674. }
  6675. }
  6676. return is_authorized;
  6677. }
  6678. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6679. static int
  6680. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  6681. {
  6682. struct read_auth_file_struct workdata;
  6683. char buf[MG_BUF_LEN];
  6684. if (!conn || !conn->dom_ctx) {
  6685. return 0;
  6686. }
  6687. memset(&workdata, 0, sizeof(workdata));
  6688. workdata.conn = conn;
  6689. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6690. return 0;
  6691. }
  6692. if (realm) {
  6693. workdata.domain = realm;
  6694. } else {
  6695. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6696. }
  6697. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6698. }
  6699. /* Public function to check http digest authentication header */
  6700. int
  6701. mg_check_digest_access_authentication(struct mg_connection *conn,
  6702. const char *realm,
  6703. const char *filename)
  6704. {
  6705. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6706. int auth;
  6707. if (!conn || !filename) {
  6708. return -1;
  6709. }
  6710. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  6711. return -2;
  6712. }
  6713. auth = authorize(conn, &file, realm);
  6714. mg_fclose(&file.access);
  6715. return auth;
  6716. }
  6717. /* Return 1 if request is authorised, 0 otherwise. */
  6718. static int
  6719. check_authorization(struct mg_connection *conn, const char *path)
  6720. {
  6721. char fname[PATH_MAX];
  6722. struct vec uri_vec, filename_vec;
  6723. const char *list;
  6724. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6725. int authorized = 1, truncated;
  6726. if (!conn || !conn->dom_ctx) {
  6727. return 0;
  6728. }
  6729. list = conn->dom_ctx->config[PROTECT_URI];
  6730. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6731. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6732. mg_snprintf(conn,
  6733. &truncated,
  6734. fname,
  6735. sizeof(fname),
  6736. "%.*s",
  6737. (int)filename_vec.len,
  6738. filename_vec.ptr);
  6739. if (truncated
  6740. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6741. mg_cry(conn,
  6742. "%s: cannot open %s: %s",
  6743. __func__,
  6744. fname,
  6745. strerror(errno));
  6746. }
  6747. break;
  6748. }
  6749. }
  6750. if (!is_file_opened(&file.access)) {
  6751. open_auth_file(conn, path, &file);
  6752. }
  6753. if (is_file_opened(&file.access)) {
  6754. authorized = authorize(conn, &file, NULL);
  6755. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6756. }
  6757. return authorized;
  6758. }
  6759. /* Internal function. Assumes conn is valid */
  6760. static void
  6761. send_authorization_request(struct mg_connection *conn, const char *realm)
  6762. {
  6763. char date[64];
  6764. time_t curtime = time(NULL);
  6765. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  6766. if (!realm) {
  6767. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6768. }
  6769. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  6770. nonce += conn->dom_ctx->nonce_count;
  6771. ++conn->dom_ctx->nonce_count;
  6772. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  6773. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6774. conn->status_code = 401;
  6775. conn->must_close = 1;
  6776. gmt_time_string(date, sizeof(date), &curtime);
  6777. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6778. send_no_cache_header(conn);
  6779. send_additional_header(conn);
  6780. mg_printf(conn,
  6781. "Date: %s\r\n"
  6782. "Connection: %s\r\n"
  6783. "Content-Length: 0\r\n"
  6784. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6785. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6786. date,
  6787. suggest_connection_header(conn),
  6788. realm,
  6789. nonce);
  6790. }
  6791. /* Interface function. Parameters are provided by the user, so do
  6792. * at least some basic checks.
  6793. */
  6794. int
  6795. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  6796. const char *realm)
  6797. {
  6798. if (conn && conn->dom_ctx) {
  6799. send_authorization_request(conn, realm);
  6800. return 0;
  6801. }
  6802. return -1;
  6803. }
  6804. #if !defined(NO_FILES)
  6805. static int
  6806. is_authorized_for_put(struct mg_connection *conn)
  6807. {
  6808. if (conn) {
  6809. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6810. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6811. int ret = 0;
  6812. if (passfile != NULL
  6813. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6814. ret = authorize(conn, &file, NULL);
  6815. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6816. }
  6817. return ret;
  6818. }
  6819. return 0;
  6820. }
  6821. #endif
  6822. int
  6823. mg_modify_passwords_file(const char *fname,
  6824. const char *domain,
  6825. const char *user,
  6826. const char *pass)
  6827. {
  6828. int found, i;
  6829. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6830. FILE *fp, *fp2;
  6831. found = 0;
  6832. fp = fp2 = NULL;
  6833. /* Regard empty password as no password - remove user record. */
  6834. if ((pass != NULL) && (pass[0] == '\0')) {
  6835. pass = NULL;
  6836. }
  6837. /* Other arguments must not be empty */
  6838. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6839. return 0;
  6840. }
  6841. /* Using the given file format, user name and domain must not contain
  6842. * ':'
  6843. */
  6844. if (strchr(user, ':') != NULL) {
  6845. return 0;
  6846. }
  6847. if (strchr(domain, ':') != NULL) {
  6848. return 0;
  6849. }
  6850. /* Do not allow control characters like newline in user name and domain.
  6851. * Do not allow excessively long names either. */
  6852. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6853. if (iscntrl(user[i])) {
  6854. return 0;
  6855. }
  6856. }
  6857. if (user[i]) {
  6858. return 0;
  6859. }
  6860. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6861. if (iscntrl(domain[i])) {
  6862. return 0;
  6863. }
  6864. }
  6865. if (domain[i]) {
  6866. return 0;
  6867. }
  6868. /* The maximum length of the path to the password file is limited */
  6869. if ((strlen(fname) + 4) >= PATH_MAX) {
  6870. return 0;
  6871. }
  6872. /* Create a temporary file name. Length has been checked before. */
  6873. strcpy(tmp, fname);
  6874. strcat(tmp, ".tmp");
  6875. /* Create the file if does not exist */
  6876. /* Use of fopen here is OK, since fname is only ASCII */
  6877. if ((fp = fopen(fname, "a+")) != NULL) {
  6878. (void)fclose(fp);
  6879. }
  6880. /* Open the given file and temporary file */
  6881. if ((fp = fopen(fname, "r")) == NULL) {
  6882. return 0;
  6883. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6884. fclose(fp);
  6885. return 0;
  6886. }
  6887. /* Copy the stuff to temporary file */
  6888. while (fgets(line, sizeof(line), fp) != NULL) {
  6889. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6890. continue;
  6891. }
  6892. u[255] = 0;
  6893. d[255] = 0;
  6894. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6895. found++;
  6896. if (pass != NULL) {
  6897. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6898. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6899. }
  6900. } else {
  6901. fprintf(fp2, "%s", line);
  6902. }
  6903. }
  6904. /* If new user, just add it */
  6905. if (!found && (pass != NULL)) {
  6906. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6907. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6908. }
  6909. /* Close files */
  6910. fclose(fp);
  6911. fclose(fp2);
  6912. /* Put the temp file in place of real file */
  6913. IGNORE_UNUSED_RESULT(remove(fname));
  6914. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6915. return 1;
  6916. }
  6917. static int
  6918. is_valid_port(unsigned long port)
  6919. {
  6920. return (port <= 0xffff);
  6921. }
  6922. static int
  6923. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6924. {
  6925. struct addrinfo hints, *res, *ressave;
  6926. int func_ret = 0;
  6927. int gai_ret;
  6928. memset(&hints, 0, sizeof(struct addrinfo));
  6929. hints.ai_family = af;
  6930. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6931. if (gai_ret != 0) {
  6932. /* gai_strerror could be used to convert gai_ret to a string */
  6933. /* POSIX return values: see
  6934. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6935. */
  6936. /* Windows return values: see
  6937. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6938. */
  6939. return 0;
  6940. }
  6941. ressave = res;
  6942. while (res) {
  6943. if (dstlen >= (size_t)res->ai_addrlen) {
  6944. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6945. func_ret = 1;
  6946. }
  6947. res = res->ai_next;
  6948. }
  6949. freeaddrinfo(ressave);
  6950. return func_ret;
  6951. }
  6952. static int
  6953. connect_socket(struct mg_context *ctx /* may be NULL */,
  6954. const char *host,
  6955. int port,
  6956. int use_ssl,
  6957. char *ebuf,
  6958. size_t ebuf_len,
  6959. SOCKET *sock /* output: socket, must not be NULL */,
  6960. union usa *sa /* output: socket address, must not be NULL */
  6961. )
  6962. {
  6963. int ip_ver = 0;
  6964. int conn_ret = -1;
  6965. *sock = INVALID_SOCKET;
  6966. memset(sa, 0, sizeof(*sa));
  6967. if (ebuf_len > 0) {
  6968. *ebuf = 0;
  6969. }
  6970. if (host == NULL) {
  6971. mg_snprintf(NULL,
  6972. NULL, /* No truncation check for ebuf */
  6973. ebuf,
  6974. ebuf_len,
  6975. "%s",
  6976. "NULL host");
  6977. return 0;
  6978. }
  6979. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  6980. mg_snprintf(NULL,
  6981. NULL, /* No truncation check for ebuf */
  6982. ebuf,
  6983. ebuf_len,
  6984. "%s",
  6985. "invalid port");
  6986. return 0;
  6987. }
  6988. #if !defined(NO_SSL)
  6989. #if !defined(NO_SSL_DL)
  6990. #ifdef OPENSSL_API_1_1
  6991. if (use_ssl && (TLS_client_method == NULL)) {
  6992. mg_snprintf(NULL,
  6993. NULL, /* No truncation check for ebuf */
  6994. ebuf,
  6995. ebuf_len,
  6996. "%s",
  6997. "SSL is not initialized");
  6998. return 0;
  6999. }
  7000. #else
  7001. if (use_ssl && (SSLv23_client_method == NULL)) {
  7002. mg_snprintf(NULL,
  7003. NULL, /* No truncation check for ebuf */
  7004. ebuf,
  7005. ebuf_len,
  7006. "%s",
  7007. "SSL is not initialized");
  7008. return 0;
  7009. }
  7010. #endif /* OPENSSL_API_1_1 */
  7011. #else
  7012. (void)use_ssl;
  7013. #endif /* NO_SSL_DL */
  7014. #else
  7015. (void)use_ssl;
  7016. #endif /* !defined(NO_SSL) */
  7017. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7018. sa->sin.sin_family = AF_INET;
  7019. sa->sin.sin_port = htons((uint16_t)port);
  7020. ip_ver = 4;
  7021. #ifdef USE_IPV6
  7022. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7023. sa->sin6.sin6_family = AF_INET6;
  7024. sa->sin6.sin6_port = htons((uint16_t)port);
  7025. ip_ver = 6;
  7026. } else if (host[0] == '[') {
  7027. /* While getaddrinfo on Windows will work with [::1],
  7028. * getaddrinfo on Linux only works with ::1 (without []). */
  7029. size_t l = strlen(host + 1);
  7030. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  7031. if (h) {
  7032. h[l - 1] = 0;
  7033. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7034. sa->sin6.sin6_family = AF_INET6;
  7035. sa->sin6.sin6_port = htons((uint16_t)port);
  7036. ip_ver = 6;
  7037. }
  7038. mg_free(h);
  7039. }
  7040. #endif
  7041. }
  7042. if (ip_ver == 0) {
  7043. mg_snprintf(NULL,
  7044. NULL, /* No truncation check for ebuf */
  7045. ebuf,
  7046. ebuf_len,
  7047. "%s",
  7048. "host not found");
  7049. return 0;
  7050. }
  7051. if (ip_ver == 4) {
  7052. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7053. }
  7054. #ifdef USE_IPV6
  7055. else if (ip_ver == 6) {
  7056. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7057. }
  7058. #endif
  7059. if (*sock == INVALID_SOCKET) {
  7060. mg_snprintf(NULL,
  7061. NULL, /* No truncation check for ebuf */
  7062. ebuf,
  7063. ebuf_len,
  7064. "socket(): %s",
  7065. strerror(ERRNO));
  7066. return 0;
  7067. }
  7068. if (0 != set_non_blocking_mode(*sock)) {
  7069. mg_snprintf(NULL,
  7070. NULL, /* No truncation check for ebuf */
  7071. ebuf,
  7072. ebuf_len,
  7073. "Cannot set socket to non-blocking: %s",
  7074. strerror(ERRNO));
  7075. closesocket(*sock);
  7076. *sock = INVALID_SOCKET;
  7077. return 0;
  7078. }
  7079. set_close_on_exec(*sock, fc(ctx));
  7080. if (ip_ver == 4) {
  7081. /* connected with IPv4 */
  7082. conn_ret = connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin));
  7083. }
  7084. #ifdef USE_IPV6
  7085. else if (ip_ver == 6) {
  7086. /* connected with IPv6 */
  7087. conn_ret =
  7088. connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6));
  7089. }
  7090. #endif
  7091. if (conn_ret != 0) {
  7092. fd_set fdset;
  7093. struct timeval timeout;
  7094. int sockerr = -1;
  7095. #if defined(_WIN32)
  7096. int len = (int)sizeof(sockerr);
  7097. #else
  7098. socklen_t len = (socklen_t)sizeof(sockerr);
  7099. #endif
  7100. FD_ZERO(&fdset);
  7101. FD_SET(*sock, &fdset);
  7102. timeout.tv_sec = 10; /* 10 second timeout */
  7103. timeout.tv_usec = 0;
  7104. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7105. /* Not connected */
  7106. mg_snprintf(NULL,
  7107. NULL, /* No truncation check for ebuf */
  7108. ebuf,
  7109. ebuf_len,
  7110. "connect(%s:%d): timeout",
  7111. host,
  7112. port);
  7113. closesocket(*sock);
  7114. *sock = INVALID_SOCKET;
  7115. return 0;
  7116. }
  7117. #if defined(_WIN32)
  7118. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)&sockerr, &len);
  7119. #else
  7120. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &len);
  7121. #endif
  7122. if (sockerr != 0) {
  7123. /* Not connected */
  7124. mg_snprintf(NULL,
  7125. NULL, /* No truncation check for ebuf */
  7126. ebuf,
  7127. ebuf_len,
  7128. "connect(%s:%d): error %s",
  7129. host,
  7130. port,
  7131. strerror(sockerr));
  7132. closesocket(*sock);
  7133. *sock = INVALID_SOCKET;
  7134. return 0;
  7135. }
  7136. }
  7137. return 1;
  7138. }
  7139. int
  7140. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7141. {
  7142. static const char *dont_escape = "._-$,;~()";
  7143. static const char *hex = "0123456789abcdef";
  7144. char *pos = dst;
  7145. const char *end = dst + dst_len - 1;
  7146. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7147. if (isalnum(*(const unsigned char *)src)
  7148. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7149. *pos = *src;
  7150. } else if (pos + 2 < end) {
  7151. pos[0] = '%';
  7152. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7153. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7154. pos += 2;
  7155. } else {
  7156. break;
  7157. }
  7158. }
  7159. *pos = '\0';
  7160. return (*src == '\0') ? (int)(pos - dst) : -1;
  7161. }
  7162. /* Return 0 on success, non-zero if an error occurs. */
  7163. static int
  7164. print_dir_entry(struct de *de)
  7165. {
  7166. size_t hrefsize;
  7167. char *href;
  7168. char size[64], mod[64];
  7169. struct tm *tm;
  7170. hrefsize = PATH_MAX * 3; /* worst case */
  7171. href = (char *)mg_malloc(hrefsize);
  7172. if (href == NULL) {
  7173. return -1;
  7174. }
  7175. if (de->file.is_directory) {
  7176. mg_snprintf(de->conn,
  7177. NULL, /* Buffer is big enough */
  7178. size,
  7179. sizeof(size),
  7180. "%s",
  7181. "[DIRECTORY]");
  7182. } else {
  7183. /* We use (signed) cast below because MSVC 6 compiler cannot
  7184. * convert unsigned __int64 to double. Sigh. */
  7185. if (de->file.size < 1024) {
  7186. mg_snprintf(de->conn,
  7187. NULL, /* Buffer is big enough */
  7188. size,
  7189. sizeof(size),
  7190. "%d",
  7191. (int)de->file.size);
  7192. } else if (de->file.size < 0x100000) {
  7193. mg_snprintf(de->conn,
  7194. NULL, /* Buffer is big enough */
  7195. size,
  7196. sizeof(size),
  7197. "%.1fk",
  7198. (double)de->file.size / 1024.0);
  7199. } else if (de->file.size < 0x40000000) {
  7200. mg_snprintf(de->conn,
  7201. NULL, /* Buffer is big enough */
  7202. size,
  7203. sizeof(size),
  7204. "%.1fM",
  7205. (double)de->file.size / 1048576);
  7206. } else {
  7207. mg_snprintf(de->conn,
  7208. NULL, /* Buffer is big enough */
  7209. size,
  7210. sizeof(size),
  7211. "%.1fG",
  7212. (double)de->file.size / 1073741824);
  7213. }
  7214. }
  7215. /* Note: mg_snprintf will not cause a buffer overflow above.
  7216. * So, string truncation checks are not required here. */
  7217. tm = localtime(&de->file.last_modified);
  7218. if (tm != NULL) {
  7219. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7220. } else {
  7221. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7222. mod[sizeof(mod) - 1] = '\0';
  7223. }
  7224. mg_url_encode(de->file_name, href, hrefsize);
  7225. mg_printf(de->conn,
  7226. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7227. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7228. de->conn->request_info.local_uri,
  7229. href,
  7230. de->file.is_directory ? "/" : "",
  7231. de->file_name,
  7232. de->file.is_directory ? "/" : "",
  7233. mod,
  7234. size);
  7235. mg_free(href);
  7236. return 0;
  7237. }
  7238. /* This function is called from send_directory() and used for
  7239. * sorting directory entries by size, or name, or modification time.
  7240. * On windows, __cdecl specification is needed in case if project is built
  7241. * with __stdcall convention. qsort always requires __cdels callback. */
  7242. static int WINCDECL
  7243. compare_dir_entries(const void *p1, const void *p2)
  7244. {
  7245. if (p1 && p2) {
  7246. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7247. const char *query_string = a->conn->request_info.query_string;
  7248. int cmp_result = 0;
  7249. if (query_string == NULL) {
  7250. query_string = "na";
  7251. }
  7252. if (a->file.is_directory && !b->file.is_directory) {
  7253. return -1; /* Always put directories on top */
  7254. } else if (!a->file.is_directory && b->file.is_directory) {
  7255. return 1; /* Always put directories on top */
  7256. } else if (*query_string == 'n') {
  7257. cmp_result = strcmp(a->file_name, b->file_name);
  7258. } else if (*query_string == 's') {
  7259. cmp_result = (a->file.size == b->file.size)
  7260. ? 0
  7261. : ((a->file.size > b->file.size) ? 1 : -1);
  7262. } else if (*query_string == 'd') {
  7263. cmp_result =
  7264. (a->file.last_modified == b->file.last_modified)
  7265. ? 0
  7266. : ((a->file.last_modified > b->file.last_modified) ? 1
  7267. : -1);
  7268. }
  7269. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7270. }
  7271. return 0;
  7272. }
  7273. static int
  7274. must_hide_file(struct mg_connection *conn, const char *path)
  7275. {
  7276. if (conn && conn->dom_ctx) {
  7277. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7278. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7279. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7280. || ((pattern != NULL)
  7281. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7282. }
  7283. return 0;
  7284. }
  7285. static int
  7286. scan_directory(struct mg_connection *conn,
  7287. const char *dir,
  7288. void *data,
  7289. int (*cb)(struct de *, void *))
  7290. {
  7291. char path[PATH_MAX];
  7292. struct dirent *dp;
  7293. DIR *dirp;
  7294. struct de de;
  7295. int truncated;
  7296. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7297. return 0;
  7298. } else {
  7299. de.conn = conn;
  7300. while ((dp = mg_readdir(dirp)) != NULL) {
  7301. /* Do not show current dir and hidden files */
  7302. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7303. || must_hide_file(conn, dp->d_name)) {
  7304. continue;
  7305. }
  7306. mg_snprintf(
  7307. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7308. /* If we don't memset stat structure to zero, mtime will have
  7309. * garbage and strftime() will segfault later on in
  7310. * print_dir_entry(). memset is required only if mg_stat()
  7311. * fails. For more details, see
  7312. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7313. memset(&de.file, 0, sizeof(de.file));
  7314. if (truncated) {
  7315. /* If the path is not complete, skip processing. */
  7316. continue;
  7317. }
  7318. if (!mg_stat(conn, path, &de.file)) {
  7319. mg_cry(conn,
  7320. "%s: mg_stat(%s) failed: %s",
  7321. __func__,
  7322. path,
  7323. strerror(ERRNO));
  7324. }
  7325. de.file_name = dp->d_name;
  7326. cb(&de, data);
  7327. }
  7328. (void)mg_closedir(dirp);
  7329. }
  7330. return 1;
  7331. }
  7332. #if !defined(NO_FILES)
  7333. static int
  7334. remove_directory(struct mg_connection *conn, const char *dir)
  7335. {
  7336. char path[PATH_MAX];
  7337. struct dirent *dp;
  7338. DIR *dirp;
  7339. struct de de;
  7340. int truncated;
  7341. int ok = 1;
  7342. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7343. return 0;
  7344. } else {
  7345. de.conn = conn;
  7346. while ((dp = mg_readdir(dirp)) != NULL) {
  7347. /* Do not show current dir (but show hidden files as they will
  7348. * also be removed) */
  7349. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7350. continue;
  7351. }
  7352. mg_snprintf(
  7353. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7354. /* If we don't memset stat structure to zero, mtime will have
  7355. * garbage and strftime() will segfault later on in
  7356. * print_dir_entry(). memset is required only if mg_stat()
  7357. * fails. For more details, see
  7358. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7359. memset(&de.file, 0, sizeof(de.file));
  7360. if (truncated) {
  7361. /* Do not delete anything shorter */
  7362. ok = 0;
  7363. continue;
  7364. }
  7365. if (!mg_stat(conn, path, &de.file)) {
  7366. mg_cry(conn,
  7367. "%s: mg_stat(%s) failed: %s",
  7368. __func__,
  7369. path,
  7370. strerror(ERRNO));
  7371. ok = 0;
  7372. }
  7373. if (de.file.is_directory) {
  7374. if (remove_directory(conn, path) == 0) {
  7375. ok = 0;
  7376. }
  7377. } else {
  7378. /* This will fail file is the file is in memory */
  7379. if (mg_remove(conn, path) == 0) {
  7380. ok = 0;
  7381. }
  7382. }
  7383. }
  7384. (void)mg_closedir(dirp);
  7385. IGNORE_UNUSED_RESULT(rmdir(dir));
  7386. }
  7387. return ok;
  7388. }
  7389. #endif
  7390. struct dir_scan_data {
  7391. struct de *entries;
  7392. unsigned int num_entries;
  7393. unsigned int arr_size;
  7394. };
  7395. /* Behaves like realloc(), but frees original pointer on failure */
  7396. static void *
  7397. realloc2(void *ptr, size_t size)
  7398. {
  7399. void *new_ptr = mg_realloc(ptr, size);
  7400. if (new_ptr == NULL) {
  7401. mg_free(ptr);
  7402. }
  7403. return new_ptr;
  7404. }
  7405. static int
  7406. dir_scan_callback(struct de *de, void *data)
  7407. {
  7408. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7409. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7410. dsd->arr_size *= 2;
  7411. dsd->entries =
  7412. (struct de *)realloc2(dsd->entries,
  7413. dsd->arr_size * sizeof(dsd->entries[0]));
  7414. }
  7415. if (dsd->entries == NULL) {
  7416. /* TODO(lsm, low): propagate an error to the caller */
  7417. dsd->num_entries = 0;
  7418. } else {
  7419. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7420. dsd->entries[dsd->num_entries].file = de->file;
  7421. dsd->entries[dsd->num_entries].conn = de->conn;
  7422. dsd->num_entries++;
  7423. }
  7424. return 0;
  7425. }
  7426. static void
  7427. handle_directory_request(struct mg_connection *conn, const char *dir)
  7428. {
  7429. unsigned int i;
  7430. int sort_direction;
  7431. struct dir_scan_data data = {NULL, 0, 128};
  7432. char date[64];
  7433. time_t curtime = time(NULL);
  7434. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7435. mg_send_http_error(conn,
  7436. 500,
  7437. "Error: Cannot open directory\nopendir(%s): %s",
  7438. dir,
  7439. strerror(ERRNO));
  7440. return;
  7441. }
  7442. gmt_time_string(date, sizeof(date), &curtime);
  7443. if (!conn) {
  7444. return;
  7445. }
  7446. sort_direction = ((conn->request_info.query_string != NULL)
  7447. && (conn->request_info.query_string[1] == 'd'))
  7448. ? 'a'
  7449. : 'd';
  7450. conn->must_close = 1;
  7451. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7452. send_static_cache_header(conn);
  7453. send_additional_header(conn);
  7454. mg_printf(conn,
  7455. "Date: %s\r\n"
  7456. "Connection: close\r\n"
  7457. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7458. date);
  7459. mg_printf(conn,
  7460. "<html><head><title>Index of %s</title>"
  7461. "<style>th {text-align: left;}</style></head>"
  7462. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7463. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7464. "<th><a href=\"?d%c\">Modified</a></th>"
  7465. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7466. "<tr><td colspan=\"3\"><hr></td></tr>",
  7467. conn->request_info.local_uri,
  7468. conn->request_info.local_uri,
  7469. sort_direction,
  7470. sort_direction,
  7471. sort_direction);
  7472. /* Print first entry - link to a parent directory */
  7473. mg_printf(conn,
  7474. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7475. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7476. conn->request_info.local_uri,
  7477. "..",
  7478. "Parent directory",
  7479. "-",
  7480. "-");
  7481. /* Sort and print directory entries */
  7482. if (data.entries != NULL) {
  7483. qsort(data.entries,
  7484. (size_t)data.num_entries,
  7485. sizeof(data.entries[0]),
  7486. compare_dir_entries);
  7487. for (i = 0; i < data.num_entries; i++) {
  7488. print_dir_entry(&data.entries[i]);
  7489. mg_free(data.entries[i].file_name);
  7490. }
  7491. mg_free(data.entries);
  7492. }
  7493. mg_printf(conn, "%s", "</table></body></html>");
  7494. conn->status_code = 200;
  7495. }
  7496. /* Send len bytes from the opened file to the client. */
  7497. static void
  7498. send_file_data(struct mg_connection *conn,
  7499. struct mg_file *filep,
  7500. int64_t offset,
  7501. int64_t len)
  7502. {
  7503. char buf[MG_BUF_LEN];
  7504. int to_read, num_read, num_written;
  7505. int64_t size;
  7506. if (!filep || !conn) {
  7507. return;
  7508. }
  7509. /* Sanity check the offset */
  7510. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7511. : (int64_t)(filep->stat.size);
  7512. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7513. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7514. /* file stored in memory */
  7515. if (len > size - offset) {
  7516. len = size - offset;
  7517. }
  7518. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7519. } else if (len > 0 && filep->access.fp != NULL) {
  7520. /* file stored on disk */
  7521. #if defined(__linux__)
  7522. /* sendfile is only available for Linux */
  7523. if ((conn->ssl == 0) && (conn->throttle == 0)
  7524. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  7525. "yes"))) {
  7526. off_t sf_offs = (off_t)offset;
  7527. ssize_t sf_sent;
  7528. int sf_file = fileno(filep->access.fp);
  7529. int loop_cnt = 0;
  7530. do {
  7531. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7532. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7533. size_t sf_tosend =
  7534. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7535. sf_sent =
  7536. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7537. if (sf_sent > 0) {
  7538. len -= sf_sent;
  7539. offset += sf_sent;
  7540. } else if (loop_cnt == 0) {
  7541. /* This file can not be sent using sendfile.
  7542. * This might be the case for pseudo-files in the
  7543. * /sys/ and /proc/ file system.
  7544. * Use the regular user mode copy code instead. */
  7545. break;
  7546. } else if (sf_sent == 0) {
  7547. /* No error, but 0 bytes sent. May be EOF? */
  7548. return;
  7549. }
  7550. loop_cnt++;
  7551. } while ((len > 0) && (sf_sent >= 0));
  7552. if (sf_sent > 0) {
  7553. return; /* OK */
  7554. }
  7555. /* sf_sent<0 means error, thus fall back to the classic way */
  7556. /* This is always the case, if sf_file is not a "normal" file,
  7557. * e.g., for sending data from the output of a CGI process. */
  7558. offset = (int64_t)sf_offs;
  7559. }
  7560. #endif
  7561. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7562. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  7563. mg_send_http_error(
  7564. conn,
  7565. 500,
  7566. "%s",
  7567. "Error: Unable to access file at requested position.");
  7568. } else {
  7569. while (len > 0) {
  7570. /* Calculate how much to read from the file in the buffer */
  7571. to_read = sizeof(buf);
  7572. if ((int64_t)to_read > len) {
  7573. to_read = (int)len;
  7574. }
  7575. /* Read from file, exit the loop on error */
  7576. if ((num_read =
  7577. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7578. <= 0) {
  7579. break;
  7580. }
  7581. /* Send read bytes to the client, exit the loop on error */
  7582. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7583. != num_read) {
  7584. break;
  7585. }
  7586. /* Both read and were successful, adjust counters */
  7587. len -= num_written;
  7588. }
  7589. }
  7590. }
  7591. }
  7592. static int
  7593. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7594. {
  7595. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7596. }
  7597. static void
  7598. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7599. {
  7600. if ((filestat != NULL) && (buf != NULL)) {
  7601. mg_snprintf(NULL,
  7602. NULL, /* All calls to construct_etag use 64 byte buffer */
  7603. buf,
  7604. buf_len,
  7605. "\"%lx.%" INT64_FMT "\"",
  7606. (unsigned long)filestat->last_modified,
  7607. filestat->size);
  7608. }
  7609. }
  7610. static void
  7611. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7612. {
  7613. if (filep != NULL && filep->fp != NULL) {
  7614. #ifdef _WIN32
  7615. (void)conn; /* Unused. */
  7616. #else
  7617. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7618. mg_cry(conn,
  7619. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7620. __func__,
  7621. strerror(ERRNO));
  7622. }
  7623. #endif
  7624. }
  7625. }
  7626. static void
  7627. handle_static_file_request(struct mg_connection *conn,
  7628. const char *path,
  7629. struct mg_file *filep,
  7630. const char *mime_type,
  7631. const char *additional_headers)
  7632. {
  7633. char date[64], lm[64], etag[64];
  7634. char range[128]; /* large enough, so there will be no overflow */
  7635. const char *msg = "OK", *hdr;
  7636. time_t curtime = time(NULL);
  7637. int64_t cl, r1, r2;
  7638. struct vec mime_vec;
  7639. int n, truncated;
  7640. char gz_path[PATH_MAX];
  7641. const char *encoding = "";
  7642. const char *cors1, *cors2, *cors3;
  7643. int allow_on_the_fly_compression;
  7644. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  7645. return;
  7646. }
  7647. if (mime_type == NULL) {
  7648. get_mime_type(conn, path, &mime_vec);
  7649. } else {
  7650. mime_vec.ptr = mime_type;
  7651. mime_vec.len = strlen(mime_type);
  7652. }
  7653. if (filep->stat.size > INT64_MAX) {
  7654. mg_send_http_error(conn,
  7655. 500,
  7656. "Error: File size is too large to send\n%" INT64_FMT,
  7657. filep->stat.size);
  7658. return;
  7659. }
  7660. cl = (int64_t)filep->stat.size;
  7661. conn->status_code = 200;
  7662. range[0] = '\0';
  7663. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7664. * it's important to rewrite the filename after resolving
  7665. * the mime type from it, to preserve the actual file's type */
  7666. allow_on_the_fly_compression = conn->accept_gzip;
  7667. if (filep->stat.is_gzipped) {
  7668. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7669. if (truncated) {
  7670. mg_send_http_error(conn,
  7671. 500,
  7672. "Error: Path of zipped file too long (%s)",
  7673. path);
  7674. return;
  7675. }
  7676. path = gz_path;
  7677. encoding = "Content-Encoding: gzip\r\n";
  7678. /* File is already compressed. No "on the fly" compression. */
  7679. allow_on_the_fly_compression = 0;
  7680. }
  7681. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7682. mg_send_http_error(conn,
  7683. 500,
  7684. "Error: Cannot open file\nfopen(%s): %s",
  7685. path,
  7686. strerror(ERRNO));
  7687. return;
  7688. }
  7689. fclose_on_exec(&filep->access, conn);
  7690. /* If Range: header specified, act accordingly */
  7691. r1 = r2 = 0;
  7692. hdr = mg_get_header(conn, "Range");
  7693. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7694. && (r1 >= 0) && (r2 >= 0)) {
  7695. /* actually, range requests don't play well with a pre-gzipped
  7696. * file (since the range is specified in the uncompressed space) */
  7697. if (filep->stat.is_gzipped) {
  7698. mg_send_http_error(
  7699. conn,
  7700. 416, /* 416 = Range Not Satisfiable */
  7701. "%s",
  7702. "Error: Range requests in gzipped files are not supported");
  7703. (void)mg_fclose(
  7704. &filep->access); /* ignore error on read only file */
  7705. return;
  7706. }
  7707. conn->status_code = 206;
  7708. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7709. mg_snprintf(conn,
  7710. NULL, /* range buffer is big enough */
  7711. range,
  7712. sizeof(range),
  7713. "Content-Range: bytes "
  7714. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7715. r1,
  7716. r1 + cl - 1,
  7717. filep->stat.size);
  7718. msg = "Partial Content";
  7719. /* Do not compress ranges. */
  7720. allow_on_the_fly_compression = 0;
  7721. }
  7722. hdr = mg_get_header(conn, "Origin");
  7723. if (hdr) {
  7724. /* Cross-origin resource sharing (CORS), see
  7725. * http://www.html5rocks.com/en/tutorials/cors/,
  7726. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7727. * -
  7728. * preflight is not supported for files. */
  7729. cors1 = "Access-Control-Allow-Origin: ";
  7730. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7731. cors3 = "\r\n";
  7732. } else {
  7733. cors1 = cors2 = cors3 = "";
  7734. }
  7735. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  7736. * according to
  7737. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7738. gmt_time_string(date, sizeof(date), &curtime);
  7739. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7740. construct_etag(etag, sizeof(etag), &filep->stat);
  7741. /* On the fly compression allowed */
  7742. if (allow_on_the_fly_compression) {
  7743. ;
  7744. /* TODO: add interface to compression module */
  7745. /* e.g., def from https://zlib.net/zlib_how.html */
  7746. /* Check license (zlib has a permissive license, but */
  7747. /* is still not MIT) and use dynamic binding like */
  7748. /* done with OpenSSL */
  7749. /* See #199 (https://github.com/civetweb/civetweb/issues/199) */
  7750. }
  7751. /* Send header */
  7752. (void)mg_printf(conn,
  7753. "HTTP/1.1 %d %s\r\n"
  7754. "%s%s%s"
  7755. "Date: %s\r\n",
  7756. conn->status_code,
  7757. msg,
  7758. cors1,
  7759. cors2,
  7760. cors3,
  7761. date);
  7762. send_static_cache_header(conn);
  7763. send_additional_header(conn);
  7764. (void)mg_printf(conn,
  7765. "Last-Modified: %s\r\n"
  7766. "Etag: %s\r\n"
  7767. "Content-Type: %.*s\r\n"
  7768. "Content-Length: %" INT64_FMT "\r\n"
  7769. "Connection: %s\r\n"
  7770. "Accept-Ranges: bytes\r\n"
  7771. "%s%s",
  7772. lm,
  7773. etag,
  7774. (int)mime_vec.len,
  7775. mime_vec.ptr,
  7776. cl,
  7777. suggest_connection_header(conn),
  7778. range,
  7779. encoding);
  7780. /* The previous code must not add any header starting with X- to make
  7781. * sure no one of the additional_headers is included twice */
  7782. if (additional_headers != NULL) {
  7783. (void)mg_printf(conn,
  7784. "%.*s\r\n\r\n",
  7785. (int)strlen(additional_headers),
  7786. additional_headers);
  7787. } else {
  7788. (void)mg_printf(conn, "\r\n");
  7789. }
  7790. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7791. send_file_data(conn, filep, r1, cl);
  7792. }
  7793. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7794. }
  7795. #if !defined(NO_CACHING)
  7796. static void
  7797. handle_not_modified_static_file_request(struct mg_connection *conn,
  7798. struct mg_file *filep)
  7799. {
  7800. char date[64], lm[64], etag[64];
  7801. time_t curtime = time(NULL);
  7802. if ((conn == NULL) || (filep == NULL)) {
  7803. return;
  7804. }
  7805. conn->status_code = 304;
  7806. gmt_time_string(date, sizeof(date), &curtime);
  7807. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7808. construct_etag(etag, sizeof(etag), &filep->stat);
  7809. (void)mg_printf(conn,
  7810. "HTTP/1.1 %d %s\r\n"
  7811. "Date: %s\r\n",
  7812. conn->status_code,
  7813. mg_get_response_code_text(conn, conn->status_code),
  7814. date);
  7815. send_static_cache_header(conn);
  7816. send_additional_header(conn);
  7817. (void)mg_printf(conn,
  7818. "Last-Modified: %s\r\n"
  7819. "Etag: %s\r\n"
  7820. "Connection: %s\r\n"
  7821. "\r\n",
  7822. lm,
  7823. etag,
  7824. suggest_connection_header(conn));
  7825. }
  7826. #endif
  7827. void
  7828. mg_send_file(struct mg_connection *conn, const char *path)
  7829. {
  7830. mg_send_mime_file(conn, path, NULL);
  7831. }
  7832. void
  7833. mg_send_mime_file(struct mg_connection *conn,
  7834. const char *path,
  7835. const char *mime_type)
  7836. {
  7837. mg_send_mime_file2(conn, path, mime_type, NULL);
  7838. }
  7839. void
  7840. mg_send_mime_file2(struct mg_connection *conn,
  7841. const char *path,
  7842. const char *mime_type,
  7843. const char *additional_headers)
  7844. {
  7845. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7846. if (!conn) {
  7847. /* No conn */
  7848. return;
  7849. }
  7850. if (mg_stat(conn, path, &file.stat)) {
  7851. if (file.stat.is_directory) {
  7852. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  7853. "yes")) {
  7854. handle_directory_request(conn, path);
  7855. } else {
  7856. mg_send_http_error(conn,
  7857. 403,
  7858. "%s",
  7859. "Error: Directory listing denied");
  7860. }
  7861. } else {
  7862. handle_static_file_request(
  7863. conn, path, &file, mime_type, additional_headers);
  7864. }
  7865. } else {
  7866. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7867. }
  7868. }
  7869. /* For a given PUT path, create all intermediate subdirectories.
  7870. * Return 0 if the path itself is a directory.
  7871. * Return 1 if the path leads to a file.
  7872. * Return -1 for if the path is too long.
  7873. * Return -2 if path can not be created.
  7874. */
  7875. static int
  7876. put_dir(struct mg_connection *conn, const char *path)
  7877. {
  7878. char buf[PATH_MAX];
  7879. const char *s, *p;
  7880. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7881. size_t len;
  7882. int res = 1;
  7883. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7884. len = (size_t)(p - path);
  7885. if (len >= sizeof(buf)) {
  7886. /* path too long */
  7887. res = -1;
  7888. break;
  7889. }
  7890. memcpy(buf, path, len);
  7891. buf[len] = '\0';
  7892. /* Try to create intermediate directory */
  7893. DEBUG_TRACE("mkdir(%s)", buf);
  7894. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7895. /* path does not exixt and can not be created */
  7896. res = -2;
  7897. break;
  7898. }
  7899. /* Is path itself a directory? */
  7900. if (p[1] == '\0') {
  7901. res = 0;
  7902. }
  7903. }
  7904. return res;
  7905. }
  7906. static void
  7907. remove_bad_file(const struct mg_connection *conn, const char *path)
  7908. {
  7909. int r = mg_remove(conn, path);
  7910. if (r != 0) {
  7911. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7912. }
  7913. }
  7914. long long
  7915. mg_store_body(struct mg_connection *conn, const char *path)
  7916. {
  7917. char buf[MG_BUF_LEN];
  7918. long long len = 0;
  7919. int ret, n;
  7920. struct mg_file fi;
  7921. if (conn->consumed_content != 0) {
  7922. mg_cry(conn, "%s: Contents already consumed", __func__);
  7923. return -11;
  7924. }
  7925. ret = put_dir(conn, path);
  7926. if (ret < 0) {
  7927. /* -1 for path too long,
  7928. * -2 for path can not be created. */
  7929. return ret;
  7930. }
  7931. if (ret != 1) {
  7932. /* Return 0 means, path itself is a directory. */
  7933. return 0;
  7934. }
  7935. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7936. return -12;
  7937. }
  7938. ret = mg_read(conn, buf, sizeof(buf));
  7939. while (ret > 0) {
  7940. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7941. if (n != ret) {
  7942. (void)mg_fclose(
  7943. &fi.access); /* File is bad and will be removed anyway. */
  7944. remove_bad_file(conn, path);
  7945. return -13;
  7946. }
  7947. len += ret;
  7948. ret = mg_read(conn, buf, sizeof(buf));
  7949. }
  7950. /* File is open for writing. If fclose fails, there was probably an
  7951. * error flushing the buffer to disk, so the file on disk might be
  7952. * broken. Delete it and return an error to the caller. */
  7953. if (mg_fclose(&fi.access) != 0) {
  7954. remove_bad_file(conn, path);
  7955. return -14;
  7956. }
  7957. return len;
  7958. }
  7959. /* Parse a buffer:
  7960. * Forward the string pointer till the end of a word, then
  7961. * terminate it and forward till the begin of the next word.
  7962. */
  7963. static int
  7964. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  7965. {
  7966. /* Forward until a space is found - use isgraph here */
  7967. /* See http://www.cplusplus.com/reference/cctype/ */
  7968. while (isgraph(**ppw)) {
  7969. (*ppw)++;
  7970. }
  7971. /* Check end of word */
  7972. if (eol) {
  7973. /* must be a end of line */
  7974. if ((**ppw != '\r') && (**ppw != '\n')) {
  7975. return -1;
  7976. }
  7977. } else {
  7978. /* must be a end of a word, but not a line */
  7979. if (**ppw != ' ') {
  7980. return -1;
  7981. }
  7982. }
  7983. /* Terminate and forward to the next word */
  7984. do {
  7985. **ppw = 0;
  7986. (*ppw)++;
  7987. } while ((**ppw) && isspace(**ppw));
  7988. /* Check after term */
  7989. if (!eol) {
  7990. /* if it's not the end of line, there must be a next word */
  7991. if (!isgraph(**ppw)) {
  7992. return -1;
  7993. }
  7994. }
  7995. /* ok */
  7996. return 1;
  7997. }
  7998. /* Parse HTTP headers from the given buffer, advance buf pointer
  7999. * to the point where parsing stopped.
  8000. * All parameters must be valid pointers (not NULL).
  8001. * Return <0 on error. */
  8002. static int
  8003. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8004. {
  8005. int i;
  8006. int num_headers = 0;
  8007. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8008. char *dp = *buf;
  8009. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8010. dp++;
  8011. }
  8012. if (dp == *buf) {
  8013. /* End of headers reached. */
  8014. break;
  8015. }
  8016. if (*dp != ':') {
  8017. /* This is not a valid field. */
  8018. return -1;
  8019. }
  8020. /* End of header key (*dp == ':') */
  8021. /* Truncate here and set the key name */
  8022. *dp = 0;
  8023. hdr[i].name = *buf;
  8024. do {
  8025. dp++;
  8026. } while (*dp == ' ');
  8027. /* The rest of the line is the value */
  8028. hdr[i].value = dp;
  8029. *buf = dp + strcspn(dp, "\r\n");
  8030. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8031. *buf = NULL;
  8032. }
  8033. num_headers = i + 1;
  8034. if (*buf) {
  8035. (*buf)[0] = 0;
  8036. (*buf)[1] = 0;
  8037. *buf += 2;
  8038. } else {
  8039. *buf = dp;
  8040. break;
  8041. }
  8042. if ((*buf)[0] == '\r') {
  8043. /* This is the end of the header */
  8044. break;
  8045. }
  8046. }
  8047. return num_headers;
  8048. }
  8049. struct mg_http_method_info {
  8050. const char *name;
  8051. int request_has_body;
  8052. int response_has_body;
  8053. int is_safe;
  8054. int is_idempotent;
  8055. int is_cacheable;
  8056. };
  8057. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8058. static struct mg_http_method_info http_methods[] = {
  8059. /* HTTP (RFC 2616) */
  8060. {"GET", 0, 1, 1, 1, 1},
  8061. {"POST", 1, 1, 0, 0, 0},
  8062. {"PUT", 1, 0, 0, 1, 0},
  8063. {"DELETE", 0, 0, 0, 1, 0},
  8064. {"HEAD", 0, 0, 1, 1, 1},
  8065. {"OPTIONS", 0, 0, 1, 1, 0},
  8066. {"CONNECT", 1, 1, 0, 0, 0},
  8067. /* TRACE method (RFC 2616) is not supported for security reasons */
  8068. /* PATCH method (RFC 5789) */
  8069. {"PATCH", 1, 0, 0, 0, 0},
  8070. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8071. /* WEBDAV (RFC 2518) */
  8072. {"PROPFIND", 0, 1, 1, 1, 0},
  8073. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8074. * Some PROPFIND results MAY be cached, with care,
  8075. * as there is no cache validation mechanism for
  8076. * most properties. This method is both safe and
  8077. * idempotent (see Section 9.1 of [RFC2616]). */
  8078. {"MKCOL", 0, 0, 0, 1, 0},
  8079. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8080. * When MKCOL is invoked without a request body,
  8081. * the newly created collection SHOULD have no
  8082. * members. A MKCOL request message may contain
  8083. * a message body. The precise behavior of a MKCOL
  8084. * request when the body is present is undefined,
  8085. * ... ==> We do not support MKCOL with body data.
  8086. * This method is idempotent, but not safe (see
  8087. * Section 9.1 of [RFC2616]). Responses to this
  8088. * method MUST NOT be cached. */
  8089. /* Unsupported WEBDAV Methods: */
  8090. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8091. /* + 11 methods from RFC 3253 */
  8092. /* ORDERPATCH (RFC 3648) */
  8093. /* ACL (RFC 3744) */
  8094. /* SEARCH (RFC 5323) */
  8095. /* + MicroSoft extensions
  8096. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8097. /* REPORT method (RFC 3253) */
  8098. {"REPORT", 1, 1, 1, 1, 1},
  8099. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8100. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8101. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8102. * to be useful for REST in case a "GET request with body" is
  8103. * required. */
  8104. {NULL, 0, 0, 0, 0, 0}
  8105. /* end of list */
  8106. };
  8107. static const struct mg_http_method_info *
  8108. get_http_method_info(const char *method)
  8109. {
  8110. /* Check if the method is known to the server. The list of all known
  8111. * HTTP methods can be found here at
  8112. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8113. */
  8114. const struct mg_http_method_info *m = http_methods;
  8115. while (m->name) {
  8116. if (!strcmp(m->name, method)) {
  8117. return m;
  8118. }
  8119. m++;
  8120. }
  8121. return NULL;
  8122. }
  8123. static int
  8124. is_valid_http_method(const char *method)
  8125. {
  8126. return (get_http_method_info(method) != NULL);
  8127. }
  8128. /* Parse HTTP request, fill in mg_request_info structure.
  8129. * This function modifies the buffer by NUL-terminating
  8130. * HTTP request components, header names and header values.
  8131. * Parameters:
  8132. * buf (in/out): pointer to the HTTP header to parse and split
  8133. * len (in): length of HTTP header buffer
  8134. * re (out): parsed header as mg_request_info
  8135. * buf and ri must be valid pointers (not NULL), len>0.
  8136. * Returns <0 on error. */
  8137. static int
  8138. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8139. {
  8140. int request_length;
  8141. int init_skip = 0;
  8142. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  8143. * remote_port */
  8144. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8145. NULL;
  8146. ri->num_headers = 0;
  8147. /* RFC says that all initial whitespaces should be ingored */
  8148. /* This included all leading \r and \n (isspace) */
  8149. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8150. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8151. buf++;
  8152. len--;
  8153. init_skip++;
  8154. }
  8155. if (len == 0) {
  8156. /* Incomplete request */
  8157. return 0;
  8158. }
  8159. /* Control characters are not allowed, including zero */
  8160. if (iscntrl(*(unsigned char *)buf)) {
  8161. return -1;
  8162. }
  8163. /* Find end of HTTP header */
  8164. request_length = get_http_header_len(buf, len);
  8165. if (request_length <= 0) {
  8166. return request_length;
  8167. }
  8168. buf[request_length - 1] = '\0';
  8169. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8170. return -1;
  8171. }
  8172. /* The first word has to be the HTTP method */
  8173. ri->request_method = buf;
  8174. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8175. return -1;
  8176. }
  8177. /* Check for a valid http method */
  8178. if (!is_valid_http_method(ri->request_method)) {
  8179. return -1;
  8180. }
  8181. /* The second word is the URI */
  8182. ri->request_uri = buf;
  8183. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8184. return -1;
  8185. }
  8186. /* Next would be the HTTP version */
  8187. ri->http_version = buf;
  8188. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8189. return -1;
  8190. }
  8191. /* Check for a valid HTTP version key */
  8192. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8193. /* Invalid request */
  8194. return -1;
  8195. }
  8196. ri->http_version += 5;
  8197. /* Parse all HTTP headers */
  8198. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8199. if (ri->num_headers < 0) {
  8200. /* Error while parsing headers */
  8201. return -1;
  8202. }
  8203. return request_length + init_skip;
  8204. }
  8205. static int
  8206. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8207. {
  8208. int response_length;
  8209. int init_skip = 0;
  8210. char *tmp, *tmp2;
  8211. long l;
  8212. /* Initialize elements. */
  8213. ri->http_version = ri->status_text = NULL;
  8214. ri->num_headers = ri->status_code = 0;
  8215. /* RFC says that all initial whitespaces should be ingored */
  8216. /* This included all leading \r and \n (isspace) */
  8217. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8218. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8219. buf++;
  8220. len--;
  8221. init_skip++;
  8222. }
  8223. if (len == 0) {
  8224. /* Incomplete request */
  8225. return 0;
  8226. }
  8227. /* Control characters are not allowed, including zero */
  8228. if (iscntrl(*(unsigned char *)buf)) {
  8229. return -1;
  8230. }
  8231. /* Find end of HTTP header */
  8232. response_length = get_http_header_len(buf, len);
  8233. if (response_length <= 0) {
  8234. return response_length;
  8235. }
  8236. buf[response_length - 1] = '\0';
  8237. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8238. return -1;
  8239. }
  8240. /* The first word is the HTTP version */
  8241. /* Check for a valid HTTP version key */
  8242. if (strncmp(buf, "HTTP/", 5) != 0) {
  8243. /* Invalid request */
  8244. return -1;
  8245. }
  8246. buf += 5;
  8247. if (!isgraph(buf[0])) {
  8248. /* Invalid request */
  8249. return -1;
  8250. }
  8251. ri->http_version = buf;
  8252. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8253. return -1;
  8254. }
  8255. /* The second word is the status as a number */
  8256. tmp = buf;
  8257. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8258. return -1;
  8259. }
  8260. l = strtol(tmp, &tmp2, 10);
  8261. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8262. /* Everything else but a 3 digit code is invalid */
  8263. return -1;
  8264. }
  8265. ri->status_code = (int)l;
  8266. /* The rest of the line is the status text */
  8267. ri->status_text = buf;
  8268. /* Find end of status text */
  8269. /* isgraph or isspace = isprint */
  8270. while (isprint(*buf)) {
  8271. buf++;
  8272. }
  8273. if ((*buf != '\r') && (*buf != '\n')) {
  8274. return -1;
  8275. }
  8276. /* Terminate string and forward buf to next line */
  8277. do {
  8278. *buf = 0;
  8279. buf++;
  8280. } while ((*buf) && isspace(*buf));
  8281. /* Parse all HTTP headers */
  8282. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8283. if (ri->num_headers < 0) {
  8284. /* Error while parsing headers */
  8285. return -1;
  8286. }
  8287. return response_length + init_skip;
  8288. }
  8289. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8290. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8291. * buffer (which marks the end of HTTP request). Buffer buf may already
  8292. * have some data. The length of the data is stored in nread.
  8293. * Upon every read operation, increase nread by the number of bytes read. */
  8294. static int
  8295. read_message(FILE *fp,
  8296. struct mg_connection *conn,
  8297. char *buf,
  8298. int bufsiz,
  8299. int *nread)
  8300. {
  8301. int request_len, n = 0;
  8302. struct timespec last_action_time;
  8303. double request_timeout;
  8304. if (!conn) {
  8305. return 0;
  8306. }
  8307. memset(&last_action_time, 0, sizeof(last_action_time));
  8308. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8309. /* value of request_timeout is in seconds, config in milliseconds */
  8310. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8311. } else {
  8312. request_timeout = -1.0;
  8313. }
  8314. if (conn->handled_requests > 0) {
  8315. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8316. request_timeout =
  8317. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8318. }
  8319. }
  8320. request_len = get_http_header_len(buf, *nread);
  8321. /* first time reading from this connection */
  8322. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8323. while (request_len == 0) {
  8324. /* Full request not yet received */
  8325. if (conn->phys_ctx->stop_flag != 0) {
  8326. /* Server is to be stopped. */
  8327. return -1;
  8328. }
  8329. if (*nread >= bufsiz) {
  8330. /* Request too long */
  8331. return -2;
  8332. }
  8333. n = pull_inner(
  8334. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8335. if (n == -2) {
  8336. /* Receive error */
  8337. return -1;
  8338. }
  8339. if (n > 0) {
  8340. *nread += n;
  8341. request_len = get_http_header_len(buf, *nread);
  8342. } else {
  8343. request_len = 0;
  8344. }
  8345. if ((request_len == 0) && (request_timeout >= 0)) {
  8346. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8347. > request_timeout) {
  8348. /* Timeout */
  8349. return -1;
  8350. }
  8351. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8352. }
  8353. }
  8354. return request_len;
  8355. }
  8356. #if !defined(NO_CACHING)
  8357. /* Return True if we should reply 304 Not Modified. */
  8358. static int
  8359. is_not_modified(const struct mg_connection *conn,
  8360. const struct mg_file_stat *filestat)
  8361. {
  8362. char etag[64];
  8363. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8364. const char *inm = mg_get_header(conn, "If-None-Match");
  8365. construct_etag(etag, sizeof(etag), filestat);
  8366. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8367. || ((ims != NULL)
  8368. && (filestat->last_modified <= parse_date_string(ims)));
  8369. }
  8370. #endif /* !NO_CACHING */
  8371. #if !defined(NO_CGI) || !defined(NO_FILES)
  8372. static int
  8373. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8374. {
  8375. const char *expect, *body;
  8376. char buf[MG_BUF_LEN];
  8377. int to_read, nread, success = 0;
  8378. int64_t buffered_len;
  8379. double timeout = -1.0;
  8380. if (!conn) {
  8381. return 0;
  8382. }
  8383. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8384. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8385. }
  8386. expect = mg_get_header(conn, "Expect");
  8387. /* assert(fp != NULL); */
  8388. if (!fp) {
  8389. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8390. return 0;
  8391. }
  8392. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8393. /* Content length is not specified by the client. */
  8394. mg_send_http_error(conn,
  8395. 411,
  8396. "%s",
  8397. "Error: Client did not specify content length");
  8398. } else if ((expect != NULL)
  8399. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8400. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8401. */
  8402. mg_send_http_error(conn,
  8403. 417,
  8404. "Error: Can not fulfill expectation %s",
  8405. expect);
  8406. } else {
  8407. if (expect != NULL) {
  8408. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8409. conn->status_code = 100;
  8410. } else {
  8411. conn->status_code = 200;
  8412. }
  8413. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8414. - conn->consumed_content;
  8415. /* assert(buffered_len >= 0); */
  8416. /* assert(conn->consumed_content == 0); */
  8417. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8418. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8419. return 0;
  8420. }
  8421. if (buffered_len > 0) {
  8422. if ((int64_t)buffered_len > conn->content_len) {
  8423. buffered_len = (int)conn->content_len;
  8424. }
  8425. body = conn->buf + conn->request_len + conn->consumed_content;
  8426. push_all(
  8427. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8428. conn->consumed_content += buffered_len;
  8429. }
  8430. nread = 0;
  8431. while (conn->consumed_content < conn->content_len) {
  8432. to_read = sizeof(buf);
  8433. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8434. to_read = (int)(conn->content_len - conn->consumed_content);
  8435. }
  8436. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8437. if (nread == -2) {
  8438. /* error */
  8439. break;
  8440. }
  8441. if (nread > 0) {
  8442. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  8443. != nread) {
  8444. break;
  8445. }
  8446. }
  8447. conn->consumed_content += nread;
  8448. }
  8449. if (conn->consumed_content == conn->content_len) {
  8450. success = (nread >= 0);
  8451. }
  8452. /* Each error code path in this function must send an error */
  8453. if (!success) {
  8454. /* NOTE: Maybe some data has already been sent. */
  8455. /* TODO (low): If some data has been sent, a correct error
  8456. * reply can no longer be sent, so just close the connection */
  8457. mg_send_http_error(conn, 500, "%s", "");
  8458. }
  8459. }
  8460. return success;
  8461. }
  8462. #endif
  8463. #if !defined(NO_CGI)
  8464. /* This structure helps to create an environment for the spawned CGI
  8465. * program.
  8466. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8467. * last element must be NULL.
  8468. * However, on Windows there is a requirement that all these
  8469. * VARIABLE=VALUE\0
  8470. * strings must reside in a contiguous buffer. The end of the buffer is
  8471. * marked by two '\0' characters.
  8472. * We satisfy both worlds: we create an envp array (which is vars), all
  8473. * entries are actually pointers inside buf. */
  8474. struct cgi_environment {
  8475. struct mg_connection *conn;
  8476. /* Data block */
  8477. char *buf; /* Environment buffer */
  8478. size_t buflen; /* Space available in buf */
  8479. size_t bufused; /* Space taken in buf */
  8480. /* Index block */
  8481. char **var; /* char **envp */
  8482. size_t varlen; /* Number of variables available in var */
  8483. size_t varused; /* Number of variables stored in var */
  8484. };
  8485. static void addenv(struct cgi_environment *env,
  8486. PRINTF_FORMAT_STRING(const char *fmt),
  8487. ...) PRINTF_ARGS(2, 3);
  8488. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8489. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8490. static void
  8491. addenv(struct cgi_environment *env, const char *fmt, ...)
  8492. {
  8493. size_t n, space;
  8494. int truncated = 0;
  8495. char *added;
  8496. va_list ap;
  8497. /* Calculate how much space is left in the buffer */
  8498. space = (env->buflen - env->bufused);
  8499. /* Calculate an estimate for the required space */
  8500. n = strlen(fmt) + 2 + 128;
  8501. do {
  8502. if (space <= n) {
  8503. /* Allocate new buffer */
  8504. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8505. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  8506. if (!added) {
  8507. /* Out of memory */
  8508. mg_cry(env->conn,
  8509. "%s: Cannot allocate memory for CGI variable [%s]",
  8510. __func__,
  8511. fmt);
  8512. return;
  8513. }
  8514. env->buf = added;
  8515. env->buflen = n;
  8516. space = (env->buflen - env->bufused);
  8517. }
  8518. /* Make a pointer to the free space int the buffer */
  8519. added = env->buf + env->bufused;
  8520. /* Copy VARIABLE=VALUE\0 string into the free space */
  8521. va_start(ap, fmt);
  8522. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8523. va_end(ap);
  8524. /* Do not add truncated strings to the environment */
  8525. if (truncated) {
  8526. /* Reallocate the buffer */
  8527. space = 0;
  8528. n = 1;
  8529. }
  8530. } while (truncated);
  8531. /* Calculate number of bytes added to the environment */
  8532. n = strlen(added) + 1;
  8533. env->bufused += n;
  8534. /* Now update the variable index */
  8535. space = (env->varlen - env->varused);
  8536. if (space < 2) {
  8537. mg_cry(env->conn,
  8538. "%s: Cannot register CGI variable [%s]",
  8539. __func__,
  8540. fmt);
  8541. return;
  8542. }
  8543. /* Append a pointer to the added string into the envp array */
  8544. env->var[env->varused] = added;
  8545. env->varused++;
  8546. }
  8547. /* Return 0 on success, non-zero if an error occurs. */
  8548. static int
  8549. prepare_cgi_environment(struct mg_connection *conn,
  8550. const char *prog,
  8551. struct cgi_environment *env)
  8552. {
  8553. const char *s;
  8554. struct vec var_vec;
  8555. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8556. int i, truncated, uri_len;
  8557. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8558. return -1;
  8559. }
  8560. env->conn = conn;
  8561. env->buflen = CGI_ENVIRONMENT_SIZE;
  8562. env->bufused = 0;
  8563. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  8564. if (env->buf == NULL) {
  8565. mg_cry(conn,
  8566. "%s: Not enough memory for environmental buffer",
  8567. __func__);
  8568. return -1;
  8569. }
  8570. env->varlen = MAX_CGI_ENVIR_VARS;
  8571. env->varused = 0;
  8572. env->var =
  8573. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  8574. if (env->var == NULL) {
  8575. mg_cry(conn,
  8576. "%s: Not enough memory for environmental variables",
  8577. __func__);
  8578. mg_free(env->buf);
  8579. return -1;
  8580. }
  8581. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  8582. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8583. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8584. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8585. /* Prepare the environment block */
  8586. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8587. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8588. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8589. #if defined(USE_IPV6)
  8590. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8591. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8592. } else
  8593. #endif
  8594. {
  8595. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8596. }
  8597. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8598. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8599. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8600. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8601. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8602. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8603. /* SCRIPT_NAME */
  8604. uri_len = (int)strlen(conn->request_info.local_uri);
  8605. if (conn->path_info == NULL) {
  8606. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8607. /* URI: /path_to_script/script.cgi */
  8608. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8609. } else {
  8610. /* URI: /path_to_script/ ... using index.cgi */
  8611. const char *index_file = strrchr(prog, '/');
  8612. if (index_file) {
  8613. addenv(env,
  8614. "SCRIPT_NAME=%s%s",
  8615. conn->request_info.local_uri,
  8616. index_file + 1);
  8617. }
  8618. }
  8619. } else {
  8620. /* URI: /path_to_script/script.cgi/path_info */
  8621. addenv(env,
  8622. "SCRIPT_NAME=%.*s",
  8623. uri_len - (int)strlen(conn->path_info),
  8624. conn->request_info.local_uri);
  8625. }
  8626. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8627. if (conn->path_info == NULL) {
  8628. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8629. } else {
  8630. addenv(env,
  8631. "PATH_TRANSLATED=%s%s",
  8632. conn->dom_ctx->config[DOCUMENT_ROOT],
  8633. conn->path_info);
  8634. }
  8635. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8636. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8637. addenv(env, "CONTENT_TYPE=%s", s);
  8638. }
  8639. if (conn->request_info.query_string != NULL) {
  8640. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8641. }
  8642. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8643. addenv(env, "CONTENT_LENGTH=%s", s);
  8644. }
  8645. if ((s = getenv("PATH")) != NULL) {
  8646. addenv(env, "PATH=%s", s);
  8647. }
  8648. if (conn->path_info != NULL) {
  8649. addenv(env, "PATH_INFO=%s", conn->path_info);
  8650. }
  8651. if (conn->status_code > 0) {
  8652. /* CGI error handler should show the status code */
  8653. addenv(env, "STATUS=%d", conn->status_code);
  8654. }
  8655. #if defined(_WIN32)
  8656. if ((s = getenv("COMSPEC")) != NULL) {
  8657. addenv(env, "COMSPEC=%s", s);
  8658. }
  8659. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8660. addenv(env, "SYSTEMROOT=%s", s);
  8661. }
  8662. if ((s = getenv("SystemDrive")) != NULL) {
  8663. addenv(env, "SystemDrive=%s", s);
  8664. }
  8665. if ((s = getenv("ProgramFiles")) != NULL) {
  8666. addenv(env, "ProgramFiles=%s", s);
  8667. }
  8668. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8669. addenv(env, "ProgramFiles(x86)=%s", s);
  8670. }
  8671. #else
  8672. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8673. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8674. }
  8675. #endif /* _WIN32 */
  8676. if ((s = getenv("PERLLIB")) != NULL) {
  8677. addenv(env, "PERLLIB=%s", s);
  8678. }
  8679. if (conn->request_info.remote_user != NULL) {
  8680. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8681. addenv(env, "%s", "AUTH_TYPE=Digest");
  8682. }
  8683. /* Add all headers as HTTP_* variables */
  8684. for (i = 0; i < conn->request_info.num_headers; i++) {
  8685. (void)mg_snprintf(conn,
  8686. &truncated,
  8687. http_var_name,
  8688. sizeof(http_var_name),
  8689. "HTTP_%s",
  8690. conn->request_info.http_headers[i].name);
  8691. if (truncated) {
  8692. mg_cry(conn,
  8693. "%s: HTTP header variable too long [%s]",
  8694. __func__,
  8695. conn->request_info.http_headers[i].name);
  8696. continue;
  8697. }
  8698. /* Convert variable name into uppercase, and change - to _ */
  8699. for (p = http_var_name; *p != '\0'; p++) {
  8700. if (*p == '-') {
  8701. *p = '_';
  8702. }
  8703. *p = (char)toupper(*(unsigned char *)p);
  8704. }
  8705. addenv(env,
  8706. "%s=%s",
  8707. http_var_name,
  8708. conn->request_info.http_headers[i].value);
  8709. }
  8710. /* Add user-specified variables */
  8711. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  8712. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8713. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8714. }
  8715. env->var[env->varused] = NULL;
  8716. env->buf[env->bufused] = '\0';
  8717. return 0;
  8718. }
  8719. static void
  8720. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8721. {
  8722. char *buf;
  8723. size_t buflen;
  8724. int headers_len, data_len, i, truncated;
  8725. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8726. const char *status, *status_text, *connection_state;
  8727. char *pbuf, dir[PATH_MAX], *p;
  8728. struct mg_request_info ri;
  8729. struct cgi_environment blk;
  8730. FILE *in = NULL, *out = NULL, *err = NULL;
  8731. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8732. pid_t pid = (pid_t)-1;
  8733. if (conn == NULL) {
  8734. return;
  8735. }
  8736. buf = NULL;
  8737. buflen = 16384;
  8738. i = prepare_cgi_environment(conn, prog, &blk);
  8739. if (i != 0) {
  8740. blk.buf = NULL;
  8741. blk.var = NULL;
  8742. goto done;
  8743. }
  8744. /* CGI must be executed in its own directory. 'dir' must point to the
  8745. * directory containing executable program, 'p' must point to the
  8746. * executable program name relative to 'dir'. */
  8747. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8748. if (truncated) {
  8749. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  8750. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8751. goto done;
  8752. }
  8753. if ((p = strrchr(dir, '/')) != NULL) {
  8754. *p++ = '\0';
  8755. } else {
  8756. dir[0] = '.';
  8757. dir[1] = '\0';
  8758. p = (char *)prog;
  8759. }
  8760. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8761. status = strerror(ERRNO);
  8762. mg_cry(conn,
  8763. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8764. prog,
  8765. status);
  8766. mg_send_http_error(conn,
  8767. 500,
  8768. "Error: Cannot create CGI pipe: %s",
  8769. status);
  8770. goto done;
  8771. }
  8772. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  8773. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8774. if (pid == (pid_t)-1) {
  8775. status = strerror(ERRNO);
  8776. mg_cry(conn,
  8777. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8778. prog,
  8779. status);
  8780. mg_send_http_error(conn,
  8781. 500,
  8782. "Error: Cannot spawn CGI process [%s]: %s",
  8783. prog,
  8784. status);
  8785. goto done;
  8786. }
  8787. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  8788. */
  8789. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8790. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8791. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8792. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8793. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8794. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8795. /* Parent closes only one side of the pipes.
  8796. * If we don't mark them as closed, close() attempt before
  8797. * return from this function throws an exception on Windows.
  8798. * Windows does not like when closed descriptor is closed again. */
  8799. (void)close(fdin[0]);
  8800. (void)close(fdout[1]);
  8801. (void)close(fderr[1]);
  8802. fdin[0] = fdout[1] = fderr[1] = -1;
  8803. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8804. status = strerror(ERRNO);
  8805. mg_cry(conn,
  8806. "Error: CGI program \"%s\": Can not open stdin: %s",
  8807. prog,
  8808. status);
  8809. mg_send_http_error(conn,
  8810. 500,
  8811. "Error: CGI can not open fdin\nfopen: %s",
  8812. status);
  8813. goto done;
  8814. }
  8815. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8816. status = strerror(ERRNO);
  8817. mg_cry(conn,
  8818. "Error: CGI program \"%s\": Can not open stdout: %s",
  8819. prog,
  8820. status);
  8821. mg_send_http_error(conn,
  8822. 500,
  8823. "Error: CGI can not open fdout\nfopen: %s",
  8824. status);
  8825. goto done;
  8826. }
  8827. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8828. status = strerror(ERRNO);
  8829. mg_cry(conn,
  8830. "Error: CGI program \"%s\": Can not open stderr: %s",
  8831. prog,
  8832. status);
  8833. mg_send_http_error(conn,
  8834. 500,
  8835. "Error: CGI can not open fdout\nfopen: %s",
  8836. status);
  8837. goto done;
  8838. }
  8839. setbuf(in, NULL);
  8840. setbuf(out, NULL);
  8841. setbuf(err, NULL);
  8842. fout.access.fp = out;
  8843. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  8844. DEBUG_TRACE("CGI: send body data (%lli)\n",
  8845. (signed long long)conn->request_info.content_length);
  8846. /* This is a POST/PUT request, or another request with body data. */
  8847. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8848. /* Error sending the body data */
  8849. mg_cry(conn,
  8850. "Error: CGI program \"%s\": Forward body data failed",
  8851. prog);
  8852. goto done;
  8853. }
  8854. }
  8855. /* Close so child gets an EOF. */
  8856. fclose(in);
  8857. in = NULL;
  8858. fdin[1] = -1;
  8859. /* Now read CGI reply into a buffer. We need to set correct
  8860. * status code, thus we need to see all HTTP headers first.
  8861. * Do not send anything back to client, until we buffer in all
  8862. * HTTP headers. */
  8863. data_len = 0;
  8864. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  8865. if (buf == NULL) {
  8866. mg_send_http_error(conn,
  8867. 500,
  8868. "Error: Not enough memory for CGI buffer (%u bytes)",
  8869. (unsigned int)buflen);
  8870. mg_cry(conn,
  8871. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  8872. "bytes)",
  8873. prog,
  8874. (unsigned int)buflen);
  8875. goto done;
  8876. }
  8877. DEBUG_TRACE("CGI: %s", "wait for response");
  8878. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  8879. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  8880. if (headers_len <= 0) {
  8881. /* Could not parse the CGI response. Check if some error message on
  8882. * stderr. */
  8883. i = pull_all(err, conn, buf, (int)buflen);
  8884. if (i > 0) {
  8885. mg_cry(conn,
  8886. "Error: CGI program \"%s\" sent error "
  8887. "message: [%.*s]",
  8888. prog,
  8889. i,
  8890. buf);
  8891. mg_send_http_error(conn,
  8892. 500,
  8893. "Error: CGI program \"%s\" sent error "
  8894. "message: [%.*s]",
  8895. prog,
  8896. i,
  8897. buf);
  8898. } else {
  8899. mg_cry(conn,
  8900. "Error: CGI program sent malformed or too big "
  8901. "(>%u bytes) HTTP headers: [%.*s]",
  8902. (unsigned)buflen,
  8903. data_len,
  8904. buf);
  8905. mg_send_http_error(conn,
  8906. 500,
  8907. "Error: CGI program sent malformed or too big "
  8908. "(>%u bytes) HTTP headers: [%.*s]",
  8909. (unsigned)buflen,
  8910. data_len,
  8911. buf);
  8912. }
  8913. goto done;
  8914. }
  8915. pbuf = buf;
  8916. buf[headers_len - 1] = '\0';
  8917. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  8918. /* Make up and send the status line */
  8919. status_text = "OK";
  8920. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  8921. != NULL) {
  8922. conn->status_code = atoi(status);
  8923. status_text = status;
  8924. while (isdigit(*(const unsigned char *)status_text)
  8925. || *status_text == ' ') {
  8926. status_text++;
  8927. }
  8928. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  8929. != NULL) {
  8930. conn->status_code = 302;
  8931. } else {
  8932. conn->status_code = 200;
  8933. }
  8934. connection_state =
  8935. get_header(ri.http_headers, ri.num_headers, "Connection");
  8936. if (!header_has_option(connection_state, "keep-alive")) {
  8937. conn->must_close = 1;
  8938. }
  8939. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  8940. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  8941. /* Send headers */
  8942. for (i = 0; i < ri.num_headers; i++) {
  8943. mg_printf(conn,
  8944. "%s: %s\r\n",
  8945. ri.http_headers[i].name,
  8946. ri.http_headers[i].value);
  8947. }
  8948. mg_write(conn, "\r\n", 2);
  8949. /* Send chunk of data that may have been read after the headers */
  8950. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  8951. /* Read the rest of CGI output and send to the client */
  8952. send_file_data(conn, &fout, 0, INT64_MAX);
  8953. DEBUG_TRACE("CGI: %s", "all data sent");
  8954. done:
  8955. mg_free(blk.var);
  8956. mg_free(blk.buf);
  8957. if (pid != (pid_t)-1) {
  8958. kill(pid, SIGKILL);
  8959. #if !defined(_WIN32)
  8960. {
  8961. int st;
  8962. while (waitpid(pid, &st, 0) != -1)
  8963. ; /* clean zombies */
  8964. }
  8965. #endif
  8966. }
  8967. if (fdin[0] != -1) {
  8968. close(fdin[0]);
  8969. }
  8970. if (fdout[1] != -1) {
  8971. close(fdout[1]);
  8972. }
  8973. if (in != NULL) {
  8974. fclose(in);
  8975. } else if (fdin[1] != -1) {
  8976. close(fdin[1]);
  8977. }
  8978. if (out != NULL) {
  8979. fclose(out);
  8980. } else if (fdout[0] != -1) {
  8981. close(fdout[0]);
  8982. }
  8983. if (err != NULL) {
  8984. fclose(err);
  8985. } else if (fderr[0] != -1) {
  8986. close(fderr[0]);
  8987. }
  8988. if (buf != NULL) {
  8989. mg_free(buf);
  8990. }
  8991. }
  8992. #endif /* !NO_CGI */
  8993. #if !defined(NO_FILES)
  8994. static void
  8995. mkcol(struct mg_connection *conn, const char *path)
  8996. {
  8997. int rc, body_len;
  8998. struct de de;
  8999. char date[64];
  9000. time_t curtime = time(NULL);
  9001. if (conn == NULL) {
  9002. return;
  9003. }
  9004. /* TODO (mid): Check the mg_send_http_error situations in this function
  9005. */
  9006. memset(&de.file, 0, sizeof(de.file));
  9007. if (!mg_stat(conn, path, &de.file)) {
  9008. mg_cry(conn,
  9009. "%s: mg_stat(%s) failed: %s",
  9010. __func__,
  9011. path,
  9012. strerror(ERRNO));
  9013. }
  9014. if (de.file.last_modified) {
  9015. /* TODO (mid): This check does not seem to make any sense ! */
  9016. /* TODO (mid): Add a webdav unit test first, before changing
  9017. * anything here. */
  9018. mg_send_http_error(
  9019. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9020. return;
  9021. }
  9022. body_len = conn->data_len - conn->request_len;
  9023. if (body_len > 0) {
  9024. mg_send_http_error(
  9025. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9026. return;
  9027. }
  9028. rc = mg_mkdir(conn, path, 0755);
  9029. if (rc == 0) {
  9030. conn->status_code = 201;
  9031. gmt_time_string(date, sizeof(date), &curtime);
  9032. mg_printf(conn,
  9033. "HTTP/1.1 %d Created\r\n"
  9034. "Date: %s\r\n",
  9035. conn->status_code,
  9036. date);
  9037. send_static_cache_header(conn);
  9038. send_additional_header(conn);
  9039. mg_printf(conn,
  9040. "Content-Length: 0\r\n"
  9041. "Connection: %s\r\n\r\n",
  9042. suggest_connection_header(conn));
  9043. } else if (rc == -1) {
  9044. if (errno == EEXIST) {
  9045. mg_send_http_error(
  9046. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9047. } else if (errno == EACCES) {
  9048. mg_send_http_error(
  9049. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9050. } else if (errno == ENOENT) {
  9051. mg_send_http_error(
  9052. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9053. } else {
  9054. mg_send_http_error(
  9055. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9056. }
  9057. }
  9058. }
  9059. static void
  9060. put_file(struct mg_connection *conn, const char *path)
  9061. {
  9062. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9063. const char *range;
  9064. int64_t r1, r2;
  9065. int rc;
  9066. char date[64];
  9067. time_t curtime = time(NULL);
  9068. if (conn == NULL) {
  9069. return;
  9070. }
  9071. if (mg_stat(conn, path, &file.stat)) {
  9072. /* File already exists */
  9073. conn->status_code = 200;
  9074. if (file.stat.is_directory) {
  9075. /* This is an already existing directory,
  9076. * so there is nothing to do for the server. */
  9077. rc = 0;
  9078. } else {
  9079. /* File exists and is not a directory. */
  9080. /* Can it be replaced? */
  9081. if (file.access.membuf != NULL) {
  9082. /* This is an "in-memory" file, that can not be replaced */
  9083. mg_send_http_error(conn,
  9084. 405,
  9085. "Error: Put not possible\nReplacing %s "
  9086. "is not supported",
  9087. path);
  9088. return;
  9089. }
  9090. /* Check if the server may write this file */
  9091. if (access(path, W_OK) == 0) {
  9092. /* Access granted */
  9093. conn->status_code = 200;
  9094. rc = 1;
  9095. } else {
  9096. mg_send_http_error(
  9097. conn,
  9098. 403,
  9099. "Error: Put not possible\nReplacing %s is not allowed",
  9100. path);
  9101. return;
  9102. }
  9103. }
  9104. } else {
  9105. /* File should be created */
  9106. conn->status_code = 201;
  9107. rc = put_dir(conn, path);
  9108. }
  9109. if (rc == 0) {
  9110. /* put_dir returns 0 if path is a directory */
  9111. gmt_time_string(date, sizeof(date), &curtime);
  9112. mg_printf(conn,
  9113. "HTTP/1.1 %d %s\r\n",
  9114. conn->status_code,
  9115. mg_get_response_code_text(NULL, conn->status_code));
  9116. send_no_cache_header(conn);
  9117. send_additional_header(conn);
  9118. mg_printf(conn,
  9119. "Date: %s\r\n"
  9120. "Content-Length: 0\r\n"
  9121. "Connection: %s\r\n\r\n",
  9122. date,
  9123. suggest_connection_header(conn));
  9124. /* Request to create a directory has been fulfilled successfully.
  9125. * No need to put a file. */
  9126. return;
  9127. }
  9128. if (rc == -1) {
  9129. /* put_dir returns -1 if the path is too long */
  9130. mg_send_http_error(conn,
  9131. 414,
  9132. "Error: Path too long\nput_dir(%s): %s",
  9133. path,
  9134. strerror(ERRNO));
  9135. return;
  9136. }
  9137. if (rc == -2) {
  9138. /* put_dir returns -2 if the directory can not be created */
  9139. mg_send_http_error(conn,
  9140. 500,
  9141. "Error: Can not create directory\nput_dir(%s): %s",
  9142. path,
  9143. strerror(ERRNO));
  9144. return;
  9145. }
  9146. /* A file should be created or overwritten. */
  9147. /* Currently CivetWeb does not nead read+write access. */
  9148. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9149. || file.access.fp == NULL) {
  9150. (void)mg_fclose(&file.access);
  9151. mg_send_http_error(conn,
  9152. 500,
  9153. "Error: Can not create file\nfopen(%s): %s",
  9154. path,
  9155. strerror(ERRNO));
  9156. return;
  9157. }
  9158. fclose_on_exec(&file.access, conn);
  9159. range = mg_get_header(conn, "Content-Range");
  9160. r1 = r2 = 0;
  9161. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9162. conn->status_code = 206; /* Partial content */
  9163. fseeko(file.access.fp, r1, SEEK_SET);
  9164. }
  9165. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9166. /* forward_body_data failed.
  9167. * The error code has already been sent to the client,
  9168. * and conn->status_code is already set. */
  9169. (void)mg_fclose(&file.access);
  9170. return;
  9171. }
  9172. if (mg_fclose(&file.access) != 0) {
  9173. /* fclose failed. This might have different reasons, but a likely
  9174. * one is "no space on disk", http 507. */
  9175. conn->status_code = 507;
  9176. }
  9177. gmt_time_string(date, sizeof(date), &curtime);
  9178. mg_printf(conn,
  9179. "HTTP/1.1 %d %s\r\n",
  9180. conn->status_code,
  9181. mg_get_response_code_text(NULL, conn->status_code));
  9182. send_no_cache_header(conn);
  9183. send_additional_header(conn);
  9184. mg_printf(conn,
  9185. "Date: %s\r\n"
  9186. "Content-Length: 0\r\n"
  9187. "Connection: %s\r\n\r\n",
  9188. date,
  9189. suggest_connection_header(conn));
  9190. }
  9191. static void
  9192. delete_file(struct mg_connection *conn, const char *path)
  9193. {
  9194. struct de de;
  9195. memset(&de.file, 0, sizeof(de.file));
  9196. if (!mg_stat(conn, path, &de.file)) {
  9197. /* mg_stat returns 0 if the file does not exist */
  9198. mg_send_http_error(conn,
  9199. 404,
  9200. "Error: Cannot delete file\nFile %s not found",
  9201. path);
  9202. return;
  9203. }
  9204. #if 0 /* Ignore if a file in memory is inside a folder */
  9205. if (de.access.membuf != NULL) {
  9206. /* the file is cached in memory */
  9207. mg_send_http_error(
  9208. conn,
  9209. 405,
  9210. "Error: Delete not possible\nDeleting %s is not supported",
  9211. path);
  9212. return;
  9213. }
  9214. #endif
  9215. if (de.file.is_directory) {
  9216. if (remove_directory(conn, path)) {
  9217. /* Delete is successful: Return 204 without content. */
  9218. mg_send_http_error(conn, 204, "%s", "");
  9219. } else {
  9220. /* Delete is not successful: Return 500 (Server error). */
  9221. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9222. }
  9223. return;
  9224. }
  9225. /* This is an existing file (not a directory).
  9226. * Check if write permission is granted. */
  9227. if (access(path, W_OK) != 0) {
  9228. /* File is read only */
  9229. mg_send_http_error(
  9230. conn,
  9231. 403,
  9232. "Error: Delete not possible\nDeleting %s is not allowed",
  9233. path);
  9234. return;
  9235. }
  9236. /* Try to delete it. */
  9237. if (mg_remove(conn, path) == 0) {
  9238. /* Delete was successful: Return 204 without content. */
  9239. mg_send_http_error(conn, 204, "%s", "");
  9240. } else {
  9241. /* Delete not successful (file locked). */
  9242. mg_send_http_error(conn,
  9243. 423,
  9244. "Error: Cannot delete file\nremove(%s): %s",
  9245. path,
  9246. strerror(ERRNO));
  9247. }
  9248. }
  9249. #endif /* !NO_FILES */
  9250. static void
  9251. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9252. static void
  9253. do_ssi_include(struct mg_connection *conn,
  9254. const char *ssi,
  9255. char *tag,
  9256. int include_level)
  9257. {
  9258. char file_name[MG_BUF_LEN], path[512], *p;
  9259. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9260. size_t len;
  9261. int truncated = 0;
  9262. if (conn == NULL) {
  9263. return;
  9264. }
  9265. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9266. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9267. * always < MG_BUF_LEN. */
  9268. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9269. /* File name is relative to the webserver root */
  9270. file_name[511] = 0;
  9271. (void)mg_snprintf(conn,
  9272. &truncated,
  9273. path,
  9274. sizeof(path),
  9275. "%s/%s",
  9276. conn->dom_ctx->config[DOCUMENT_ROOT],
  9277. file_name);
  9278. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9279. /* File name is relative to the webserver working directory
  9280. * or it is absolute system path */
  9281. file_name[511] = 0;
  9282. (void)
  9283. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9284. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9285. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9286. /* File name is relative to the currect document */
  9287. file_name[511] = 0;
  9288. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9289. if (!truncated) {
  9290. if ((p = strrchr(path, '/')) != NULL) {
  9291. p[1] = '\0';
  9292. }
  9293. len = strlen(path);
  9294. (void)mg_snprintf(conn,
  9295. &truncated,
  9296. path + len,
  9297. sizeof(path) - len,
  9298. "%s",
  9299. file_name);
  9300. }
  9301. } else {
  9302. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  9303. return;
  9304. }
  9305. if (truncated) {
  9306. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  9307. return;
  9308. }
  9309. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9310. mg_cry(conn,
  9311. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9312. tag,
  9313. path,
  9314. strerror(ERRNO));
  9315. } else {
  9316. fclose_on_exec(&file.access, conn);
  9317. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9318. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9319. path) > 0) {
  9320. send_ssi_file(conn, path, &file, include_level + 1);
  9321. } else {
  9322. send_file_data(conn, &file, 0, INT64_MAX);
  9323. }
  9324. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9325. }
  9326. }
  9327. #if !defined(NO_POPEN)
  9328. static void
  9329. do_ssi_exec(struct mg_connection *conn, char *tag)
  9330. {
  9331. char cmd[1024] = "";
  9332. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9333. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9334. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  9335. } else {
  9336. cmd[1023] = 0;
  9337. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9338. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  9339. } else {
  9340. send_file_data(conn, &file, 0, INT64_MAX);
  9341. pclose(file.access.fp);
  9342. }
  9343. }
  9344. }
  9345. #endif /* !NO_POPEN */
  9346. static int
  9347. mg_fgetc(struct mg_file *filep, int offset)
  9348. {
  9349. if (filep == NULL) {
  9350. return EOF;
  9351. }
  9352. if ((filep->access.membuf != NULL) && (offset >= 0)
  9353. && (((unsigned int)(offset)) < filep->stat.size)) {
  9354. return ((const unsigned char *)filep->access.membuf)[offset];
  9355. } else if (filep->access.fp != NULL) {
  9356. return fgetc(filep->access.fp);
  9357. } else {
  9358. return EOF;
  9359. }
  9360. }
  9361. static void
  9362. send_ssi_file(struct mg_connection *conn,
  9363. const char *path,
  9364. struct mg_file *filep,
  9365. int include_level)
  9366. {
  9367. char buf[MG_BUF_LEN];
  9368. int ch, offset, len, in_tag, in_ssi_tag;
  9369. if (include_level > 10) {
  9370. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  9371. return;
  9372. }
  9373. in_tag = in_ssi_tag = len = offset = 0;
  9374. /* Read file, byte by byte, and look for SSI include tags */
  9375. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9376. if (in_tag) {
  9377. /* We are in a tag, either SSI tag or html tag */
  9378. if (ch == '>') {
  9379. /* Tag is closing */
  9380. buf[len++] = '>';
  9381. if (in_ssi_tag) {
  9382. /* Handle SSI tag */
  9383. buf[len] = 0;
  9384. if (!memcmp(buf + 5, "include", 7)) {
  9385. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9386. #if !defined(NO_POPEN)
  9387. } else if (!memcmp(buf + 5, "exec", 4)) {
  9388. do_ssi_exec(conn, buf + 9);
  9389. #endif /* !NO_POPEN */
  9390. } else {
  9391. mg_cry(conn,
  9392. "%s: unknown SSI "
  9393. "command: \"%s\"",
  9394. path,
  9395. buf);
  9396. }
  9397. len = 0;
  9398. in_ssi_tag = in_tag = 0;
  9399. } else {
  9400. /* Not an SSI tag */
  9401. /* Flush buffer */
  9402. (void)mg_write(conn, buf, (size_t)len);
  9403. len = 0;
  9404. in_tag = 0;
  9405. }
  9406. } else {
  9407. /* Tag is still open */
  9408. buf[len++] = (char)(ch & 0xff);
  9409. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9410. /* All SSI tags start with <!--# */
  9411. in_ssi_tag = 1;
  9412. }
  9413. if ((len + 2) > (int)sizeof(buf)) {
  9414. /* Tag to long for buffer */
  9415. mg_cry(conn, "%s: tag is too large", path);
  9416. return;
  9417. }
  9418. }
  9419. } else {
  9420. /* We are not in a tag yet. */
  9421. if (ch == '<') {
  9422. /* Tag is opening */
  9423. in_tag = 1;
  9424. /* Flush current buffer */
  9425. (void)mg_write(conn, buf, (size_t)len);
  9426. /* Store the < */
  9427. len = 1;
  9428. buf[0] = '<';
  9429. } else {
  9430. /* No Tag */
  9431. /* Add data to buffer */
  9432. buf[len++] = (char)(ch & 0xff);
  9433. /* Flush if buffer is full */
  9434. if (len == (int)sizeof(buf)) {
  9435. mg_write(conn, buf, (size_t)len);
  9436. len = 0;
  9437. }
  9438. }
  9439. }
  9440. }
  9441. /* Send the rest of buffered data */
  9442. if (len > 0) {
  9443. mg_write(conn, buf, (size_t)len);
  9444. }
  9445. }
  9446. static void
  9447. handle_ssi_file_request(struct mg_connection *conn,
  9448. const char *path,
  9449. struct mg_file *filep)
  9450. {
  9451. char date[64];
  9452. time_t curtime = time(NULL);
  9453. const char *cors1, *cors2, *cors3;
  9454. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9455. return;
  9456. }
  9457. if (mg_get_header(conn, "Origin")) {
  9458. /* Cross-origin resource sharing (CORS). */
  9459. cors1 = "Access-Control-Allow-Origin: ";
  9460. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9461. cors3 = "\r\n";
  9462. } else {
  9463. cors1 = cors2 = cors3 = "";
  9464. }
  9465. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9466. /* File exists (precondition for calling this function),
  9467. * but can not be opened by the server. */
  9468. mg_send_http_error(conn,
  9469. 500,
  9470. "Error: Cannot read file\nfopen(%s): %s",
  9471. path,
  9472. strerror(ERRNO));
  9473. } else {
  9474. conn->must_close = 1;
  9475. gmt_time_string(date, sizeof(date), &curtime);
  9476. fclose_on_exec(&filep->access, conn);
  9477. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9478. send_no_cache_header(conn);
  9479. send_additional_header(conn);
  9480. mg_printf(conn,
  9481. "%s%s%s"
  9482. "Date: %s\r\n"
  9483. "Content-Type: text/html\r\n"
  9484. "Connection: %s\r\n\r\n",
  9485. cors1,
  9486. cors2,
  9487. cors3,
  9488. date,
  9489. suggest_connection_header(conn));
  9490. send_ssi_file(conn, path, filep, 0);
  9491. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9492. }
  9493. }
  9494. #if !defined(NO_FILES)
  9495. static void
  9496. send_options(struct mg_connection *conn)
  9497. {
  9498. char date[64];
  9499. time_t curtime = time(NULL);
  9500. if (!conn) {
  9501. return;
  9502. }
  9503. conn->status_code = 200;
  9504. conn->must_close = 1;
  9505. gmt_time_string(date, sizeof(date), &curtime);
  9506. /* We do not set a "Cache-Control" header here, but leave the default.
  9507. * Since browsers do not send an OPTIONS request, we can not test the
  9508. * effect anyway. */
  9509. mg_printf(conn,
  9510. "HTTP/1.1 200 OK\r\n"
  9511. "Date: %s\r\n"
  9512. "Connection: %s\r\n"
  9513. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9514. "PROPFIND, MKCOL\r\n"
  9515. "DAV: 1\r\n",
  9516. date,
  9517. suggest_connection_header(conn));
  9518. send_additional_header(conn);
  9519. mg_printf(conn, "\r\n");
  9520. }
  9521. /* Writes PROPFIND properties for a collection element */
  9522. static void
  9523. print_props(struct mg_connection *conn,
  9524. const char *uri,
  9525. struct mg_file_stat *filep)
  9526. {
  9527. char mtime[64];
  9528. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9529. return;
  9530. }
  9531. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9532. mg_printf(conn,
  9533. "<d:response>"
  9534. "<d:href>%s</d:href>"
  9535. "<d:propstat>"
  9536. "<d:prop>"
  9537. "<d:resourcetype>%s</d:resourcetype>"
  9538. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9539. "<d:getlastmodified>%s</d:getlastmodified>"
  9540. "</d:prop>"
  9541. "<d:status>HTTP/1.1 200 OK</d:status>"
  9542. "</d:propstat>"
  9543. "</d:response>\n",
  9544. uri,
  9545. filep->is_directory ? "<d:collection/>" : "",
  9546. filep->size,
  9547. mtime);
  9548. }
  9549. static int
  9550. print_dav_dir_entry(struct de *de, void *data)
  9551. {
  9552. char href[PATH_MAX];
  9553. int truncated;
  9554. struct mg_connection *conn = (struct mg_connection *)data;
  9555. if (!de || !conn) {
  9556. return -1;
  9557. }
  9558. mg_snprintf(conn,
  9559. &truncated,
  9560. href,
  9561. sizeof(href),
  9562. "%s%s",
  9563. conn->request_info.local_uri,
  9564. de->file_name);
  9565. if (!truncated) {
  9566. size_t href_encoded_size;
  9567. char *href_encoded;
  9568. href_encoded_size = PATH_MAX * 3; /* worst case */
  9569. href_encoded = (char *)mg_malloc(href_encoded_size);
  9570. if (href_encoded == NULL) {
  9571. return -1;
  9572. }
  9573. mg_url_encode(href, href_encoded, href_encoded_size);
  9574. print_props(conn, href_encoded, &de->file);
  9575. mg_free(href_encoded);
  9576. }
  9577. return 0;
  9578. }
  9579. static void
  9580. handle_propfind(struct mg_connection *conn,
  9581. const char *path,
  9582. struct mg_file_stat *filep)
  9583. {
  9584. const char *depth = mg_get_header(conn, "Depth");
  9585. char date[64];
  9586. time_t curtime = time(NULL);
  9587. gmt_time_string(date, sizeof(date), &curtime);
  9588. if (!conn || !path || !filep || !conn->dom_ctx) {
  9589. return;
  9590. }
  9591. conn->must_close = 1;
  9592. conn->status_code = 207;
  9593. mg_printf(conn,
  9594. "HTTP/1.1 207 Multi-Status\r\n"
  9595. "Date: %s\r\n",
  9596. date);
  9597. send_static_cache_header(conn);
  9598. send_additional_header(conn);
  9599. mg_printf(conn,
  9600. "Connection: %s\r\n"
  9601. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9602. suggest_connection_header(conn));
  9603. mg_printf(conn,
  9604. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9605. "<d:multistatus xmlns:d='DAV:'>\n");
  9606. /* Print properties for the requested resource itself */
  9607. print_props(conn, conn->request_info.local_uri, filep);
  9608. /* If it is a directory, print directory entries too if Depth is not 0
  9609. */
  9610. if (filep && filep->is_directory
  9611. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9612. "yes")
  9613. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9614. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9615. }
  9616. mg_printf(conn, "%s\n", "</d:multistatus>");
  9617. }
  9618. #endif
  9619. void
  9620. mg_lock_connection(struct mg_connection *conn)
  9621. {
  9622. if (conn) {
  9623. (void)pthread_mutex_lock(&conn->mutex);
  9624. }
  9625. }
  9626. void
  9627. mg_unlock_connection(struct mg_connection *conn)
  9628. {
  9629. if (conn) {
  9630. (void)pthread_mutex_unlock(&conn->mutex);
  9631. }
  9632. }
  9633. void
  9634. mg_lock_context(struct mg_context *ctx)
  9635. {
  9636. if (ctx) {
  9637. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9638. }
  9639. }
  9640. void
  9641. mg_unlock_context(struct mg_context *ctx)
  9642. {
  9643. if (ctx) {
  9644. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9645. }
  9646. }
  9647. #if defined(USE_TIMERS)
  9648. #define TIMER_API static
  9649. #include "timer.inl"
  9650. #endif /* USE_TIMERS */
  9651. #ifdef USE_LUA
  9652. #include "mod_lua.inl"
  9653. #endif /* USE_LUA */
  9654. #ifdef USE_DUKTAPE
  9655. #include "mod_duktape.inl"
  9656. #endif /* USE_DUKTAPE */
  9657. #if defined(USE_WEBSOCKET)
  9658. #if !defined(NO_SSL_DL)
  9659. #define SHA_API static
  9660. #include "sha1.inl"
  9661. #endif
  9662. static int
  9663. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9664. {
  9665. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9666. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9667. SHA_CTX sha_ctx;
  9668. int truncated;
  9669. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9670. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9671. if (truncated) {
  9672. conn->must_close = 1;
  9673. return 0;
  9674. }
  9675. SHA1_Init(&sha_ctx);
  9676. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9677. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9678. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9679. mg_printf(conn,
  9680. "HTTP/1.1 101 Switching Protocols\r\n"
  9681. "Upgrade: websocket\r\n"
  9682. "Connection: Upgrade\r\n"
  9683. "Sec-WebSocket-Accept: %s\r\n",
  9684. b64_sha);
  9685. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9686. mg_printf(conn,
  9687. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9688. conn->request_info.acceptedWebSocketSubprotocol);
  9689. } else {
  9690. mg_printf(conn, "%s", "\r\n");
  9691. }
  9692. return 1;
  9693. }
  9694. static void
  9695. read_websocket(struct mg_connection *conn,
  9696. mg_websocket_data_handler ws_data_handler,
  9697. void *callback_data)
  9698. {
  9699. /* Pointer to the beginning of the portion of the incoming websocket
  9700. * message queue.
  9701. * The original websocket upgrade request is never removed, so the queue
  9702. * begins after it. */
  9703. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9704. int n, error, exit_by_callback;
  9705. /* body_len is the length of the entire queue in bytes
  9706. * len is the length of the current message
  9707. * data_len is the length of the current message's data payload
  9708. * header_len is the length of the current message's header */
  9709. size_t i, len, mask_len = 0, header_len, body_len;
  9710. uint64_t data_len = 0;
  9711. /* "The masking key is a 32-bit value chosen at random by the client."
  9712. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9713. */
  9714. unsigned char mask[4];
  9715. /* data points to the place where the message is stored when passed to
  9716. * the
  9717. * websocket_data callback. This is either mem on the stack, or a
  9718. * dynamically allocated buffer if it is too large. */
  9719. unsigned char mem[4096];
  9720. unsigned char mop; /* mask flag and opcode */
  9721. double timeout = -1.0;
  9722. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  9723. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9724. }
  9725. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  9726. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9727. }
  9728. conn->in_websocket_handling = 1;
  9729. mg_set_thread_name("wsock");
  9730. /* Loop continuously, reading messages from the socket, invoking the
  9731. * callback, and waiting repeatedly until an error occurs. */
  9732. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  9733. header_len = 0;
  9734. assert(conn->data_len >= conn->request_len);
  9735. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9736. len = buf[1] & 127;
  9737. mask_len = (buf[1] & 128) ? 4 : 0;
  9738. if ((len < 126) && (body_len >= mask_len)) {
  9739. /* inline 7-bit length field */
  9740. data_len = len;
  9741. header_len = 2 + mask_len;
  9742. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9743. /* 16-bit length field */
  9744. header_len = 4 + mask_len;
  9745. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9746. } else if (body_len >= (10 + mask_len)) {
  9747. /* 64-bit length field */
  9748. uint32_t l1, l2;
  9749. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9750. memcpy(&l2, &buf[6], 4);
  9751. header_len = 10 + mask_len;
  9752. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9753. if (data_len > (uint64_t)0x7FFF0000ul) {
  9754. /* no can do */
  9755. mg_cry(conn, "websocket out of memory; closing connection");
  9756. break;
  9757. }
  9758. }
  9759. }
  9760. if ((header_len > 0) && (body_len >= header_len)) {
  9761. /* Allocate space to hold websocket payload */
  9762. unsigned char *data = mem;
  9763. if ((size_t)data_len > (size_t)sizeof(mem)) {
  9764. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  9765. conn->phys_ctx);
  9766. if (data == NULL) {
  9767. /* Allocation failed, exit the loop and then close the
  9768. * connection */
  9769. mg_cry(conn, "websocket out of memory; closing connection");
  9770. break;
  9771. }
  9772. }
  9773. /* Copy the mask before we shift the queue and destroy it */
  9774. if (mask_len > 0) {
  9775. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9776. } else {
  9777. memset(mask, 0, sizeof(mask));
  9778. }
  9779. /* Read frame payload from the first message in the queue into
  9780. * data and advance the queue by moving the memory in place. */
  9781. assert(body_len >= header_len);
  9782. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  9783. mop = buf[0]; /* current mask and opcode */
  9784. /* Overflow case */
  9785. len = body_len - header_len;
  9786. memcpy(data, buf + header_len, len);
  9787. error = 0;
  9788. while ((uint64_t)len < data_len) {
  9789. n = pull_inner(NULL,
  9790. conn,
  9791. (char *)(data + len),
  9792. (int)(data_len - len),
  9793. timeout);
  9794. if (n <= -2) {
  9795. error = 1;
  9796. break;
  9797. } else if (n > 0) {
  9798. len += (size_t)n;
  9799. } else {
  9800. /* Timeout: should retry */
  9801. /* TODO: retry condition */
  9802. }
  9803. }
  9804. if (error) {
  9805. mg_cry(conn, "Websocket pull failed; closing connection");
  9806. if (data != mem) {
  9807. mg_free(data);
  9808. }
  9809. break;
  9810. }
  9811. conn->data_len = conn->request_len;
  9812. } else {
  9813. mop = buf[0]; /* current mask and opcode, overwritten by
  9814. * memmove() */
  9815. /* Length of the message being read at the front of the
  9816. * queue. Cast to 31 bit is OK, since we limited
  9817. * data_len before. */
  9818. len = (size_t)data_len + header_len;
  9819. /* Copy the data payload into the data pointer for the
  9820. * callback. Cast to 31 bit is OK, since we
  9821. * limited data_len */
  9822. memcpy(data, buf + header_len, (size_t)data_len);
  9823. /* Move the queue forward len bytes */
  9824. memmove(buf, buf + len, body_len - len);
  9825. /* Mark the queue as advanced */
  9826. conn->data_len -= (int)len;
  9827. }
  9828. /* Apply mask if necessary */
  9829. if (mask_len > 0) {
  9830. for (i = 0; i < (size_t)data_len; i++) {
  9831. data[i] ^= mask[i & 3];
  9832. }
  9833. }
  9834. /* Exit the loop if callback signals to exit (server side),
  9835. * or "connection close" opcode received (client side). */
  9836. exit_by_callback = 0;
  9837. if ((ws_data_handler != NULL)
  9838. && !ws_data_handler(conn,
  9839. mop,
  9840. (char *)data,
  9841. (size_t)data_len,
  9842. callback_data)) {
  9843. exit_by_callback = 1;
  9844. }
  9845. if (data != mem) {
  9846. mg_free(data);
  9847. }
  9848. if (exit_by_callback
  9849. || ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9850. /* Opcode == 8, connection close */
  9851. break;
  9852. }
  9853. /* Not breaking the loop, process next websocket frame. */
  9854. } else {
  9855. /* Read from the socket into the next available location in the
  9856. * message queue. */
  9857. n = pull_inner(NULL,
  9858. conn,
  9859. conn->buf + conn->data_len,
  9860. conn->buf_size - conn->data_len,
  9861. timeout);
  9862. if (n <= -2) {
  9863. /* Error, no bytes read */
  9864. break;
  9865. }
  9866. if (n > 0) {
  9867. conn->data_len += n;
  9868. } else {
  9869. /* Timeout: should retry */
  9870. /* TODO: get timeout def */
  9871. }
  9872. }
  9873. }
  9874. mg_set_thread_name("worker");
  9875. conn->in_websocket_handling = 0;
  9876. }
  9877. static int
  9878. mg_websocket_write_exec(struct mg_connection *conn,
  9879. int opcode,
  9880. const char *data,
  9881. size_t dataLen,
  9882. uint32_t masking_key)
  9883. {
  9884. unsigned char header[14];
  9885. size_t headerLen = 1;
  9886. int retval = -1;
  9887. #if defined(__GNUC__) || defined(__MINGW32__)
  9888. /* Disable spurious conversion warning for GCC */
  9889. #pragma GCC diagnostic push
  9890. #pragma GCC diagnostic ignored "-Wconversion"
  9891. #endif
  9892. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  9893. #if defined(__GNUC__) || defined(__MINGW32__)
  9894. #pragma GCC diagnostic pop
  9895. #endif
  9896. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  9897. if (dataLen < 126) {
  9898. /* inline 7-bit length field */
  9899. header[1] = (unsigned char)dataLen;
  9900. headerLen = 2;
  9901. } else if (dataLen <= 0xFFFF) {
  9902. /* 16-bit length field */
  9903. uint16_t len = htons((uint16_t)dataLen);
  9904. header[1] = 126;
  9905. memcpy(header + 2, &len, 2);
  9906. headerLen = 4;
  9907. } else {
  9908. /* 64-bit length field */
  9909. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  9910. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  9911. header[1] = 127;
  9912. memcpy(header + 2, &len1, 4);
  9913. memcpy(header + 6, &len2, 4);
  9914. headerLen = 10;
  9915. }
  9916. if (masking_key) {
  9917. /* add mask */
  9918. header[1] |= 0x80;
  9919. memcpy(header + headerLen, &masking_key, 4);
  9920. headerLen += 4;
  9921. }
  9922. /* Note that POSIX/Winsock's send() is threadsafe
  9923. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  9924. * but mongoose's mg_printf/mg_write is not (because of the loop in
  9925. * push(), although that is only a problem if the packet is large or
  9926. * outgoing buffer is full). */
  9927. /* TODO: Check if this lock should be moved to user land.
  9928. * Currently the server sets this lock for websockets, but
  9929. * not for any other connection. It must be set for every
  9930. * conn read/written by more than one thread, no matter if
  9931. * it is a websocket or regular connection. */
  9932. (void)mg_lock_connection(conn);
  9933. retval = mg_write(conn, header, headerLen);
  9934. if (dataLen > 0) {
  9935. retval = mg_write(conn, data, dataLen);
  9936. }
  9937. /* TODO: Remove this unlock as well, when lock is moved. */
  9938. mg_unlock_connection(conn);
  9939. return retval;
  9940. }
  9941. int
  9942. mg_websocket_write(struct mg_connection *conn,
  9943. int opcode,
  9944. const char *data,
  9945. size_t dataLen)
  9946. {
  9947. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  9948. }
  9949. static void
  9950. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  9951. {
  9952. size_t i = 0;
  9953. i = 0;
  9954. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  9955. /* Convert in 32 bit words, if data is 4 byte aligned */
  9956. while (i < (in_len - 3)) {
  9957. *(uint32_t *)(void *)(out + i) =
  9958. *(uint32_t *)(void *)(in + i) ^ masking_key;
  9959. i += 4;
  9960. }
  9961. }
  9962. if (i != in_len) {
  9963. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  9964. while (i < in_len) {
  9965. *(uint8_t *)(void *)(out + i) =
  9966. *(uint8_t *)(void *)(in + i)
  9967. ^ *(((uint8_t *)&masking_key) + (i % 4));
  9968. i++;
  9969. }
  9970. }
  9971. }
  9972. int
  9973. mg_websocket_client_write(struct mg_connection *conn,
  9974. int opcode,
  9975. const char *data,
  9976. size_t dataLen)
  9977. {
  9978. int retval = -1;
  9979. char *masked_data =
  9980. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  9981. uint32_t masking_key = (uint32_t)get_random();
  9982. if (masked_data == NULL) {
  9983. /* Return -1 in an error case */
  9984. mg_cry(conn,
  9985. "Cannot allocate buffer for masked websocket response: "
  9986. "Out of memory");
  9987. return -1;
  9988. }
  9989. mask_data(data, dataLen, masking_key, masked_data);
  9990. retval = mg_websocket_write_exec(
  9991. conn, opcode, masked_data, dataLen, masking_key);
  9992. mg_free(masked_data);
  9993. return retval;
  9994. }
  9995. static void
  9996. handle_websocket_request(struct mg_connection *conn,
  9997. const char *path,
  9998. int is_callback_resource,
  9999. struct mg_websocket_subprotocols *subprotocols,
  10000. mg_websocket_connect_handler ws_connect_handler,
  10001. mg_websocket_ready_handler ws_ready_handler,
  10002. mg_websocket_data_handler ws_data_handler,
  10003. mg_websocket_close_handler ws_close_handler,
  10004. void *cbData)
  10005. {
  10006. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10007. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10008. int lua_websock = 0;
  10009. #if !defined(USE_LUA)
  10010. (void)path;
  10011. #endif
  10012. /* Step 1: Check websocket protocol version. */
  10013. /* Step 1.1: Check Sec-WebSocket-Key. */
  10014. if (!websock_key) {
  10015. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10016. * requires a Sec-WebSocket-Key header.
  10017. */
  10018. /* It could be the hixie draft version
  10019. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10020. */
  10021. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10022. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10023. char key3[8];
  10024. if ((key1 != NULL) && (key2 != NULL)) {
  10025. /* This version uses 8 byte body data in a GET request */
  10026. conn->content_len = 8;
  10027. if (8 == mg_read(conn, key3, 8)) {
  10028. /* This is the hixie version */
  10029. mg_send_http_error(conn,
  10030. 426,
  10031. "%s",
  10032. "Protocol upgrade to RFC 6455 required");
  10033. return;
  10034. }
  10035. }
  10036. /* This is an unknown version */
  10037. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10038. return;
  10039. }
  10040. /* Step 1.2: Check websocket protocol version. */
  10041. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10042. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10043. /* Reject wrong versions */
  10044. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10045. return;
  10046. }
  10047. /* Step 1.3: Could check for "Host", but we do not really nead this
  10048. * value for anything, so just ignore it. */
  10049. /* Step 2: If a callback is responsible, call it. */
  10050. if (is_callback_resource) {
  10051. /* Step 2.1 check and select subprotocol */
  10052. const char *protocols[64]; // max 64 headers
  10053. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10054. "Sec-WebSocket-Protocol",
  10055. protocols,
  10056. 64);
  10057. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10058. int cnt = 0;
  10059. int idx;
  10060. unsigned long len;
  10061. const char *sep, *curSubProtocol,
  10062. *acceptedWebSocketSubprotocol = NULL;
  10063. /* look for matching subprotocol */
  10064. do {
  10065. const char *protocol = protocols[cnt];
  10066. do {
  10067. sep = strchr(protocol, ',');
  10068. curSubProtocol = protocol;
  10069. len = sep ? (unsigned long)(sep - protocol)
  10070. : (unsigned long)strlen(protocol);
  10071. while (sep && isspace(*++sep))
  10072. ; // ignore leading whitespaces
  10073. protocol = sep;
  10074. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10075. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10076. && (strncmp(curSubProtocol,
  10077. subprotocols->subprotocols[idx],
  10078. len) == 0)) {
  10079. acceptedWebSocketSubprotocol =
  10080. subprotocols->subprotocols[idx];
  10081. break;
  10082. }
  10083. }
  10084. } while (sep && !acceptedWebSocketSubprotocol);
  10085. } while (++cnt < nbSubprotocolHeader
  10086. && !acceptedWebSocketSubprotocol);
  10087. conn->request_info.acceptedWebSocketSubprotocol =
  10088. acceptedWebSocketSubprotocol;
  10089. } else if (nbSubprotocolHeader > 0) {
  10090. /* keep legacy behavior */
  10091. const char *protocol = protocols[0];
  10092. /* The protocol is a comma separated list of names. */
  10093. /* The server must only return one value from this list. */
  10094. /* First check if it is a list or just a single value. */
  10095. const char *sep = strrchr(protocol, ',');
  10096. if (sep == NULL) {
  10097. /* Just a single protocol -> accept it. */
  10098. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10099. } else {
  10100. /* Multiple protocols -> accept the last one. */
  10101. /* This is just a quick fix if the client offers multiple
  10102. * protocols. The handler should have a list of accepted
  10103. * protocols on his own
  10104. * and use it to select one protocol among those the client
  10105. * has
  10106. * offered.
  10107. */
  10108. while (isspace(*++sep)) {
  10109. ; /* ignore leading whitespaces */
  10110. }
  10111. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10112. }
  10113. }
  10114. if ((ws_connect_handler != NULL)
  10115. && (ws_connect_handler(conn, cbData) != 0)) {
  10116. /* C callback has returned non-zero, do not proceed with
  10117. * handshake.
  10118. */
  10119. /* Note that C callbacks are no longer called when Lua is
  10120. * responsible, so C can no longer filter callbacks for Lua. */
  10121. return;
  10122. }
  10123. }
  10124. #if defined(USE_LUA)
  10125. /* Step 3: No callback. Check if Lua is responsible. */
  10126. else {
  10127. /* Step 3.1: Check if Lua is responsible. */
  10128. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10129. lua_websock = match_prefix(
  10130. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10131. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10132. path);
  10133. }
  10134. if (lua_websock) {
  10135. /* Step 3.2: Lua is responsible: call it. */
  10136. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10137. if (!conn->lua_websocket_state) {
  10138. /* Lua rejected the new client */
  10139. return;
  10140. }
  10141. }
  10142. }
  10143. #endif
  10144. /* Step 4: Check if there is a responsible websocket handler. */
  10145. if (!is_callback_resource && !lua_websock) {
  10146. /* There is no callback, and Lua is not responsible either. */
  10147. /* Reply with a 404 Not Found. We are still at a standard
  10148. * HTTP request here, before the websocket handshake, so
  10149. * we can still send standard HTTP error replies. */
  10150. mg_send_http_error(conn, 404, "%s", "Not found");
  10151. return;
  10152. }
  10153. /* Step 5: The websocket connection has been accepted */
  10154. if (!send_websocket_handshake(conn, websock_key)) {
  10155. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10156. return;
  10157. }
  10158. /* Step 6: Call the ready handler */
  10159. if (is_callback_resource) {
  10160. if (ws_ready_handler != NULL) {
  10161. ws_ready_handler(conn, cbData);
  10162. }
  10163. #if defined(USE_LUA)
  10164. } else if (lua_websock) {
  10165. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10166. /* the ready handler returned false */
  10167. return;
  10168. }
  10169. #endif
  10170. }
  10171. /* Step 7: Enter the read loop */
  10172. if (is_callback_resource) {
  10173. read_websocket(conn, ws_data_handler, cbData);
  10174. #if defined(USE_LUA)
  10175. } else if (lua_websock) {
  10176. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10177. #endif
  10178. }
  10179. /* Step 8: Call the close handler */
  10180. if (ws_close_handler) {
  10181. ws_close_handler(conn, cbData);
  10182. }
  10183. }
  10184. static int
  10185. is_websocket_protocol(const struct mg_connection *conn)
  10186. {
  10187. const char *upgrade, *connection;
  10188. /* A websocket protocoll has the following HTTP headers:
  10189. *
  10190. * Connection: Upgrade
  10191. * Upgrade: Websocket
  10192. */
  10193. upgrade = mg_get_header(conn, "Upgrade");
  10194. if (upgrade == NULL) {
  10195. return 0; /* fail early, don't waste time checking other header
  10196. * fields
  10197. */
  10198. }
  10199. if (!mg_strcasestr(upgrade, "websocket")) {
  10200. return 0;
  10201. }
  10202. connection = mg_get_header(conn, "Connection");
  10203. if (connection == NULL) {
  10204. return 0;
  10205. }
  10206. if (!mg_strcasestr(connection, "upgrade")) {
  10207. return 0;
  10208. }
  10209. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10210. * "Sec-WebSocket-Version" are also required.
  10211. * Don't check them here, since even an unsupported websocket protocol
  10212. * request still IS a websocket request (in contrast to a standard HTTP
  10213. * request). It will fail later in handle_websocket_request.
  10214. */
  10215. return 1;
  10216. }
  10217. #endif /* !USE_WEBSOCKET */
  10218. static int
  10219. isbyte(int n)
  10220. {
  10221. return (n >= 0) && (n <= 255);
  10222. }
  10223. static int
  10224. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10225. {
  10226. int n, a, b, c, d, slash = 32, len = 0;
  10227. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10228. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10229. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10230. && (slash < 33)) {
  10231. len = n;
  10232. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10233. | (uint32_t)d;
  10234. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10235. }
  10236. return len;
  10237. }
  10238. static int
  10239. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10240. {
  10241. int throttle = 0;
  10242. struct vec vec, val;
  10243. uint32_t net, mask;
  10244. char mult;
  10245. double v;
  10246. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10247. mult = ',';
  10248. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10249. || (v < 0) || ((lowercase(&mult) != 'k')
  10250. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10251. continue;
  10252. }
  10253. v *= (lowercase(&mult) == 'k')
  10254. ? 1024
  10255. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10256. if (vec.len == 1 && vec.ptr[0] == '*') {
  10257. throttle = (int)v;
  10258. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10259. if ((remote_ip & mask) == net) {
  10260. throttle = (int)v;
  10261. }
  10262. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10263. throttle = (int)v;
  10264. }
  10265. }
  10266. return throttle;
  10267. }
  10268. static uint32_t
  10269. get_remote_ip(const struct mg_connection *conn)
  10270. {
  10271. if (!conn) {
  10272. return 0;
  10273. }
  10274. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10275. }
  10276. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10277. #include "handle_form.inl"
  10278. #if defined(MG_LEGACY_INTERFACE)
  10279. /* Implement the deprecated mg_upload function by calling the new
  10280. * mg_handle_form_request function. While mg_upload could only handle
  10281. * HTML forms sent as POST request in multipart/form-data format
  10282. * containing only file input elements, mg_handle_form_request can
  10283. * handle all form input elements and all standard request methods. */
  10284. struct mg_upload_user_data {
  10285. struct mg_connection *conn;
  10286. const char *destination_dir;
  10287. int num_uploaded_files;
  10288. };
  10289. /* Helper function for deprecated mg_upload. */
  10290. static int
  10291. mg_upload_field_found(const char *key,
  10292. const char *filename,
  10293. char *path,
  10294. size_t pathlen,
  10295. void *user_data)
  10296. {
  10297. int truncated = 0;
  10298. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10299. (void)key;
  10300. if (!filename) {
  10301. mg_cry(fud->conn, "%s: No filename set", __func__);
  10302. return FORM_FIELD_STORAGE_ABORT;
  10303. }
  10304. mg_snprintf(fud->conn,
  10305. &truncated,
  10306. path,
  10307. pathlen - 1,
  10308. "%s/%s",
  10309. fud->destination_dir,
  10310. filename);
  10311. if (!truncated) {
  10312. mg_cry(fud->conn, "%s: File path too long", __func__);
  10313. return FORM_FIELD_STORAGE_ABORT;
  10314. }
  10315. return FORM_FIELD_STORAGE_STORE;
  10316. }
  10317. /* Helper function for deprecated mg_upload. */
  10318. static int
  10319. mg_upload_field_get(const char *key,
  10320. const char *value,
  10321. size_t value_size,
  10322. void *user_data)
  10323. {
  10324. /* Function should never be called */
  10325. (void)key;
  10326. (void)value;
  10327. (void)value_size;
  10328. (void)user_data;
  10329. return 0;
  10330. }
  10331. /* Helper function for deprecated mg_upload. */
  10332. static int
  10333. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10334. {
  10335. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10336. (void)file_size;
  10337. fud->num_uploaded_files++;
  10338. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  10339. return 0;
  10340. }
  10341. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10342. int
  10343. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10344. {
  10345. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10346. struct mg_form_data_handler fdh = {mg_upload_field_found,
  10347. mg_upload_field_get,
  10348. mg_upload_field_stored,
  10349. 0};
  10350. int ret;
  10351. fdh.user_data = (void *)&fud;
  10352. ret = mg_handle_form_request(conn, &fdh);
  10353. if (ret < 0) {
  10354. mg_cry(conn, "%s: Error while parsing the request", __func__);
  10355. }
  10356. return fud.num_uploaded_files;
  10357. }
  10358. #endif
  10359. static int
  10360. get_first_ssl_listener_index(const struct mg_context *ctx)
  10361. {
  10362. unsigned int i;
  10363. int idx = -1;
  10364. if (ctx) {
  10365. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  10366. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  10367. }
  10368. }
  10369. return idx;
  10370. }
  10371. static void
  10372. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  10373. {
  10374. char host[1025];
  10375. const char *host_header;
  10376. size_t hostlen;
  10377. host_header = mg_get_header(conn, "Host");
  10378. hostlen = sizeof(host);
  10379. if (host_header != NULL) {
  10380. char *pos;
  10381. mg_strlcpy(host, host_header, hostlen);
  10382. host[hostlen - 1] = '\0';
  10383. pos = strchr(host, ':');
  10384. if (pos != NULL) {
  10385. *pos = '\0';
  10386. }
  10387. } else {
  10388. /* Cannot get host from the Host: header.
  10389. * Fallback to our IP address. */
  10390. if (conn) {
  10391. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  10392. }
  10393. }
  10394. /* Send host, port, uri and (if it exists) ?query_string */
  10395. if (conn) {
  10396. mg_printf(conn,
  10397. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  10398. host,
  10399. #if defined(USE_IPV6)
  10400. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  10401. == AF_INET6)
  10402. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10403. .lsa.sin6.sin6_port)
  10404. :
  10405. #endif
  10406. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10407. .lsa.sin.sin_port),
  10408. conn->request_info.local_uri,
  10409. (conn->request_info.query_string == NULL) ? "" : "?",
  10410. (conn->request_info.query_string == NULL)
  10411. ? ""
  10412. : conn->request_info.query_string);
  10413. }
  10414. }
  10415. static void
  10416. mg_set_handler_type(struct mg_context *phys_ctx,
  10417. struct mg_domain_context *dom_ctx,
  10418. const char *uri,
  10419. int handler_type,
  10420. int is_delete_request,
  10421. mg_request_handler handler,
  10422. struct mg_websocket_subprotocols *subprotocols,
  10423. mg_websocket_connect_handler connect_handler,
  10424. mg_websocket_ready_handler ready_handler,
  10425. mg_websocket_data_handler data_handler,
  10426. mg_websocket_close_handler close_handler,
  10427. mg_authorization_handler auth_handler,
  10428. void *cbdata)
  10429. {
  10430. struct mg_handler_info *tmp_rh, **lastref;
  10431. size_t urilen = strlen(uri);
  10432. if (handler_type == WEBSOCKET_HANDLER) {
  10433. /* assert(handler == NULL); */
  10434. /* assert(is_delete_request || connect_handler!=NULL ||
  10435. * ready_handler!=NULL || data_handler!=NULL ||
  10436. * close_handler!=NULL);
  10437. */
  10438. /* assert(auth_handler == NULL); */
  10439. if (handler != NULL) {
  10440. return;
  10441. }
  10442. if (!is_delete_request && (connect_handler == NULL)
  10443. && (ready_handler == NULL) && (data_handler == NULL)
  10444. && (close_handler == NULL)) {
  10445. return;
  10446. }
  10447. if (auth_handler != NULL) {
  10448. return;
  10449. }
  10450. } else if (handler_type == REQUEST_HANDLER) {
  10451. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10452. * data_handler==NULL && close_handler==NULL); */
  10453. /* assert(is_delete_request || (handler!=NULL));
  10454. */
  10455. /* assert(auth_handler == NULL); */
  10456. if ((connect_handler != NULL) || (ready_handler != NULL)
  10457. || (data_handler != NULL) || (close_handler != NULL)) {
  10458. return;
  10459. }
  10460. if (!is_delete_request && (handler == NULL)) {
  10461. return;
  10462. }
  10463. if (auth_handler != NULL) {
  10464. return;
  10465. }
  10466. } else { /* AUTH_HANDLER */
  10467. /* assert(handler == NULL); */
  10468. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10469. * data_handler==NULL && close_handler==NULL); */
  10470. /* assert(auth_handler != NULL); */
  10471. if (handler != NULL) {
  10472. return;
  10473. }
  10474. if ((connect_handler != NULL) || (ready_handler != NULL)
  10475. || (data_handler != NULL) || (close_handler != NULL)) {
  10476. return;
  10477. }
  10478. if (!is_delete_request && (auth_handler == NULL)) {
  10479. return;
  10480. }
  10481. }
  10482. if (!phys_ctx || !dom_ctx) {
  10483. return;
  10484. }
  10485. mg_lock_context(phys_ctx);
  10486. /* first try to find an existing handler */
  10487. lastref = &(dom_ctx->handlers);
  10488. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10489. if (tmp_rh->handler_type == handler_type) {
  10490. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10491. if (!is_delete_request) {
  10492. /* update existing handler */
  10493. if (handler_type == REQUEST_HANDLER) {
  10494. tmp_rh->handler = handler;
  10495. } else if (handler_type == WEBSOCKET_HANDLER) {
  10496. tmp_rh->subprotocols = subprotocols;
  10497. tmp_rh->connect_handler = connect_handler;
  10498. tmp_rh->ready_handler = ready_handler;
  10499. tmp_rh->data_handler = data_handler;
  10500. tmp_rh->close_handler = close_handler;
  10501. } else { /* AUTH_HANDLER */
  10502. tmp_rh->auth_handler = auth_handler;
  10503. }
  10504. tmp_rh->cbdata = cbdata;
  10505. } else {
  10506. /* remove existing handler */
  10507. *lastref = tmp_rh->next;
  10508. mg_free(tmp_rh->uri);
  10509. mg_free(tmp_rh);
  10510. }
  10511. mg_unlock_context(phys_ctx);
  10512. return;
  10513. }
  10514. }
  10515. lastref = &(tmp_rh->next);
  10516. }
  10517. if (is_delete_request) {
  10518. /* no handler to set, this was a remove request to a non-existing
  10519. * handler */
  10520. mg_unlock_context(phys_ctx);
  10521. return;
  10522. }
  10523. tmp_rh =
  10524. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  10525. 1,
  10526. phys_ctx);
  10527. if (tmp_rh == NULL) {
  10528. mg_unlock_context(phys_ctx);
  10529. mg_cry(fc(phys_ctx),
  10530. "%s",
  10531. "Cannot create new request handler struct, OOM");
  10532. return;
  10533. }
  10534. tmp_rh->uri = mg_strdup(uri);
  10535. if (!tmp_rh->uri) {
  10536. mg_unlock_context(phys_ctx);
  10537. mg_free(tmp_rh);
  10538. mg_cry(fc(phys_ctx),
  10539. "%s",
  10540. "Cannot create new request handler struct, OOM");
  10541. return;
  10542. }
  10543. tmp_rh->uri_len = urilen;
  10544. if (handler_type == REQUEST_HANDLER) {
  10545. tmp_rh->handler = handler;
  10546. } else if (handler_type == WEBSOCKET_HANDLER) {
  10547. tmp_rh->subprotocols = subprotocols;
  10548. tmp_rh->connect_handler = connect_handler;
  10549. tmp_rh->ready_handler = ready_handler;
  10550. tmp_rh->data_handler = data_handler;
  10551. tmp_rh->close_handler = close_handler;
  10552. } else { /* AUTH_HANDLER */
  10553. tmp_rh->auth_handler = auth_handler;
  10554. }
  10555. tmp_rh->cbdata = cbdata;
  10556. tmp_rh->handler_type = handler_type;
  10557. tmp_rh->next = NULL;
  10558. *lastref = tmp_rh;
  10559. mg_unlock_context(phys_ctx);
  10560. }
  10561. void
  10562. mg_set_request_handler(struct mg_context *ctx,
  10563. const char *uri,
  10564. mg_request_handler handler,
  10565. void *cbdata)
  10566. {
  10567. mg_set_handler_type(ctx,
  10568. &(ctx->dd),
  10569. uri,
  10570. REQUEST_HANDLER,
  10571. handler == NULL,
  10572. handler,
  10573. NULL,
  10574. NULL,
  10575. NULL,
  10576. NULL,
  10577. NULL,
  10578. NULL,
  10579. cbdata);
  10580. }
  10581. void
  10582. mg_set_websocket_handler(struct mg_context *ctx,
  10583. const char *uri,
  10584. mg_websocket_connect_handler connect_handler,
  10585. mg_websocket_ready_handler ready_handler,
  10586. mg_websocket_data_handler data_handler,
  10587. mg_websocket_close_handler close_handler,
  10588. void *cbdata)
  10589. {
  10590. mg_set_websocket_handler_with_subprotocols(ctx,
  10591. uri,
  10592. NULL,
  10593. connect_handler,
  10594. ready_handler,
  10595. data_handler,
  10596. close_handler,
  10597. cbdata);
  10598. }
  10599. void
  10600. mg_set_websocket_handler_with_subprotocols(
  10601. struct mg_context *ctx,
  10602. const char *uri,
  10603. struct mg_websocket_subprotocols *subprotocols,
  10604. mg_websocket_connect_handler connect_handler,
  10605. mg_websocket_ready_handler ready_handler,
  10606. mg_websocket_data_handler data_handler,
  10607. mg_websocket_close_handler close_handler,
  10608. void *cbdata)
  10609. {
  10610. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  10611. && (data_handler == NULL)
  10612. && (close_handler == NULL);
  10613. mg_set_handler_type(ctx,
  10614. &(ctx->dd),
  10615. uri,
  10616. WEBSOCKET_HANDLER,
  10617. is_delete_request,
  10618. NULL,
  10619. subprotocols,
  10620. connect_handler,
  10621. ready_handler,
  10622. data_handler,
  10623. close_handler,
  10624. NULL,
  10625. cbdata);
  10626. }
  10627. void
  10628. mg_set_auth_handler(struct mg_context *ctx,
  10629. const char *uri,
  10630. mg_request_handler handler,
  10631. void *cbdata)
  10632. {
  10633. mg_set_handler_type(ctx,
  10634. &(ctx->dd),
  10635. uri,
  10636. AUTH_HANDLER,
  10637. handler == NULL,
  10638. NULL,
  10639. NULL,
  10640. NULL,
  10641. NULL,
  10642. NULL,
  10643. NULL,
  10644. handler,
  10645. cbdata);
  10646. }
  10647. static int
  10648. get_request_handler(struct mg_connection *conn,
  10649. int handler_type,
  10650. mg_request_handler *handler,
  10651. struct mg_websocket_subprotocols **subprotocols,
  10652. mg_websocket_connect_handler *connect_handler,
  10653. mg_websocket_ready_handler *ready_handler,
  10654. mg_websocket_data_handler *data_handler,
  10655. mg_websocket_close_handler *close_handler,
  10656. mg_authorization_handler *auth_handler,
  10657. void **cbdata)
  10658. {
  10659. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10660. if (request_info) {
  10661. const char *uri = request_info->local_uri;
  10662. size_t urilen = strlen(uri);
  10663. struct mg_handler_info *tmp_rh;
  10664. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  10665. return 0;
  10666. }
  10667. mg_lock_context(conn->phys_ctx);
  10668. /* first try for an exact match */
  10669. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10670. tmp_rh = tmp_rh->next) {
  10671. if (tmp_rh->handler_type == handler_type) {
  10672. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10673. if (handler_type == WEBSOCKET_HANDLER) {
  10674. *subprotocols = tmp_rh->subprotocols;
  10675. *connect_handler = tmp_rh->connect_handler;
  10676. *ready_handler = tmp_rh->ready_handler;
  10677. *data_handler = tmp_rh->data_handler;
  10678. *close_handler = tmp_rh->close_handler;
  10679. } else if (handler_type == REQUEST_HANDLER) {
  10680. *handler = tmp_rh->handler;
  10681. } else { /* AUTH_HANDLER */
  10682. *auth_handler = tmp_rh->auth_handler;
  10683. }
  10684. *cbdata = tmp_rh->cbdata;
  10685. mg_unlock_context(conn->phys_ctx);
  10686. return 1;
  10687. }
  10688. }
  10689. }
  10690. /* next try for a partial match, we will accept uri/something */
  10691. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10692. tmp_rh = tmp_rh->next) {
  10693. if (tmp_rh->handler_type == handler_type) {
  10694. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10695. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  10696. if (handler_type == WEBSOCKET_HANDLER) {
  10697. *subprotocols = tmp_rh->subprotocols;
  10698. *connect_handler = tmp_rh->connect_handler;
  10699. *ready_handler = tmp_rh->ready_handler;
  10700. *data_handler = tmp_rh->data_handler;
  10701. *close_handler = tmp_rh->close_handler;
  10702. } else if (handler_type == REQUEST_HANDLER) {
  10703. *handler = tmp_rh->handler;
  10704. } else { /* AUTH_HANDLER */
  10705. *auth_handler = tmp_rh->auth_handler;
  10706. }
  10707. *cbdata = tmp_rh->cbdata;
  10708. mg_unlock_context(conn->phys_ctx);
  10709. return 1;
  10710. }
  10711. }
  10712. }
  10713. /* finally try for pattern match */
  10714. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10715. tmp_rh = tmp_rh->next) {
  10716. if (tmp_rh->handler_type == handler_type) {
  10717. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10718. if (handler_type == WEBSOCKET_HANDLER) {
  10719. *subprotocols = tmp_rh->subprotocols;
  10720. *connect_handler = tmp_rh->connect_handler;
  10721. *ready_handler = tmp_rh->ready_handler;
  10722. *data_handler = tmp_rh->data_handler;
  10723. *close_handler = tmp_rh->close_handler;
  10724. } else if (handler_type == REQUEST_HANDLER) {
  10725. *handler = tmp_rh->handler;
  10726. } else { /* AUTH_HANDLER */
  10727. *auth_handler = tmp_rh->auth_handler;
  10728. }
  10729. *cbdata = tmp_rh->cbdata;
  10730. mg_unlock_context(conn->phys_ctx);
  10731. return 1;
  10732. }
  10733. }
  10734. }
  10735. mg_unlock_context(conn->phys_ctx);
  10736. }
  10737. return 0; /* none found */
  10738. }
  10739. /* Check if the script file is in a path, allowed for script files.
  10740. * This can be used if uploading files is possible not only for the server
  10741. * admin, and the upload mechanism does not check the file extension.
  10742. */
  10743. static int
  10744. is_in_script_path(const struct mg_connection *conn, const char *path)
  10745. {
  10746. /* TODO (Feature): Add config value for allowed script path.
  10747. * Default: All allowed. */
  10748. (void)conn;
  10749. (void)path;
  10750. return 1;
  10751. }
  10752. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10753. static int
  10754. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10755. void *cbdata)
  10756. {
  10757. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10758. if (pcallbacks->websocket_connect) {
  10759. return pcallbacks->websocket_connect(conn);
  10760. }
  10761. /* No handler set - assume "OK" */
  10762. return 0;
  10763. }
  10764. static void
  10765. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10766. {
  10767. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10768. if (pcallbacks->websocket_ready) {
  10769. pcallbacks->websocket_ready(conn);
  10770. }
  10771. }
  10772. static int
  10773. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10774. int bits,
  10775. char *data,
  10776. size_t len,
  10777. void *cbdata)
  10778. {
  10779. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10780. if (pcallbacks->websocket_data) {
  10781. return pcallbacks->websocket_data(conn, bits, data, len);
  10782. }
  10783. /* No handler set - assume "OK" */
  10784. return 1;
  10785. }
  10786. #endif
  10787. /* This is the heart of the Civetweb's logic.
  10788. * This function is called when the request is read, parsed and validated,
  10789. * and Civetweb must decide what action to take: serve a file, or
  10790. * a directory, or call embedded function, etcetera. */
  10791. static void
  10792. handle_request(struct mg_connection *conn)
  10793. {
  10794. struct mg_request_info *ri = &conn->request_info;
  10795. char path[PATH_MAX];
  10796. int uri_len, ssl_index;
  10797. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  10798. is_put_or_delete_request = 0, is_callback_resource = 0;
  10799. int i;
  10800. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10801. mg_request_handler callback_handler = NULL;
  10802. struct mg_websocket_subprotocols *subprotocols;
  10803. mg_websocket_connect_handler ws_connect_handler = NULL;
  10804. mg_websocket_ready_handler ws_ready_handler = NULL;
  10805. mg_websocket_data_handler ws_data_handler = NULL;
  10806. mg_websocket_close_handler ws_close_handler = NULL;
  10807. void *callback_data = NULL;
  10808. mg_authorization_handler auth_handler = NULL;
  10809. void *auth_callback_data = NULL;
  10810. int handler_type;
  10811. time_t curtime = time(NULL);
  10812. char date[64];
  10813. path[0] = 0;
  10814. /* 1. get the request url */
  10815. /* 1.1. split into url and query string */
  10816. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  10817. != NULL) {
  10818. *((char *)conn->request_info.query_string++) = '\0';
  10819. }
  10820. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  10821. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  10822. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  10823. if (ssl_index >= 0) {
  10824. redirect_to_https_port(conn, ssl_index);
  10825. } else {
  10826. /* A http to https forward port has been specified,
  10827. * but no https port to forward to. */
  10828. mg_send_http_error(conn,
  10829. 503,
  10830. "%s",
  10831. "Error: SSL forward not configured properly");
  10832. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  10833. }
  10834. return;
  10835. }
  10836. uri_len = (int)strlen(ri->local_uri);
  10837. /* 1.3. decode url (if config says so) */
  10838. if (should_decode_url(conn)) {
  10839. mg_url_decode(
  10840. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  10841. }
  10842. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  10843. * not possible */
  10844. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  10845. /* step 1. completed, the url is known now */
  10846. uri_len = (int)strlen(ri->local_uri);
  10847. DEBUG_TRACE("URL: %s", ri->local_uri);
  10848. /* 2. if this ip has limited speed, set it for this connection */
  10849. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  10850. get_remote_ip(conn),
  10851. ri->local_uri);
  10852. /* 3. call a "handle everything" callback, if registered */
  10853. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  10854. /* Note that since V1.7 the "begin_request" function is called
  10855. * before an authorization check. If an authorization check is
  10856. * required, use a request_handler instead. */
  10857. i = conn->phys_ctx->callbacks.begin_request(conn);
  10858. if (i > 0) {
  10859. /* callback already processed the request. Store the
  10860. return value as a status code for the access log. */
  10861. conn->status_code = i;
  10862. discard_unread_request_data(conn);
  10863. return;
  10864. } else if (i == 0) {
  10865. /* civetweb should process the request */
  10866. } else {
  10867. /* unspecified - may change with the next version */
  10868. return;
  10869. }
  10870. }
  10871. /* request not yet handled by a handler or redirect, so the request
  10872. * is processed here */
  10873. /* 4. Check for CORS preflight requests and handle them (if configured).
  10874. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  10875. */
  10876. if (!strcmp(ri->request_method, "OPTIONS")) {
  10877. /* Send a response to CORS preflights only if
  10878. * access_control_allow_methods is not NULL and not an empty string.
  10879. * In this case, scripts can still handle CORS. */
  10880. const char *cors_meth_cfg =
  10881. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  10882. const char *cors_orig_cfg =
  10883. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10884. const char *cors_origin =
  10885. get_header(ri->http_headers, ri->num_headers, "Origin");
  10886. const char *cors_acrm = get_header(ri->http_headers,
  10887. ri->num_headers,
  10888. "Access-Control-Request-Method");
  10889. /* Todo: check if cors_origin is in cors_orig_cfg.
  10890. * Or, let the client check this. */
  10891. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  10892. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  10893. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  10894. /* This is a valid CORS preflight, and the server is configured
  10895. * to
  10896. * handle it automatically. */
  10897. const char *cors_acrh =
  10898. get_header(ri->http_headers,
  10899. ri->num_headers,
  10900. "Access-Control-Request-Headers");
  10901. gmt_time_string(date, sizeof(date), &curtime);
  10902. mg_printf(conn,
  10903. "HTTP/1.1 200 OK\r\n"
  10904. "Date: %s\r\n"
  10905. "Access-Control-Allow-Origin: %s\r\n"
  10906. "Access-Control-Allow-Methods: %s\r\n"
  10907. "Content-Length: 0\r\n"
  10908. "Connection: %s\r\n",
  10909. date,
  10910. cors_orig_cfg,
  10911. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  10912. suggest_connection_header(conn));
  10913. if (cors_acrh != NULL) {
  10914. /* CORS request is asking for additional headers */
  10915. const char *cors_hdr_cfg =
  10916. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  10917. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  10918. /* Allow only if access_control_allow_headers is
  10919. * not NULL and not an empty string. If this
  10920. * configuration is set to *, allow everything.
  10921. * Otherwise this configuration must be a list
  10922. * of allowed HTTP header names. */
  10923. mg_printf(conn,
  10924. "Access-Control-Allow-Headers: %s\r\n",
  10925. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  10926. : cors_hdr_cfg));
  10927. }
  10928. }
  10929. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  10930. mg_printf(conn, "\r\n");
  10931. return;
  10932. }
  10933. }
  10934. /* 5. interpret the url to find out how the request must be handled
  10935. */
  10936. /* 5.1. first test, if the request targets the regular http(s)://
  10937. * protocol namespace or the websocket ws(s):// protocol namespace.
  10938. */
  10939. is_websocket_request = is_websocket_protocol(conn);
  10940. #if defined(USE_WEBSOCKET)
  10941. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  10942. #else
  10943. handler_type = REQUEST_HANDLER;
  10944. #endif /* defined(USE_WEBSOCKET) */
  10945. /* 5.2. check if the request will be handled by a callback */
  10946. if (get_request_handler(conn,
  10947. handler_type,
  10948. &callback_handler,
  10949. &subprotocols,
  10950. &ws_connect_handler,
  10951. &ws_ready_handler,
  10952. &ws_data_handler,
  10953. &ws_close_handler,
  10954. NULL,
  10955. &callback_data)) {
  10956. /* 5.2.1. A callback will handle this request. All requests
  10957. * handled
  10958. * by a callback have to be considered as requests to a script
  10959. * resource. */
  10960. is_callback_resource = 1;
  10961. is_script_resource = 1;
  10962. is_put_or_delete_request = is_put_or_delete_method(conn);
  10963. } else {
  10964. no_callback_resource:
  10965. /* 5.2.2. No callback is responsible for this request. The URI
  10966. * addresses a file based resource (static content or Lua/cgi
  10967. * scripts in the file system). */
  10968. is_callback_resource = 0;
  10969. interpret_uri(conn,
  10970. path,
  10971. sizeof(path),
  10972. &file.stat,
  10973. &is_found,
  10974. &is_script_resource,
  10975. &is_websocket_request,
  10976. &is_put_or_delete_request);
  10977. }
  10978. /* 6. authorization check */
  10979. /* 6.1. a custom authorization handler is installed */
  10980. if (get_request_handler(conn,
  10981. AUTH_HANDLER,
  10982. NULL,
  10983. NULL,
  10984. NULL,
  10985. NULL,
  10986. NULL,
  10987. NULL,
  10988. &auth_handler,
  10989. &auth_callback_data)) {
  10990. if (!auth_handler(conn, auth_callback_data)) {
  10991. return;
  10992. }
  10993. } else if (is_put_or_delete_request && !is_script_resource
  10994. && !is_callback_resource) {
  10995. /* 6.2. this request is a PUT/DELETE to a real file */
  10996. /* 6.2.1. thus, the server must have real files */
  10997. #if defined(NO_FILES)
  10998. if (1) {
  10999. #else
  11000. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11001. #endif
  11002. /* This server does not have any real files, thus the
  11003. * PUT/DELETE methods are not valid. */
  11004. mg_send_http_error(conn,
  11005. 405,
  11006. "%s method not allowed",
  11007. conn->request_info.request_method);
  11008. return;
  11009. }
  11010. #if !defined(NO_FILES)
  11011. /* 6.2.2. Check if put authorization for static files is
  11012. * available.
  11013. */
  11014. if (!is_authorized_for_put(conn)) {
  11015. send_authorization_request(conn, NULL);
  11016. return;
  11017. }
  11018. #endif
  11019. } else {
  11020. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11021. * or it is a PUT or DELETE request to a resource that does not
  11022. * correspond to a file. Check authorization. */
  11023. if (!check_authorization(conn, path)) {
  11024. send_authorization_request(conn, NULL);
  11025. return;
  11026. }
  11027. }
  11028. /* request is authorized or does not need authorization */
  11029. /* 7. check if there are request handlers for this uri */
  11030. if (is_callback_resource) {
  11031. if (!is_websocket_request) {
  11032. i = callback_handler(conn, callback_data);
  11033. if (i > 0) {
  11034. /* Do nothing, callback has served the request. Store
  11035. * then return value as status code for the log and discard
  11036. * all data from the client not used by the callback. */
  11037. conn->status_code = i;
  11038. discard_unread_request_data(conn);
  11039. } else {
  11040. /* The handler did NOT handle the request. */
  11041. /* Some proper reactions would be:
  11042. * a) close the connections without sending anything
  11043. * b) send a 404 not found
  11044. * c) try if there is a file matching the URI
  11045. * It would be possible to do a, b or c in the callback
  11046. * implementation, and return 1 - we cannot do anything
  11047. * here, that is not possible in the callback.
  11048. *
  11049. * TODO: What would be the best reaction here?
  11050. * (Note: The reaction may change, if there is a better
  11051. *idea.)
  11052. */
  11053. /* For the moment, use option c: We look for a proper file,
  11054. * but since a file request is not always a script resource,
  11055. * the authorization check might be different. */
  11056. interpret_uri(conn,
  11057. path,
  11058. sizeof(path),
  11059. &file.stat,
  11060. &is_found,
  11061. &is_script_resource,
  11062. &is_websocket_request,
  11063. &is_put_or_delete_request);
  11064. callback_handler = NULL;
  11065. /* Here we are at a dead end:
  11066. * According to URI matching, a callback should be
  11067. * responsible for handling the request,
  11068. * we called it, but the callback declared itself
  11069. * not responsible.
  11070. * We use a goto here, to get out of this dead end,
  11071. * and continue with the default handling.
  11072. * A goto here is simpler and better to understand
  11073. * than some curious loop. */
  11074. goto no_callback_resource;
  11075. }
  11076. } else {
  11077. #if defined(USE_WEBSOCKET)
  11078. handle_websocket_request(conn,
  11079. path,
  11080. is_callback_resource,
  11081. subprotocols,
  11082. ws_connect_handler,
  11083. ws_ready_handler,
  11084. ws_data_handler,
  11085. ws_close_handler,
  11086. callback_data);
  11087. #endif
  11088. }
  11089. return;
  11090. }
  11091. /* 8. handle websocket requests */
  11092. #if defined(USE_WEBSOCKET)
  11093. if (is_websocket_request) {
  11094. if (is_script_resource) {
  11095. if (is_in_script_path(conn, path)) {
  11096. /* Websocket Lua script */
  11097. handle_websocket_request(conn,
  11098. path,
  11099. 0 /* Lua Script */,
  11100. NULL,
  11101. NULL,
  11102. NULL,
  11103. NULL,
  11104. NULL,
  11105. conn->phys_ctx->user_data);
  11106. } else {
  11107. /* Script was in an illegal path */
  11108. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11109. }
  11110. } else {
  11111. #if defined(MG_LEGACY_INTERFACE)
  11112. handle_websocket_request(
  11113. conn,
  11114. path,
  11115. !is_script_resource /* could be deprecated global callback */,
  11116. NULL,
  11117. deprecated_websocket_connect_wrapper,
  11118. deprecated_websocket_ready_wrapper,
  11119. deprecated_websocket_data_wrapper,
  11120. NULL,
  11121. conn->phys_ctx->user_data);
  11122. #else
  11123. mg_send_http_error(conn, 404, "%s", "Not found");
  11124. #endif
  11125. }
  11126. return;
  11127. } else
  11128. #endif
  11129. #if defined(NO_FILES)
  11130. /* 9a. In case the server uses only callbacks, this uri is
  11131. * unknown.
  11132. * Then, all request handling ends here. */
  11133. mg_send_http_error(conn, 404, "%s", "Not Found");
  11134. #else
  11135. /* 9b. This request is either for a static file or resource handled
  11136. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11137. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11138. mg_send_http_error(conn, 404, "%s", "Not Found");
  11139. return;
  11140. }
  11141. /* 10. Request is handled by a script */
  11142. if (is_script_resource) {
  11143. handle_file_based_request(conn, path, &file);
  11144. return;
  11145. }
  11146. /* 11. Handle put/delete/mkcol requests */
  11147. if (is_put_or_delete_request) {
  11148. /* 11.1. PUT method */
  11149. if (!strcmp(ri->request_method, "PUT")) {
  11150. put_file(conn, path);
  11151. return;
  11152. }
  11153. /* 11.2. DELETE method */
  11154. if (!strcmp(ri->request_method, "DELETE")) {
  11155. delete_file(conn, path);
  11156. return;
  11157. }
  11158. /* 11.3. MKCOL method */
  11159. if (!strcmp(ri->request_method, "MKCOL")) {
  11160. mkcol(conn, path);
  11161. return;
  11162. }
  11163. /* 11.4. PATCH method
  11164. * This method is not supported for static resources,
  11165. * only for scripts (Lua, CGI) and callbacks. */
  11166. mg_send_http_error(conn,
  11167. 405,
  11168. "%s method not allowed",
  11169. conn->request_info.request_method);
  11170. return;
  11171. }
  11172. /* 11. File does not exist, or it was configured that it should be
  11173. * hidden */
  11174. if (!is_found || (must_hide_file(conn, path))) {
  11175. mg_send_http_error(conn, 404, "%s", "Not found");
  11176. return;
  11177. }
  11178. /* 12. Directory uris should end with a slash */
  11179. if (file.stat.is_directory && (uri_len > 0)
  11180. && (ri->local_uri[uri_len - 1] != '/')) {
  11181. gmt_time_string(date, sizeof(date), &curtime);
  11182. mg_printf(conn,
  11183. "HTTP/1.1 301 Moved Permanently\r\n"
  11184. "Location: %s/\r\n"
  11185. "Date: %s\r\n"
  11186. /* "Cache-Control: private\r\n" (= default) */
  11187. "Content-Length: 0\r\n"
  11188. "Connection: %s\r\n",
  11189. ri->request_uri,
  11190. date,
  11191. suggest_connection_header(conn));
  11192. send_additional_header(conn);
  11193. mg_printf(conn, "\r\n");
  11194. return;
  11195. }
  11196. /* 13. Handle other methods than GET/HEAD */
  11197. /* 13.1. Handle PROPFIND */
  11198. if (!strcmp(ri->request_method, "PROPFIND")) {
  11199. handle_propfind(conn, path, &file.stat);
  11200. return;
  11201. }
  11202. /* 13.2. Handle OPTIONS for files */
  11203. if (!strcmp(ri->request_method, "OPTIONS")) {
  11204. /* This standard handler is only used for real files.
  11205. * Scripts should support the OPTIONS method themselves, to allow a
  11206. * maximum flexibility.
  11207. * Lua and CGI scripts may fully support CORS this way (including
  11208. * preflights). */
  11209. send_options(conn);
  11210. return;
  11211. }
  11212. /* 13.3. everything but GET and HEAD (e.g. POST) */
  11213. if ((0 != strcmp(ri->request_method, "GET"))
  11214. && (0 != strcmp(ri->request_method, "HEAD"))) {
  11215. mg_send_http_error(conn,
  11216. 405,
  11217. "%s method not allowed",
  11218. conn->request_info.request_method);
  11219. return;
  11220. }
  11221. /* 14. directories */
  11222. if (file.stat.is_directory) {
  11223. /* Substitute files have already been handled above. */
  11224. /* Here we can either generate and send a directory listing,
  11225. * or send an "access denied" error. */
  11226. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11227. "yes")) {
  11228. handle_directory_request(conn, path);
  11229. } else {
  11230. mg_send_http_error(conn,
  11231. 403,
  11232. "%s",
  11233. "Error: Directory listing denied");
  11234. }
  11235. return;
  11236. }
  11237. handle_file_based_request(conn, path, &file);
  11238. #endif /* !defined(NO_FILES) */
  11239. #if 0
  11240. /* Perform redirect and auth checks before calling begin_request()
  11241. * handler.
  11242. * Otherwise, begin_request() would need to perform auth checks and
  11243. * redirects. */
  11244. #endif
  11245. }
  11246. static void
  11247. handle_file_based_request(struct mg_connection *conn,
  11248. const char *path,
  11249. struct mg_file *file)
  11250. {
  11251. if (!conn || !conn->dom_ctx) {
  11252. return;
  11253. }
  11254. if (0) {
  11255. #ifdef USE_LUA
  11256. } else if (match_prefix(
  11257. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  11258. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  11259. path) > 0) {
  11260. if (is_in_script_path(conn, path)) {
  11261. /* Lua server page: an SSI like page containing mostly plain
  11262. * html
  11263. * code
  11264. * plus some tags with server generated contents. */
  11265. handle_lsp_request(conn, path, file, NULL);
  11266. } else {
  11267. /* Script was in an illegal path */
  11268. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11269. }
  11270. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  11271. strlen(
  11272. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  11273. path) > 0) {
  11274. if (is_in_script_path(conn, path)) {
  11275. /* Lua in-server module script: a CGI like script used to
  11276. * generate
  11277. * the
  11278. * entire reply. */
  11279. mg_exec_lua_script(conn, path, NULL);
  11280. } else {
  11281. /* Script was in an illegal path */
  11282. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11283. }
  11284. #endif
  11285. #if defined(USE_DUKTAPE)
  11286. } else if (match_prefix(
  11287. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  11288. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  11289. path) > 0) {
  11290. if (is_in_script_path(conn, path)) {
  11291. /* Call duktape to generate the page */
  11292. mg_exec_duktape_script(conn, path);
  11293. } else {
  11294. /* Script was in an illegal path */
  11295. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11296. }
  11297. #endif
  11298. #if !defined(NO_CGI)
  11299. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  11300. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  11301. path) > 0) {
  11302. if (is_in_script_path(conn, path)) {
  11303. /* CGI scripts may support all HTTP methods */
  11304. handle_cgi_request(conn, path);
  11305. } else {
  11306. /* Script was in an illegal path */
  11307. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11308. }
  11309. #endif /* !NO_CGI */
  11310. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  11311. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  11312. path) > 0) {
  11313. if (is_in_script_path(conn, path)) {
  11314. handle_ssi_file_request(conn, path, file);
  11315. } else {
  11316. /* Script was in an illegal path */
  11317. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11318. }
  11319. #if !defined(NO_CACHING)
  11320. } else if ((!conn->in_error_handler)
  11321. && is_not_modified(conn, &file->stat)) {
  11322. /* Send 304 "Not Modified" - this must not send any body data */
  11323. handle_not_modified_static_file_request(conn, file);
  11324. #endif /* !NO_CACHING */
  11325. } else {
  11326. handle_static_file_request(conn, path, file, NULL, NULL);
  11327. }
  11328. }
  11329. static void
  11330. close_all_listening_sockets(struct mg_context *ctx)
  11331. {
  11332. unsigned int i;
  11333. if (!ctx) {
  11334. return;
  11335. }
  11336. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11337. closesocket(ctx->listening_sockets[i].sock);
  11338. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  11339. }
  11340. mg_free(ctx->listening_sockets);
  11341. ctx->listening_sockets = NULL;
  11342. mg_free(ctx->listening_socket_fds);
  11343. ctx->listening_socket_fds = NULL;
  11344. }
  11345. /* Valid listening port specification is: [ip_address:]port[s]
  11346. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  11347. * Examples for IPv6: [::]:80, [::1]:80,
  11348. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  11349. * see https://tools.ietf.org/html/rfc3513#section-2.2
  11350. * In order to bind to both, IPv4 and IPv6, you can either add
  11351. * both ports using 8080,[::]:8080, or the short form +8080.
  11352. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  11353. * one only accepting IPv4 the other only IPv6. +8080 creates
  11354. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  11355. * environment, they might work differently, or might not work
  11356. * at all - it must be tested what options work best in the
  11357. * relevant network environment.
  11358. */
  11359. static int
  11360. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  11361. {
  11362. unsigned int a, b, c, d, port;
  11363. int ch, len;
  11364. const char *cb;
  11365. #if defined(USE_IPV6)
  11366. char buf[100] = {0};
  11367. #endif
  11368. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  11369. * Also, all-zeroes in the socket address means binding to all addresses
  11370. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  11371. memset(so, 0, sizeof(*so));
  11372. so->lsa.sin.sin_family = AF_INET;
  11373. *ip_version = 0;
  11374. /* Initialize port and len as invalid. */
  11375. port = 0;
  11376. len = 0;
  11377. /* Test for different ways to format this string */
  11378. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  11379. == 5) {
  11380. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  11381. so->lsa.sin.sin_addr.s_addr =
  11382. htonl((a << 24) | (b << 16) | (c << 8) | d);
  11383. so->lsa.sin.sin_port = htons((uint16_t)port);
  11384. *ip_version = 4;
  11385. #if defined(USE_IPV6)
  11386. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  11387. && mg_inet_pton(
  11388. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  11389. /* IPv6 address, examples: see above */
  11390. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  11391. */
  11392. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11393. *ip_version = 6;
  11394. #endif
  11395. } else if ((vec->ptr[0] == '+')
  11396. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  11397. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  11398. /* Add 1 to len for the + character we skipped before */
  11399. len++;
  11400. #if defined(USE_IPV6)
  11401. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  11402. so->lsa.sin6.sin6_family = AF_INET6;
  11403. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11404. *ip_version = 4 + 6;
  11405. #else
  11406. /* Bind to IPv4 only, since IPv6 is not built in. */
  11407. so->lsa.sin.sin_port = htons((uint16_t)port);
  11408. *ip_version = 4;
  11409. #endif
  11410. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  11411. /* If only port is specified, bind to IPv4, INADDR_ANY */
  11412. so->lsa.sin.sin_port = htons((uint16_t)port);
  11413. *ip_version = 4;
  11414. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  11415. /* Could be a hostname */
  11416. /* Will only work for RFC 952 compliant hostnames,
  11417. * starting with a letter, containing only letters,
  11418. * digits and hyphen ('-'). Newer specs may allow
  11419. * more, but this is not guaranteed here, since it
  11420. * may interfere with rules for port option lists. */
  11421. *(char *)cb = 0; /* Use a const cast here and modify the string.
  11422. * We are going to restore the string later. */
  11423. if (mg_inet_pton(
  11424. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  11425. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11426. *ip_version = 4;
  11427. so->lsa.sin.sin_family = AF_INET;
  11428. so->lsa.sin.sin_port = htons((uint16_t)port);
  11429. len += (int)(cb - vec->ptr) + 1;
  11430. } else {
  11431. port = 0;
  11432. len = 0;
  11433. }
  11434. #if defined(USE_IPV6)
  11435. } else if (mg_inet_pton(AF_INET6,
  11436. vec->ptr,
  11437. &so->lsa.sin6,
  11438. sizeof(so->lsa.sin6))) {
  11439. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11440. *ip_version = 6;
  11441. so->lsa.sin6.sin6_family = AF_INET6;
  11442. so->lsa.sin.sin_port = htons((uint16_t)port);
  11443. len += (int)(cb - vec->ptr) + 1;
  11444. } else {
  11445. port = 0;
  11446. len = 0;
  11447. }
  11448. #endif
  11449. }
  11450. *(char *)cb = ':'; /* restore the string */
  11451. } else {
  11452. /* Parsing failure. */
  11453. }
  11454. /* sscanf and the option splitting code ensure the following condition
  11455. */
  11456. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11457. *ip_version = 0;
  11458. return 0;
  11459. }
  11460. ch = vec->ptr[len]; /* Next character after the port number */
  11461. so->is_ssl = (ch == 's');
  11462. so->ssl_redir = (ch == 'r');
  11463. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11464. if (is_valid_port(port)
  11465. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  11466. return 1;
  11467. }
  11468. /* Reset ip_version to 0 of there is an error */
  11469. *ip_version = 0;
  11470. return 0;
  11471. }
  11472. /* Is there any SSL port in use? */
  11473. static int
  11474. is_ssl_port_used(const char *ports)
  11475. {
  11476. if (ports) {
  11477. if (strchr(ports, 's')) {
  11478. return 1;
  11479. }
  11480. if (strchr(ports, 'r')) {
  11481. return 1;
  11482. }
  11483. }
  11484. return 0;
  11485. }
  11486. static int
  11487. set_ports_option(struct mg_context *phys_ctx)
  11488. {
  11489. const char *list;
  11490. int on = 1;
  11491. #if defined(USE_IPV6)
  11492. int off = 0;
  11493. #endif
  11494. struct vec vec;
  11495. struct socket so, *ptr;
  11496. struct pollfd *pfd;
  11497. union usa usa;
  11498. socklen_t len;
  11499. int ip_version;
  11500. int portsTotal = 0;
  11501. int portsOk = 0;
  11502. if (!phys_ctx) {
  11503. return 0;
  11504. }
  11505. memset(&so, 0, sizeof(so));
  11506. memset(&usa, 0, sizeof(usa));
  11507. len = sizeof(usa);
  11508. list = phys_ctx->dd.config[LISTENING_PORTS];
  11509. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11510. portsTotal++;
  11511. if (!parse_port_string(&vec, &so, &ip_version)) {
  11512. mg_cry(fc(phys_ctx),
  11513. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  11514. (int)vec.len,
  11515. vec.ptr,
  11516. portsTotal,
  11517. "[IP_ADDRESS:]PORT[s|r]");
  11518. continue;
  11519. }
  11520. #if !defined(NO_SSL)
  11521. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  11522. mg_cry(fc(phys_ctx),
  11523. "Cannot add SSL socket (entry %i)",
  11524. portsTotal);
  11525. continue;
  11526. }
  11527. #endif
  11528. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  11529. == INVALID_SOCKET) {
  11530. mg_cry(fc(phys_ctx), "cannot create socket (entry %i)", portsTotal);
  11531. continue;
  11532. }
  11533. #ifdef _WIN32
  11534. /* Windows SO_REUSEADDR lets many procs binds to a
  11535. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  11536. * if someone already has the socket -- DTL */
  11537. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  11538. * Windows might need a few seconds before
  11539. * the same port can be used again in the
  11540. * same process, so a short Sleep may be
  11541. * required between mg_stop and mg_start.
  11542. */
  11543. if (setsockopt(so.sock,
  11544. SOL_SOCKET,
  11545. SO_EXCLUSIVEADDRUSE,
  11546. (SOCK_OPT_TYPE)&on,
  11547. sizeof(on)) != 0) {
  11548. /* Set reuse option, but don't abort on errors. */
  11549. mg_cry(fc(ctx),
  11550. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  11551. portsTotal);
  11552. }
  11553. #else
  11554. if (setsockopt(so.sock,
  11555. SOL_SOCKET,
  11556. SO_REUSEADDR,
  11557. (SOCK_OPT_TYPE)&on,
  11558. sizeof(on)) != 0) {
  11559. /* Set reuse option, but don't abort on errors. */
  11560. mg_cry(fc(phys_ctx),
  11561. "cannot set socket option SO_REUSEADDR (entry %i)",
  11562. portsTotal);
  11563. }
  11564. #endif
  11565. if (ip_version > 4) {
  11566. #if defined(USE_IPV6)
  11567. if (ip_version == 6) {
  11568. if (so.lsa.sa.sa_family == AF_INET6
  11569. && setsockopt(so.sock,
  11570. IPPROTO_IPV6,
  11571. IPV6_V6ONLY,
  11572. (void *)&off,
  11573. sizeof(off)) != 0) {
  11574. /* Set IPv6 only option, but don't abort on errors. */
  11575. mg_cry(fc(phys_ctx),
  11576. "cannot set socket option IPV6_V6ONLY (entry %i)",
  11577. portsTotal);
  11578. }
  11579. }
  11580. #else
  11581. mg_cry(fc(phys_ctx), "IPv6 not available");
  11582. closesocket(so.sock);
  11583. so.sock = INVALID_SOCKET;
  11584. continue;
  11585. #endif
  11586. }
  11587. if (so.lsa.sa.sa_family == AF_INET) {
  11588. len = sizeof(so.lsa.sin);
  11589. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11590. mg_cry(fc(phys_ctx),
  11591. "cannot bind to %.*s: %d (%s)",
  11592. (int)vec.len,
  11593. vec.ptr,
  11594. (int)ERRNO,
  11595. strerror(errno));
  11596. closesocket(so.sock);
  11597. so.sock = INVALID_SOCKET;
  11598. continue;
  11599. }
  11600. }
  11601. #if defined(USE_IPV6)
  11602. else if (so.lsa.sa.sa_family == AF_INET6) {
  11603. len = sizeof(so.lsa.sin6);
  11604. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11605. mg_cry(fc(phys_ctx),
  11606. "cannot bind to IPv6 %.*s: %d (%s)",
  11607. (int)vec.len,
  11608. vec.ptr,
  11609. (int)ERRNO,
  11610. strerror(errno));
  11611. closesocket(so.sock);
  11612. so.sock = INVALID_SOCKET;
  11613. continue;
  11614. }
  11615. }
  11616. #endif
  11617. else {
  11618. mg_cry(fc(phys_ctx),
  11619. "cannot bind: address family not supported (entry %i)",
  11620. portsTotal);
  11621. closesocket(so.sock);
  11622. so.sock = INVALID_SOCKET;
  11623. continue;
  11624. }
  11625. if (listen(so.sock, SOMAXCONN) != 0) {
  11626. mg_cry(fc(phys_ctx),
  11627. "cannot listen to %.*s: %d (%s)",
  11628. (int)vec.len,
  11629. vec.ptr,
  11630. (int)ERRNO,
  11631. strerror(errno));
  11632. closesocket(so.sock);
  11633. so.sock = INVALID_SOCKET;
  11634. continue;
  11635. }
  11636. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  11637. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  11638. int err = (int)ERRNO;
  11639. mg_cry(fc(phys_ctx),
  11640. "call to getsockname failed %.*s: %d (%s)",
  11641. (int)vec.len,
  11642. vec.ptr,
  11643. err,
  11644. strerror(errno));
  11645. closesocket(so.sock);
  11646. so.sock = INVALID_SOCKET;
  11647. continue;
  11648. }
  11649. /* Update lsa port in case of random free ports */
  11650. #if defined(USE_IPV6)
  11651. if (so.lsa.sa.sa_family == AF_INET6) {
  11652. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  11653. } else
  11654. #endif
  11655. {
  11656. so.lsa.sin.sin_port = usa.sin.sin_port;
  11657. }
  11658. if ((ptr = (struct socket *)
  11659. mg_realloc_ctx(phys_ctx->listening_sockets,
  11660. (phys_ctx->num_listening_sockets + 1)
  11661. * sizeof(phys_ctx->listening_sockets[0]),
  11662. phys_ctx)) == NULL) {
  11663. mg_cry(fc(phys_ctx), "%s", "Out of memory");
  11664. closesocket(so.sock);
  11665. so.sock = INVALID_SOCKET;
  11666. continue;
  11667. }
  11668. if ((pfd = (struct pollfd *)
  11669. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  11670. (phys_ctx->num_listening_sockets + 1)
  11671. * sizeof(phys_ctx->listening_socket_fds[0]),
  11672. phys_ctx)) == NULL) {
  11673. mg_cry(fc(phys_ctx), "%s", "Out of memory");
  11674. closesocket(so.sock);
  11675. so.sock = INVALID_SOCKET;
  11676. mg_free(ptr);
  11677. continue;
  11678. }
  11679. set_close_on_exec(so.sock, fc(phys_ctx));
  11680. phys_ctx->listening_sockets = ptr;
  11681. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  11682. phys_ctx->listening_socket_fds = pfd;
  11683. phys_ctx->num_listening_sockets++;
  11684. portsOk++;
  11685. }
  11686. if (portsOk != portsTotal) {
  11687. close_all_listening_sockets(phys_ctx);
  11688. portsOk = 0;
  11689. }
  11690. return portsOk;
  11691. }
  11692. static const char *
  11693. header_val(const struct mg_connection *conn, const char *header)
  11694. {
  11695. const char *header_value;
  11696. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11697. return "-";
  11698. } else {
  11699. return header_value;
  11700. }
  11701. }
  11702. static void
  11703. log_access(const struct mg_connection *conn)
  11704. {
  11705. const struct mg_request_info *ri;
  11706. struct mg_file fi;
  11707. char date[64], src_addr[IP_ADDR_STR_LEN];
  11708. struct tm *tm;
  11709. const char *referer;
  11710. const char *user_agent;
  11711. char buf[4096];
  11712. if (!conn || !conn->dom_ctx) {
  11713. return;
  11714. }
  11715. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  11716. if (mg_fopen(conn,
  11717. conn->dom_ctx->config[ACCESS_LOG_FILE],
  11718. MG_FOPEN_MODE_APPEND,
  11719. &fi) == 0) {
  11720. fi.access.fp = NULL;
  11721. }
  11722. } else {
  11723. fi.access.fp = NULL;
  11724. }
  11725. /* Log is written to a file and/or a callback. If both are not set,
  11726. * executing the rest of the function is pointless. */
  11727. if ((fi.access.fp == NULL)
  11728. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  11729. return;
  11730. }
  11731. tm = localtime(&conn->conn_birth_time);
  11732. if (tm != NULL) {
  11733. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11734. } else {
  11735. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11736. date[sizeof(date) - 1] = '\0';
  11737. }
  11738. ri = &conn->request_info;
  11739. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11740. referer = header_val(conn, "Referer");
  11741. user_agent = header_val(conn, "User-Agent");
  11742. mg_snprintf(conn,
  11743. NULL, /* Ignore truncation in access log */
  11744. buf,
  11745. sizeof(buf),
  11746. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11747. src_addr,
  11748. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11749. date,
  11750. ri->request_method ? ri->request_method : "-",
  11751. ri->request_uri ? ri->request_uri : "-",
  11752. ri->query_string ? "?" : "",
  11753. ri->query_string ? ri->query_string : "",
  11754. ri->http_version,
  11755. conn->status_code,
  11756. conn->num_bytes_sent,
  11757. referer,
  11758. user_agent);
  11759. if (conn->phys_ctx->callbacks.log_access) {
  11760. conn->phys_ctx->callbacks.log_access(conn, buf);
  11761. }
  11762. if (fi.access.fp) {
  11763. int ok = 1;
  11764. flockfile(fi.access.fp);
  11765. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11766. ok = 0;
  11767. }
  11768. if (fflush(fi.access.fp) != 0) {
  11769. ok = 0;
  11770. }
  11771. funlockfile(fi.access.fp);
  11772. if (mg_fclose(&fi.access) != 0) {
  11773. ok = 0;
  11774. }
  11775. if (!ok) {
  11776. mg_cry(conn,
  11777. "Error writing log file %s",
  11778. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  11779. }
  11780. }
  11781. }
  11782. /* Verify given socket address against the ACL.
  11783. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  11784. */
  11785. static int
  11786. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  11787. {
  11788. int allowed, flag;
  11789. uint32_t net, mask;
  11790. struct vec vec;
  11791. if (phys_ctx) {
  11792. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  11793. /* If any ACL is set, deny by default */
  11794. allowed = (list == NULL) ? '+' : '-';
  11795. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11796. flag = vec.ptr[0];
  11797. if ((flag != '+' && flag != '-')
  11798. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  11799. mg_cry(fc(phys_ctx),
  11800. "%s: subnet must be [+|-]x.x.x.x[/x]",
  11801. __func__);
  11802. return -1;
  11803. }
  11804. if (net == (remote_ip & mask)) {
  11805. allowed = flag;
  11806. }
  11807. }
  11808. return allowed == '+';
  11809. }
  11810. return -1;
  11811. }
  11812. #if !defined(_WIN32)
  11813. static int
  11814. set_uid_option(struct mg_context *phys_ctx)
  11815. {
  11816. int success = 0;
  11817. if (phys_ctx) {
  11818. /* We are currently running as curr_uid. */
  11819. const uid_t curr_uid = getuid();
  11820. /* If set, we want to run as run_as_user. */
  11821. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  11822. const struct passwd *to_pw = NULL;
  11823. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  11824. /* run_as_user does not exist on the system. We can't proceed
  11825. * further. */
  11826. mg_cry(fc(phys_ctx),
  11827. "%s: unknown user [%s]",
  11828. __func__,
  11829. run_as_user);
  11830. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  11831. /* There was either no request to change user, or we're already
  11832. * running as run_as_user. Nothing else to do.
  11833. */
  11834. success = 1;
  11835. } else {
  11836. /* Valid change request. */
  11837. if (setgid(to_pw->pw_gid) == -1) {
  11838. mg_cry(fc(phys_ctx),
  11839. "%s: setgid(%s): %s",
  11840. __func__,
  11841. run_as_user,
  11842. strerror(errno));
  11843. } else if (setgroups(0, NULL) == -1) {
  11844. mg_cry(fc(phys_ctx),
  11845. "%s: setgroups(): %s",
  11846. __func__,
  11847. strerror(errno));
  11848. } else if (setuid(to_pw->pw_uid) == -1) {
  11849. mg_cry(fc(phys_ctx),
  11850. "%s: setuid(%s): %s",
  11851. __func__,
  11852. run_as_user,
  11853. strerror(errno));
  11854. } else {
  11855. success = 1;
  11856. }
  11857. }
  11858. }
  11859. return success;
  11860. }
  11861. #endif /* !_WIN32 */
  11862. static void
  11863. tls_dtor(void *key)
  11864. {
  11865. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  11866. /* key == pthread_getspecific(sTlsKey); */
  11867. if (tls) {
  11868. if (tls->is_master == 2) {
  11869. tls->is_master = -3; /* Mark memory as dead */
  11870. mg_free(tls);
  11871. }
  11872. }
  11873. pthread_setspecific(sTlsKey, NULL);
  11874. }
  11875. #if !defined(NO_SSL)
  11876. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  11877. struct mg_domain_context *dom_ctx,
  11878. const char *pem,
  11879. const char *chain);
  11880. static const char *ssl_error(void);
  11881. static int
  11882. refresh_trust(struct mg_connection *conn)
  11883. {
  11884. static int reload_lock = 0;
  11885. static long int data_check = 0;
  11886. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  11887. struct stat cert_buf;
  11888. long int t;
  11889. const char *pem;
  11890. const char *chain;
  11891. int should_verify_peer;
  11892. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  11893. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  11894. * refresh_trust still can not work. */
  11895. return 0;
  11896. }
  11897. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  11898. if (chain == NULL) {
  11899. /* pem is not NULL here */
  11900. chain = pem;
  11901. }
  11902. if (*chain == 0) {
  11903. chain = NULL;
  11904. }
  11905. t = data_check;
  11906. if (stat(pem, &cert_buf) != -1) {
  11907. t = (long int)cert_buf.st_mtime;
  11908. }
  11909. if (data_check != t) {
  11910. data_check = t;
  11911. should_verify_peer = 0;
  11912. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11913. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  11914. == 0) {
  11915. should_verify_peer = 1;
  11916. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  11917. "optional") == 0) {
  11918. should_verify_peer = 1;
  11919. }
  11920. }
  11921. if (should_verify_peer) {
  11922. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  11923. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  11924. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  11925. ca_file,
  11926. ca_path) != 1) {
  11927. mg_cry(fc(conn->phys_ctx),
  11928. "SSL_CTX_load_verify_locations error: %s "
  11929. "ssl_verify_peer requires setting "
  11930. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11931. "present in "
  11932. "the .conf file?",
  11933. ssl_error());
  11934. return 0;
  11935. }
  11936. }
  11937. if (1 == mg_atomic_inc(p_reload_lock)) {
  11938. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  11939. == 0) {
  11940. return 0;
  11941. }
  11942. *p_reload_lock = 0;
  11943. }
  11944. }
  11945. /* lock while cert is reloading */
  11946. while (*p_reload_lock) {
  11947. sleep(1);
  11948. }
  11949. return 1;
  11950. }
  11951. #ifdef OPENSSL_API_1_1
  11952. #else
  11953. static pthread_mutex_t *ssl_mutexes;
  11954. #endif /* OPENSSL_API_1_1 */
  11955. static int
  11956. sslize(struct mg_connection *conn,
  11957. SSL_CTX *s,
  11958. int (*func)(SSL *),
  11959. volatile int *stop_server)
  11960. {
  11961. int ret, err;
  11962. int short_trust;
  11963. unsigned i;
  11964. if (!conn) {
  11965. return 0;
  11966. }
  11967. short_trust =
  11968. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  11969. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  11970. if (short_trust) {
  11971. int trust_ret = refresh_trust(conn);
  11972. if (!trust_ret) {
  11973. return trust_ret;
  11974. }
  11975. }
  11976. conn->ssl = SSL_new(s);
  11977. if (conn->ssl == NULL) {
  11978. return 0;
  11979. }
  11980. SSL_set_app_data(conn->ssl, (char *)conn);
  11981. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  11982. if (ret != 1) {
  11983. err = SSL_get_error(conn->ssl, ret);
  11984. (void)err; /* TODO: set some error message */
  11985. SSL_free(conn->ssl);
  11986. conn->ssl = NULL;
  11987. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11988. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11989. #ifndef OPENSSL_API_1_1
  11990. ERR_remove_state(0);
  11991. #endif
  11992. return 0;
  11993. }
  11994. /* SSL functions may fail and require to be called again:
  11995. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  11996. * Here "func" could be SSL_connect or SSL_accept. */
  11997. for (i = 16; i <= 1024; i *= 2) {
  11998. ret = func(conn->ssl);
  11999. if (ret != 1) {
  12000. err = SSL_get_error(conn->ssl, ret);
  12001. if ((err == SSL_ERROR_WANT_CONNECT)
  12002. || (err == SSL_ERROR_WANT_ACCEPT)
  12003. || (err == SSL_ERROR_WANT_READ)
  12004. || (err == SSL_ERROR_WANT_WRITE)) {
  12005. /* Need to retry the function call "later".
  12006. * See https://linux.die.net/man/3/ssl_get_error
  12007. * This is typical for non-blocking sockets. */
  12008. if (*stop_server) {
  12009. /* Don't wait if the server is going to be stopped. */
  12010. break;
  12011. }
  12012. mg_sleep(i);
  12013. } else if (err == SSL_ERROR_SYSCALL) {
  12014. /* This is an IO error. Look at errno. */
  12015. err = errno;
  12016. /* TODO: set some error message */
  12017. (void)err;
  12018. break;
  12019. } else {
  12020. /* This is an SSL specific error */
  12021. /* TODO: set some error message */
  12022. break;
  12023. }
  12024. } else {
  12025. /* success */
  12026. break;
  12027. }
  12028. }
  12029. if (ret != 1) {
  12030. SSL_free(conn->ssl);
  12031. conn->ssl = NULL;
  12032. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12033. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12034. #ifndef OPENSSL_API_1_1
  12035. ERR_remove_state(0);
  12036. #endif
  12037. return 0;
  12038. }
  12039. return 1;
  12040. }
  12041. /* Return OpenSSL error message (from CRYPTO lib) */
  12042. static const char *
  12043. ssl_error(void)
  12044. {
  12045. unsigned long err;
  12046. err = ERR_get_error();
  12047. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  12048. }
  12049. static int
  12050. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  12051. {
  12052. int i;
  12053. const char hexdigit[] = "0123456789abcdef";
  12054. if ((memlen <= 0) || (buflen <= 0)) {
  12055. return 0;
  12056. }
  12057. if (buflen < (3 * memlen)) {
  12058. return 0;
  12059. }
  12060. for (i = 0; i < memlen; i++) {
  12061. if (i > 0) {
  12062. buf[3 * i - 1] = ' ';
  12063. }
  12064. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  12065. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  12066. }
  12067. buf[3 * memlen - 1] = 0;
  12068. return 1;
  12069. }
  12070. static void
  12071. ssl_get_client_cert_info(struct mg_connection *conn)
  12072. {
  12073. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  12074. if (cert) {
  12075. char str_subject[1024];
  12076. char str_issuer[1024];
  12077. char str_finger[1024];
  12078. unsigned char buf[256];
  12079. char *str_serial = NULL;
  12080. unsigned int ulen;
  12081. int ilen;
  12082. unsigned char *tmp_buf;
  12083. unsigned char *tmp_p;
  12084. /* Handle to algorithm used for fingerprint */
  12085. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  12086. /* Get Subject and issuer */
  12087. X509_NAME *subj = X509_get_subject_name(cert);
  12088. X509_NAME *iss = X509_get_issuer_name(cert);
  12089. /* Get serial number */
  12090. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  12091. /* Translate serial number to a hex string */
  12092. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12093. str_serial = BN_bn2hex(serial_bn);
  12094. BN_free(serial_bn);
  12095. /* Translate subject and issuer to a string */
  12096. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12097. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12098. /* Calculate SHA1 fingerprint and store as a hex string */
  12099. ulen = 0;
  12100. /* ASN1_digest is deprecated. Do the calculation manually,
  12101. * using EVP_Digest. */
  12102. ilen = i2d_X509(cert, NULL);
  12103. tmp_buf = (ilen > 0)
  12104. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  12105. conn->phys_ctx)
  12106. : NULL;
  12107. if (tmp_buf) {
  12108. tmp_p = tmp_buf;
  12109. (void)i2d_X509(cert, &tmp_p);
  12110. if (!EVP_Digest(
  12111. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12112. ulen = 0;
  12113. }
  12114. mg_free(tmp_buf);
  12115. }
  12116. if (!hexdump2string(
  12117. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12118. *str_finger = 0;
  12119. }
  12120. conn->request_info.client_cert = (struct mg_client_cert *)
  12121. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  12122. if (conn->request_info.client_cert) {
  12123. conn->request_info.client_cert->peer_cert = (void *)cert;
  12124. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  12125. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  12126. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  12127. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  12128. } else {
  12129. mg_cry(conn,
  12130. "Out of memory: Cannot allocate memory for client "
  12131. "certificate");
  12132. }
  12133. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  12134. * see https://linux.die.net/man/3/bn_bn2hex */
  12135. OPENSSL_free(str_serial);
  12136. }
  12137. }
  12138. #ifdef OPENSSL_API_1_1
  12139. #else
  12140. static void
  12141. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  12142. {
  12143. (void)line;
  12144. (void)file;
  12145. if (mode & 1) {
  12146. /* 1 is CRYPTO_LOCK */
  12147. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  12148. } else {
  12149. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  12150. }
  12151. }
  12152. #endif /* OPENSSL_API_1_1 */
  12153. #if !defined(NO_SSL_DL)
  12154. static void *
  12155. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  12156. {
  12157. union {
  12158. void *p;
  12159. void (*fp)(void);
  12160. } u;
  12161. void *dll_handle;
  12162. struct ssl_func *fp;
  12163. int ok;
  12164. int truncated = 0;
  12165. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  12166. mg_snprintf(NULL,
  12167. NULL, /* No truncation check for ebuf */
  12168. ebuf,
  12169. ebuf_len,
  12170. "%s: cannot load %s",
  12171. __func__,
  12172. dll_name);
  12173. return NULL;
  12174. }
  12175. ok = 1;
  12176. for (fp = sw; fp->name != NULL; fp++) {
  12177. #ifdef _WIN32
  12178. /* GetProcAddress() returns pointer to function */
  12179. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  12180. #else
  12181. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  12182. * pointers to function pointers. We need to use a union to make a
  12183. * cast. */
  12184. u.p = dlsym(dll_handle, fp->name);
  12185. #endif /* _WIN32 */
  12186. if (u.fp == NULL) {
  12187. if (ok) {
  12188. mg_snprintf(NULL,
  12189. &truncated,
  12190. ebuf,
  12191. ebuf_len,
  12192. "%s: %s: cannot find %s",
  12193. __func__,
  12194. dll_name,
  12195. fp->name);
  12196. ok = 0;
  12197. } else {
  12198. size_t cur_len = strlen(ebuf);
  12199. if (!truncated) {
  12200. mg_snprintf(NULL,
  12201. &truncated,
  12202. ebuf + cur_len,
  12203. ebuf_len - cur_len - 3,
  12204. ", %s",
  12205. fp->name);
  12206. if (truncated) {
  12207. /* If truncated, add "..." */
  12208. strcat(ebuf, "...");
  12209. }
  12210. }
  12211. }
  12212. /* Debug:
  12213. * printf("Missing function: %s\n", fp->name); */
  12214. } else {
  12215. fp->ptr = u.fp;
  12216. }
  12217. }
  12218. if (!ok) {
  12219. (void)dlclose(dll_handle);
  12220. return NULL;
  12221. }
  12222. return dll_handle;
  12223. }
  12224. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  12225. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  12226. #endif /* NO_SSL_DL */
  12227. #if defined(SSL_ALREADY_INITIALIZED)
  12228. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  12229. #else
  12230. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  12231. #endif
  12232. static int
  12233. initialize_ssl(char *ebuf, size_t ebuf_len)
  12234. {
  12235. #ifdef OPENSSL_API_1_1
  12236. if (ebuf_len > 0) {
  12237. ebuf[0] = 0;
  12238. }
  12239. #if !defined(NO_SSL_DL)
  12240. if (!cryptolib_dll_handle) {
  12241. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12242. if (!cryptolib_dll_handle) {
  12243. mg_snprintf(NULL,
  12244. NULL, /* No truncation check for ebuf */
  12245. ebuf,
  12246. ebuf_len,
  12247. "%s: error loading library %s",
  12248. __func__,
  12249. CRYPTO_LIB);
  12250. DEBUG_TRACE("%s", ebuf);
  12251. return 0;
  12252. }
  12253. }
  12254. #endif /* NO_SSL_DL */
  12255. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12256. return 1;
  12257. }
  12258. #else /* not OPENSSL_API_1_1 */
  12259. int i;
  12260. size_t size;
  12261. if (ebuf_len > 0) {
  12262. ebuf[0] = 0;
  12263. }
  12264. #if !defined(NO_SSL_DL)
  12265. if (!cryptolib_dll_handle) {
  12266. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12267. if (!cryptolib_dll_handle) {
  12268. mg_snprintf(NULL,
  12269. NULL, /* No truncation check for ebuf */
  12270. ebuf,
  12271. ebuf_len,
  12272. "%s: error loading library %s",
  12273. __func__,
  12274. CRYPTO_LIB);
  12275. DEBUG_TRACE("%s", ebuf);
  12276. return 0;
  12277. }
  12278. }
  12279. #endif /* NO_SSL_DL */
  12280. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12281. return 1;
  12282. }
  12283. /* Initialize locking callbacks, needed for thread safety.
  12284. * http://www.openssl.org/support/faq.html#PROG1
  12285. */
  12286. i = CRYPTO_num_locks();
  12287. if (i < 0) {
  12288. i = 0;
  12289. }
  12290. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  12291. if (size == 0) {
  12292. ssl_mutexes = NULL;
  12293. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  12294. mg_snprintf(NULL,
  12295. NULL, /* No truncation check for ebuf */
  12296. ebuf,
  12297. ebuf_len,
  12298. "%s: cannot allocate mutexes: %s",
  12299. __func__,
  12300. ssl_error());
  12301. DEBUG_TRACE("%s", ebuf);
  12302. return 0;
  12303. }
  12304. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12305. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  12306. }
  12307. CRYPTO_set_locking_callback(&ssl_locking_callback);
  12308. CRYPTO_set_id_callback(&mg_current_thread_id);
  12309. #endif /* OPENSSL_API_1_1 */
  12310. #if !defined(NO_SSL_DL)
  12311. if (!ssllib_dll_handle) {
  12312. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  12313. if (!ssllib_dll_handle) {
  12314. DEBUG_TRACE("%s", ebuf);
  12315. return 0;
  12316. }
  12317. }
  12318. #endif /* NO_SSL_DL */
  12319. #ifdef OPENSSL_API_1_1
  12320. /* Initialize SSL library */
  12321. OPENSSL_init_ssl(0, NULL);
  12322. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  12323. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  12324. NULL);
  12325. #else
  12326. /* Initialize SSL library */
  12327. SSL_library_init();
  12328. SSL_load_error_strings();
  12329. #endif
  12330. return 1;
  12331. }
  12332. static int
  12333. ssl_use_pem_file(struct mg_context *phys_ctx,
  12334. struct mg_domain_context *dom_ctx,
  12335. const char *pem,
  12336. const char *chain)
  12337. {
  12338. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12339. mg_cry(fc(phys_ctx),
  12340. "%s: cannot open certificate file %s: %s",
  12341. __func__,
  12342. pem,
  12343. ssl_error());
  12344. return 0;
  12345. }
  12346. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  12347. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12348. mg_cry(fc(phys_ctx),
  12349. "%s: cannot open private key file %s: %s",
  12350. __func__,
  12351. pem,
  12352. ssl_error());
  12353. return 0;
  12354. }
  12355. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  12356. mg_cry(fc(phys_ctx),
  12357. "%s: certificate and private key do not match: %s",
  12358. __func__,
  12359. pem);
  12360. return 0;
  12361. }
  12362. /* In contrast to OpenSSL, wolfSSL does not support certificate
  12363. * chain files that contain private keys and certificates in
  12364. * SSL_CTX_use_certificate_chain_file.
  12365. * The CivetWeb-Server used pem-Files that contained both information.
  12366. * In order to make wolfSSL work, it is split in two files.
  12367. * One file that contains key and certificate used by the server and
  12368. * an optional chain file for the ssl stack.
  12369. */
  12370. if (chain) {
  12371. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  12372. mg_cry(fc(phys_ctx),
  12373. "%s: cannot use certificate chain file %s: %s",
  12374. __func__,
  12375. pem,
  12376. ssl_error());
  12377. return 0;
  12378. }
  12379. }
  12380. return 1;
  12381. }
  12382. #ifdef OPENSSL_API_1_1
  12383. static unsigned long
  12384. ssl_get_protocol(int version_id)
  12385. {
  12386. long unsigned ret = SSL_OP_ALL;
  12387. if (version_id > 0)
  12388. ret |= SSL_OP_NO_SSLv2;
  12389. if (version_id > 1)
  12390. ret |= SSL_OP_NO_SSLv3;
  12391. if (version_id > 2)
  12392. ret |= SSL_OP_NO_TLSv1;
  12393. if (version_id > 3)
  12394. ret |= SSL_OP_NO_TLSv1_1;
  12395. return ret;
  12396. }
  12397. #else
  12398. static long
  12399. ssl_get_protocol(int version_id)
  12400. {
  12401. long ret = SSL_OP_ALL;
  12402. if (version_id > 0)
  12403. ret |= SSL_OP_NO_SSLv2;
  12404. if (version_id > 1)
  12405. ret |= SSL_OP_NO_SSLv3;
  12406. if (version_id > 2)
  12407. ret |= SSL_OP_NO_TLSv1;
  12408. if (version_id > 3)
  12409. ret |= SSL_OP_NO_TLSv1_1;
  12410. return ret;
  12411. }
  12412. #endif /* OPENSSL_API_1_1 */
  12413. /* SSL callback documentation:
  12414. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  12415. * https://linux.die.net/man/3/ssl_set_info_callback */
  12416. static void
  12417. ssl_info_callback(SSL *ssl, int what, int ret)
  12418. {
  12419. (void)ret;
  12420. if (what & SSL_CB_HANDSHAKE_START) {
  12421. SSL_get_app_data(ssl);
  12422. }
  12423. if (what & SSL_CB_HANDSHAKE_DONE) {
  12424. /* TODO: check for openSSL 1.1 */
  12425. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  12426. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  12427. }
  12428. }
  12429. static int
  12430. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  12431. {
  12432. struct mg_context *ctx = (struct mg_context *)arg;
  12433. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  12434. (void)ad;
  12435. /* Old clients (Win XP) will not support SNI. Then, there
  12436. * is no server name available in the request - we can
  12437. * only work with the default certificate.
  12438. * Multiple HTTPS hosts on one IP+port are only possible
  12439. * with a certificate containing all alternative names.
  12440. */
  12441. if ((servername == NULL) || (*servername == 0)) {
  12442. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  12443. return SSL_TLSEXT_ERR_NOACK;
  12444. }
  12445. DEBUG_TRACE("TLS connection to host %s", servername);
  12446. (void)ctx;
  12447. /* TODO for SNI: check all available server names.
  12448. * For the matching server name get the matching_ssl_ctx
  12449. * and call
  12450. * SSL_set_SSL_CTX(ssl, matching_ssl_ctx);
  12451. * to use this certificate. A different document_root
  12452. * may be required as well.
  12453. */
  12454. return SSL_TLSEXT_ERR_OK;
  12455. }
  12456. /* Setup SSL CTX as required by CivetWeb */
  12457. static int
  12458. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  12459. struct mg_domain_context *dom_ctx,
  12460. const char *pem,
  12461. const char *chain)
  12462. {
  12463. int callback_ret;
  12464. int should_verify_peer;
  12465. int peer_certificate_optional;
  12466. const char *ca_path;
  12467. const char *ca_file;
  12468. int use_default_verify_paths;
  12469. int verify_depth;
  12470. time_t now_rt = time(NULL);
  12471. struct timespec now_mt;
  12472. md5_byte_t ssl_context_id[16];
  12473. md5_state_t md5state;
  12474. int protocol_ver;
  12475. #ifdef OPENSSL_API_1_1
  12476. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  12477. mg_cry(fc(phys_ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  12478. return 0;
  12479. }
  12480. #else
  12481. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  12482. mg_cry(fc(phys_ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  12483. return 0;
  12484. }
  12485. #endif /* OPENSSL_API_1_1 */
  12486. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  12487. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  12488. | SSL_OP_NO_TLSv1_1);
  12489. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  12490. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  12491. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  12492. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  12493. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  12494. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12495. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  12496. #if !defined(NO_SSL_DL)
  12497. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  12498. #endif /* NO_SSL_DL */
  12499. #ifdef __clang__
  12500. #pragma clang diagnostic push
  12501. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  12502. #endif
  12503. /* Depending on the OpenSSL version, the callback may be
  12504. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  12505. * yielding in an "incompatible-pointer-type" warning for the other
  12506. * version. It seems to be "unclear" what is correct:
  12507. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  12508. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  12509. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  12510. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  12511. * Disable this warning here.
  12512. * Alternative would be a version dependent ssl_info_callback and
  12513. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  12514. */
  12515. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  12516. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  12517. ssl_servername_callback);
  12518. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  12519. #ifdef __clang__
  12520. #pragma clang diagnostic pop
  12521. #endif
  12522. /* If a callback has been specified, call it. */
  12523. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  12524. ? 0
  12525. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  12526. phys_ctx->user_data));
  12527. /* If callback returns 0, civetweb sets up the SSL certificate.
  12528. * If it returns 1, civetweb assumes the calback already did this.
  12529. * If it returns -1, initializing ssl fails. */
  12530. if (callback_ret < 0) {
  12531. mg_cry(fc(phys_ctx), "SSL callback returned error: %i", callback_ret);
  12532. return 0;
  12533. }
  12534. if (callback_ret > 0) {
  12535. /* Callback did everything. */
  12536. return 1;
  12537. }
  12538. /* Use some UID as session context ID. */
  12539. md5_init(&md5state);
  12540. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  12541. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  12542. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  12543. md5_append(&md5state,
  12544. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  12545. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  12546. md5_append(&md5state,
  12547. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  12548. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  12549. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  12550. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  12551. md5_finish(&md5state, ssl_context_id);
  12552. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  12553. (const unsigned char *)&ssl_context_id,
  12554. sizeof(ssl_context_id));
  12555. if (pem != NULL) {
  12556. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  12557. return 0;
  12558. }
  12559. }
  12560. /* Should we support client certificates? */
  12561. /* Default is "no". */
  12562. should_verify_peer = 0;
  12563. peer_certificate_optional = 0;
  12564. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12565. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  12566. /* Yes, they are mandatory */
  12567. should_verify_peer = 1;
  12568. peer_certificate_optional = 0;
  12569. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  12570. "optional") == 0) {
  12571. /* Yes, they are optional */
  12572. should_verify_peer = 1;
  12573. peer_certificate_optional = 1;
  12574. }
  12575. }
  12576. use_default_verify_paths =
  12577. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  12578. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  12579. == 0);
  12580. if (should_verify_peer) {
  12581. ca_path = dom_ctx->config[SSL_CA_PATH];
  12582. ca_file = dom_ctx->config[SSL_CA_FILE];
  12583. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  12584. != 1) {
  12585. mg_cry(fc(phys_ctx),
  12586. "SSL_CTX_load_verify_locations error: %s "
  12587. "ssl_verify_peer requires setting "
  12588. "either ssl_ca_path or ssl_ca_file. "
  12589. "Is any of them present in the "
  12590. ".conf file?",
  12591. ssl_error());
  12592. return 0;
  12593. }
  12594. if (peer_certificate_optional) {
  12595. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  12596. } else {
  12597. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  12598. SSL_VERIFY_PEER
  12599. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  12600. NULL);
  12601. }
  12602. if (use_default_verify_paths
  12603. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  12604. mg_cry(fc(phys_ctx),
  12605. "SSL_CTX_set_default_verify_paths error: %s",
  12606. ssl_error());
  12607. return 0;
  12608. }
  12609. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  12610. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  12611. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  12612. }
  12613. }
  12614. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  12615. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  12616. dom_ctx->config[SSL_CIPHER_LIST]) != 1) {
  12617. mg_cry(fc(phys_ctx),
  12618. "SSL_CTX_set_cipher_list error: %s",
  12619. ssl_error());
  12620. }
  12621. }
  12622. return 1;
  12623. }
  12624. /* Check if SSL is required.
  12625. * If so, dynamically load SSL library
  12626. * and set up ctx->ssl_ctx pointer. */
  12627. static int
  12628. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  12629. {
  12630. void *ssl_ctx = 0;
  12631. int callback_ret;
  12632. const char *pem;
  12633. const char *chain;
  12634. char ebuf[128];
  12635. if (!phys_ctx) {
  12636. return 0;
  12637. }
  12638. if (!is_ssl_port_used(phys_ctx->dd.config[LISTENING_PORTS])) {
  12639. /* No SSL port is set. No need to setup SSL. */
  12640. return 1;
  12641. }
  12642. if (!dom_ctx) {
  12643. dom_ctx = &(phys_ctx->dd);
  12644. }
  12645. /* Check for external SSL_CTX */
  12646. callback_ret =
  12647. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  12648. ? 0
  12649. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  12650. phys_ctx->user_data));
  12651. if (callback_ret < 0) {
  12652. mg_cry(fc(phys_ctx),
  12653. "external_ssl_ctx callback returned error: %i",
  12654. callback_ret);
  12655. return 0;
  12656. } else if (callback_ret > 0) {
  12657. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  12658. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12659. mg_cry(fc(phys_ctx), "%s", ebuf);
  12660. return 0;
  12661. }
  12662. return 1;
  12663. }
  12664. /* else: external_ssl_ctx does not exist or returns 0,
  12665. * CivetWeb should continue initializing SSL */
  12666. /* If PEM file is not specified and the init_ssl callback
  12667. * is not specified, setup will fail. */
  12668. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  12669. && (phys_ctx->callbacks.init_ssl == NULL)) {
  12670. /* No certificate and no callback:
  12671. * Essential data to set up TLS is missing.
  12672. */
  12673. mg_cry(fc(phys_ctx),
  12674. "Initializing SSL failed: -%s is not set",
  12675. config_options[SSL_CERTIFICATE].name);
  12676. return 0;
  12677. }
  12678. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12679. if (chain == NULL) {
  12680. chain = pem;
  12681. }
  12682. if ((chain != NULL) && (*chain == 0)) {
  12683. chain = NULL;
  12684. }
  12685. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12686. mg_cry(fc(phys_ctx), "%s", ebuf);
  12687. return 0;
  12688. }
  12689. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  12690. }
  12691. static void
  12692. uninitialize_ssl(void)
  12693. {
  12694. #ifdef OPENSSL_API_1_1
  12695. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12696. /* Shutdown according to
  12697. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12698. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12699. */
  12700. CONF_modules_unload(1);
  12701. #else
  12702. int i;
  12703. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12704. /* Shutdown according to
  12705. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12706. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12707. */
  12708. CRYPTO_set_locking_callback(NULL);
  12709. CRYPTO_set_id_callback(NULL);
  12710. ENGINE_cleanup();
  12711. CONF_modules_unload(1);
  12712. ERR_free_strings();
  12713. EVP_cleanup();
  12714. CRYPTO_cleanup_all_ex_data();
  12715. ERR_remove_state(0);
  12716. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12717. pthread_mutex_destroy(&ssl_mutexes[i]);
  12718. }
  12719. mg_free(ssl_mutexes);
  12720. ssl_mutexes = NULL;
  12721. #endif /* OPENSSL_API_1_1 */
  12722. }
  12723. }
  12724. #endif /* !NO_SSL */
  12725. static int
  12726. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  12727. {
  12728. if (phys_ctx) {
  12729. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12730. const char *path;
  12731. if (!dom_ctx) {
  12732. dom_ctx = &(phys_ctx->dd);
  12733. }
  12734. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  12735. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  12736. mg_cry(fc(phys_ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  12737. return 0;
  12738. }
  12739. return 1;
  12740. }
  12741. return 0;
  12742. }
  12743. static int
  12744. set_acl_option(struct mg_context *phys_ctx)
  12745. {
  12746. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  12747. }
  12748. static void
  12749. reset_per_request_attributes(struct mg_connection *conn)
  12750. {
  12751. if (!conn) {
  12752. return;
  12753. }
  12754. conn->connection_type =
  12755. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  12756. conn->num_bytes_sent = conn->consumed_content = 0;
  12757. conn->path_info = NULL;
  12758. conn->status_code = -1;
  12759. conn->content_len = -1;
  12760. conn->is_chunked = 0;
  12761. conn->must_close = 0;
  12762. conn->request_len = 0;
  12763. conn->throttle = 0;
  12764. conn->data_len = 0;
  12765. conn->chunk_remainder = 0;
  12766. conn->accept_gzip = 0;
  12767. conn->response_info.content_length = conn->request_info.content_length = -1;
  12768. conn->response_info.http_version = conn->request_info.http_version = NULL;
  12769. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  12770. conn->response_info.status_text = NULL;
  12771. conn->response_info.status_code = 0;
  12772. conn->request_info.remote_user = NULL;
  12773. conn->request_info.request_method = NULL;
  12774. conn->request_info.request_uri = NULL;
  12775. conn->request_info.local_uri = NULL;
  12776. #if defined(MG_LEGACY_INTERFACE)
  12777. /* Legacy before split into local_uri and request_uri */
  12778. conn->request_info.uri = NULL;
  12779. #endif
  12780. }
  12781. #if 0
  12782. /* Note: set_sock_timeout is not required for non-blocking sockets.
  12783. * Leave this function here (commented out) for reference until
  12784. * CivetWeb 1.9 is tested, and the tests confirme this function is
  12785. * no longer required.
  12786. */
  12787. static int
  12788. set_sock_timeout(SOCKET sock, int milliseconds)
  12789. {
  12790. int r0 = 0, r1, r2;
  12791. #ifdef _WIN32
  12792. /* Windows specific */
  12793. DWORD tv = (DWORD)milliseconds;
  12794. #else
  12795. /* Linux, ... (not Windows) */
  12796. struct timeval tv;
  12797. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  12798. * max. time waiting for the acknowledged of TCP data before the connection
  12799. * will be forcefully closed and ETIMEDOUT is returned to the application.
  12800. * If this option is not set, the default timeout of 20-30 minutes is used.
  12801. */
  12802. /* #define TCP_USER_TIMEOUT (18) */
  12803. #if defined(TCP_USER_TIMEOUT)
  12804. unsigned int uto = (unsigned int)milliseconds;
  12805. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  12806. #endif
  12807. memset(&tv, 0, sizeof(tv));
  12808. tv.tv_sec = milliseconds / 1000;
  12809. tv.tv_usec = (milliseconds * 1000) % 1000000;
  12810. #endif /* _WIN32 */
  12811. r1 = setsockopt(
  12812. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12813. r2 = setsockopt(
  12814. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12815. return r0 || r1 || r2;
  12816. }
  12817. #endif
  12818. static int
  12819. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  12820. {
  12821. if (setsockopt(sock,
  12822. IPPROTO_TCP,
  12823. TCP_NODELAY,
  12824. (SOCK_OPT_TYPE)&nodelay_on,
  12825. sizeof(nodelay_on)) != 0) {
  12826. /* Error */
  12827. return 1;
  12828. }
  12829. /* OK */
  12830. return 0;
  12831. }
  12832. static void
  12833. close_socket_gracefully(struct mg_connection *conn)
  12834. {
  12835. #if defined(_WIN32)
  12836. char buf[MG_BUF_LEN];
  12837. int n;
  12838. #endif
  12839. struct linger linger;
  12840. int error_code = 0;
  12841. int linger_timeout = -2;
  12842. socklen_t opt_len = sizeof(error_code);
  12843. if (!conn) {
  12844. return;
  12845. }
  12846. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  12847. * "Note that enabling a nonzero timeout on a nonblocking socket
  12848. * is not recommended.", so set it to blocking now */
  12849. set_blocking_mode(conn->client.sock);
  12850. /* Send FIN to the client */
  12851. shutdown(conn->client.sock, SHUTDOWN_WR);
  12852. #if defined(_WIN32)
  12853. /* Read and discard pending incoming data. If we do not do that and
  12854. * close
  12855. * the socket, the data in the send buffer may be discarded. This
  12856. * behaviour is seen on Windows, when client keeps sending data
  12857. * when server decides to close the connection; then when client
  12858. * does recv() it gets no data back. */
  12859. do {
  12860. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  12861. } while (n > 0);
  12862. #endif
  12863. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  12864. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  12865. }
  12866. /* Set linger option according to configuration */
  12867. if (linger_timeout >= 0) {
  12868. /* Set linger option to avoid socket hanging out after close. This
  12869. * prevent ephemeral port exhaust problem under high QPS. */
  12870. linger.l_onoff = 1;
  12871. #if defined(_MSC_VER)
  12872. #pragma warning(push)
  12873. #pragma warning(disable : 4244)
  12874. #endif
  12875. #if defined(__GNUC__) || defined(__MINGW32__)
  12876. #pragma GCC diagnostic push
  12877. #pragma GCC diagnostic ignored "-Wconversion"
  12878. #endif
  12879. /* Data type of linger structure elements may differ,
  12880. * so we don't know what cast we need here.
  12881. * Disable type conversion warnings. */
  12882. linger.l_linger = (linger_timeout + 999) / 1000;
  12883. #if defined(__GNUC__) || defined(__MINGW32__)
  12884. #pragma GCC diagnostic pop
  12885. #endif
  12886. #if defined(_MSC_VER)
  12887. #pragma warning(pop)
  12888. #endif
  12889. } else {
  12890. linger.l_onoff = 0;
  12891. linger.l_linger = 0;
  12892. }
  12893. if (linger_timeout < -1) {
  12894. /* Default: don't configure any linger */
  12895. } else if (getsockopt(conn->client.sock,
  12896. SOL_SOCKET,
  12897. SO_ERROR,
  12898. (char *)&error_code,
  12899. &opt_len) != 0) {
  12900. /* Cannot determine if socket is already closed. This should
  12901. * not occur and never did in a test. Log an error message
  12902. * and continue. */
  12903. mg_cry(conn,
  12904. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  12905. __func__,
  12906. strerror(ERRNO));
  12907. } else if (error_code == ECONNRESET) {
  12908. /* Socket already closed by client/peer, close socket without linger
  12909. */
  12910. } else {
  12911. /* Set linger timeout */
  12912. if (setsockopt(conn->client.sock,
  12913. SOL_SOCKET,
  12914. SO_LINGER,
  12915. (char *)&linger,
  12916. sizeof(linger)) != 0) {
  12917. mg_cry(conn,
  12918. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  12919. __func__,
  12920. linger.l_onoff,
  12921. linger.l_linger,
  12922. strerror(ERRNO));
  12923. }
  12924. }
  12925. /* Now we know that our FIN is ACK-ed, safe to close */
  12926. closesocket(conn->client.sock);
  12927. conn->client.sock = INVALID_SOCKET;
  12928. }
  12929. static void
  12930. close_connection(struct mg_connection *conn)
  12931. {
  12932. #if defined(USE_SERVER_STATS)
  12933. conn->conn_state = 6; /* to close */
  12934. #endif
  12935. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12936. if (conn->lua_websocket_state) {
  12937. lua_websocket_close(conn, conn->lua_websocket_state);
  12938. conn->lua_websocket_state = NULL;
  12939. }
  12940. #endif
  12941. mg_lock_connection(conn);
  12942. /* Set close flag, so keep-alive loops will stop */
  12943. conn->must_close = 1;
  12944. /* call the connection_close callback if assigned */
  12945. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  12946. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  12947. conn->phys_ctx->callbacks.connection_close(conn);
  12948. }
  12949. }
  12950. /* Reset user data, after close callback is called.
  12951. * Do not reuse it. If the user needs a destructor,
  12952. * it must be done in the connection_close callback. */
  12953. mg_set_user_connection_data(conn, NULL);
  12954. #if defined(USE_SERVER_STATS)
  12955. conn->conn_state = 7; /* closing */
  12956. #endif
  12957. #ifndef NO_SSL
  12958. if (conn->ssl != NULL) {
  12959. /* Run SSL_shutdown twice to ensure completly close SSL connection
  12960. */
  12961. SSL_shutdown(conn->ssl);
  12962. SSL_free(conn->ssl);
  12963. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12964. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12965. #ifndef OPENSSL_API_1_1
  12966. ERR_remove_state(0);
  12967. #endif
  12968. conn->ssl = NULL;
  12969. }
  12970. #endif
  12971. if (conn->client.sock != INVALID_SOCKET) {
  12972. close_socket_gracefully(conn);
  12973. conn->client.sock = INVALID_SOCKET;
  12974. }
  12975. mg_unlock_connection(conn);
  12976. #if defined(USE_SERVER_STATS)
  12977. conn->conn_state = 8; /* closed */
  12978. #endif
  12979. }
  12980. void
  12981. mg_close_connection(struct mg_connection *conn)
  12982. {
  12983. #if defined(USE_WEBSOCKET)
  12984. struct mg_context *client_ctx = NULL;
  12985. #endif /* defined(USE_WEBSOCKET) */
  12986. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  12987. return;
  12988. }
  12989. #if defined(USE_WEBSOCKET)
  12990. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  12991. if (conn->in_websocket_handling) {
  12992. /* Set close flag, so the server thread can exit. */
  12993. conn->must_close = 1;
  12994. return;
  12995. }
  12996. }
  12997. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  12998. unsigned int i;
  12999. /* ws/wss client */
  13000. client_ctx = conn->phys_ctx;
  13001. /* client context: loops must end */
  13002. client_ctx->stop_flag = 1;
  13003. conn->must_close = 1;
  13004. /* We need to get the client thread out of the select/recv call
  13005. * here. */
  13006. /* Since we use a sleep quantum of some seconds to check for recv
  13007. * timeouts, we will just wait a few seconds in mg_join_thread. */
  13008. /* join worker thread */
  13009. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  13010. if (client_ctx->worker_threadids[i] != 0) {
  13011. mg_join_thread(client_ctx->worker_threadids[i]);
  13012. }
  13013. }
  13014. }
  13015. #endif /* defined(USE_WEBSOCKET) */
  13016. close_connection(conn);
  13017. #ifndef NO_SSL
  13018. if (conn->client_ssl_ctx != NULL) {
  13019. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  13020. }
  13021. #endif
  13022. #if defined(USE_WEBSOCKET)
  13023. if (client_ctx != NULL) {
  13024. /* free context */
  13025. mg_free(client_ctx->worker_threadids);
  13026. mg_free(client_ctx);
  13027. (void)pthread_mutex_destroy(&conn->mutex);
  13028. mg_free(conn);
  13029. } else if (client_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  13030. mg_free(conn);
  13031. }
  13032. #else
  13033. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  13034. mg_free(conn);
  13035. }
  13036. #endif /* defined(USE_WEBSOCKET) */
  13037. }
  13038. /* Only for memory statistics */
  13039. static struct mg_context common_client_context;
  13040. static struct mg_connection *
  13041. mg_connect_client_impl(const struct mg_client_options *client_options,
  13042. int use_ssl,
  13043. char *ebuf,
  13044. size_t ebuf_len)
  13045. {
  13046. struct mg_connection *conn = NULL;
  13047. SOCKET sock;
  13048. union usa sa;
  13049. struct sockaddr *psa;
  13050. socklen_t len;
  13051. unsigned max_req_size =
  13052. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  13053. /* Size of structures, aligned to 8 bytes */
  13054. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  13055. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  13056. conn = (struct mg_connection *)mg_calloc_ctx(1,
  13057. conn_size + ctx_size
  13058. + max_req_size,
  13059. &common_client_context);
  13060. if (conn == NULL) {
  13061. mg_snprintf(NULL,
  13062. NULL, /* No truncation check for ebuf */
  13063. ebuf,
  13064. ebuf_len,
  13065. "calloc(): %s",
  13066. strerror(ERRNO));
  13067. return NULL;
  13068. }
  13069. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  13070. conn->buf = (((char *)conn) + conn_size + ctx_size);
  13071. conn->buf_size = (int)max_req_size;
  13072. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  13073. if (!connect_socket(&common_client_context,
  13074. client_options->host,
  13075. client_options->port,
  13076. use_ssl,
  13077. ebuf,
  13078. ebuf_len,
  13079. &sock,
  13080. &sa)) {
  13081. /* ebuf is set by connect_socket,
  13082. * free all memory and return NULL; */
  13083. mg_free(conn);
  13084. return NULL;
  13085. }
  13086. #ifndef NO_SSL
  13087. #ifdef OPENSSL_API_1_1
  13088. if (use_ssl
  13089. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  13090. mg_snprintf(NULL,
  13091. NULL, /* No truncation check for ebuf */
  13092. ebuf,
  13093. ebuf_len,
  13094. "SSL_CTX_new error");
  13095. closesocket(sock);
  13096. mg_free(conn);
  13097. return NULL;
  13098. }
  13099. #else
  13100. if (use_ssl
  13101. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  13102. == NULL) {
  13103. mg_snprintf(NULL,
  13104. NULL, /* No truncation check for ebuf */
  13105. ebuf,
  13106. ebuf_len,
  13107. "SSL_CTX_new error");
  13108. closesocket(sock);
  13109. mg_free(conn);
  13110. return NULL;
  13111. }
  13112. #endif /* OPENSSL_API_1_1 */
  13113. #endif /* NO_SSL */
  13114. #ifdef USE_IPV6
  13115. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  13116. : sizeof(conn->client.rsa.sin6);
  13117. psa = (sa.sa.sa_family == AF_INET)
  13118. ? (struct sockaddr *)&(conn->client.rsa.sin)
  13119. : (struct sockaddr *)&(conn->client.rsa.sin6);
  13120. #else
  13121. len = sizeof(conn->client.rsa.sin);
  13122. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  13123. #endif
  13124. conn->client.sock = sock;
  13125. conn->client.lsa = sa;
  13126. if (getsockname(sock, psa, &len) != 0) {
  13127. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  13128. }
  13129. conn->client.is_ssl = use_ssl ? 1 : 0;
  13130. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13131. #ifndef NO_SSL
  13132. if (use_ssl) {
  13133. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  13134. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  13135. * SSL_CTX_set_verify call is needed to switch off server
  13136. * certificate checking, which is off by default in OpenSSL and
  13137. * on in yaSSL. */
  13138. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  13139. * SSL_VERIFY_PEER, verify_ssl_server); */
  13140. if (client_options->client_cert) {
  13141. if (!ssl_use_pem_file(&common_client_context,
  13142. &(common_client_context.dd),
  13143. client_options->client_cert,
  13144. NULL)) {
  13145. mg_snprintf(NULL,
  13146. NULL, /* No truncation check for ebuf */
  13147. ebuf,
  13148. ebuf_len,
  13149. "Can not use SSL client certificate");
  13150. SSL_CTX_free(conn->client_ssl_ctx);
  13151. closesocket(sock);
  13152. mg_free(conn);
  13153. return NULL;
  13154. }
  13155. }
  13156. if (client_options->server_cert) {
  13157. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  13158. client_options->server_cert,
  13159. NULL);
  13160. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  13161. } else {
  13162. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  13163. }
  13164. if (!sslize(conn,
  13165. conn->client_ssl_ctx,
  13166. SSL_connect,
  13167. &(conn->phys_ctx->stop_flag))) {
  13168. mg_snprintf(NULL,
  13169. NULL, /* No truncation check for ebuf */
  13170. ebuf,
  13171. ebuf_len,
  13172. "SSL connection error");
  13173. SSL_CTX_free(conn->client_ssl_ctx);
  13174. closesocket(sock);
  13175. mg_free(conn);
  13176. return NULL;
  13177. }
  13178. }
  13179. #endif
  13180. if (0 != set_non_blocking_mode(sock)) {
  13181. /* TODO: handle error */
  13182. ;
  13183. }
  13184. return conn;
  13185. }
  13186. CIVETWEB_API struct mg_connection *
  13187. mg_connect_client_secure(const struct mg_client_options *client_options,
  13188. char *error_buffer,
  13189. size_t error_buffer_size)
  13190. {
  13191. return mg_connect_client_impl(client_options,
  13192. 1,
  13193. error_buffer,
  13194. error_buffer_size);
  13195. }
  13196. struct mg_connection *
  13197. mg_connect_client(const char *host,
  13198. int port,
  13199. int use_ssl,
  13200. char *error_buffer,
  13201. size_t error_buffer_size)
  13202. {
  13203. struct mg_client_options opts;
  13204. memset(&opts, 0, sizeof(opts));
  13205. opts.host = host;
  13206. opts.port = port;
  13207. return mg_connect_client_impl(&opts,
  13208. use_ssl,
  13209. error_buffer,
  13210. error_buffer_size);
  13211. }
  13212. static const struct {
  13213. const char *proto;
  13214. size_t proto_len;
  13215. unsigned default_port;
  13216. } abs_uri_protocols[] = {{"http://", 7, 80},
  13217. {"https://", 8, 443},
  13218. {"ws://", 5, 80},
  13219. {"wss://", 6, 443},
  13220. {NULL, 0, 0}};
  13221. /* Check if the uri is valid.
  13222. * return 0 for invalid uri,
  13223. * return 1 for *,
  13224. * return 2 for relative uri,
  13225. * return 3 for absolute uri without port,
  13226. * return 4 for absolute uri with port */
  13227. static int
  13228. get_uri_type(const char *uri)
  13229. {
  13230. int i;
  13231. const char *hostend, *portbegin;
  13232. char *portend;
  13233. unsigned long port;
  13234. /* According to the HTTP standard
  13235. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  13236. * URI can be an asterisk (*) or should start with slash (relative uri),
  13237. * or it should start with the protocol (absolute uri). */
  13238. if ((uri[0] == '*') && (uri[1] == '\0')) {
  13239. /* asterisk */
  13240. return 1;
  13241. }
  13242. /* Valid URIs according to RFC 3986
  13243. * (https://www.ietf.org/rfc/rfc3986.txt)
  13244. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  13245. * and unreserved characters A-Z a-z 0-9 and -._~
  13246. * and % encoded symbols.
  13247. */
  13248. for (i = 0; uri[i] != 0; i++) {
  13249. if (uri[i] < 33) {
  13250. /* control characters and spaces are invalid */
  13251. return 0;
  13252. }
  13253. if (uri[i] > 126) {
  13254. /* non-ascii characters must be % encoded */
  13255. return 0;
  13256. } else {
  13257. switch (uri[i]) {
  13258. case '"': /* 34 */
  13259. case '<': /* 60 */
  13260. case '>': /* 62 */
  13261. case '\\': /* 92 */
  13262. case '^': /* 94 */
  13263. case '`': /* 96 */
  13264. case '{': /* 123 */
  13265. case '|': /* 124 */
  13266. case '}': /* 125 */
  13267. return 0;
  13268. default:
  13269. /* character is ok */
  13270. break;
  13271. }
  13272. }
  13273. }
  13274. /* A relative uri starts with a / character */
  13275. if (uri[0] == '/') {
  13276. /* relative uri */
  13277. return 2;
  13278. }
  13279. /* It could be an absolute uri: */
  13280. /* This function only checks if the uri is valid, not if it is
  13281. * addressing the current server. So civetweb can also be used
  13282. * as a proxy server. */
  13283. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13284. if (mg_strncasecmp(uri,
  13285. abs_uri_protocols[i].proto,
  13286. abs_uri_protocols[i].proto_len) == 0) {
  13287. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  13288. if (!hostend) {
  13289. return 0;
  13290. }
  13291. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  13292. if (!portbegin) {
  13293. return 3;
  13294. }
  13295. port = strtoul(portbegin + 1, &portend, 10);
  13296. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  13297. return 0;
  13298. }
  13299. return 4;
  13300. }
  13301. }
  13302. return 0;
  13303. }
  13304. /* Return NULL or the relative uri at the current server */
  13305. static const char *
  13306. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  13307. {
  13308. const char *server_domain;
  13309. size_t server_domain_len;
  13310. size_t request_domain_len = 0;
  13311. unsigned long port = 0;
  13312. int i, auth_domain_check_enabled;
  13313. const char *hostbegin = NULL;
  13314. const char *hostend = NULL;
  13315. const char *portbegin;
  13316. char *portend;
  13317. auth_domain_check_enabled =
  13318. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  13319. /* DNS is case insensitive, so use case insensitive string compare here
  13320. */
  13321. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13322. if (mg_strncasecmp(uri,
  13323. abs_uri_protocols[i].proto,
  13324. abs_uri_protocols[i].proto_len) == 0) {
  13325. hostbegin = uri + abs_uri_protocols[i].proto_len;
  13326. hostend = strchr(hostbegin, '/');
  13327. if (!hostend) {
  13328. return 0;
  13329. }
  13330. portbegin = strchr(hostbegin, ':');
  13331. if ((!portbegin) || (portbegin > hostend)) {
  13332. port = abs_uri_protocols[i].default_port;
  13333. request_domain_len = (size_t)(hostend - hostbegin);
  13334. } else {
  13335. port = strtoul(portbegin + 1, &portend, 10);
  13336. if ((portend != hostend) || (port <= 0)
  13337. || !is_valid_port(port)) {
  13338. return 0;
  13339. }
  13340. request_domain_len = (size_t)(portbegin - hostbegin);
  13341. }
  13342. /* protocol found, port set */
  13343. break;
  13344. }
  13345. }
  13346. if (!port) {
  13347. /* port remains 0 if the protocol is not found */
  13348. return 0;
  13349. }
  13350. /* Check if the request is directed to a different server. */
  13351. /* First check if the port is the same (IPv4 and IPv6). */
  13352. #if defined(USE_IPV6)
  13353. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  13354. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  13355. /* Request is directed to a different port */
  13356. return 0;
  13357. }
  13358. } else
  13359. #endif
  13360. {
  13361. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  13362. /* Request is directed to a different port */
  13363. return 0;
  13364. }
  13365. }
  13366. /* Finally check if the server corresponds to the authentication
  13367. * domain of the server (the server domain).
  13368. * Allow full matches (like http://mydomain.com/path/file.ext), and
  13369. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  13370. * but do not allow substrings (like
  13371. * http://notmydomain.com/path/file.ext
  13372. * or http://mydomain.com.fake/path/file.ext).
  13373. */
  13374. if (auth_domain_check_enabled) {
  13375. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  13376. server_domain_len = strlen(server_domain);
  13377. if (!server_domain_len) {
  13378. return 0;
  13379. }
  13380. if ((request_domain_len == server_domain_len)
  13381. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  13382. /* Request is directed to this server - full name match. */
  13383. } else {
  13384. if (request_domain_len < (server_domain_len + 2)) {
  13385. /* Request is directed to another server: The server name is
  13386. * longer
  13387. * than
  13388. * the request name. Drop this case here to avoid overflows
  13389. * in
  13390. * the
  13391. * following checks. */
  13392. return 0;
  13393. }
  13394. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  13395. /* Request is directed to another server: It could be a
  13396. * substring
  13397. * like notmyserver.com */
  13398. return 0;
  13399. }
  13400. if (0 != memcmp(server_domain,
  13401. hostbegin + request_domain_len - server_domain_len,
  13402. server_domain_len)) {
  13403. /* Request is directed to another server:
  13404. * The server name is different. */
  13405. return 0;
  13406. }
  13407. }
  13408. }
  13409. return hostend;
  13410. }
  13411. static int
  13412. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13413. {
  13414. if (ebuf_len > 0) {
  13415. ebuf[0] = '\0';
  13416. }
  13417. *err = 0;
  13418. reset_per_request_attributes(conn);
  13419. if (!conn) {
  13420. mg_snprintf(conn,
  13421. NULL, /* No truncation check for ebuf */
  13422. ebuf,
  13423. ebuf_len,
  13424. "%s",
  13425. "Internal error");
  13426. *err = 500;
  13427. return 0;
  13428. }
  13429. /* Set the time the request was received. This value should be used for
  13430. * timeouts. */
  13431. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  13432. conn->request_len =
  13433. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  13434. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  13435. */
  13436. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  13437. mg_snprintf(conn,
  13438. NULL, /* No truncation check for ebuf */
  13439. ebuf,
  13440. ebuf_len,
  13441. "%s",
  13442. "Invalid message size");
  13443. *err = 500;
  13444. return 0;
  13445. }
  13446. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  13447. mg_snprintf(conn,
  13448. NULL, /* No truncation check for ebuf */
  13449. ebuf,
  13450. ebuf_len,
  13451. "%s",
  13452. "Message too large");
  13453. *err = 413;
  13454. return 0;
  13455. }
  13456. if (conn->request_len <= 0) {
  13457. if (conn->data_len > 0) {
  13458. mg_snprintf(conn,
  13459. NULL, /* No truncation check for ebuf */
  13460. ebuf,
  13461. ebuf_len,
  13462. "%s",
  13463. "Malformed message");
  13464. *err = 400;
  13465. } else {
  13466. /* Server did not recv anything -> just close the connection */
  13467. conn->must_close = 1;
  13468. mg_snprintf(conn,
  13469. NULL, /* No truncation check for ebuf */
  13470. ebuf,
  13471. ebuf_len,
  13472. "%s",
  13473. "No data received");
  13474. *err = 0;
  13475. }
  13476. return 0;
  13477. }
  13478. return 1;
  13479. }
  13480. static int
  13481. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13482. {
  13483. const char *cl;
  13484. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13485. return 0;
  13486. }
  13487. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  13488. <= 0) {
  13489. mg_snprintf(conn,
  13490. NULL, /* No truncation check for ebuf */
  13491. ebuf,
  13492. ebuf_len,
  13493. "%s",
  13494. "Bad request");
  13495. *err = 400;
  13496. return 0;
  13497. }
  13498. /* Message is a valid request */
  13499. if ((cl = get_header(conn->request_info.http_headers,
  13500. conn->request_info.num_headers,
  13501. "Content-Length")) != NULL) {
  13502. /* Request/response has content length set */
  13503. char *endptr = NULL;
  13504. conn->content_len = strtoll(cl, &endptr, 10);
  13505. if (endptr == cl) {
  13506. mg_snprintf(conn,
  13507. NULL, /* No truncation check for ebuf */
  13508. ebuf,
  13509. ebuf_len,
  13510. "%s",
  13511. "Bad request");
  13512. *err = 411;
  13513. return 0;
  13514. }
  13515. /* Publish the content length back to the request info. */
  13516. conn->request_info.content_length = conn->content_len;
  13517. } else if ((cl = get_header(conn->request_info.http_headers,
  13518. conn->request_info.num_headers,
  13519. "Transfer-Encoding")) != NULL
  13520. && !mg_strcasecmp(cl, "chunked")) {
  13521. conn->is_chunked = 1;
  13522. conn->content_len = -1; /* unknown content length */
  13523. } else if (get_http_method_info(conn->request_info.request_method)
  13524. ->request_has_body) {
  13525. /* POST or PUT request without content length set */
  13526. conn->content_len = -1; /* unknown content length */
  13527. } else {
  13528. /* Other request */
  13529. conn->content_len = 0; /* No content */
  13530. }
  13531. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  13532. return 1;
  13533. }
  13534. /* conn is assumed to be valid in this internal function */
  13535. static int
  13536. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13537. {
  13538. const char *cl;
  13539. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13540. return 0;
  13541. }
  13542. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  13543. <= 0) {
  13544. mg_snprintf(conn,
  13545. NULL, /* No truncation check for ebuf */
  13546. ebuf,
  13547. ebuf_len,
  13548. "%s",
  13549. "Bad response");
  13550. *err = 400;
  13551. return 0;
  13552. }
  13553. /* Message is a valid response */
  13554. if ((cl = get_header(conn->response_info.http_headers,
  13555. conn->response_info.num_headers,
  13556. "Content-Length")) != NULL) {
  13557. /* Request/response has content length set */
  13558. char *endptr = NULL;
  13559. conn->content_len = strtoll(cl, &endptr, 10);
  13560. if (endptr == cl) {
  13561. mg_snprintf(conn,
  13562. NULL, /* No truncation check for ebuf */
  13563. ebuf,
  13564. ebuf_len,
  13565. "%s",
  13566. "Bad request");
  13567. *err = 411;
  13568. return 0;
  13569. }
  13570. /* Publish the content length back to the response info. */
  13571. conn->response_info.content_length = conn->content_len;
  13572. /* TODO: check if it is still used in response_info */
  13573. conn->request_info.content_length = conn->content_len;
  13574. } else if ((cl = get_header(conn->response_info.http_headers,
  13575. conn->response_info.num_headers,
  13576. "Transfer-Encoding")) != NULL
  13577. && !mg_strcasecmp(cl, "chunked")) {
  13578. conn->is_chunked = 1;
  13579. conn->content_len = -1; /* unknown content length */
  13580. } else {
  13581. conn->content_len = -1; /* unknown content length */
  13582. }
  13583. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  13584. return 1;
  13585. }
  13586. int
  13587. mg_get_response(struct mg_connection *conn,
  13588. char *ebuf,
  13589. size_t ebuf_len,
  13590. int timeout)
  13591. {
  13592. int err, ret;
  13593. char txt[32]; /* will not overflow */
  13594. char *save_timeout;
  13595. char *new_timeout;
  13596. if (ebuf_len > 0) {
  13597. ebuf[0] = '\0';
  13598. }
  13599. if (!conn) {
  13600. mg_snprintf(conn,
  13601. NULL, /* No truncation check for ebuf */
  13602. ebuf,
  13603. ebuf_len,
  13604. "%s",
  13605. "Parameter error");
  13606. return -1;
  13607. }
  13608. /* Implementation of API function for HTTP clients */
  13609. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  13610. if (timeout >= 0) {
  13611. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  13612. new_timeout = txt;
  13613. /* Not required for non-blocking sockets.
  13614. set_sock_timeout(conn->client.sock, timeout);
  13615. */
  13616. } else {
  13617. new_timeout = NULL;
  13618. }
  13619. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  13620. ret = get_response(conn, ebuf, ebuf_len, &err);
  13621. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  13622. #if defined(MG_LEGACY_INTERFACE)
  13623. /* TODO: 1) uri is deprecated;
  13624. * 2) here, ri.uri is the http response code */
  13625. conn->request_info.uri = conn->request_info.request_uri;
  13626. #endif
  13627. conn->request_info.local_uri = conn->request_info.request_uri;
  13628. /* TODO (mid): Define proper return values - maybe return length?
  13629. * For the first test use <0 for error and >0 for OK */
  13630. return (ret == 0) ? -1 : +1;
  13631. }
  13632. struct mg_connection *
  13633. mg_download(const char *host,
  13634. int port,
  13635. int use_ssl,
  13636. char *ebuf,
  13637. size_t ebuf_len,
  13638. const char *fmt,
  13639. ...)
  13640. {
  13641. struct mg_connection *conn;
  13642. va_list ap;
  13643. int i;
  13644. int reqerr;
  13645. if (ebuf_len > 0) {
  13646. ebuf[0] = '\0';
  13647. }
  13648. va_start(ap, fmt);
  13649. /* open a connection */
  13650. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  13651. if (conn != NULL) {
  13652. i = mg_vprintf(conn, fmt, ap);
  13653. if (i <= 0) {
  13654. mg_snprintf(conn,
  13655. NULL, /* No truncation check for ebuf */
  13656. ebuf,
  13657. ebuf_len,
  13658. "%s",
  13659. "Error sending request");
  13660. } else {
  13661. get_response(conn, ebuf, ebuf_len, &reqerr);
  13662. #if defined(MG_LEGACY_INTERFACE)
  13663. /* TODO: 1) uri is deprecated;
  13664. * 2) here, ri.uri is the http response code */
  13665. conn->request_info.uri = conn->request_info.request_uri;
  13666. #endif
  13667. conn->request_info.local_uri = conn->request_info.request_uri;
  13668. }
  13669. }
  13670. /* if an error occured, close the connection */
  13671. if ((ebuf[0] != '\0') && (conn != NULL)) {
  13672. mg_close_connection(conn);
  13673. conn = NULL;
  13674. }
  13675. va_end(ap);
  13676. return conn;
  13677. }
  13678. struct websocket_client_thread_data {
  13679. struct mg_connection *conn;
  13680. mg_websocket_data_handler data_handler;
  13681. mg_websocket_close_handler close_handler;
  13682. void *callback_data;
  13683. };
  13684. #if defined(USE_WEBSOCKET)
  13685. #ifdef _WIN32
  13686. static unsigned __stdcall websocket_client_thread(void *data)
  13687. #else
  13688. static void *
  13689. websocket_client_thread(void *data)
  13690. #endif
  13691. {
  13692. struct websocket_client_thread_data *cdata =
  13693. (struct websocket_client_thread_data *)data;
  13694. mg_set_thread_name("ws-clnt");
  13695. if (cdata->conn->phys_ctx) {
  13696. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  13697. /* 3 indicates a websocket client thread */
  13698. /* TODO: check if conn->phys_ctx can be set */
  13699. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  13700. 3);
  13701. }
  13702. }
  13703. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  13704. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  13705. if (cdata->close_handler != NULL) {
  13706. cdata->close_handler(cdata->conn, cdata->callback_data);
  13707. }
  13708. /* The websocket_client context has only this thread. If it runs out,
  13709. set the stop_flag to 2 (= "stopped"). */
  13710. cdata->conn->phys_ctx->stop_flag = 2;
  13711. mg_free((void *)cdata);
  13712. #ifdef _WIN32
  13713. return 0;
  13714. #else
  13715. return NULL;
  13716. #endif
  13717. }
  13718. #endif
  13719. struct mg_connection *
  13720. mg_connect_websocket_client(const char *host,
  13721. int port,
  13722. int use_ssl,
  13723. char *error_buffer,
  13724. size_t error_buffer_size,
  13725. const char *path,
  13726. const char *origin,
  13727. mg_websocket_data_handler data_func,
  13728. mg_websocket_close_handler close_func,
  13729. void *user_data)
  13730. {
  13731. struct mg_connection *conn = NULL;
  13732. #if defined(USE_WEBSOCKET)
  13733. struct mg_context *newctx = NULL;
  13734. struct websocket_client_thread_data *thread_data;
  13735. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  13736. static const char *handshake_req;
  13737. if (origin != NULL) {
  13738. handshake_req = "GET %s HTTP/1.1\r\n"
  13739. "Host: %s\r\n"
  13740. "Upgrade: websocket\r\n"
  13741. "Connection: Upgrade\r\n"
  13742. "Sec-WebSocket-Key: %s\r\n"
  13743. "Sec-WebSocket-Version: 13\r\n"
  13744. "Origin: %s\r\n"
  13745. "\r\n";
  13746. } else {
  13747. handshake_req = "GET %s HTTP/1.1\r\n"
  13748. "Host: %s\r\n"
  13749. "Upgrade: websocket\r\n"
  13750. "Connection: Upgrade\r\n"
  13751. "Sec-WebSocket-Key: %s\r\n"
  13752. "Sec-WebSocket-Version: 13\r\n"
  13753. "\r\n";
  13754. }
  13755. /* Establish the client connection and request upgrade */
  13756. conn = mg_download(host,
  13757. port,
  13758. use_ssl,
  13759. error_buffer,
  13760. error_buffer_size,
  13761. handshake_req,
  13762. path,
  13763. host,
  13764. magic,
  13765. origin);
  13766. /* Connection object will be null if something goes wrong */
  13767. if (conn == NULL) {
  13768. if (!*error_buffer) {
  13769. /* There should be already an error message */
  13770. mg_snprintf(conn,
  13771. NULL, /* No truncation check for ebuf */
  13772. error_buffer,
  13773. error_buffer_size,
  13774. "Unexpected error");
  13775. }
  13776. return NULL;
  13777. }
  13778. if (conn->response_info.status_code != 101) {
  13779. /* We sent an "upgrade" request. For a correct websocket
  13780. * protocol handshake, we expect a "101 Continue" response.
  13781. * Otherwise it is a protocol violation. Maybe the HTTP
  13782. * Server does not know websockets. */
  13783. if (!*error_buffer) {
  13784. /* set an error, if not yet set */
  13785. mg_snprintf(conn,
  13786. NULL, /* No truncation check for ebuf */
  13787. error_buffer,
  13788. error_buffer_size,
  13789. "Unexpected server reply");
  13790. }
  13791. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  13792. mg_free(conn);
  13793. return NULL;
  13794. }
  13795. /* For client connections, mg_context is fake. Since we need to set a
  13796. * callback function, we need to create a copy and modify it. */
  13797. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  13798. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  13799. newctx->user_data = user_data;
  13800. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  13801. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  13802. newctx->worker_threadids =
  13803. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  13804. sizeof(pthread_t),
  13805. newctx);
  13806. conn->phys_ctx = newctx;
  13807. conn->dom_ctx = &(newctx->dd);
  13808. thread_data = (struct websocket_client_thread_data *)
  13809. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  13810. thread_data->conn = conn;
  13811. thread_data->data_handler = data_func;
  13812. thread_data->close_handler = close_func;
  13813. thread_data->callback_data = user_data;
  13814. /* Start a thread to read the websocket client connection
  13815. * This thread will automatically stop when mg_disconnect is
  13816. * called on the client connection */
  13817. if (mg_start_thread_with_id(websocket_client_thread,
  13818. (void *)thread_data,
  13819. newctx->worker_threadids) != 0) {
  13820. mg_free((void *)thread_data);
  13821. mg_free((void *)newctx->worker_threadids);
  13822. mg_free((void *)newctx);
  13823. mg_free((void *)conn);
  13824. conn = NULL;
  13825. DEBUG_TRACE("%s",
  13826. "Websocket client connect thread could not be started\r\n");
  13827. }
  13828. #else
  13829. /* Appease "unused parameter" warnings */
  13830. (void)host;
  13831. (void)port;
  13832. (void)use_ssl;
  13833. (void)error_buffer;
  13834. (void)error_buffer_size;
  13835. (void)path;
  13836. (void)origin;
  13837. (void)user_data;
  13838. (void)data_func;
  13839. (void)close_func;
  13840. #endif
  13841. return conn;
  13842. }
  13843. /* Prepare connection data structure */
  13844. static void
  13845. init_connection(struct mg_connection *conn)
  13846. {
  13847. /* Is keep alive allowed by the server */
  13848. int keep_alive_enabled =
  13849. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  13850. if (!keep_alive_enabled) {
  13851. conn->must_close = 1;
  13852. }
  13853. /* Important: on new connection, reset the receiving buffer. Credit
  13854. * goes to crule42. */
  13855. conn->data_len = 0;
  13856. conn->handled_requests = 0;
  13857. mg_set_user_connection_data(conn, NULL);
  13858. #if defined(USE_SERVER_STATS)
  13859. conn->conn_state = 2; /* init */
  13860. #endif
  13861. /* call the init_connection callback if assigned */
  13862. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  13863. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13864. void *conn_data = NULL;
  13865. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  13866. mg_set_user_connection_data(conn, conn_data);
  13867. }
  13868. }
  13869. }
  13870. /* Process a connection - may handle multiple requests
  13871. * using the same connection.
  13872. * Must be called with a valid connection (conn and
  13873. * conn->phys_ctx must be valid).
  13874. */
  13875. static void
  13876. process_new_connection(struct mg_connection *conn)
  13877. {
  13878. struct mg_request_info *ri = &conn->request_info;
  13879. int keep_alive, discard_len;
  13880. char ebuf[100];
  13881. const char *hostend;
  13882. int reqerr, uri_type;
  13883. #if defined(USE_SERVER_STATS)
  13884. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  13885. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  13886. if (mcon > (conn->phys_ctx->max_connections)) {
  13887. /* could use atomic compare exchange, but this
  13888. * seems overkill for statistics data */
  13889. conn->phys_ctx->max_connections = mcon;
  13890. }
  13891. #endif
  13892. init_connection(conn);
  13893. DEBUG_TRACE("Start processing connection from %s",
  13894. conn->request_info.remote_addr);
  13895. /* Loop over multiple requests sent using the same connection
  13896. * (while "keep alive"). */
  13897. do {
  13898. DEBUG_TRACE("calling get_request (%i times for this connection)",
  13899. conn->handled_requests + 1);
  13900. #if defined(USE_SERVER_STATS)
  13901. conn->conn_state = 3; /* ready */
  13902. #endif
  13903. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  13904. /* The request sent by the client could not be understood by
  13905. * the server, or it was incomplete or a timeout. Send an
  13906. * error message and close the connection. */
  13907. if (reqerr > 0) {
  13908. /*assert(ebuf[0] != '\0');*/
  13909. mg_send_http_error(conn, reqerr, "%s", ebuf);
  13910. }
  13911. } else if (strcmp(ri->http_version, "1.0")
  13912. && strcmp(ri->http_version, "1.1")) {
  13913. mg_snprintf(conn,
  13914. NULL, /* No truncation check for ebuf */
  13915. ebuf,
  13916. sizeof(ebuf),
  13917. "Bad HTTP version: [%s]",
  13918. ri->http_version);
  13919. mg_send_http_error(conn, 505, "%s", ebuf);
  13920. }
  13921. if (ebuf[0] == '\0') {
  13922. uri_type = get_uri_type(conn->request_info.request_uri);
  13923. switch (uri_type) {
  13924. case 1:
  13925. /* Asterisk */
  13926. conn->request_info.local_uri = NULL;
  13927. break;
  13928. case 2:
  13929. /* relative uri */
  13930. conn->request_info.local_uri = conn->request_info.request_uri;
  13931. break;
  13932. case 3:
  13933. case 4:
  13934. /* absolute uri (with/without port) */
  13935. hostend = get_rel_url_at_current_server(
  13936. conn->request_info.request_uri, conn);
  13937. if (hostend) {
  13938. conn->request_info.local_uri = hostend;
  13939. } else {
  13940. conn->request_info.local_uri = NULL;
  13941. }
  13942. break;
  13943. default:
  13944. mg_snprintf(conn,
  13945. NULL, /* No truncation check for ebuf */
  13946. ebuf,
  13947. sizeof(ebuf),
  13948. "Invalid URI");
  13949. mg_send_http_error(conn, 400, "%s", ebuf);
  13950. conn->request_info.local_uri = NULL;
  13951. break;
  13952. }
  13953. #if defined(MG_LEGACY_INTERFACE)
  13954. /* Legacy before split into local_uri and request_uri */
  13955. conn->request_info.uri = conn->request_info.local_uri;
  13956. #endif
  13957. }
  13958. DEBUG_TRACE("http: %s, error: %s",
  13959. (ri->http_version ? ri->http_version : "none"),
  13960. (ebuf[0] ? ebuf : "none"));
  13961. if (ebuf[0] == '\0') {
  13962. if (conn->request_info.local_uri) {
  13963. /* handle request to local server */
  13964. #if defined(USE_SERVER_STATS)
  13965. conn->conn_state = 4; /* processing */
  13966. #endif
  13967. handle_request(conn);
  13968. #if defined(USE_SERVER_STATS)
  13969. conn->conn_state = 5; /* processed */
  13970. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  13971. conn->consumed_content);
  13972. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  13973. conn->num_bytes_sent);
  13974. #endif
  13975. DEBUG_TRACE("%s", "handle_request done");
  13976. if (conn->phys_ctx->callbacks.end_request != NULL) {
  13977. conn->phys_ctx->callbacks.end_request(conn,
  13978. conn->status_code);
  13979. DEBUG_TRACE("%s", "end_request callback done");
  13980. }
  13981. log_access(conn);
  13982. } else {
  13983. /* TODO: handle non-local request (PROXY) */
  13984. conn->must_close = 1;
  13985. }
  13986. } else {
  13987. conn->must_close = 1;
  13988. }
  13989. if (ri->remote_user != NULL) {
  13990. mg_free((void *)ri->remote_user);
  13991. /* Important! When having connections with and without auth
  13992. * would cause double free and then crash */
  13993. ri->remote_user = NULL;
  13994. }
  13995. /* NOTE(lsm): order is important here. should_keep_alive() call
  13996. * is using parsed request, which will be invalid after
  13997. * memmove's below.
  13998. * Therefore, memorize should_keep_alive() result now for later
  13999. * use in loop exit condition. */
  14000. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  14001. && (conn->content_len >= 0);
  14002. /* Discard all buffered data for this request */
  14003. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  14004. && ((conn->request_len + conn->content_len)
  14005. < (int64_t)conn->data_len))
  14006. ? (int)(conn->request_len + conn->content_len)
  14007. : conn->data_len;
  14008. /*assert(discard_len >= 0);*/
  14009. if (discard_len < 0) {
  14010. DEBUG_TRACE("internal error: discard_len = %li",
  14011. (long int)discard_len);
  14012. break;
  14013. }
  14014. conn->data_len -= discard_len;
  14015. if (conn->data_len > 0) {
  14016. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  14017. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  14018. }
  14019. /* assert(conn->data_len >= 0); */
  14020. /* assert(conn->data_len <= conn->buf_size); */
  14021. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  14022. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  14023. (long int)conn->data_len,
  14024. (long int)conn->buf_size);
  14025. break;
  14026. }
  14027. conn->handled_requests++;
  14028. } while (keep_alive);
  14029. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  14030. conn->request_info.remote_addr,
  14031. difftime(time(NULL), conn->conn_birth_time));
  14032. close_connection(conn);
  14033. #if defined(USE_SERVER_STATS)
  14034. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  14035. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  14036. #endif
  14037. }
  14038. #if defined(ALTERNATIVE_QUEUE)
  14039. static void
  14040. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14041. {
  14042. unsigned int i;
  14043. for (;;) {
  14044. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14045. /* find a free worker slot and signal it */
  14046. if (ctx->client_socks[i].in_use == 0) {
  14047. ctx->client_socks[i] = *sp;
  14048. ctx->client_socks[i].in_use = 1;
  14049. event_signal(ctx->client_wait_events[i]);
  14050. return;
  14051. }
  14052. }
  14053. /* queue is full */
  14054. mg_sleep(1);
  14055. }
  14056. }
  14057. static int
  14058. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14059. {
  14060. DEBUG_TRACE("%s", "going idle");
  14061. ctx->client_socks[thread_index].in_use = 0;
  14062. event_wait(ctx->client_wait_events[thread_index]);
  14063. *sp = ctx->client_socks[thread_index];
  14064. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14065. return !ctx->stop_flag;
  14066. }
  14067. #else /* ALTERNATIVE_QUEUE */
  14068. /* Worker threads take accepted socket from the queue */
  14069. static int
  14070. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14071. {
  14072. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14073. (void)thread_index;
  14074. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14075. DEBUG_TRACE("%s", "going idle");
  14076. /* If the queue is empty, wait. We're idle at this point. */
  14077. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  14078. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  14079. }
  14080. /* If we're stopping, sq_head may be equal to sq_tail. */
  14081. if (ctx->sq_head > ctx->sq_tail) {
  14082. /* Copy socket from the queue and increment tail */
  14083. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  14084. ctx->sq_tail++;
  14085. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14086. /* Wrap pointers if needed */
  14087. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  14088. ctx->sq_tail -= QUEUE_SIZE(ctx);
  14089. ctx->sq_head -= QUEUE_SIZE(ctx);
  14090. }
  14091. }
  14092. (void)pthread_cond_signal(&ctx->sq_empty);
  14093. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14094. return !ctx->stop_flag;
  14095. #undef QUEUE_SIZE
  14096. }
  14097. /* Master thread adds accepted socket to a queue */
  14098. static void
  14099. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14100. {
  14101. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14102. if (!ctx) {
  14103. return;
  14104. }
  14105. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14106. /* If the queue is full, wait */
  14107. while ((ctx->stop_flag == 0)
  14108. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  14109. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  14110. }
  14111. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  14112. /* Copy socket to the queue and increment head */
  14113. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  14114. ctx->sq_head++;
  14115. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  14116. }
  14117. (void)pthread_cond_signal(&ctx->sq_full);
  14118. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14119. #undef QUEUE_SIZE
  14120. }
  14121. #endif /* ALTERNATIVE_QUEUE */
  14122. struct worker_thread_args {
  14123. struct mg_context *ctx;
  14124. int index;
  14125. };
  14126. static void *
  14127. worker_thread_run(struct worker_thread_args *thread_args)
  14128. {
  14129. struct mg_context *ctx = thread_args->ctx;
  14130. struct mg_connection *conn;
  14131. struct mg_workerTLS tls;
  14132. #if defined(MG_LEGACY_INTERFACE)
  14133. uint32_t addr;
  14134. #endif
  14135. mg_set_thread_name("worker");
  14136. tls.is_master = 0;
  14137. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14138. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14139. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14140. #endif
  14141. /* Initialize thread local storage before calling any callback */
  14142. pthread_setspecific(sTlsKey, &tls);
  14143. if (ctx->callbacks.init_thread) {
  14144. /* call init_thread for a worker thread (type 1) */
  14145. ctx->callbacks.init_thread(ctx, 1);
  14146. }
  14147. /* Connection structure has been pre-allocated */
  14148. if (((int)thread_args->index < 0)
  14149. || ((unsigned)thread_args->index
  14150. >= (unsigned)ctx->cfg_worker_threads)) {
  14151. mg_cry(fc(ctx),
  14152. "Internal error: Invalid worker index %i",
  14153. (int)thread_args->index);
  14154. return NULL;
  14155. }
  14156. conn = ctx->worker_connections + thread_args->index;
  14157. /* Request buffers are not pre-allocated. They are private to the
  14158. * request and do not contain any state information that might be
  14159. * of interest to anyone observing a server status. */
  14160. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  14161. if (conn->buf == NULL) {
  14162. mg_cry(fc(ctx),
  14163. "Out of memory: Cannot allocate buffer for worker %i",
  14164. (int)thread_args->index);
  14165. return NULL;
  14166. }
  14167. conn->buf_size = (int)ctx->max_request_size;
  14168. conn->phys_ctx = ctx;
  14169. conn->dom_ctx = &(ctx->dd); /* Use default domain, until more is knwon */
  14170. conn->thread_index = thread_args->index;
  14171. conn->request_info.user_data = ctx->user_data;
  14172. /* Allocate a mutex for this connection to allow communication both
  14173. * within the request handler and from elsewhere in the application
  14174. */
  14175. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  14176. #if defined(USE_SERVER_STATS)
  14177. conn->conn_state = 1; /* not consumed */
  14178. #endif
  14179. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  14180. * signal sq_empty condvar to wake up the master waiting in
  14181. * produce_socket() */
  14182. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  14183. conn->conn_birth_time = time(NULL);
  14184. /* Fill in IP, port info early so even if SSL setup below fails,
  14185. * error handler would have the corresponding info.
  14186. * Thanks to Johannes Winkelmann for the patch.
  14187. */
  14188. #if defined(USE_IPV6)
  14189. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  14190. conn->request_info.remote_port =
  14191. ntohs(conn->client.rsa.sin6.sin6_port);
  14192. } else
  14193. #endif
  14194. {
  14195. conn->request_info.remote_port =
  14196. ntohs(conn->client.rsa.sin.sin_port);
  14197. }
  14198. sockaddr_to_string(conn->request_info.remote_addr,
  14199. sizeof(conn->request_info.remote_addr),
  14200. &conn->client.rsa);
  14201. DEBUG_TRACE("Start processing connection from %s",
  14202. conn->request_info.remote_addr);
  14203. #if defined(MG_LEGACY_INTERFACE)
  14204. /* This legacy interface only works for the IPv4 case */
  14205. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  14206. memcpy(&conn->request_info.remote_ip, &addr, 4);
  14207. #endif
  14208. conn->request_info.is_ssl = conn->client.is_ssl;
  14209. if (conn->client.is_ssl) {
  14210. #ifndef NO_SSL
  14211. /* HTTPS connection */
  14212. if (sslize(conn,
  14213. conn->dom_ctx->ssl_ctx,
  14214. SSL_accept,
  14215. &(conn->phys_ctx->stop_flag))) {
  14216. /* Get SSL client certificate information (if set) */
  14217. ssl_get_client_cert_info(conn);
  14218. /* process HTTPS connection */
  14219. process_new_connection(conn);
  14220. /* Free client certificate info */
  14221. if (conn->request_info.client_cert) {
  14222. mg_free((void *)(conn->request_info.client_cert->subject));
  14223. mg_free((void *)(conn->request_info.client_cert->issuer));
  14224. mg_free((void *)(conn->request_info.client_cert->serial));
  14225. mg_free((void *)(conn->request_info.client_cert->finger));
  14226. /* Free certificate memory */
  14227. X509_free(
  14228. (X509 *)conn->request_info.client_cert->peer_cert);
  14229. conn->request_info.client_cert->peer_cert = 0;
  14230. conn->request_info.client_cert->subject = 0;
  14231. conn->request_info.client_cert->issuer = 0;
  14232. conn->request_info.client_cert->serial = 0;
  14233. conn->request_info.client_cert->finger = 0;
  14234. mg_free(conn->request_info.client_cert);
  14235. conn->request_info.client_cert = 0;
  14236. }
  14237. }
  14238. #endif
  14239. } else {
  14240. /* process HTTP connection */
  14241. process_new_connection(conn);
  14242. }
  14243. DEBUG_TRACE("%s", "Connection closed");
  14244. }
  14245. pthread_setspecific(sTlsKey, NULL);
  14246. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14247. CloseHandle(tls.pthread_cond_helper_mutex);
  14248. #endif
  14249. pthread_mutex_destroy(&conn->mutex);
  14250. /* Free the request buffer. */
  14251. conn->buf_size = 0;
  14252. mg_free(conn->buf);
  14253. conn->buf = NULL;
  14254. #if defined(USE_SERVER_STATS)
  14255. conn->conn_state = 9; /* done */
  14256. #endif
  14257. DEBUG_TRACE("%s", "exiting");
  14258. return NULL;
  14259. }
  14260. /* Threads have different return types on Windows and Unix. */
  14261. #ifdef _WIN32
  14262. static unsigned __stdcall worker_thread(void *thread_func_param)
  14263. {
  14264. struct worker_thread_args *pwta =
  14265. (struct worker_thread_args *)thread_func_param;
  14266. worker_thread_run(pwta);
  14267. mg_free(thread_func_param);
  14268. return 0;
  14269. }
  14270. #else
  14271. static void *
  14272. worker_thread(void *thread_func_param)
  14273. {
  14274. struct worker_thread_args *pwta =
  14275. (struct worker_thread_args *)thread_func_param;
  14276. worker_thread_run(pwta);
  14277. mg_free(thread_func_param);
  14278. return NULL;
  14279. }
  14280. #endif /* _WIN32 */
  14281. static void
  14282. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  14283. {
  14284. struct socket so;
  14285. char src_addr[IP_ADDR_STR_LEN];
  14286. socklen_t len = sizeof(so.rsa);
  14287. int on = 1;
  14288. if (!listener) {
  14289. return;
  14290. }
  14291. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  14292. == INVALID_SOCKET) {
  14293. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  14294. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  14295. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  14296. closesocket(so.sock);
  14297. } else {
  14298. /* Put so socket structure into the queue */
  14299. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  14300. set_close_on_exec(so.sock, fc(ctx));
  14301. so.is_ssl = listener->is_ssl;
  14302. so.ssl_redir = listener->ssl_redir;
  14303. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  14304. mg_cry(fc(ctx),
  14305. "%s: getsockname() failed: %s",
  14306. __func__,
  14307. strerror(ERRNO));
  14308. }
  14309. /* Set TCP keep-alive. This is needed because if HTTP-level
  14310. * keep-alive
  14311. * is enabled, and client resets the connection, server won't get
  14312. * TCP FIN or RST and will keep the connection open forever. With
  14313. * TCP keep-alive, next keep-alive handshake will figure out that
  14314. * the client is down and will close the server end.
  14315. * Thanks to Igor Klopov who suggested the patch. */
  14316. if (setsockopt(so.sock,
  14317. SOL_SOCKET,
  14318. SO_KEEPALIVE,
  14319. (SOCK_OPT_TYPE)&on,
  14320. sizeof(on)) != 0) {
  14321. mg_cry(fc(ctx),
  14322. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  14323. __func__,
  14324. strerror(ERRNO));
  14325. }
  14326. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  14327. * to effectively fill up the underlying IP packet payload and
  14328. * reduce the overhead of sending lots of small buffers. However
  14329. * this hurts the server's throughput (ie. operations per second)
  14330. * when HTTP 1.1 persistent connections are used and the responses
  14331. * are relatively small (eg. less than 1400 bytes).
  14332. */
  14333. if ((ctx != NULL) && (ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  14334. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  14335. if (set_tcp_nodelay(so.sock, 1) != 0) {
  14336. mg_cry(fc(ctx),
  14337. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  14338. __func__,
  14339. strerror(ERRNO));
  14340. }
  14341. }
  14342. /* We are using non-blocking sockets. Thus, the
  14343. * set_sock_timeout(so.sock, timeout);
  14344. * call is no longer required. */
  14345. /* The "non blocking" property should already be
  14346. * inherited from the parent socket. Set it for
  14347. * non-compliant socket implementations. */
  14348. set_non_blocking_mode(so.sock);
  14349. so.in_use = 0;
  14350. produce_socket(ctx, &so);
  14351. }
  14352. }
  14353. static void
  14354. master_thread_run(void *thread_func_param)
  14355. {
  14356. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  14357. struct mg_workerTLS tls;
  14358. struct pollfd *pfd;
  14359. unsigned int i;
  14360. unsigned int workerthreadcount;
  14361. if (!ctx) {
  14362. return;
  14363. }
  14364. mg_set_thread_name("master");
  14365. /* Increase priority of the master thread */
  14366. #if defined(_WIN32)
  14367. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  14368. #elif defined(USE_MASTER_THREAD_PRIORITY)
  14369. int min_prio = sched_get_priority_min(SCHED_RR);
  14370. int max_prio = sched_get_priority_max(SCHED_RR);
  14371. if ((min_prio >= 0) && (max_prio >= 0)
  14372. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  14373. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  14374. struct sched_param sched_param = {0};
  14375. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  14376. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  14377. }
  14378. #endif
  14379. /* Initialize thread local storage */
  14380. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14381. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14382. #endif
  14383. tls.is_master = 1;
  14384. pthread_setspecific(sTlsKey, &tls);
  14385. if (ctx->callbacks.init_thread) {
  14386. /* Callback for the master thread (type 0) */
  14387. ctx->callbacks.init_thread(ctx, 0);
  14388. }
  14389. /* Server starts *now* */
  14390. ctx->start_time = time(NULL);
  14391. /* Start the server */
  14392. pfd = ctx->listening_socket_fds;
  14393. while (ctx->stop_flag == 0) {
  14394. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14395. pfd[i].fd = ctx->listening_sockets[i].sock;
  14396. pfd[i].events = POLLIN;
  14397. }
  14398. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  14399. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14400. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  14401. * successful poll, and POLLIN is defined as
  14402. * (POLLRDNORM | POLLRDBAND)
  14403. * Therefore, we're checking pfd[i].revents & POLLIN, not
  14404. * pfd[i].revents == POLLIN. */
  14405. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  14406. accept_new_connection(&ctx->listening_sockets[i], ctx);
  14407. }
  14408. }
  14409. }
  14410. }
  14411. /* Here stop_flag is 1 - Initiate shutdown. */
  14412. DEBUG_TRACE("%s", "stopping workers");
  14413. /* Stop signal received: somebody called mg_stop. Quit. */
  14414. close_all_listening_sockets(ctx);
  14415. /* Wakeup workers that are waiting for connections to handle. */
  14416. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14417. #if defined(ALTERNATIVE_QUEUE)
  14418. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14419. event_signal(ctx->client_wait_events[i]);
  14420. /* Since we know all sockets, we can shutdown the connections. */
  14421. if (ctx->client_socks[i].in_use) {
  14422. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  14423. }
  14424. }
  14425. #else
  14426. pthread_cond_broadcast(&ctx->sq_full);
  14427. #endif
  14428. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14429. /* Join all worker threads to avoid leaking threads. */
  14430. workerthreadcount = ctx->cfg_worker_threads;
  14431. for (i = 0; i < workerthreadcount; i++) {
  14432. if (ctx->worker_threadids[i] != 0) {
  14433. mg_join_thread(ctx->worker_threadids[i]);
  14434. }
  14435. }
  14436. #if defined(USE_LUA)
  14437. /* Free Lua state of lua background task */
  14438. if (ctx->lua_background_state) {
  14439. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14440. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  14441. if (lua_istable(lstate, -1)) {
  14442. reg_boolean(lstate, "shutdown", 1);
  14443. lua_pop(lstate, 1);
  14444. mg_sleep(2);
  14445. }
  14446. lua_close(lstate);
  14447. ctx->lua_background_state = 0;
  14448. }
  14449. #endif
  14450. DEBUG_TRACE("%s", "exiting");
  14451. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14452. CloseHandle(tls.pthread_cond_helper_mutex);
  14453. #endif
  14454. pthread_setspecific(sTlsKey, NULL);
  14455. /* Signal mg_stop() that we're done.
  14456. * WARNING: This must be the very last thing this
  14457. * thread does, as ctx becomes invalid after this line. */
  14458. ctx->stop_flag = 2;
  14459. }
  14460. /* Threads have different return types on Windows and Unix. */
  14461. #ifdef _WIN32
  14462. static unsigned __stdcall master_thread(void *thread_func_param)
  14463. {
  14464. master_thread_run(thread_func_param);
  14465. return 0;
  14466. }
  14467. #else
  14468. static void *
  14469. master_thread(void *thread_func_param)
  14470. {
  14471. master_thread_run(thread_func_param);
  14472. return NULL;
  14473. }
  14474. #endif /* _WIN32 */
  14475. static void
  14476. free_context(struct mg_context *ctx)
  14477. {
  14478. int i;
  14479. struct mg_handler_info *tmp_rh;
  14480. if (ctx == NULL) {
  14481. return;
  14482. }
  14483. if (ctx->callbacks.exit_context) {
  14484. ctx->callbacks.exit_context(ctx);
  14485. }
  14486. /* All threads exited, no sync is needed. Destroy thread mutex and
  14487. * condvars
  14488. */
  14489. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  14490. #if defined(ALTERNATIVE_QUEUE)
  14491. mg_free(ctx->client_socks);
  14492. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14493. event_destroy(ctx->client_wait_events[i]);
  14494. }
  14495. mg_free(ctx->client_wait_events);
  14496. #else
  14497. (void)pthread_cond_destroy(&ctx->sq_empty);
  14498. (void)pthread_cond_destroy(&ctx->sq_full);
  14499. #endif
  14500. /* Destroy other context global data structures mutex */
  14501. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  14502. #if defined(USE_TIMERS)
  14503. timers_exit(ctx);
  14504. #endif
  14505. /* Deallocate config parameters */
  14506. for (i = 0; i < NUM_OPTIONS; i++) {
  14507. if (ctx->dd.config[i] != NULL) {
  14508. #if defined(_MSC_VER)
  14509. #pragma warning(suppress : 6001)
  14510. #endif
  14511. mg_free(ctx->dd.config[i]);
  14512. }
  14513. }
  14514. /* Deallocate request handlers */
  14515. while (ctx->dd.handlers) {
  14516. tmp_rh = ctx->dd.handlers;
  14517. ctx->dd.handlers = tmp_rh->next;
  14518. mg_free(tmp_rh->uri);
  14519. mg_free(tmp_rh);
  14520. }
  14521. #ifndef NO_SSL
  14522. /* Deallocate SSL context */
  14523. if (ctx->dd.ssl_ctx != NULL) {
  14524. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  14525. int callback_ret =
  14526. (ctx->callbacks.external_ssl_ctx == NULL)
  14527. ? 0
  14528. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  14529. if (callback_ret == 0) {
  14530. SSL_CTX_free(ctx->dd.ssl_ctx);
  14531. }
  14532. // else ignore error and ommit SSL_CTX_free in case callback_ret is 1
  14533. }
  14534. #endif /* !NO_SSL */
  14535. /* Deallocate worker thread ID array */
  14536. if (ctx->worker_threadids != NULL) {
  14537. mg_free(ctx->worker_threadids);
  14538. }
  14539. /* Deallocate worker thread ID array */
  14540. if (ctx->worker_connections != NULL) {
  14541. mg_free(ctx->worker_connections);
  14542. }
  14543. /* deallocate system name string */
  14544. mg_free(ctx->systemName);
  14545. /* Deallocate context itself */
  14546. mg_free(ctx);
  14547. }
  14548. void
  14549. mg_stop(struct mg_context *ctx)
  14550. {
  14551. pthread_t mt;
  14552. if (!ctx) {
  14553. return;
  14554. }
  14555. /* We don't use a lock here. Calling mg_stop with the same ctx from
  14556. * two threads is not allowed. */
  14557. mt = ctx->masterthreadid;
  14558. if (mt == 0) {
  14559. return;
  14560. }
  14561. ctx->masterthreadid = 0;
  14562. /* Set stop flag, so all threads know they have to exit. */
  14563. ctx->stop_flag = 1;
  14564. /* Wait until everything has stopped. */
  14565. while (ctx->stop_flag != 2) {
  14566. (void)mg_sleep(10);
  14567. }
  14568. mg_join_thread(mt);
  14569. free_context(ctx);
  14570. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14571. (void)WSACleanup();
  14572. #endif /* _WIN32 && !__SYMBIAN32__ */
  14573. }
  14574. static void
  14575. get_system_name(char **sysName)
  14576. {
  14577. #if defined(_WIN32)
  14578. #if !defined(__SYMBIAN32__)
  14579. #if defined(_WIN32_WCE)
  14580. *sysName = mg_strdup("WinCE");
  14581. #else
  14582. char name[128];
  14583. DWORD dwVersion = 0;
  14584. DWORD dwMajorVersion = 0;
  14585. DWORD dwMinorVersion = 0;
  14586. DWORD dwBuild = 0;
  14587. BOOL wowRet, isWoW = FALSE;
  14588. #ifdef _MSC_VER
  14589. #pragma warning(push)
  14590. /* GetVersion was declared deprecated */
  14591. #pragma warning(disable : 4996)
  14592. #endif
  14593. dwVersion = GetVersion();
  14594. #ifdef _MSC_VER
  14595. #pragma warning(pop)
  14596. #endif
  14597. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14598. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14599. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  14600. (void)dwBuild;
  14601. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  14602. sprintf(name,
  14603. "Windows %u.%u%s",
  14604. (unsigned)dwMajorVersion,
  14605. (unsigned)dwMinorVersion,
  14606. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  14607. *sysName = mg_strdup(name);
  14608. #endif
  14609. #else
  14610. *sysName = mg_strdup("Symbian");
  14611. #endif
  14612. #else
  14613. struct utsname name;
  14614. memset(&name, 0, sizeof(name));
  14615. uname(&name);
  14616. *sysName = mg_strdup(name.sysname);
  14617. #endif
  14618. }
  14619. struct mg_context *
  14620. mg_start(const struct mg_callbacks *callbacks,
  14621. void *user_data,
  14622. const char **options)
  14623. {
  14624. struct mg_context *ctx;
  14625. const char *name, *value, *default_value;
  14626. int idx, ok, workerthreadcount;
  14627. unsigned int i;
  14628. int itmp;
  14629. void (*exit_callback)(const struct mg_context *ctx) = 0;
  14630. struct mg_workerTLS tls;
  14631. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14632. WSADATA data;
  14633. WSAStartup(MAKEWORD(2, 2), &data);
  14634. #endif /* _WIN32 && !__SYMBIAN32__ */
  14635. /* Allocate context and initialize reasonable general case defaults. */
  14636. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  14637. return NULL;
  14638. }
  14639. /* Random number generator will initialize at the first call */
  14640. ctx->dd.auth_nonce_mask =
  14641. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  14642. if (mg_init_library_called == 0) {
  14643. /* Legacy INIT, if mg_start is called without mg_init_library.
  14644. * Note: This may cause a memory leak */
  14645. const char *ports_option =
  14646. config_options[LISTENING_PORTS].default_value;
  14647. if (options) {
  14648. const char **run_options = options;
  14649. const char *optname = config_options[LISTENING_PORTS].name;
  14650. /* Try to find the "listening_ports" option */
  14651. while (*run_options) {
  14652. if (!strcmp(*run_options, optname)) {
  14653. ports_option = run_options[1];
  14654. }
  14655. run_options += 2;
  14656. }
  14657. }
  14658. if (is_ssl_port_used(ports_option)) {
  14659. /* Initialize with SSL support */
  14660. mg_init_library(MG_FEATURES_TLS);
  14661. } else {
  14662. /* Initialize without SSL support */
  14663. mg_init_library(MG_FEATURES_DEFAULT);
  14664. }
  14665. }
  14666. tls.is_master = -1;
  14667. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14668. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14669. tls.pthread_cond_helper_mutex = NULL;
  14670. #endif
  14671. pthread_setspecific(sTlsKey, &tls);
  14672. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  14673. #if !defined(ALTERNATIVE_QUEUE)
  14674. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  14675. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  14676. #endif
  14677. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  14678. if (!ok) {
  14679. /* Fatal error - abort start. However, this situation should never
  14680. * occur in practice. */
  14681. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  14682. mg_free(ctx);
  14683. pthread_setspecific(sTlsKey, NULL);
  14684. return NULL;
  14685. }
  14686. if (callbacks) {
  14687. ctx->callbacks = *callbacks;
  14688. exit_callback = callbacks->exit_context;
  14689. ctx->callbacks.exit_context = 0;
  14690. }
  14691. ctx->user_data = user_data;
  14692. ctx->dd.handlers = NULL;
  14693. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14694. ctx->dd.shared_lua_websockets = 0;
  14695. #endif
  14696. while (options && (name = *options++) != NULL) {
  14697. if ((idx = get_option_index(name)) == -1) {
  14698. mg_cry(fc(ctx), "Invalid option: %s", name);
  14699. free_context(ctx);
  14700. pthread_setspecific(sTlsKey, NULL);
  14701. return NULL;
  14702. } else if ((value = *options++) == NULL) {
  14703. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  14704. free_context(ctx);
  14705. pthread_setspecific(sTlsKey, NULL);
  14706. return NULL;
  14707. }
  14708. if (ctx->dd.config[idx] != NULL) {
  14709. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  14710. mg_free(ctx->dd.config[idx]);
  14711. }
  14712. ctx->dd.config[idx] = mg_strdup(value);
  14713. DEBUG_TRACE("[%s] -> [%s]", name, value);
  14714. }
  14715. /* Set default value if needed */
  14716. for (i = 0; config_options[i].name != NULL; i++) {
  14717. default_value = config_options[i].default_value;
  14718. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  14719. ctx->dd.config[i] = mg_strdup(default_value);
  14720. }
  14721. }
  14722. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  14723. if (itmp < 1024) {
  14724. mg_cry(fc(ctx), "max_request_size too small");
  14725. free_context(ctx);
  14726. pthread_setspecific(sTlsKey, NULL);
  14727. return NULL;
  14728. }
  14729. ctx->max_request_size = (unsigned)itmp;
  14730. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  14731. if (workerthreadcount > MAX_WORKER_THREADS) {
  14732. mg_cry(fc(ctx), "Too many worker threads");
  14733. free_context(ctx);
  14734. pthread_setspecific(sTlsKey, NULL);
  14735. return NULL;
  14736. }
  14737. if (workerthreadcount <= 0) {
  14738. mg_cry(fc(ctx), "Invalid number of worker threads");
  14739. free_context(ctx);
  14740. pthread_setspecific(sTlsKey, NULL);
  14741. return NULL;
  14742. }
  14743. #if defined(NO_FILES)
  14744. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  14745. mg_cry(fc(ctx), "%s", "Document root must not be set");
  14746. free_context(ctx);
  14747. pthread_setspecific(sTlsKey, NULL);
  14748. return NULL;
  14749. }
  14750. #endif
  14751. get_system_name(&ctx->systemName);
  14752. #if defined(USE_LUA)
  14753. /* If a Lua background script has been configured, start it. */
  14754. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  14755. char ebuf[256];
  14756. struct vec opt_vec;
  14757. struct vec eq_vec;
  14758. const char *sparams;
  14759. lua_State *state = (void *)mg_prepare_lua_context_script(
  14760. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  14761. if (!state) {
  14762. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  14763. free_context(ctx);
  14764. pthread_setspecific(sTlsKey, NULL);
  14765. return NULL;
  14766. }
  14767. ctx->lua_background_state = (void *)state;
  14768. lua_newtable(state);
  14769. reg_boolean(state, "shutdown", 0);
  14770. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  14771. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  14772. reg_llstring(
  14773. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  14774. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  14775. break;
  14776. }
  14777. lua_setglobal(state, LUABACKGROUNDPARAMS);
  14778. } else {
  14779. ctx->lua_background_state = 0;
  14780. }
  14781. #endif
  14782. /* NOTE(lsm): order is important here. SSL certificates must
  14783. * be initialized before listening ports. UID must be set last. */
  14784. if (!set_gpass_option(ctx, NULL) ||
  14785. #if !defined(NO_SSL)
  14786. !init_ssl_ctx(ctx, NULL) ||
  14787. #endif
  14788. !set_ports_option(ctx) ||
  14789. #if !defined(_WIN32)
  14790. !set_uid_option(ctx) ||
  14791. #endif
  14792. !set_acl_option(ctx)) {
  14793. free_context(ctx);
  14794. pthread_setspecific(sTlsKey, NULL);
  14795. return NULL;
  14796. }
  14797. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  14798. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  14799. * won't kill the whole process. */
  14800. (void)signal(SIGPIPE, SIG_IGN);
  14801. #endif /* !_WIN32 && !__SYMBIAN32__ */
  14802. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  14803. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14804. sizeof(pthread_t),
  14805. ctx);
  14806. if (ctx->worker_threadids == NULL) {
  14807. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  14808. free_context(ctx);
  14809. pthread_setspecific(sTlsKey, NULL);
  14810. return NULL;
  14811. }
  14812. ctx->worker_connections =
  14813. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14814. sizeof(struct mg_connection),
  14815. ctx);
  14816. if (ctx->worker_connections == NULL) {
  14817. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  14818. free_context(ctx);
  14819. pthread_setspecific(sTlsKey, NULL);
  14820. return NULL;
  14821. }
  14822. #if defined(ALTERNATIVE_QUEUE)
  14823. ctx->client_wait_events =
  14824. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  14825. ctx->cfg_worker_threads,
  14826. ctx);
  14827. if (ctx->client_wait_events == NULL) {
  14828. mg_cry(fc(ctx), "Not enough memory for worker event array");
  14829. mg_free(ctx->worker_threadids);
  14830. free_context(ctx);
  14831. pthread_setspecific(sTlsKey, NULL);
  14832. return NULL;
  14833. }
  14834. ctx->client_socks =
  14835. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  14836. ctx->cfg_worker_threads,
  14837. ctx);
  14838. if (ctx->client_wait_events == NULL) {
  14839. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  14840. mg_free(ctx->client_socks);
  14841. mg_free(ctx->worker_threadids);
  14842. free_context(ctx);
  14843. pthread_setspecific(sTlsKey, NULL);
  14844. return NULL;
  14845. }
  14846. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14847. ctx->client_wait_events[i] = event_create();
  14848. if (ctx->client_wait_events[i] == 0) {
  14849. mg_cry(fc(ctx), "Error creating worker event %i", i);
  14850. while (i > 0) {
  14851. i--;
  14852. event_destroy(ctx->client_wait_events[i]);
  14853. }
  14854. mg_free(ctx->client_socks);
  14855. mg_free(ctx->worker_threadids);
  14856. free_context(ctx);
  14857. pthread_setspecific(sTlsKey, NULL);
  14858. return NULL;
  14859. }
  14860. }
  14861. #endif
  14862. #if defined(USE_TIMERS)
  14863. if (timers_init(ctx) != 0) {
  14864. mg_cry(fc(ctx), "Error creating timers");
  14865. free_context(ctx);
  14866. pthread_setspecific(sTlsKey, NULL);
  14867. return NULL;
  14868. }
  14869. #endif
  14870. /* Context has been created - init user libraries */
  14871. if (ctx->callbacks.init_context) {
  14872. ctx->callbacks.init_context(ctx);
  14873. }
  14874. ctx->callbacks.exit_context = exit_callback;
  14875. ctx->context_type = CONTEXT_SERVER; /* server context */
  14876. /* Start master (listening) thread */
  14877. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  14878. /* Start worker threads */
  14879. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14880. struct worker_thread_args *wta = (struct worker_thread_args *)
  14881. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  14882. if (wta) {
  14883. wta->ctx = ctx;
  14884. wta->index = (int)i;
  14885. }
  14886. if ((wta == NULL)
  14887. || (mg_start_thread_with_id(worker_thread,
  14888. wta,
  14889. &ctx->worker_threadids[i]) != 0)) {
  14890. /* thread was not created */
  14891. if (wta != NULL) {
  14892. mg_free(wta);
  14893. }
  14894. if (i > 0) {
  14895. mg_cry(fc(ctx),
  14896. "Cannot start worker thread %i: error %ld",
  14897. i + 1,
  14898. (long)ERRNO);
  14899. } else {
  14900. mg_cry(fc(ctx),
  14901. "Cannot create threads: error %ld",
  14902. (long)ERRNO);
  14903. free_context(ctx);
  14904. pthread_setspecific(sTlsKey, NULL);
  14905. return NULL;
  14906. }
  14907. break;
  14908. }
  14909. }
  14910. pthread_setspecific(sTlsKey, NULL);
  14911. return ctx;
  14912. }
  14913. /* Feature check API function */
  14914. unsigned
  14915. mg_check_feature(unsigned feature)
  14916. {
  14917. static const unsigned feature_set = 0
  14918. /* Set bits for available features according to API documentation.
  14919. * This bit mask is created at compile time, according to the active
  14920. * preprocessor defines. It is a single const value at runtime. */
  14921. #if !defined(NO_FILES)
  14922. | 0x0001u
  14923. #endif
  14924. #if !defined(NO_SSL)
  14925. | 0x0002u
  14926. #endif
  14927. #if !defined(NO_CGI)
  14928. | 0x0004u
  14929. #endif
  14930. #if defined(USE_IPV6)
  14931. | 0x0008u
  14932. #endif
  14933. #if defined(USE_WEBSOCKET)
  14934. | 0x0010u
  14935. #endif
  14936. #if defined(USE_LUA)
  14937. | 0x0020u
  14938. #endif
  14939. #if defined(USE_DUKTAPE)
  14940. | 0x0040u
  14941. #endif
  14942. #if !defined(NO_CACHING)
  14943. | 0x0080u
  14944. #endif
  14945. #if defined(USE_SERVER_STATS)
  14946. | 0x0100u
  14947. #endif
  14948. /* Set some extra bits not defined in the API documentation.
  14949. * These bits may change without further notice. */
  14950. #if defined(MG_LEGACY_INTERFACE)
  14951. | 0x8000u
  14952. #endif
  14953. #if defined(MEMORY_DEBUGGING)
  14954. | 0x0100u
  14955. #endif
  14956. #if defined(USE_TIMERS)
  14957. | 0x0200u
  14958. #endif
  14959. #if !defined(NO_NONCE_CHECK)
  14960. | 0x0400u
  14961. #endif
  14962. #if !defined(NO_POPEN)
  14963. | 0x0800u
  14964. #endif
  14965. ;
  14966. return (feature & feature_set);
  14967. }
  14968. /* strcat with additional NULL check to avoid clang scan-build warning. */
  14969. #define strcat0(a, b) \
  14970. { \
  14971. if ((a != NULL) && (b != NULL)) { \
  14972. strcat(a, b); \
  14973. } \
  14974. }
  14975. /* Get system information. It can be printed or stored by the caller.
  14976. * Return the size of available information. */
  14977. static int
  14978. mg_get_system_info_impl(char *buffer, int buflen)
  14979. {
  14980. char block[256];
  14981. int system_info_length = 0;
  14982. #if defined(_WIN32)
  14983. const char *eol = "\r\n";
  14984. #else
  14985. const char *eol = "\n";
  14986. #endif
  14987. const char *eoobj = "}";
  14988. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  14989. if ((buffer == NULL) || (buflen < 1)) {
  14990. buflen = 0;
  14991. } else {
  14992. *buffer = 0;
  14993. }
  14994. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  14995. system_info_length += (int)strlen(block);
  14996. if (system_info_length < buflen) {
  14997. strcat0(buffer, block);
  14998. }
  14999. /* Server version */
  15000. {
  15001. const char *version = mg_version();
  15002. mg_snprintf(NULL,
  15003. NULL,
  15004. block,
  15005. sizeof(block),
  15006. "\"version\" : \"%s\",%s",
  15007. version,
  15008. eol);
  15009. system_info_length += (int)strlen(block);
  15010. if (system_info_length < buflen) {
  15011. strcat0(buffer, block);
  15012. }
  15013. }
  15014. /* System info */
  15015. {
  15016. #if defined(_WIN32)
  15017. #if !defined(__SYMBIAN32__)
  15018. DWORD dwVersion = 0;
  15019. DWORD dwMajorVersion = 0;
  15020. DWORD dwMinorVersion = 0;
  15021. SYSTEM_INFO si;
  15022. GetSystemInfo(&si);
  15023. #ifdef _MSC_VER
  15024. #pragma warning(push)
  15025. /* GetVersion was declared deprecated */
  15026. #pragma warning(disable : 4996)
  15027. #endif
  15028. dwVersion = GetVersion();
  15029. #ifdef _MSC_VER
  15030. #pragma warning(pop)
  15031. #endif
  15032. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15033. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15034. mg_snprintf(NULL,
  15035. NULL,
  15036. block,
  15037. sizeof(block),
  15038. "\"os\" : \"Windows %u.%u\",%s",
  15039. (unsigned)dwMajorVersion,
  15040. (unsigned)dwMinorVersion,
  15041. eol);
  15042. system_info_length += (int)strlen(block);
  15043. if (system_info_length < buflen) {
  15044. strcat0(buffer, block);
  15045. }
  15046. mg_snprintf(NULL,
  15047. NULL,
  15048. block,
  15049. sizeof(block),
  15050. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  15051. (unsigned)si.wProcessorArchitecture,
  15052. (unsigned)si.dwNumberOfProcessors,
  15053. (unsigned)si.dwActiveProcessorMask,
  15054. eol);
  15055. system_info_length += (int)strlen(block);
  15056. if (system_info_length < buflen) {
  15057. strcat0(buffer, block);
  15058. }
  15059. #else
  15060. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  15061. system_info_length += (int)strlen(block);
  15062. if (system_info_length < buflen) {
  15063. strcat0(buffer, block);
  15064. }
  15065. #endif
  15066. #else
  15067. struct utsname name;
  15068. memset(&name, 0, sizeof(name));
  15069. uname(&name);
  15070. mg_snprintf(NULL,
  15071. NULL,
  15072. block,
  15073. sizeof(block),
  15074. "\"os\" : \"%s %s (%s) - %s\",%s",
  15075. name.sysname,
  15076. name.version,
  15077. name.release,
  15078. name.machine,
  15079. eol);
  15080. system_info_length += (int)strlen(block);
  15081. if (system_info_length < buflen) {
  15082. strcat0(buffer, block);
  15083. }
  15084. #endif
  15085. }
  15086. /* Features */
  15087. {
  15088. mg_snprintf(NULL,
  15089. NULL,
  15090. block,
  15091. sizeof(block),
  15092. "\"features\" : %lu,%s"
  15093. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  15094. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  15095. eol,
  15096. mg_check_feature(1) ? " Files" : "",
  15097. mg_check_feature(2) ? " HTTPS" : "",
  15098. mg_check_feature(4) ? " CGI" : "",
  15099. mg_check_feature(8) ? " IPv6" : "",
  15100. mg_check_feature(16) ? " WebSockets" : "",
  15101. mg_check_feature(32) ? " Lua" : "",
  15102. mg_check_feature(64) ? " JavaScript" : "",
  15103. mg_check_feature(128) ? " Cache" : "",
  15104. mg_check_feature(256) ? " Stats" : "",
  15105. eol);
  15106. system_info_length += (int)strlen(block);
  15107. if (system_info_length < buflen) {
  15108. strcat0(buffer, block);
  15109. }
  15110. #ifdef USE_LUA
  15111. mg_snprintf(NULL,
  15112. NULL,
  15113. block,
  15114. sizeof(block),
  15115. "\"lua_version\" : \"%u (%s)\",%s",
  15116. (unsigned)LUA_VERSION_NUM,
  15117. LUA_RELEASE,
  15118. eol);
  15119. system_info_length += (int)strlen(block);
  15120. if (system_info_length < buflen) {
  15121. strcat0(buffer, block);
  15122. }
  15123. #endif
  15124. #if defined(USE_DUKTAPE)
  15125. mg_snprintf(NULL,
  15126. NULL,
  15127. block,
  15128. sizeof(block),
  15129. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  15130. (unsigned)DUK_VERSION / 10000,
  15131. ((unsigned)DUK_VERSION / 100) % 100,
  15132. (unsigned)DUK_VERSION % 100,
  15133. eol);
  15134. system_info_length += (int)strlen(block);
  15135. if (system_info_length < buflen) {
  15136. strcat0(buffer, block);
  15137. }
  15138. #endif
  15139. }
  15140. /* Build date */
  15141. {
  15142. #if defined(__GNUC__)
  15143. #pragma GCC diagnostic push
  15144. /* Disable bogus compiler warning -Wdate-time */
  15145. #pragma GCC diagnostic ignored "-Wall"
  15146. #pragma GCC diagnostic ignored "-Werror"
  15147. #endif
  15148. mg_snprintf(NULL,
  15149. NULL,
  15150. block,
  15151. sizeof(block),
  15152. "\"build\" : \"%s\",%s",
  15153. __DATE__,
  15154. eol);
  15155. #if defined(__GNUC__)
  15156. #pragma GCC diagnostic pop
  15157. #endif
  15158. system_info_length += (int)strlen(block);
  15159. if (system_info_length < buflen) {
  15160. strcat0(buffer, block);
  15161. }
  15162. }
  15163. /* Compiler information */
  15164. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  15165. {
  15166. #if defined(_MSC_VER)
  15167. mg_snprintf(NULL,
  15168. NULL,
  15169. block,
  15170. sizeof(block),
  15171. "\"compiler\" : \"MSC: %u (%u)\",%s",
  15172. (unsigned)_MSC_VER,
  15173. (unsigned)_MSC_FULL_VER,
  15174. eol);
  15175. system_info_length += (int)strlen(block);
  15176. if (system_info_length < buflen) {
  15177. strcat0(buffer, block);
  15178. }
  15179. #elif defined(__MINGW64__)
  15180. mg_snprintf(NULL,
  15181. NULL,
  15182. block,
  15183. sizeof(block),
  15184. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  15185. (unsigned)__MINGW64_VERSION_MAJOR,
  15186. (unsigned)__MINGW64_VERSION_MINOR,
  15187. eol);
  15188. system_info_length += (int)strlen(block);
  15189. if (system_info_length < buflen) {
  15190. strcat0(buffer, block);
  15191. }
  15192. mg_snprintf(NULL,
  15193. NULL,
  15194. block,
  15195. sizeof(block),
  15196. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15197. (unsigned)__MINGW32_MAJOR_VERSION,
  15198. (unsigned)__MINGW32_MINOR_VERSION,
  15199. eol);
  15200. system_info_length += (int)strlen(block);
  15201. if (system_info_length < buflen) {
  15202. strcat0(buffer, block);
  15203. }
  15204. #elif defined(__MINGW32__)
  15205. mg_snprintf(NULL,
  15206. NULL,
  15207. block,
  15208. sizeof(block),
  15209. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15210. (unsigned)__MINGW32_MAJOR_VERSION,
  15211. (unsigned)__MINGW32_MINOR_VERSION,
  15212. eol);
  15213. system_info_length += (int)strlen(block);
  15214. if (system_info_length < buflen) {
  15215. strcat0(buffer, block);
  15216. }
  15217. #elif defined(__clang__)
  15218. mg_snprintf(NULL,
  15219. NULL,
  15220. block,
  15221. sizeof(block),
  15222. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  15223. __clang_major__,
  15224. __clang_minor__,
  15225. __clang_patchlevel__,
  15226. __clang_version__,
  15227. eol);
  15228. system_info_length += (int)strlen(block);
  15229. if (system_info_length < buflen) {
  15230. strcat0(buffer, block);
  15231. }
  15232. #elif defined(__GNUC__)
  15233. mg_snprintf(NULL,
  15234. NULL,
  15235. block,
  15236. sizeof(block),
  15237. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  15238. (unsigned)__GNUC__,
  15239. (unsigned)__GNUC_MINOR__,
  15240. (unsigned)__GNUC_PATCHLEVEL__,
  15241. eol);
  15242. system_info_length += (int)strlen(block);
  15243. if (system_info_length < buflen) {
  15244. strcat0(buffer, block);
  15245. }
  15246. #elif defined(__INTEL_COMPILER)
  15247. mg_snprintf(NULL,
  15248. NULL,
  15249. block,
  15250. sizeof(block),
  15251. "\"compiler\" : \"Intel C/C++: %u\",%s",
  15252. (unsigned)__INTEL_COMPILER,
  15253. eol);
  15254. system_info_length += (int)strlen(block);
  15255. if (system_info_length < buflen) {
  15256. strcat0(buffer, block);
  15257. }
  15258. #elif defined(__BORLANDC__)
  15259. mg_snprintf(NULL,
  15260. NULL,
  15261. block,
  15262. sizeof(block),
  15263. "\"compiler\" : \"Borland C: 0x%x\",%s",
  15264. (unsigned)__BORLANDC__,
  15265. eol);
  15266. system_info_length += (int)strlen(block);
  15267. if (system_info_length < buflen) {
  15268. strcat0(buffer, block);
  15269. }
  15270. #elif defined(__SUNPRO_C)
  15271. mg_snprintf(NULL,
  15272. NULL,
  15273. block,
  15274. sizeof(block),
  15275. "\"compiler\" : \"Solaris: 0x%x\",%s",
  15276. (unsigned)__SUNPRO_C,
  15277. eol);
  15278. system_info_length += (int)strlen(block);
  15279. if (system_info_length < buflen) {
  15280. strcat0(buffer, block);
  15281. }
  15282. #else
  15283. mg_snprintf(NULL,
  15284. NULL,
  15285. block,
  15286. sizeof(block),
  15287. "\"compiler\" : \"other\",%s",
  15288. eol);
  15289. system_info_length += (int)strlen(block);
  15290. if (system_info_length < buflen) {
  15291. strcat0(buffer, block);
  15292. }
  15293. #endif
  15294. }
  15295. /* Determine 32/64 bit data mode.
  15296. * see https://en.wikipedia.org/wiki/64-bit_computing */
  15297. {
  15298. mg_snprintf(
  15299. NULL,
  15300. NULL,
  15301. block,
  15302. sizeof(block),
  15303. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  15304. "ptr:%u, size:%u, time:%u\"%s",
  15305. (unsigned)sizeof(short),
  15306. (unsigned)sizeof(int),
  15307. (unsigned)sizeof(long),
  15308. (unsigned)sizeof(long long),
  15309. (unsigned)sizeof(float),
  15310. (unsigned)sizeof(double),
  15311. (unsigned)sizeof(long double),
  15312. (unsigned)sizeof(char),
  15313. (unsigned)sizeof(wchar_t),
  15314. (unsigned)sizeof(void *),
  15315. (unsigned)sizeof(size_t),
  15316. (unsigned)sizeof(time_t),
  15317. eol);
  15318. system_info_length += (int)strlen(block);
  15319. if (system_info_length < buflen) {
  15320. strcat0(buffer, block);
  15321. }
  15322. }
  15323. /* Terminate string */
  15324. if ((buflen > 0) && buffer && buffer[0]) {
  15325. if (system_info_length < buflen) {
  15326. strcat0(buffer, eoobj);
  15327. strcat0(buffer, eol);
  15328. }
  15329. }
  15330. system_info_length += reserved_len;
  15331. return system_info_length;
  15332. }
  15333. #if defined(USE_SERVER_STATS)
  15334. /* Get context information. It can be printed or stored by the caller.
  15335. * Return the size of available information. */
  15336. static int
  15337. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  15338. {
  15339. char block[256];
  15340. int context_info_length = 0;
  15341. #if defined(_WIN32)
  15342. const char *eol = "\r\n";
  15343. #else
  15344. const char *eol = "\n";
  15345. #endif
  15346. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  15347. const char *eoobj = "}";
  15348. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15349. if ((buffer == NULL) || (buflen < 1)) {
  15350. buflen = 0;
  15351. } else {
  15352. *buffer = 0;
  15353. }
  15354. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15355. context_info_length += (int)strlen(block);
  15356. if (context_info_length < buflen) {
  15357. strcat0(buffer, block);
  15358. }
  15359. /* Memory information */
  15360. if (ms) {
  15361. mg_snprintf(NULL,
  15362. NULL,
  15363. block,
  15364. sizeof(block),
  15365. "\"memory\" : {%s"
  15366. "\"blocks\" : %i,%s"
  15367. "\"used\" : %" INT64_FMT ",%s"
  15368. "\"maxUsed\" : %" INT64_FMT "%s"
  15369. "}%s%s",
  15370. eol,
  15371. ms->blockCount,
  15372. eol,
  15373. ms->totalMemUsed,
  15374. eol,
  15375. ms->maxMemUsed,
  15376. eol,
  15377. (ctx ? "," : ""),
  15378. eol);
  15379. context_info_length += (int)strlen(block);
  15380. if (context_info_length + reserved_len < buflen) {
  15381. strcat0(buffer, block);
  15382. }
  15383. }
  15384. /* Connections information */
  15385. if (ctx) {
  15386. mg_snprintf(NULL,
  15387. NULL,
  15388. block,
  15389. sizeof(block),
  15390. "\"connections\" : {%s"
  15391. "\"active\" : %i,%s"
  15392. "\"maxActive\" : %i,%s"
  15393. "\"total\" : %" INT64_FMT "%s"
  15394. "},%s",
  15395. eol,
  15396. ctx->active_connections,
  15397. eol,
  15398. ctx->max_connections,
  15399. eol,
  15400. ctx->total_connections,
  15401. eol,
  15402. eol);
  15403. context_info_length += (int)strlen(block);
  15404. if (context_info_length + reserved_len < buflen) {
  15405. strcat0(buffer, block);
  15406. }
  15407. }
  15408. /* Requests information */
  15409. if (ctx) {
  15410. mg_snprintf(NULL,
  15411. NULL,
  15412. block,
  15413. sizeof(block),
  15414. "\"requests\" : {%s"
  15415. "\"total\" : %" INT64_FMT "%s"
  15416. "},%s",
  15417. eol,
  15418. ctx->total_requests,
  15419. eol,
  15420. eol);
  15421. context_info_length += (int)strlen(block);
  15422. if (context_info_length + reserved_len < buflen) {
  15423. strcat0(buffer, block);
  15424. }
  15425. }
  15426. /* Data information */
  15427. if (ctx) {
  15428. mg_snprintf(NULL,
  15429. NULL,
  15430. block,
  15431. sizeof(block),
  15432. "\"data\" : {%s"
  15433. "\"read\" : %" INT64_FMT "%s,"
  15434. "\"written\" : %" INT64_FMT "%s"
  15435. "},%s",
  15436. eol,
  15437. ctx->total_data_read,
  15438. eol,
  15439. ctx->total_data_written,
  15440. eol,
  15441. eol);
  15442. context_info_length += (int)strlen(block);
  15443. if (context_info_length + reserved_len < buflen) {
  15444. strcat0(buffer, block);
  15445. }
  15446. }
  15447. /* Execution time information */
  15448. if (ctx) {
  15449. char start_time_str[64] = {0};
  15450. char now_str[64] = {0};
  15451. time_t start_time = ctx->start_time;
  15452. time_t now = time(NULL);
  15453. gmt_time_string(start_time_str,
  15454. sizeof(start_time_str) - 1,
  15455. &start_time);
  15456. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15457. mg_snprintf(NULL,
  15458. NULL,
  15459. block,
  15460. sizeof(block),
  15461. "\"time\" : {%s"
  15462. "\"uptime\" : %.0f,%s"
  15463. "\"start\" : \"%s\",%s"
  15464. "\"now\" : \"%s\"%s"
  15465. "}%s",
  15466. eol,
  15467. difftime(now, start_time),
  15468. eol,
  15469. start_time_str,
  15470. eol,
  15471. now_str,
  15472. eol,
  15473. eol);
  15474. context_info_length += (int)strlen(block);
  15475. if (context_info_length + reserved_len < buflen) {
  15476. strcat0(buffer, block);
  15477. }
  15478. }
  15479. /* Terminate string */
  15480. if ((buflen > 0) && buffer && buffer[0]) {
  15481. if (context_info_length < buflen) {
  15482. strcat0(buffer, eoobj);
  15483. strcat0(buffer, eol);
  15484. }
  15485. }
  15486. context_info_length += reserved_len;
  15487. return context_info_length;
  15488. }
  15489. #endif
  15490. #ifdef MG_EXPERIMENTAL_INTERFACES
  15491. /* Get connection information. It can be printed or stored by the caller.
  15492. * Return the size of available information. */
  15493. static int
  15494. mg_get_connection_info_impl(const struct mg_context *ctx,
  15495. int idx,
  15496. char *buffer,
  15497. int buflen)
  15498. {
  15499. const struct mg_connection *conn;
  15500. const struct mg_request_info *ri;
  15501. char block[256];
  15502. int connection_info_length = 0;
  15503. int state = 0;
  15504. const char *state_str = "unknown";
  15505. #if defined(_WIN32)
  15506. const char *eol = "\r\n";
  15507. #else
  15508. const char *eol = "\n";
  15509. #endif
  15510. const char *eoobj = "}";
  15511. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15512. if ((buffer == NULL) || (buflen < 1)) {
  15513. buflen = 0;
  15514. } else {
  15515. *buffer = 0;
  15516. }
  15517. if ((ctx == NULL) || (idx < 0)) {
  15518. /* Parameter error */
  15519. return 0;
  15520. }
  15521. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  15522. /* Out of range */
  15523. return 0;
  15524. }
  15525. /* Take connection [idx]. This connection is not locked in
  15526. * any way, so some other thread might use it. */
  15527. conn = (ctx->worker_connections) + idx;
  15528. /* Initialize output string */
  15529. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15530. connection_info_length += (int)strlen(block);
  15531. if (connection_info_length < buflen) {
  15532. strcat0(buffer, block);
  15533. }
  15534. /* Init variables */
  15535. ri = &(conn->request_info);
  15536. #if defined(USE_SERVER_STATS)
  15537. state = conn->conn_state;
  15538. /* State as string */
  15539. switch (state) {
  15540. case 0:
  15541. state_str = "undefined";
  15542. break;
  15543. case 1:
  15544. state_str = "not used";
  15545. break;
  15546. case 2:
  15547. state_str = "init";
  15548. break;
  15549. case 3:
  15550. state_str = "ready";
  15551. break;
  15552. case 4:
  15553. state_str = "processing";
  15554. break;
  15555. case 5:
  15556. state_str = "processed";
  15557. break;
  15558. case 6:
  15559. state_str = "to close";
  15560. break;
  15561. case 7:
  15562. state_str = "closing";
  15563. break;
  15564. case 8:
  15565. state_str = "closed";
  15566. break;
  15567. case 9:
  15568. state_str = "done";
  15569. break;
  15570. }
  15571. #endif
  15572. /* Connection info */
  15573. if ((state >= 3) && (state < 9)) {
  15574. mg_snprintf(NULL,
  15575. NULL,
  15576. block,
  15577. sizeof(block),
  15578. "\"connection\" : {%s"
  15579. "\"remote\" : {%s"
  15580. "\"protocol\" : \"%s\",%s"
  15581. "\"addr\" : \"%s\",%s"
  15582. "\"port\" : %u%s"
  15583. "},%s"
  15584. "\"handled_requests\" : %u%s"
  15585. "},%s",
  15586. eol,
  15587. eol,
  15588. get_proto_name(conn),
  15589. eol,
  15590. ri->remote_addr,
  15591. eol,
  15592. ri->remote_port,
  15593. eol,
  15594. eol,
  15595. conn->handled_requests,
  15596. eol,
  15597. eol);
  15598. connection_info_length += (int)strlen(block);
  15599. if (connection_info_length + reserved_len < buflen) {
  15600. strcat0(buffer, block);
  15601. }
  15602. }
  15603. /* Request info */
  15604. if ((state >= 4) && (state < 6)) {
  15605. mg_snprintf(NULL,
  15606. NULL,
  15607. block,
  15608. sizeof(block),
  15609. "\"request_info\" : {%s"
  15610. "\"method\" : \"%s\",%s"
  15611. "\"uri\" : \"%s\",%s"
  15612. "\"query\" : %s%s%s%s"
  15613. "},%s",
  15614. eol,
  15615. ri->request_method,
  15616. eol,
  15617. ri->request_uri,
  15618. eol,
  15619. ri->query_string ? "\"" : "",
  15620. ri->query_string ? ri->query_string : "null",
  15621. ri->query_string ? "\"" : "",
  15622. eol,
  15623. eol);
  15624. connection_info_length += (int)strlen(block);
  15625. if (connection_info_length + reserved_len < buflen) {
  15626. strcat0(buffer, block);
  15627. }
  15628. }
  15629. /* Execution time information */
  15630. if ((state >= 2) && (state < 9)) {
  15631. char start_time_str[64] = {0};
  15632. char now_str[64] = {0};
  15633. time_t start_time = conn->conn_birth_time;
  15634. time_t now = time(NULL);
  15635. gmt_time_string(start_time_str,
  15636. sizeof(start_time_str) - 1,
  15637. &start_time);
  15638. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15639. mg_snprintf(NULL,
  15640. NULL,
  15641. block,
  15642. sizeof(block),
  15643. "\"time\" : {%s"
  15644. "\"uptime\" : %.0f,%s"
  15645. "\"start\" : \"%s\",%s"
  15646. "\"now\" : \"%s\"%s"
  15647. "},%s",
  15648. eol,
  15649. difftime(now, start_time),
  15650. eol,
  15651. start_time_str,
  15652. eol,
  15653. now_str,
  15654. eol,
  15655. eol);
  15656. connection_info_length += (int)strlen(block);
  15657. if (connection_info_length + reserved_len < buflen) {
  15658. strcat0(buffer, block);
  15659. }
  15660. }
  15661. /* Remote user name */
  15662. if ((ri->remote_user) && (state < 9)) {
  15663. mg_snprintf(NULL,
  15664. NULL,
  15665. block,
  15666. sizeof(block),
  15667. "\"user\" : {%s"
  15668. "\"name\" : \"%s\",%s"
  15669. "},%s",
  15670. eol,
  15671. ri->remote_user,
  15672. eol,
  15673. eol);
  15674. connection_info_length += (int)strlen(block);
  15675. if (connection_info_length + reserved_len < buflen) {
  15676. strcat0(buffer, block);
  15677. }
  15678. }
  15679. /* Data block */
  15680. if (state >= 3) {
  15681. mg_snprintf(NULL,
  15682. NULL,
  15683. block,
  15684. sizeof(block),
  15685. "\"data\" : {%s"
  15686. "\"read\" : %" INT64_FMT ",%s"
  15687. "\"written\" : %" INT64_FMT "%s"
  15688. "},%s",
  15689. eol,
  15690. conn->consumed_content,
  15691. eol,
  15692. conn->num_bytes_sent,
  15693. eol,
  15694. eol);
  15695. connection_info_length += (int)strlen(block);
  15696. if (connection_info_length + reserved_len < buflen) {
  15697. strcat0(buffer, block);
  15698. }
  15699. }
  15700. /* State */
  15701. mg_snprintf(NULL,
  15702. NULL,
  15703. block,
  15704. sizeof(block),
  15705. "\"state\" : \"%s\"%s",
  15706. state_str,
  15707. eol);
  15708. connection_info_length += (int)strlen(block);
  15709. if (connection_info_length + reserved_len < buflen) {
  15710. strcat0(buffer, block);
  15711. }
  15712. /* Terminate string */
  15713. if ((buflen > 0) && buffer && buffer[0]) {
  15714. if (connection_info_length < buflen) {
  15715. strcat0(buffer, eoobj);
  15716. strcat0(buffer, eol);
  15717. }
  15718. }
  15719. connection_info_length += reserved_len;
  15720. return connection_info_length;
  15721. }
  15722. #endif
  15723. /* Get system information. It can be printed or stored by the caller.
  15724. * Return the size of available information. */
  15725. int
  15726. mg_get_system_info(char *buffer, int buflen)
  15727. {
  15728. if ((buffer == NULL) || (buflen < 1)) {
  15729. return mg_get_system_info_impl(NULL, 0);
  15730. } else {
  15731. /* Reset buffer, so we can always use strcat. */
  15732. buffer[0] = 0;
  15733. return mg_get_system_info_impl(buffer, buflen);
  15734. }
  15735. }
  15736. /* Get context information. It can be printed or stored by the caller.
  15737. * Return the size of available information. */
  15738. int
  15739. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  15740. {
  15741. #if defined(USE_SERVER_STATS)
  15742. if ((buffer == NULL) || (buflen < 1)) {
  15743. return mg_get_context_info_impl(ctx, NULL, 0);
  15744. } else {
  15745. /* Reset buffer, so we can always use strcat. */
  15746. buffer[0] = 0;
  15747. return mg_get_context_info_impl(ctx, buffer, buflen);
  15748. }
  15749. #else
  15750. (void)ctx;
  15751. if ((buffer != NULL) && (buflen > 0)) {
  15752. buffer[0] = 0;
  15753. }
  15754. return 0;
  15755. #endif
  15756. }
  15757. #ifdef MG_EXPERIMENTAL_INTERFACES
  15758. int
  15759. mg_get_connection_info(const struct mg_context *ctx,
  15760. int idx,
  15761. char *buffer,
  15762. int buflen)
  15763. {
  15764. if ((buffer == NULL) || (buflen < 1)) {
  15765. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  15766. } else {
  15767. /* Reset buffer, so we can always use strcat. */
  15768. buffer[0] = 0;
  15769. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  15770. }
  15771. }
  15772. #endif
  15773. /* Initialize this library. This function does not need to be thread safe.
  15774. */
  15775. unsigned
  15776. mg_init_library(unsigned features)
  15777. {
  15778. #if !defined(NO_SSL)
  15779. char ebuf[128];
  15780. #endif
  15781. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  15782. unsigned features_inited = features_to_init;
  15783. if (mg_init_library_called <= 0) {
  15784. /* Not initialized yet */
  15785. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  15786. return 0;
  15787. }
  15788. }
  15789. mg_global_lock();
  15790. if (mg_init_library_called <= 0) {
  15791. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  15792. /* Fatal error - abort start. However, this situation should
  15793. * never occur in practice. */
  15794. return 0;
  15795. }
  15796. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15797. InitializeCriticalSection(&global_log_file_lock);
  15798. #endif /* _WIN32 && !__SYMBIAN32__ */
  15799. #if !defined(_WIN32)
  15800. pthread_mutexattr_init(&pthread_mutex_attr);
  15801. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  15802. #endif
  15803. #if defined(USE_LUA)
  15804. lua_init_optional_libraries();
  15805. #endif
  15806. }
  15807. #if !defined(NO_SSL)
  15808. if (features_to_init & 2) {
  15809. if (!mg_ssl_initialized) {
  15810. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  15811. mg_ssl_initialized = 1;
  15812. } else {
  15813. (void)ebuf;
  15814. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  15815. features_inited &= ~(2u);
  15816. }
  15817. } else {
  15818. /* ssl already initialized */
  15819. }
  15820. }
  15821. #endif
  15822. /* Start WinSock for Windows */
  15823. if (mg_init_library_called <= 0) {
  15824. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15825. WSADATA data;
  15826. WSAStartup(MAKEWORD(2, 2), &data);
  15827. #endif /* _WIN32 && !__SYMBIAN32__ */
  15828. mg_init_library_called = 1;
  15829. } else {
  15830. mg_init_library_called++;
  15831. }
  15832. mg_global_unlock();
  15833. return features_inited;
  15834. }
  15835. /* Un-initialize this library. */
  15836. unsigned
  15837. mg_exit_library(void)
  15838. {
  15839. if (mg_init_library_called <= 0) {
  15840. return 0;
  15841. }
  15842. mg_global_lock();
  15843. mg_init_library_called--;
  15844. if (mg_init_library_called == 0) {
  15845. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15846. (void)WSACleanup();
  15847. #endif /* _WIN32 && !__SYMBIAN32__ */
  15848. #if !defined(NO_SSL)
  15849. if (mg_ssl_initialized) {
  15850. uninitialize_ssl();
  15851. mg_ssl_initialized = 0;
  15852. }
  15853. #endif
  15854. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15855. (void)DeleteCriticalSection(&global_log_file_lock);
  15856. #endif /* _WIN32 && !__SYMBIAN32__ */
  15857. #if !defined(_WIN32)
  15858. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  15859. #endif
  15860. (void)pthread_key_delete(sTlsKey);
  15861. #if defined(USE_LUA)
  15862. lua_exit_optional_libraries();
  15863. #endif
  15864. mg_global_unlock();
  15865. (void)pthread_mutex_destroy(&global_lock_mutex);
  15866. return 1;
  15867. }
  15868. mg_global_unlock();
  15869. return 1;
  15870. }
  15871. /* End of civetweb.c */