civetweb.c 500 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850
  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(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  76. #define mg_static_assert _Static_assert
  77. #elif defined(__cplusplus) && __cplusplus >= 201103L
  78. #define mg_static_assert static_assert
  79. #else
  80. char static_assert_replacement[1];
  81. #define mg_static_assert(cond, txt) \
  82. extern char static_assert_replacement[(cond) ? 1 : -1]
  83. #endif
  84. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  85. "int data type size check");
  86. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  87. "pointer data type size check");
  88. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  89. /* Alternative queue is well tested and should be the new default */
  90. #ifdef NO_ALTERNATIVE_QUEUE
  91. #ifdef ALTERNATIVE_QUEUE
  92. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  93. #endif
  94. #else
  95. #define ALTERNATIVE_QUEUE
  96. #endif
  97. /* DTL -- including winsock2.h works better if lean and mean */
  98. #ifndef WIN32_LEAN_AND_MEAN
  99. #define WIN32_LEAN_AND_MEAN
  100. #endif
  101. #if defined(__SYMBIAN32__)
  102. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  103. * Symbian is no longer maintained since 2014-01-01.
  104. * Recent versions of CivetWeb are no longer tested for Symbian.
  105. * It makes no sense, to support an abandoned operating system.
  106. * All remaining "#ifdef __SYMBIAN__" cases will be dropped from
  107. * the code sooner or later.
  108. */
  109. #pragma message \
  110. "Symbian is no longer maintained. CivetWeb will drop Symbian support."
  111. #define NO_SSL /* SSL is not supported */
  112. #define NO_CGI /* CGI is not supported */
  113. #define PATH_MAX FILENAME_MAX
  114. #endif /* __SYMBIAN32__ */
  115. #ifndef CIVETWEB_HEADER_INCLUDED
  116. /* Include the header file here, so the CivetWeb interface is defined for the
  117. * entire implementation, including the following forward definitions. */
  118. #include "civetweb.h"
  119. #endif
  120. #if !defined(DEBUG_TRACE)
  121. #if defined(DEBUG)
  122. static void DEBUG_TRACE_FUNC(const char *func,
  123. unsigned line,
  124. PRINTF_FORMAT_STRING(const char *fmt),
  125. ...) PRINTF_ARGS(3, 4);
  126. #define DEBUG_TRACE(fmt, ...) \
  127. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  128. #define NEED_DEBUG_TRACE_FUNC
  129. #else
  130. #define DEBUG_TRACE(fmt, ...) \
  131. do { \
  132. } while (0)
  133. #endif /* DEBUG */
  134. #endif /* DEBUG_TRACE */
  135. #if !defined(DEBUG_ASSERT)
  136. #if defined(DEBUG)
  137. #define DEBUG_ASSERT(cond) \
  138. do { \
  139. if (!(cond)) { \
  140. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  141. exit(2); /* Exit with error */ \
  142. } \
  143. } while (0)
  144. #else
  145. #define DEBUG_ASSERT(cond)
  146. #endif /* DEBUG */
  147. #endif
  148. #ifndef IGNORE_UNUSED_RESULT
  149. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  150. #endif
  151. #if defined(__GNUC__) || defined(__MINGW32__)
  152. /* GCC unused function attribute seems fundamentally broken.
  153. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  154. * OR UNUSED" for individual functions failed.
  155. * Either the compiler creates an "unused-function" warning if a
  156. * function is not marked with __attribute__((unused)).
  157. * On the other hand, if the function is marked with this attribute,
  158. * but is used, the compiler raises a completely idiotic
  159. * "used-but-marked-unused" warning - and
  160. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  161. * raises error: unknown option after "#pragma GCC diagnostic".
  162. * Disable this warning completely, until the GCC guys sober up
  163. * again.
  164. */
  165. #pragma GCC diagnostic ignored "-Wunused-function"
  166. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  167. #else
  168. #define FUNCTION_MAY_BE_UNUSED
  169. #endif
  170. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  171. #include <sys/types.h>
  172. #include <sys/stat.h>
  173. #include <errno.h>
  174. #include <signal.h>
  175. #include <fcntl.h>
  176. #endif /* !_WIN32_WCE */
  177. #ifdef __clang__
  178. /* When using -Weverything, clang does not accept it's own headers
  179. * in a release build configuration. Disable what is too much in
  180. * -Weverything. */
  181. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  182. #endif
  183. #if defined(__GNUC__) || defined(__MINGW32__)
  184. /* Who on earth came to the conclusion, using __DATE__ should rise
  185. * an "expansion of date or time macro is not reproducible"
  186. * warning. That's exactly what was intended by using this macro.
  187. * Just disable this nonsense warning. */
  188. /* And disabling them does not work either:
  189. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  190. * #pragma clang diagnostic ignored "-Wdate-time"
  191. * So we just have to disable ALL warnings for some lines
  192. * of code.
  193. * This seems to be a known GCC bug, not resolved since 2012:
  194. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  195. */
  196. #endif
  197. #ifdef __MACH__ /* Apple OSX section */
  198. #ifdef __clang__
  199. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  200. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  201. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  202. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  203. #endif
  204. #endif
  205. #define CLOCK_MONOTONIC (1)
  206. #define CLOCK_REALTIME (2)
  207. #include <sys/errno.h>
  208. #include <sys/time.h>
  209. #include <mach/clock.h>
  210. #include <mach/mach.h>
  211. #include <mach/mach_time.h>
  212. /* clock_gettime is not implemented on OSX prior to 10.12 */
  213. static int
  214. _civet_clock_gettime(int clk_id, struct timespec *t)
  215. {
  216. memset(t, 0, sizeof(*t));
  217. if (clk_id == CLOCK_REALTIME) {
  218. struct timeval now;
  219. int rv = gettimeofday(&now, NULL);
  220. if (rv) {
  221. return rv;
  222. }
  223. t->tv_sec = now.tv_sec;
  224. t->tv_nsec = now.tv_usec * 1000;
  225. return 0;
  226. } else if (clk_id == CLOCK_MONOTONIC) {
  227. static uint64_t clock_start_time = 0;
  228. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  229. uint64_t now = mach_absolute_time();
  230. if (clock_start_time == 0) {
  231. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  232. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  233. /* appease "unused variable" warning for release builds */
  234. (void)mach_status;
  235. clock_start_time = now;
  236. }
  237. now = (uint64_t)((double)(now - clock_start_time)
  238. * (double)timebase_ifo.numer
  239. / (double)timebase_ifo.denom);
  240. t->tv_sec = now / 1000000000;
  241. t->tv_nsec = now % 1000000000;
  242. return 0;
  243. }
  244. return -1; /* EINVAL - Clock ID is unknown */
  245. }
  246. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  247. #ifdef __CLOCK_AVAILABILITY
  248. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  249. * declared but it may be NULL at runtime. So we need to check before using
  250. * it. */
  251. static int
  252. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  253. {
  254. if (clock_gettime) {
  255. return clock_gettime(clk_id, t);
  256. }
  257. return _civet_clock_gettime(clk_id, t);
  258. }
  259. #define clock_gettime _civet_safe_clock_gettime
  260. #else
  261. #define clock_gettime _civet_clock_gettime
  262. #endif
  263. #endif
  264. #include <time.h>
  265. #include <stdlib.h>
  266. #include <stdarg.h>
  267. #include <string.h>
  268. #include <ctype.h>
  269. #include <limits.h>
  270. #include <stddef.h>
  271. #include <stdio.h>
  272. #include <stdint.h>
  273. #ifndef INT64_MAX
  274. #define INT64_MAX (9223372036854775807)
  275. #endif
  276. #ifndef MAX_WORKER_THREADS
  277. #define MAX_WORKER_THREADS (1024 * 64)
  278. #endif
  279. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  280. #define SOCKET_TIMEOUT_QUANTUM (2000)
  281. #endif
  282. #define SHUTDOWN_RD (0)
  283. #define SHUTDOWN_WR (1)
  284. #define SHUTDOWN_BOTH (2)
  285. mg_static_assert(MAX_WORKER_THREADS >= 1,
  286. "worker threads must be a positive number");
  287. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  288. "size_t data type size check");
  289. #if defined(_WIN32) \
  290. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  291. #include <windows.h>
  292. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  293. #include <ws2tcpip.h>
  294. typedef const char *SOCK_OPT_TYPE;
  295. #if !defined(PATH_MAX)
  296. #define W_PATH_MAX (MAX_PATH)
  297. /* at most three UTF-8 chars per wchar_t */
  298. #define PATH_MAX (W_PATH_MAX * 3)
  299. #else
  300. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  301. #endif
  302. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  303. #ifndef _IN_PORT_T
  304. #ifndef in_port_t
  305. #define in_port_t u_short
  306. #endif
  307. #endif
  308. #ifndef _WIN32_WCE
  309. #include <process.h>
  310. #include <direct.h>
  311. #include <io.h>
  312. #else /* _WIN32_WCE */
  313. #define NO_CGI /* WinCE has no pipes */
  314. #define NO_POPEN /* WinCE has no popen */
  315. typedef long off_t;
  316. #define errno ((int)(GetLastError()))
  317. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  318. #endif /* _WIN32_WCE */
  319. #define MAKEUQUAD(lo, hi) \
  320. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  321. #define RATE_DIFF (10000000) /* 100 nsecs */
  322. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  323. #define SYS2UNIX_TIME(lo, hi) \
  324. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  325. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  326. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  327. * Also use _strtoui64 on modern M$ compilers */
  328. #if defined(_MSC_VER)
  329. #if (_MSC_VER < 1300)
  330. #define STRX(x) #x
  331. #define STR(x) STRX(x)
  332. #define __func__ __FILE__ ":" STR(__LINE__)
  333. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  334. #define strtoll(x, y, z) (_atoi64(x))
  335. #else
  336. #define __func__ __FUNCTION__
  337. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  338. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  339. #endif
  340. #endif /* _MSC_VER */
  341. #define ERRNO ((int)(GetLastError()))
  342. #define NO_SOCKLEN_T
  343. #if defined(_WIN64) || defined(__MINGW64__)
  344. #define SSL_LIB "ssleay64.dll"
  345. #define CRYPTO_LIB "libeay64.dll"
  346. #else
  347. #define SSL_LIB "ssleay32.dll"
  348. #define CRYPTO_LIB "libeay32.dll"
  349. #endif
  350. #define O_NONBLOCK (0)
  351. #ifndef W_OK
  352. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  353. #endif
  354. #if !defined(EWOULDBLOCK)
  355. #define EWOULDBLOCK WSAEWOULDBLOCK
  356. #endif /* !EWOULDBLOCK */
  357. #define _POSIX_
  358. #define INT64_FMT "I64d"
  359. #define UINT64_FMT "I64u"
  360. #define WINCDECL __cdecl
  361. #define vsnprintf_impl _vsnprintf
  362. #define access _access
  363. #define mg_sleep(x) (Sleep(x))
  364. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  365. #ifndef popen
  366. #define popen(x, y) (_popen(x, y))
  367. #endif
  368. #ifndef pclose
  369. #define pclose(x) (_pclose(x))
  370. #endif
  371. #define close(x) (_close(x))
  372. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  373. #define RTLD_LAZY (0)
  374. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  375. #define fdopen(x, y) (_fdopen((x), (y)))
  376. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  377. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  378. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  379. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  380. #define sleep(x) (Sleep((x)*1000))
  381. #define rmdir(x) (_rmdir(x))
  382. #define timegm(x) (_mkgmtime(x))
  383. #if !defined(fileno)
  384. #define fileno(x) (_fileno(x))
  385. #endif /* !fileno MINGW #defines fileno */
  386. typedef HANDLE pthread_mutex_t;
  387. typedef DWORD pthread_key_t;
  388. typedef HANDLE pthread_t;
  389. typedef struct {
  390. CRITICAL_SECTION threadIdSec;
  391. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  392. } pthread_cond_t;
  393. #ifndef __clockid_t_defined
  394. typedef DWORD clockid_t;
  395. #endif
  396. #ifndef CLOCK_MONOTONIC
  397. #define CLOCK_MONOTONIC (1)
  398. #endif
  399. #ifndef CLOCK_REALTIME
  400. #define CLOCK_REALTIME (2)
  401. #endif
  402. #ifndef CLOCK_THREAD
  403. #define CLOCK_THREAD (3)
  404. #endif
  405. #ifndef CLOCK_PROCESS
  406. #define CLOCK_PROCESS (4)
  407. #endif
  408. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  409. #define _TIMESPEC_DEFINED
  410. #endif
  411. #ifndef _TIMESPEC_DEFINED
  412. struct timespec {
  413. time_t tv_sec; /* seconds */
  414. long tv_nsec; /* nanoseconds */
  415. };
  416. #endif
  417. #if !defined(WIN_PTHREADS_TIME_H)
  418. #define MUST_IMPLEMENT_CLOCK_GETTIME
  419. #endif
  420. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  421. #define clock_gettime mg_clock_gettime
  422. static int
  423. clock_gettime(clockid_t clk_id, struct timespec *tp)
  424. {
  425. FILETIME ft;
  426. ULARGE_INTEGER li, li2;
  427. BOOL ok = FALSE;
  428. double d;
  429. static double perfcnt_per_sec = 0.0;
  430. if (tp) {
  431. memset(tp, 0, sizeof(*tp));
  432. if (clk_id == CLOCK_REALTIME) {
  433. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  434. GetSystemTimeAsFileTime(&ft);
  435. li.LowPart = ft.dwLowDateTime;
  436. li.HighPart = ft.dwHighDateTime;
  437. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  438. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  439. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  440. ok = TRUE;
  441. /* END: CLOCK_REALTIME */
  442. } else if (clk_id == CLOCK_MONOTONIC) {
  443. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  444. if (perfcnt_per_sec == 0.0) {
  445. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  446. perfcnt_per_sec = 1.0 / li.QuadPart;
  447. }
  448. if (perfcnt_per_sec != 0.0) {
  449. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  450. d = li.QuadPart * perfcnt_per_sec;
  451. tp->tv_sec = (time_t)d;
  452. d -= tp->tv_sec;
  453. tp->tv_nsec = (long)(d * 1.0E9);
  454. ok = TRUE;
  455. }
  456. /* END: CLOCK_MONOTONIC */
  457. } else if (clk_id == CLOCK_THREAD) {
  458. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  459. FILETIME t_create, t_exit, t_kernel, t_user;
  460. if (GetThreadTimes(GetCurrentThread(),
  461. &t_create,
  462. &t_exit,
  463. &t_kernel,
  464. &t_user)) {
  465. li.LowPart = t_user.dwLowDateTime;
  466. li.HighPart = t_user.dwHighDateTime;
  467. li2.LowPart = t_kernel.dwLowDateTime;
  468. li2.HighPart = t_kernel.dwHighDateTime;
  469. li.QuadPart += li2.QuadPart;
  470. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  471. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  472. ok = TRUE;
  473. }
  474. /* END: CLOCK_THREAD */
  475. } else if (clk_id == CLOCK_PROCESS) {
  476. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  477. FILETIME t_create, t_exit, t_kernel, t_user;
  478. if (GetProcessTimes(GetCurrentProcess(),
  479. &t_create,
  480. &t_exit,
  481. &t_kernel,
  482. &t_user)) {
  483. li.LowPart = t_user.dwLowDateTime;
  484. li.HighPart = t_user.dwHighDateTime;
  485. li2.LowPart = t_kernel.dwLowDateTime;
  486. li2.HighPart = t_kernel.dwHighDateTime;
  487. li.QuadPart += li2.QuadPart;
  488. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  489. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  490. ok = TRUE;
  491. }
  492. /* END: CLOCK_PROCESS */
  493. } else {
  494. /* BEGIN: unknown clock */
  495. /* ok = FALSE; already set by init */
  496. /* END: unknown clock */
  497. }
  498. }
  499. return ok ? 0 : -1;
  500. }
  501. #endif
  502. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  503. static int pthread_mutex_lock(pthread_mutex_t *);
  504. static int pthread_mutex_unlock(pthread_mutex_t *);
  505. static void path_to_unicode(const struct mg_connection *conn,
  506. const char *path,
  507. wchar_t *wbuf,
  508. size_t wbuf_len);
  509. /* All file operations need to be rewritten to solve #246. */
  510. #include "file_ops.inl"
  511. struct mg_file;
  512. static const char *
  513. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  514. /* POSIX dirent interface */
  515. struct dirent {
  516. char d_name[PATH_MAX];
  517. };
  518. typedef struct DIR {
  519. HANDLE handle;
  520. WIN32_FIND_DATAW info;
  521. struct dirent result;
  522. } DIR;
  523. #if defined(_WIN32) && !defined(POLLIN)
  524. #ifndef HAVE_POLL
  525. struct pollfd {
  526. SOCKET fd;
  527. short events;
  528. short revents;
  529. };
  530. #define POLLIN (0x0300)
  531. #endif
  532. #endif
  533. /* Mark required libraries */
  534. #if defined(_MSC_VER)
  535. #pragma comment(lib, "Ws2_32.lib")
  536. #endif
  537. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  538. WINDOWS / UNIX include block */
  539. #include <sys/wait.h>
  540. #include <sys/socket.h>
  541. #include <sys/poll.h>
  542. #include <netinet/in.h>
  543. #include <arpa/inet.h>
  544. #include <sys/time.h>
  545. #include <sys/utsname.h>
  546. #include <stdint.h>
  547. #include <inttypes.h>
  548. #include <netdb.h>
  549. #include <netinet/tcp.h>
  550. typedef const void *SOCK_OPT_TYPE;
  551. #if defined(ANDROID)
  552. typedef unsigned short int in_port_t;
  553. #endif
  554. #include <pwd.h>
  555. #include <unistd.h>
  556. #include <grp.h>
  557. #include <dirent.h>
  558. #define vsnprintf_impl vsnprintf
  559. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  560. #include <dlfcn.h>
  561. #endif
  562. #include <pthread.h>
  563. #if defined(__MACH__)
  564. #define SSL_LIB "libssl.dylib"
  565. #define CRYPTO_LIB "libcrypto.dylib"
  566. #else
  567. #if !defined(SSL_LIB)
  568. #define SSL_LIB "libssl.so"
  569. #endif
  570. #if !defined(CRYPTO_LIB)
  571. #define CRYPTO_LIB "libcrypto.so"
  572. #endif
  573. #endif
  574. #ifndef O_BINARY
  575. #define O_BINARY (0)
  576. #endif /* O_BINARY */
  577. #define closesocket(a) (close(a))
  578. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  579. #define mg_remove(conn, x) (remove(x))
  580. #define mg_sleep(x) (usleep((x)*1000))
  581. #define mg_opendir(conn, x) (opendir(x))
  582. #define mg_closedir(x) (closedir(x))
  583. #define mg_readdir(x) (readdir(x))
  584. #define ERRNO (errno)
  585. #define INVALID_SOCKET (-1)
  586. #define INT64_FMT PRId64
  587. #define UINT64_FMT PRIu64
  588. typedef int SOCKET;
  589. #define WINCDECL
  590. #if defined(__hpux)
  591. /* HPUX 11 does not have monotonic, fall back to realtime */
  592. #ifndef CLOCK_MONOTONIC
  593. #define CLOCK_MONOTONIC CLOCK_REALTIME
  594. #endif
  595. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  596. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  597. * the prototypes use int* rather than socklen_t* which matches the
  598. * actual library expectation. When called with the wrong size arg
  599. * accept() returns a zero client inet addr and check_acl() always
  600. * fails. Since socklen_t is widely used below, just force replace
  601. * their typedef with int. - DTL
  602. */
  603. #define socklen_t int
  604. #endif /* hpux */
  605. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  606. WINDOWS / UNIX include block */
  607. /* va_copy should always be a macro, C99 and C++11 - DTL */
  608. #ifndef va_copy
  609. #define va_copy(x, y) ((x) = (y))
  610. #endif
  611. #ifdef _WIN32
  612. /* Create substitutes for POSIX functions in Win32. */
  613. #if defined(__MINGW32__)
  614. /* Show no warning in case system functions are not used. */
  615. #pragma GCC diagnostic push
  616. #pragma GCC diagnostic ignored "-Wunused-function"
  617. #endif
  618. static CRITICAL_SECTION global_log_file_lock;
  619. FUNCTION_MAY_BE_UNUSED
  620. static DWORD
  621. pthread_self(void)
  622. {
  623. return GetCurrentThreadId();
  624. }
  625. FUNCTION_MAY_BE_UNUSED
  626. static int
  627. pthread_key_create(
  628. pthread_key_t *key,
  629. void (*_ignored)(void *) /* destructor not supported for Windows */
  630. )
  631. {
  632. (void)_ignored;
  633. if ((key != 0)) {
  634. *key = TlsAlloc();
  635. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  636. }
  637. return -2;
  638. }
  639. FUNCTION_MAY_BE_UNUSED
  640. static int
  641. pthread_key_delete(pthread_key_t key)
  642. {
  643. return TlsFree(key) ? 0 : 1;
  644. }
  645. FUNCTION_MAY_BE_UNUSED
  646. static int
  647. pthread_setspecific(pthread_key_t key, void *value)
  648. {
  649. return TlsSetValue(key, value) ? 0 : 1;
  650. }
  651. FUNCTION_MAY_BE_UNUSED
  652. static void *
  653. pthread_getspecific(pthread_key_t key)
  654. {
  655. return TlsGetValue(key);
  656. }
  657. #if defined(__MINGW32__)
  658. /* Enable unused function warning again */
  659. #pragma GCC diagnostic pop
  660. #endif
  661. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  662. #else
  663. static pthread_mutexattr_t pthread_mutex_attr;
  664. #endif /* _WIN32 */
  665. #define PASSWORDS_FILE_NAME ".htpasswd"
  666. #define CGI_ENVIRONMENT_SIZE (4096)
  667. #define MAX_CGI_ENVIR_VARS (256)
  668. #define MG_BUF_LEN (8192)
  669. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  670. #if defined(_WIN32_WCE)
  671. /* Create substitutes for POSIX functions in Win32. */
  672. #if defined(__MINGW32__)
  673. /* Show no warning in case system functions are not used. */
  674. #pragma GCC diagnostic push
  675. #pragma GCC diagnostic ignored "-Wunused-function"
  676. #endif
  677. FUNCTION_MAY_BE_UNUSED
  678. static time_t
  679. time(time_t *ptime)
  680. {
  681. time_t t;
  682. SYSTEMTIME st;
  683. FILETIME ft;
  684. GetSystemTime(&st);
  685. SystemTimeToFileTime(&st, &ft);
  686. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  687. if (ptime != NULL) {
  688. *ptime = t;
  689. }
  690. return t;
  691. }
  692. FUNCTION_MAY_BE_UNUSED
  693. static struct tm *
  694. localtime_s(const time_t *ptime, struct tm *ptm)
  695. {
  696. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  697. FILETIME ft, lft;
  698. SYSTEMTIME st;
  699. TIME_ZONE_INFORMATION tzinfo;
  700. if (ptm == NULL) {
  701. return NULL;
  702. }
  703. *(int64_t *)&ft = t;
  704. FileTimeToLocalFileTime(&ft, &lft);
  705. FileTimeToSystemTime(&lft, &st);
  706. ptm->tm_year = st.wYear - 1900;
  707. ptm->tm_mon = st.wMonth - 1;
  708. ptm->tm_wday = st.wDayOfWeek;
  709. ptm->tm_mday = st.wDay;
  710. ptm->tm_hour = st.wHour;
  711. ptm->tm_min = st.wMinute;
  712. ptm->tm_sec = st.wSecond;
  713. ptm->tm_yday = 0; /* hope nobody uses this */
  714. ptm->tm_isdst =
  715. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  716. return ptm;
  717. }
  718. FUNCTION_MAY_BE_UNUSED
  719. static struct tm *
  720. gmtime_s(const time_t *ptime, struct tm *ptm)
  721. {
  722. /* FIXME(lsm): fix this. */
  723. return localtime_s(ptime, ptm);
  724. }
  725. static int mg_atomic_inc(volatile int *addr);
  726. static struct tm tm_array[MAX_WORKER_THREADS];
  727. static int tm_index = 0;
  728. FUNCTION_MAY_BE_UNUSED
  729. static struct tm *
  730. localtime(const time_t *ptime)
  731. {
  732. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  733. return localtime_s(ptime, tm_array + i);
  734. }
  735. FUNCTION_MAY_BE_UNUSED
  736. static struct tm *
  737. gmtime(const time_t *ptime)
  738. {
  739. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  740. return gmtime_s(ptime, tm_array + i);
  741. }
  742. FUNCTION_MAY_BE_UNUSED
  743. static size_t
  744. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  745. {
  746. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  747. * for WinCE"); */
  748. return 0;
  749. }
  750. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  751. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  752. #define remove(f) mg_remove(NULL, f)
  753. FUNCTION_MAY_BE_UNUSED
  754. static int
  755. rename(const char *a, const char *b)
  756. {
  757. wchar_t wa[W_PATH_MAX];
  758. wchar_t wb[W_PATH_MAX];
  759. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  760. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  761. return MoveFileW(wa, wb) ? 0 : -1;
  762. }
  763. struct stat {
  764. int64_t st_size;
  765. time_t st_mtime;
  766. };
  767. FUNCTION_MAY_BE_UNUSED
  768. static int
  769. stat(const char *name, struct stat *st)
  770. {
  771. wchar_t wbuf[W_PATH_MAX];
  772. WIN32_FILE_ATTRIBUTE_DATA attr;
  773. time_t creation_time, write_time;
  774. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  775. memset(&attr, 0, sizeof(attr));
  776. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  777. st->st_size =
  778. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  779. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  780. attr.ftLastWriteTime.dwHighDateTime);
  781. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  782. attr.ftCreationTime.dwHighDateTime);
  783. if (creation_time > write_time) {
  784. st->st_mtime = creation_time;
  785. } else {
  786. st->st_mtime = write_time;
  787. }
  788. return 0;
  789. }
  790. #define access(x, a) 1 /* not required anyway */
  791. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  792. /* Values from errno.h in Windows SDK (Visual Studio). */
  793. #define EEXIST 17
  794. #define EACCES 13
  795. #define ENOENT 2
  796. #if defined(__MINGW32__)
  797. /* Enable unused function warning again */
  798. #pragma GCC diagnostic pop
  799. #endif
  800. #endif /* defined(_WIN32_WCE) */
  801. #if defined(__GNUC__) || defined(__MINGW32__)
  802. /* Show no warning in case system functions are not used. */
  803. #define GCC_VERSION \
  804. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  805. #if GCC_VERSION >= 40500
  806. #pragma GCC diagnostic push
  807. #pragma GCC diagnostic ignored "-Wunused-function"
  808. #endif /* GCC_VERSION >= 40500 */
  809. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  810. #if defined(__clang__)
  811. /* Show no warning in case system functions are not used. */
  812. #pragma clang diagnostic push
  813. #pragma clang diagnostic ignored "-Wunused-function"
  814. #endif
  815. static pthread_mutex_t global_lock_mutex;
  816. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  817. /* Forward declaration for Windows */
  818. FUNCTION_MAY_BE_UNUSED
  819. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  820. FUNCTION_MAY_BE_UNUSED
  821. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  822. #endif
  823. FUNCTION_MAY_BE_UNUSED
  824. static void
  825. mg_global_lock(void)
  826. {
  827. (void)pthread_mutex_lock(&global_lock_mutex);
  828. }
  829. FUNCTION_MAY_BE_UNUSED
  830. static void
  831. mg_global_unlock(void)
  832. {
  833. (void)pthread_mutex_unlock(&global_lock_mutex);
  834. }
  835. FUNCTION_MAY_BE_UNUSED
  836. static int
  837. mg_atomic_inc(volatile int *addr)
  838. {
  839. int ret;
  840. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  841. /* Depending on the SDK, this function uses either
  842. * (volatile unsigned int *) or (volatile LONG *),
  843. * so whatever you use, the other SDK is likely to raise a warning. */
  844. ret = InterlockedIncrement((volatile long *)addr);
  845. #elif defined(__GNUC__) \
  846. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  847. && !defined(NO_ATOMICS)
  848. ret = __sync_add_and_fetch(addr, 1);
  849. #else
  850. mg_global_lock();
  851. ret = (++(*addr));
  852. mg_global_unlock();
  853. #endif
  854. return ret;
  855. }
  856. FUNCTION_MAY_BE_UNUSED
  857. static int
  858. mg_atomic_dec(volatile int *addr)
  859. {
  860. int ret;
  861. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  862. /* Depending on the SDK, this function uses either
  863. * (volatile unsigned int *) or (volatile LONG *),
  864. * so whatever you use, the other SDK is likely to raise a warning. */
  865. ret = InterlockedDecrement((volatile long *)addr);
  866. #elif defined(__GNUC__) \
  867. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  868. && !defined(NO_ATOMICS)
  869. ret = __sync_sub_and_fetch(addr, 1);
  870. #else
  871. mg_global_lock();
  872. ret = (--(*addr));
  873. mg_global_unlock();
  874. #endif
  875. return ret;
  876. }
  877. #if defined(USE_SERVER_STATS)
  878. static int64_t
  879. mg_atomic_add(volatile int64_t *addr, int64_t value)
  880. {
  881. int64_t ret;
  882. #if defined(_WIN64) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  883. ret = InterlockedAdd64(addr, value);
  884. #elif defined(__GNUC__) \
  885. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  886. && !defined(NO_ATOMICS)
  887. ret = __sync_add_and_fetch(addr, value);
  888. #else
  889. mg_global_lock();
  890. *addr += value;
  891. ret = (*addr);
  892. mg_global_unlock();
  893. #endif
  894. return ret;
  895. }
  896. #endif
  897. #if defined(__GNUC__)
  898. /* Show no warning in case system functions are not used. */
  899. #if GCC_VERSION >= 40500
  900. #pragma GCC diagnostic pop
  901. #endif /* GCC_VERSION >= 40500 */
  902. #endif /* defined(__GNUC__) */
  903. #if defined(__clang__)
  904. /* Show no warning in case system functions are not used. */
  905. #pragma clang diagnostic pop
  906. #endif
  907. #if defined(USE_SERVER_STATS)
  908. struct mg_memory_stat {
  909. volatile int64_t totalMemUsed;
  910. volatile int64_t maxMemUsed;
  911. volatile int blockCount;
  912. };
  913. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  914. static void *
  915. mg_malloc_ex(size_t size,
  916. struct mg_context *ctx,
  917. const char *file,
  918. unsigned line)
  919. {
  920. void *data = malloc(size + 2 * sizeof(uintptr_t));
  921. void *memory = 0;
  922. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  923. #if defined(MEMORY_DEBUGGING)
  924. char mallocStr[256];
  925. #else
  926. (void)file;
  927. (void)line;
  928. #endif
  929. if (data) {
  930. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  931. if (mmem > mstat->maxMemUsed) {
  932. /* could use atomic compare exchange, but this
  933. * seems overkill for statistics data */
  934. mstat->maxMemUsed = mmem;
  935. }
  936. mg_atomic_inc(&mstat->blockCount);
  937. ((uintptr_t *)data)[0] = size;
  938. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  939. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  940. }
  941. #if defined(MEMORY_DEBUGGING)
  942. sprintf(mallocStr,
  943. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  944. memory,
  945. (unsigned long)size,
  946. (unsigned long)mstat->totalMemUsed,
  947. (unsigned long)mstat->blockCount,
  948. file,
  949. line);
  950. #if defined(_WIN32)
  951. OutputDebugStringA(mallocStr);
  952. #else
  953. DEBUG_TRACE("%s", mallocStr);
  954. #endif
  955. #endif
  956. return memory;
  957. }
  958. static void *
  959. mg_calloc_ex(size_t count,
  960. size_t size,
  961. struct mg_context *ctx,
  962. const char *file,
  963. unsigned line)
  964. {
  965. void *data = mg_malloc_ex(size * count, ctx, file, line);
  966. if (data) {
  967. memset(data, 0, size * count);
  968. }
  969. return data;
  970. }
  971. static void
  972. mg_free_ex(void *memory, const char *file, unsigned line)
  973. {
  974. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  975. #if defined(MEMORY_DEBUGGING)
  976. char mallocStr[256];
  977. #else
  978. (void)file;
  979. (void)line;
  980. #endif
  981. if (memory) {
  982. uintptr_t size = ((uintptr_t *)data)[0];
  983. struct mg_memory_stat *mstat =
  984. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  985. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  986. mg_atomic_dec(&mstat->blockCount);
  987. #if defined(MEMORY_DEBUGGING)
  988. sprintf(mallocStr,
  989. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  990. memory,
  991. (unsigned long)size,
  992. (unsigned long)mstat->totalMemUsed,
  993. (unsigned long)mstat->blockCount,
  994. file,
  995. line);
  996. #if defined(_WIN32)
  997. OutputDebugStringA(mallocStr);
  998. #else
  999. DEBUG_TRACE("%s", mallocStr);
  1000. #endif
  1001. #endif
  1002. free(data);
  1003. }
  1004. }
  1005. static void *
  1006. mg_realloc_ex(void *memory,
  1007. size_t newsize,
  1008. struct mg_context *ctx,
  1009. const char *file,
  1010. unsigned line)
  1011. {
  1012. void *data;
  1013. void *_realloc;
  1014. uintptr_t oldsize;
  1015. #if defined(MEMORY_DEBUGGING)
  1016. char mallocStr[256];
  1017. #else
  1018. (void)file;
  1019. (void)line;
  1020. #endif
  1021. if (newsize) {
  1022. if (memory) {
  1023. /* Reallocate existing block */
  1024. struct mg_memory_stat *mstat;
  1025. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1026. oldsize = ((uintptr_t *)data)[0];
  1027. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1028. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1029. if (_realloc) {
  1030. data = _realloc;
  1031. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1032. #if defined(MEMORY_DEBUGGING)
  1033. sprintf(mallocStr,
  1034. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1035. memory,
  1036. (unsigned long)oldsize,
  1037. (unsigned long)mstat->totalMemUsed,
  1038. (unsigned long)mstat->blockCount,
  1039. file,
  1040. line);
  1041. #if defined(_WIN32)
  1042. OutputDebugStringA(mallocStr);
  1043. #else
  1044. DEBUG_TRACE("%s", mallocStr);
  1045. #endif
  1046. #endif
  1047. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1048. #if defined(MEMORY_DEBUGGING)
  1049. sprintf(mallocStr,
  1050. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1051. memory,
  1052. (unsigned long)newsize,
  1053. (unsigned long)mstat->totalMemUsed,
  1054. (unsigned long)mstat->blockCount,
  1055. file,
  1056. line);
  1057. #if defined(_WIN32)
  1058. OutputDebugStringA(mallocStr);
  1059. #else
  1060. DEBUG_TRACE("%s", mallocStr);
  1061. #endif
  1062. #endif
  1063. *(uintptr_t *)data = newsize;
  1064. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1065. } else {
  1066. #if defined(MEMORY_DEBUGGING)
  1067. #if defined(_WIN32)
  1068. OutputDebugStringA("MEM: realloc failed\n");
  1069. #else
  1070. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1071. #endif
  1072. #endif
  1073. return _realloc;
  1074. }
  1075. } else {
  1076. /* Allocate new block */
  1077. data = mg_malloc_ex(newsize, ctx, file, line);
  1078. }
  1079. } else {
  1080. /* Free existing block */
  1081. data = 0;
  1082. mg_free_ex(memory, file, line);
  1083. }
  1084. return data;
  1085. }
  1086. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1087. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1088. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1089. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1090. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1091. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1092. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1093. #else /* USE_SERVER_STATS */
  1094. static __inline void *
  1095. mg_malloc(size_t a)
  1096. {
  1097. return malloc(a);
  1098. }
  1099. static __inline void *
  1100. mg_calloc(size_t a, size_t b)
  1101. {
  1102. return calloc(a, b);
  1103. }
  1104. static __inline void *
  1105. mg_realloc(void *a, size_t b)
  1106. {
  1107. return realloc(a, b);
  1108. }
  1109. static __inline void
  1110. mg_free(void *a)
  1111. {
  1112. free(a);
  1113. }
  1114. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1115. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1116. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1117. #define mg_free_ctx(a, c) mg_free(a)
  1118. #endif /* USE_SERVER_STATS */
  1119. static void mg_vsnprintf(const struct mg_connection *conn,
  1120. int *truncated,
  1121. char *buf,
  1122. size_t buflen,
  1123. const char *fmt,
  1124. va_list ap);
  1125. static void mg_snprintf(const struct mg_connection *conn,
  1126. int *truncated,
  1127. char *buf,
  1128. size_t buflen,
  1129. PRINTF_FORMAT_STRING(const char *fmt),
  1130. ...) PRINTF_ARGS(5, 6);
  1131. /* This following lines are just meant as a reminder to use the mg-functions
  1132. * for memory management */
  1133. #ifdef malloc
  1134. #undef malloc
  1135. #endif
  1136. #ifdef calloc
  1137. #undef calloc
  1138. #endif
  1139. #ifdef realloc
  1140. #undef realloc
  1141. #endif
  1142. #ifdef free
  1143. #undef free
  1144. #endif
  1145. #ifdef snprintf
  1146. #undef snprintf
  1147. #endif
  1148. #ifdef vsnprintf
  1149. #undef vsnprintf
  1150. #endif
  1151. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1152. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1153. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1154. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1155. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1156. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  1157. * but this define only works well for Windows. */
  1158. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1159. #endif
  1160. /* mg_init_library counter */
  1161. static int mg_init_library_called = 0;
  1162. #if !defined(NO_SSL)
  1163. static int mg_ssl_initialized = 0;
  1164. #endif
  1165. static pthread_key_t sTlsKey; /* Thread local storage index */
  1166. static int thread_idx_max = 0;
  1167. struct mg_workerTLS {
  1168. int is_master;
  1169. unsigned long thread_idx;
  1170. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1171. HANDLE pthread_cond_helper_mutex;
  1172. struct mg_workerTLS *next_waiting_thread;
  1173. #endif
  1174. };
  1175. #if defined(__GNUC__) || defined(__MINGW32__)
  1176. /* Show no warning in case system functions are not used. */
  1177. #if GCC_VERSION >= 40500
  1178. #pragma GCC diagnostic push
  1179. #pragma GCC diagnostic ignored "-Wunused-function"
  1180. #endif /* GCC_VERSION >= 40500 */
  1181. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1182. #if defined(__clang__)
  1183. /* Show no warning in case system functions are not used. */
  1184. #pragma clang diagnostic push
  1185. #pragma clang diagnostic ignored "-Wunused-function"
  1186. #endif
  1187. /* Get a unique thread ID as unsigned long, independent from the data type
  1188. * of thread IDs defined by the operating system API.
  1189. * If two calls to mg_current_thread_id return the same value, they calls
  1190. * are done from the same thread. If they return different values, they are
  1191. * done from different threads. (Provided this function is used in the same
  1192. * process context and threads are not repeatedly created and deleted, but
  1193. * CivetWeb does not do that).
  1194. * This function must match the signature required for SSL id callbacks:
  1195. * CRYPTO_set_id_callback
  1196. */
  1197. FUNCTION_MAY_BE_UNUSED
  1198. static unsigned long
  1199. mg_current_thread_id(void)
  1200. {
  1201. #ifdef _WIN32
  1202. return GetCurrentThreadId();
  1203. #else
  1204. #ifdef __clang__
  1205. #pragma clang diagnostic push
  1206. #pragma clang diagnostic ignored "-Wunreachable-code"
  1207. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1208. * or not, so one of the two conditions will be unreachable by construction.
  1209. * Unfortunately the C standard does not define a way to check this at
  1210. * compile time, since the #if preprocessor conditions can not use the sizeof
  1211. * operator as an argument. */
  1212. #endif
  1213. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1214. /* This is the problematic case for CRYPTO_set_id_callback:
  1215. * The OS pthread_t can not be cast to unsigned long. */
  1216. struct mg_workerTLS *tls =
  1217. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1218. if (tls == NULL) {
  1219. /* SSL called from an unknown thread: Create some thread index.
  1220. */
  1221. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1222. tls->is_master = -2; /* -2 means "3rd party thread" */
  1223. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1224. pthread_setspecific(sTlsKey, tls);
  1225. }
  1226. return tls->thread_idx;
  1227. } else {
  1228. /* pthread_t may be any data type, so a simple cast to unsigned long
  1229. * can rise a warning/error, depending on the platform.
  1230. * Here memcpy is used as an anything-to-anything cast. */
  1231. unsigned long ret = 0;
  1232. pthread_t t = pthread_self();
  1233. memcpy(&ret, &t, sizeof(pthread_t));
  1234. return ret;
  1235. }
  1236. #ifdef __clang__
  1237. #pragma clang diagnostic pop
  1238. #endif
  1239. #endif
  1240. }
  1241. FUNCTION_MAY_BE_UNUSED
  1242. static uint64_t
  1243. mg_get_current_time_ns(void)
  1244. {
  1245. struct timespec tsnow;
  1246. clock_gettime(CLOCK_REALTIME, &tsnow);
  1247. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1248. }
  1249. #if defined(__GNUC__)
  1250. /* Show no warning in case system functions are not used. */
  1251. #if GCC_VERSION >= 40500
  1252. #pragma GCC diagnostic pop
  1253. #endif /* GCC_VERSION >= 40500 */
  1254. #endif /* defined(__GNUC__) */
  1255. #if defined(__clang__)
  1256. /* Show no warning in case system functions are not used. */
  1257. #pragma clang diagnostic pop
  1258. #endif
  1259. #if defined(NEED_DEBUG_TRACE_FUNC)
  1260. static void
  1261. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1262. {
  1263. va_list args;
  1264. uint64_t nsnow;
  1265. static uint64_t nslast;
  1266. struct timespec tsnow;
  1267. /* Get some operating system independent thread id */
  1268. unsigned long thread_id = mg_current_thread_id();
  1269. clock_gettime(CLOCK_REALTIME, &tsnow);
  1270. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1271. + ((uint64_t)tsnow.tv_nsec);
  1272. if (!nslast) {
  1273. nslast = nsnow;
  1274. }
  1275. flockfile(stdout);
  1276. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1277. (unsigned long)tsnow.tv_sec,
  1278. (unsigned long)tsnow.tv_nsec,
  1279. nsnow - nslast,
  1280. thread_id,
  1281. func,
  1282. line);
  1283. va_start(args, fmt);
  1284. vprintf(fmt, args);
  1285. va_end(args);
  1286. putchar('\n');
  1287. fflush(stdout);
  1288. funlockfile(stdout);
  1289. nslast = nsnow;
  1290. }
  1291. #endif /* NEED_DEBUG_TRACE_FUNC */
  1292. #define MD5_STATIC static
  1293. #include "md5.inl"
  1294. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1295. #ifdef NO_SOCKLEN_T
  1296. typedef int socklen_t;
  1297. #endif /* NO_SOCKLEN_T */
  1298. #define _DARWIN_UNLIMITED_SELECT
  1299. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1300. #if !defined(MSG_NOSIGNAL)
  1301. #define MSG_NOSIGNAL (0)
  1302. #endif
  1303. #if !defined(SOMAXCONN)
  1304. #define SOMAXCONN (100)
  1305. #endif
  1306. /* Size of the accepted socket queue */
  1307. #if !defined(MGSQLEN)
  1308. #define MGSQLEN (20)
  1309. #endif
  1310. #if defined(NO_SSL)
  1311. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1312. typedef struct SSL_CTX SSL_CTX;
  1313. #else
  1314. #if defined(NO_SSL_DL)
  1315. #include <openssl/ssl.h>
  1316. #include <openssl/err.h>
  1317. #include <openssl/crypto.h>
  1318. #include <openssl/x509.h>
  1319. #include <openssl/pem.h>
  1320. #include <openssl/engine.h>
  1321. #include <openssl/conf.h>
  1322. #include <openssl/dh.h>
  1323. #include <openssl/bn.h>
  1324. #include <openssl/opensslv.h>
  1325. #else
  1326. /* SSL loaded dynamically from DLL.
  1327. * I put the prototypes here to be independent from OpenSSL source
  1328. * installation. */
  1329. typedef struct ssl_st SSL;
  1330. typedef struct ssl_method_st SSL_METHOD;
  1331. typedef struct ssl_ctx_st SSL_CTX;
  1332. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1333. typedef struct x509_name X509_NAME;
  1334. typedef struct asn1_integer ASN1_INTEGER;
  1335. typedef struct bignum BIGNUM;
  1336. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1337. typedef struct evp_md EVP_MD;
  1338. typedef struct x509 X509;
  1339. #define SSL_CTRL_OPTIONS (32)
  1340. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1341. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1342. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1343. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1344. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1345. #define SSL_VERIFY_NONE (0)
  1346. #define SSL_VERIFY_PEER (1)
  1347. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1348. #define SSL_VERIFY_CLIENT_ONCE (4)
  1349. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1350. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1351. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1352. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1353. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1354. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1355. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1356. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1357. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1358. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1359. #define SSL_CB_HANDSHAKE_START (0x10)
  1360. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1361. #define SSL_ERROR_NONE (0)
  1362. #define SSL_ERROR_SSL (1)
  1363. #define SSL_ERROR_WANT_READ (2)
  1364. #define SSL_ERROR_WANT_WRITE (3)
  1365. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1366. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1367. #define SSL_ERROR_ZERO_RETURN (6)
  1368. #define SSL_ERROR_WANT_CONNECT (7)
  1369. #define SSL_ERROR_WANT_ACCEPT (8)
  1370. #define TLSEXT_TYPE_server_name (0)
  1371. #define TLSEXT_NAMETYPE_host_name (0)
  1372. #define SSL_TLSEXT_ERR_OK (0)
  1373. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1374. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1375. #define SSL_TLSEXT_ERR_NOACK (3)
  1376. struct ssl_func {
  1377. const char *name; /* SSL function name */
  1378. void (*ptr)(void); /* Function pointer */
  1379. };
  1380. #ifdef OPENSSL_API_1_1
  1381. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1382. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1383. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1384. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1385. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1386. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1387. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1388. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1389. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1390. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1391. #define OPENSSL_init_ssl \
  1392. (*(int (*)(uint64_t opts, \
  1393. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1394. #define SSL_CTX_use_PrivateKey_file \
  1395. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1396. #define SSL_CTX_use_certificate_file \
  1397. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1398. #define SSL_CTX_set_default_passwd_cb \
  1399. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1400. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1401. #define SSL_CTX_use_certificate_chain_file \
  1402. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1403. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1404. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1405. #define SSL_CTX_set_verify \
  1406. (*(void (*)(SSL_CTX *, \
  1407. int, \
  1408. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1409. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1410. #define SSL_CTX_load_verify_locations \
  1411. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1412. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1413. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1414. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1415. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1416. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1417. #define SSL_CIPHER_get_name \
  1418. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1419. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1420. #define SSL_CTX_set_session_id_context \
  1421. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1422. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1423. #define SSL_CTX_set_cipher_list \
  1424. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1425. #define SSL_CTX_set_options \
  1426. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1427. #define SSL_CTX_set_info_callback \
  1428. (*(void (*)(SSL_CTX * ctx, \
  1429. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1430. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1431. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1432. #define SSL_CTX_callback_ctrl \
  1433. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1434. #define SSL_get_servername \
  1435. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1436. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1437. #define SSL_CTX_clear_options(ctx, op) \
  1438. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1439. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1440. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1441. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1442. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1443. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1444. SSL_CTX_callback_ctrl(ctx, \
  1445. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1446. (void (*)(void))cb)
  1447. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1448. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1449. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1450. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1451. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1452. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1453. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1454. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1455. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1456. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1457. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1458. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1459. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1460. #define X509_NAME_oneline \
  1461. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1462. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1463. #define EVP_get_digestbyname \
  1464. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1465. #define EVP_Digest \
  1466. (*(int (*)( \
  1467. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1468. crypto_sw[10].ptr)
  1469. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1470. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1471. #define ASN1_INTEGER_to_BN \
  1472. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1473. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1474. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1475. #define OPENSSL_free(a) CRYPTO_free(a)
  1476. /* init_ssl_ctx() function updates this array.
  1477. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1478. * of respective functions. The macros above (like SSL_connect()) are really
  1479. * just calling these functions indirectly via the pointer. */
  1480. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1481. {"SSL_accept", NULL},
  1482. {"SSL_connect", NULL},
  1483. {"SSL_read", NULL},
  1484. {"SSL_write", NULL},
  1485. {"SSL_get_error", NULL},
  1486. {"SSL_set_fd", NULL},
  1487. {"SSL_new", NULL},
  1488. {"SSL_CTX_new", NULL},
  1489. {"TLS_server_method", NULL},
  1490. {"OPENSSL_init_ssl", NULL},
  1491. {"SSL_CTX_use_PrivateKey_file", NULL},
  1492. {"SSL_CTX_use_certificate_file", NULL},
  1493. {"SSL_CTX_set_default_passwd_cb", NULL},
  1494. {"SSL_CTX_free", NULL},
  1495. {"SSL_CTX_use_certificate_chain_file", NULL},
  1496. {"TLS_client_method", NULL},
  1497. {"SSL_pending", NULL},
  1498. {"SSL_CTX_set_verify", NULL},
  1499. {"SSL_shutdown", NULL},
  1500. {"SSL_CTX_load_verify_locations", NULL},
  1501. {"SSL_CTX_set_default_verify_paths", NULL},
  1502. {"SSL_CTX_set_verify_depth", NULL},
  1503. {"SSL_get_peer_certificate", NULL},
  1504. {"SSL_get_version", NULL},
  1505. {"SSL_get_current_cipher", NULL},
  1506. {"SSL_CIPHER_get_name", NULL},
  1507. {"SSL_CTX_check_private_key", NULL},
  1508. {"SSL_CTX_set_session_id_context", NULL},
  1509. {"SSL_CTX_ctrl", NULL},
  1510. {"SSL_CTX_set_cipher_list", NULL},
  1511. {"SSL_CTX_set_options", NULL},
  1512. {"SSL_CTX_set_info_callback", NULL},
  1513. {"SSL_get_ex_data", NULL},
  1514. {"SSL_set_ex_data", NULL},
  1515. {"SSL_CTX_callback_ctrl", NULL},
  1516. {"SSL_get_servername", NULL},
  1517. {"SSL_set_SSL_CTX", NULL},
  1518. {NULL, NULL}};
  1519. /* Similar array as ssl_sw. These functions could be located in different
  1520. * lib. */
  1521. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1522. {"ERR_error_string", NULL},
  1523. {"ERR_remove_state", NULL},
  1524. {"CONF_modules_unload", NULL},
  1525. {"X509_free", NULL},
  1526. {"X509_get_subject_name", NULL},
  1527. {"X509_get_issuer_name", NULL},
  1528. {"X509_NAME_oneline", NULL},
  1529. {"X509_get_serialNumber", NULL},
  1530. {"EVP_get_digestbyname", NULL},
  1531. {"EVP_Digest", NULL},
  1532. {"i2d_X509", NULL},
  1533. {"BN_bn2hex", NULL},
  1534. {"ASN1_INTEGER_to_BN", NULL},
  1535. {"BN_free", NULL},
  1536. {"CRYPTO_free", NULL},
  1537. {NULL, NULL}};
  1538. #else
  1539. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1540. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1541. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1542. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1543. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1544. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1545. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1546. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1547. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1548. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1549. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1550. #define SSL_CTX_use_PrivateKey_file \
  1551. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1552. #define SSL_CTX_use_certificate_file \
  1553. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1554. #define SSL_CTX_set_default_passwd_cb \
  1555. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1556. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1557. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1558. #define SSL_CTX_use_certificate_chain_file \
  1559. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1560. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1561. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1562. #define SSL_CTX_set_verify \
  1563. (*(void (*)(SSL_CTX *, \
  1564. int, \
  1565. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1566. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1567. #define SSL_CTX_load_verify_locations \
  1568. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1569. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1570. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1571. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1572. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1573. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1574. #define SSL_CIPHER_get_name \
  1575. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1576. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1577. #define SSL_CTX_set_session_id_context \
  1578. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1579. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1580. #define SSL_CTX_set_cipher_list \
  1581. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1582. #define SSL_CTX_set_info_callback \
  1583. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1584. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1585. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1586. #define SSL_CTX_callback_ctrl \
  1587. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1588. #define SSL_get_servername \
  1589. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1590. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1591. #define SSL_CTX_set_options(ctx, op) \
  1592. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1593. #define SSL_CTX_clear_options(ctx, op) \
  1594. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1595. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1596. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1597. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1598. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1599. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1600. SSL_CTX_callback_ctrl(ctx, \
  1601. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1602. (void (*)(void))cb)
  1603. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1604. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1605. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1606. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1607. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1608. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1609. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1610. #define CRYPTO_set_locking_callback \
  1611. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1612. #define CRYPTO_set_id_callback \
  1613. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1614. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1615. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1616. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1617. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1618. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1619. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1620. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1621. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1622. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1623. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1624. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1625. #define X509_NAME_oneline \
  1626. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1627. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1628. #define i2c_ASN1_INTEGER \
  1629. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1630. #define EVP_get_digestbyname \
  1631. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1632. #define EVP_Digest \
  1633. (*(int (*)( \
  1634. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1635. crypto_sw[18].ptr)
  1636. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1637. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1638. #define ASN1_INTEGER_to_BN \
  1639. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1640. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1641. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1642. #define OPENSSL_free(a) CRYPTO_free(a)
  1643. /* init_ssl_ctx() function updates this array.
  1644. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1645. * of respective functions. The macros above (like SSL_connect()) are really
  1646. * just calling these functions indirectly via the pointer. */
  1647. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1648. {"SSL_accept", NULL},
  1649. {"SSL_connect", NULL},
  1650. {"SSL_read", NULL},
  1651. {"SSL_write", NULL},
  1652. {"SSL_get_error", NULL},
  1653. {"SSL_set_fd", NULL},
  1654. {"SSL_new", NULL},
  1655. {"SSL_CTX_new", NULL},
  1656. {"SSLv23_server_method", NULL},
  1657. {"SSL_library_init", NULL},
  1658. {"SSL_CTX_use_PrivateKey_file", NULL},
  1659. {"SSL_CTX_use_certificate_file", NULL},
  1660. {"SSL_CTX_set_default_passwd_cb", NULL},
  1661. {"SSL_CTX_free", NULL},
  1662. {"SSL_load_error_strings", NULL},
  1663. {"SSL_CTX_use_certificate_chain_file", NULL},
  1664. {"SSLv23_client_method", NULL},
  1665. {"SSL_pending", NULL},
  1666. {"SSL_CTX_set_verify", NULL},
  1667. {"SSL_shutdown", NULL},
  1668. {"SSL_CTX_load_verify_locations", NULL},
  1669. {"SSL_CTX_set_default_verify_paths", NULL},
  1670. {"SSL_CTX_set_verify_depth", NULL},
  1671. {"SSL_get_peer_certificate", NULL},
  1672. {"SSL_get_version", NULL},
  1673. {"SSL_get_current_cipher", NULL},
  1674. {"SSL_CIPHER_get_name", NULL},
  1675. {"SSL_CTX_check_private_key", NULL},
  1676. {"SSL_CTX_set_session_id_context", NULL},
  1677. {"SSL_CTX_ctrl", NULL},
  1678. {"SSL_CTX_set_cipher_list", NULL},
  1679. {"SSL_CTX_set_info_callback", NULL},
  1680. {"SSL_get_ex_data", NULL},
  1681. {"SSL_set_ex_data", NULL},
  1682. {"SSL_CTX_callback_ctrl", NULL},
  1683. {"SSL_get_servername", NULL},
  1684. {"SSL_set_SSL_CTX", NULL},
  1685. {NULL, NULL}};
  1686. /* Similar array as ssl_sw. These functions could be located in different
  1687. * lib. */
  1688. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1689. {"CRYPTO_set_locking_callback", NULL},
  1690. {"CRYPTO_set_id_callback", NULL},
  1691. {"ERR_get_error", NULL},
  1692. {"ERR_error_string", NULL},
  1693. {"ERR_remove_state", NULL},
  1694. {"ERR_free_strings", NULL},
  1695. {"ENGINE_cleanup", NULL},
  1696. {"CONF_modules_unload", NULL},
  1697. {"CRYPTO_cleanup_all_ex_data", NULL},
  1698. {"EVP_cleanup", NULL},
  1699. {"X509_free", NULL},
  1700. {"X509_get_subject_name", NULL},
  1701. {"X509_get_issuer_name", NULL},
  1702. {"X509_NAME_oneline", NULL},
  1703. {"X509_get_serialNumber", NULL},
  1704. {"i2c_ASN1_INTEGER", NULL},
  1705. {"EVP_get_digestbyname", NULL},
  1706. {"EVP_Digest", NULL},
  1707. {"i2d_X509", NULL},
  1708. {"BN_bn2hex", NULL},
  1709. {"ASN1_INTEGER_to_BN", NULL},
  1710. {"BN_free", NULL},
  1711. {"CRYPTO_free", NULL},
  1712. {NULL, NULL}};
  1713. #endif /* OPENSSL_API_1_1 */
  1714. #endif /* NO_SSL_DL */
  1715. #endif /* NO_SSL */
  1716. #if !defined(NO_CACHING)
  1717. static const char *month_names[] = {"Jan",
  1718. "Feb",
  1719. "Mar",
  1720. "Apr",
  1721. "May",
  1722. "Jun",
  1723. "Jul",
  1724. "Aug",
  1725. "Sep",
  1726. "Oct",
  1727. "Nov",
  1728. "Dec"};
  1729. #endif /* !NO_CACHING */
  1730. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1731. * the
  1732. * union u. */
  1733. union usa {
  1734. struct sockaddr sa;
  1735. struct sockaddr_in sin;
  1736. #if defined(USE_IPV6)
  1737. struct sockaddr_in6 sin6;
  1738. #endif
  1739. };
  1740. /* Describes a string (chunk of memory). */
  1741. struct vec {
  1742. const char *ptr;
  1743. size_t len;
  1744. };
  1745. struct mg_file_stat {
  1746. /* File properties filled by mg_stat: */
  1747. uint64_t size;
  1748. time_t last_modified;
  1749. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1750. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1751. * case we need a "Content-Eencoding: gzip" header */
  1752. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1753. };
  1754. struct mg_file_in_memory {
  1755. char *p;
  1756. uint32_t pos;
  1757. char mode;
  1758. };
  1759. struct mg_file_access {
  1760. /* File properties filled by mg_fopen: */
  1761. FILE *fp;
  1762. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1763. * support library. Use some struct mg_file_in_memory *mf; instead of
  1764. * membuf char pointer. */
  1765. const char *membuf;
  1766. };
  1767. struct mg_file {
  1768. struct mg_file_stat stat;
  1769. struct mg_file_access access;
  1770. };
  1771. #define STRUCT_FILE_INITIALIZER \
  1772. { \
  1773. { \
  1774. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1775. } \
  1776. , \
  1777. { \
  1778. (FILE *) NULL, (const char *)NULL \
  1779. } \
  1780. }
  1781. /* Describes listening socket, or socket which was accept()-ed by the master
  1782. * thread and queued for future handling by the worker thread. */
  1783. struct socket {
  1784. SOCKET sock; /* Listening socket */
  1785. union usa lsa; /* Local socket address */
  1786. union usa rsa; /* Remote socket address */
  1787. unsigned char is_ssl; /* Is port SSL-ed */
  1788. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1789. * port */
  1790. unsigned char in_use; /* Is valid */
  1791. };
  1792. /* Enum const for all options must be in sync with
  1793. * static struct mg_option config_options[]
  1794. * This is tested in the unit test (test/private.c)
  1795. * "Private Config Options"
  1796. */
  1797. enum {
  1798. LISTENING_PORTS,
  1799. NUM_THREADS,
  1800. RUN_AS_USER,
  1801. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1802. * socket option typedef TCP_NODELAY. */
  1803. MAX_REQUEST_SIZE,
  1804. LINGER_TIMEOUT,
  1805. #if defined(__linux__)
  1806. ALLOW_SENDFILE_CALL,
  1807. #endif
  1808. #if defined(_WIN32)
  1809. CASE_SENSITIVE_FILES,
  1810. #endif
  1811. THROTTLE,
  1812. ACCESS_LOG_FILE,
  1813. ERROR_LOG_FILE,
  1814. ENABLE_KEEP_ALIVE,
  1815. REQUEST_TIMEOUT,
  1816. KEEP_ALIVE_TIMEOUT,
  1817. #if defined(USE_WEBSOCKET)
  1818. WEBSOCKET_TIMEOUT,
  1819. #endif
  1820. DECODE_URL,
  1821. #if defined(USE_LUA)
  1822. LUA_BACKGROUND_SCRIPT,
  1823. LUA_BACKGROUND_SCRIPT_PARAMS,
  1824. #endif
  1825. DOCUMENT_ROOT,
  1826. CGI_EXTENSIONS,
  1827. CGI_ENVIRONMENT,
  1828. PUT_DELETE_PASSWORDS_FILE,
  1829. CGI_INTERPRETER,
  1830. PROTECT_URI,
  1831. AUTHENTICATION_DOMAIN,
  1832. ENABLE_AUTH_DOMAIN_CHECK,
  1833. SSI_EXTENSIONS,
  1834. ENABLE_DIRECTORY_LISTING,
  1835. GLOBAL_PASSWORDS_FILE,
  1836. INDEX_FILES,
  1837. ACCESS_CONTROL_LIST,
  1838. EXTRA_MIME_TYPES,
  1839. SSL_CERTIFICATE,
  1840. SSL_CERTIFICATE_CHAIN,
  1841. URL_REWRITE_PATTERN,
  1842. HIDE_FILES,
  1843. SSL_DO_VERIFY_PEER,
  1844. SSL_CA_PATH,
  1845. SSL_CA_FILE,
  1846. SSL_VERIFY_DEPTH,
  1847. SSL_DEFAULT_VERIFY_PATHS,
  1848. SSL_CIPHER_LIST,
  1849. SSL_PROTOCOL_VERSION,
  1850. SSL_SHORT_TRUST,
  1851. #if defined(USE_LUA)
  1852. LUA_PRELOAD_FILE,
  1853. LUA_SCRIPT_EXTENSIONS,
  1854. LUA_SERVER_PAGE_EXTENSIONS,
  1855. #endif
  1856. #if defined(USE_DUKTAPE)
  1857. DUKTAPE_SCRIPT_EXTENSIONS,
  1858. #endif
  1859. #if defined(USE_WEBSOCKET)
  1860. WEBSOCKET_ROOT,
  1861. #endif
  1862. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1863. LUA_WEBSOCKET_EXTENSIONS,
  1864. #endif
  1865. ACCESS_CONTROL_ALLOW_ORIGIN,
  1866. ACCESS_CONTROL_ALLOW_METHODS,
  1867. ACCESS_CONTROL_ALLOW_HEADERS,
  1868. ERROR_PAGES,
  1869. #if !defined(NO_CACHING)
  1870. STATIC_FILE_MAX_AGE,
  1871. #endif
  1872. #if !defined(NO_SSL)
  1873. STRICT_HTTPS_MAX_AGE,
  1874. #endif
  1875. ADDITIONAL_HEADER,
  1876. ALLOW_INDEX_SCRIPT_SUB_RES,
  1877. NUM_OPTIONS
  1878. };
  1879. /* Config option name, config types, default value.
  1880. * Must be in the same order as the enum const above.
  1881. */
  1882. static struct mg_option config_options[] = {
  1883. /* Once for each server */
  1884. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1885. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1886. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1887. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1888. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1889. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1890. #if defined(__linux__)
  1891. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1892. #endif
  1893. #if defined(_WIN32)
  1894. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1895. #endif
  1896. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1897. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1898. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1899. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1900. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1901. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1902. #if defined(USE_WEBSOCKET)
  1903. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1904. #endif
  1905. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1906. #if defined(USE_LUA)
  1907. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1908. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1909. #endif
  1910. /* Once for each domain */
  1911. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1912. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1913. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1914. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1915. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1916. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1917. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1918. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1919. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1920. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1921. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1922. {"index_files",
  1923. MG_CONFIG_TYPE_STRING_LIST,
  1924. #ifdef USE_LUA
  1925. "index.xhtml,index.html,index.htm,"
  1926. "index.lp,index.lsp,index.lua,index.cgi,"
  1927. "index.shtml,index.php"},
  1928. #else
  1929. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1930. #endif
  1931. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1932. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1933. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1934. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1935. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1936. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1937. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1938. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1939. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1940. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1941. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1942. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1943. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  1944. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1945. #if defined(USE_LUA)
  1946. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1947. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1948. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1949. #endif
  1950. #if defined(USE_DUKTAPE)
  1951. /* The support for duktape is still in alpha version state.
  1952. * The name of this config option might change. */
  1953. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1954. #endif
  1955. #if defined(USE_WEBSOCKET)
  1956. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1957. #endif
  1958. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1959. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1960. #endif
  1961. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1962. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1963. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1964. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1965. #if !defined(NO_CACHING)
  1966. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1967. #endif
  1968. #if !defined(NO_SSL)
  1969. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1970. #endif
  1971. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1972. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1973. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1974. /* Check if the config_options and the corresponding enum have compatible
  1975. * sizes. */
  1976. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1977. == (NUM_OPTIONS + 1),
  1978. "config_options and enum not sync");
  1979. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1980. struct mg_handler_info {
  1981. /* Name/Pattern of the URI. */
  1982. char *uri;
  1983. size_t uri_len;
  1984. /* handler type */
  1985. int handler_type;
  1986. /* Handler for http/https or authorization requests. */
  1987. mg_request_handler handler;
  1988. /* Handler for ws/wss (websocket) requests. */
  1989. mg_websocket_connect_handler connect_handler;
  1990. mg_websocket_ready_handler ready_handler;
  1991. mg_websocket_data_handler data_handler;
  1992. mg_websocket_close_handler close_handler;
  1993. /* accepted subprotocols for ws/wss requests. */
  1994. struct mg_websocket_subprotocols *subprotocols;
  1995. /* Handler for authorization requests */
  1996. mg_authorization_handler auth_handler;
  1997. /* User supplied argument for the handler function. */
  1998. void *cbdata;
  1999. /* next handler in a linked list */
  2000. struct mg_handler_info *next;
  2001. };
  2002. enum {
  2003. CONTEXT_INVALID,
  2004. CONTEXT_SERVER,
  2005. CONTEXT_HTTP_CLIENT,
  2006. CONTEXT_WS_CLIENT
  2007. };
  2008. struct mg_domain_context {
  2009. SSL_CTX *ssl_ctx; /* SSL context */
  2010. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2011. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2012. /* Server nonce */
  2013. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2014. unsigned long nonce_count; /* Used nonces, used for authentication */
  2015. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2016. /* linked list of shared lua websockets */
  2017. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2018. #endif
  2019. /* Linked list of domains */
  2020. struct mg_domain_context *next;
  2021. };
  2022. struct mg_context {
  2023. /* Part 1 - Physical context:
  2024. * This holds threads, ports, timeouts, ...
  2025. * set for the entire server, independent from the
  2026. * addressed hostname.
  2027. */
  2028. /* Connection related */
  2029. int context_type; /* See CONTEXT_* above */
  2030. struct socket *listening_sockets;
  2031. struct pollfd *listening_socket_fds;
  2032. unsigned int num_listening_sockets;
  2033. struct mg_connection *worker_connections; /* The connection struct, pre-
  2034. * allocated for each worker */
  2035. #if defined(USE_SERVER_STATS)
  2036. int active_connections;
  2037. int max_connections;
  2038. int64_t total_connections;
  2039. int64_t total_requests;
  2040. int64_t total_data_read;
  2041. int64_t total_data_written;
  2042. #endif
  2043. /* Thread related */
  2044. volatile int stop_flag; /* Should we stop event loop */
  2045. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2046. pthread_t masterthreadid; /* The master thread ID */
  2047. unsigned int
  2048. cfg_worker_threads; /* The number of configured worker threads. */
  2049. pthread_t *worker_threadids; /* The worker thread IDs */
  2050. /* Connection to thread dispatching */
  2051. #ifdef ALTERNATIVE_QUEUE
  2052. struct socket *client_socks;
  2053. void **client_wait_events;
  2054. #else
  2055. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2056. volatile int sq_head; /* Head of the socket queue */
  2057. volatile int sq_tail; /* Tail of the socket queue */
  2058. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2059. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2060. #endif
  2061. /* Memory related */
  2062. unsigned int max_request_size; /* The max request size */
  2063. #if defined(USE_SERVER_STATS)
  2064. struct mg_memory_stat ctx_memory;
  2065. #endif
  2066. /* Operating system related */
  2067. char *systemName; /* What operating system is running */
  2068. time_t start_time; /* Server start time, used for authentication
  2069. * and for diagnstics. */
  2070. #if defined(USE_TIMERS)
  2071. struct ttimers *timers;
  2072. #endif
  2073. /* Lua specific: Background operations and shared websockets */
  2074. #if defined(USE_LUA)
  2075. void *lua_background_state;
  2076. #endif
  2077. /* Server nonce */
  2078. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2079. /* Server callbacks */
  2080. struct mg_callbacks callbacks; /* User-defined callback function */
  2081. void *user_data; /* User-defined data */
  2082. /* Part 2 - Logical domain:
  2083. * This holds hostname, TLS certificate, document root, ...
  2084. * set for a domain hosted at the server.
  2085. * There may be multiple domains hosted at one physical server.
  2086. * The default domain "dd" is the first element of a list of
  2087. * domains.
  2088. */
  2089. struct mg_domain_context dd; /* default domain */
  2090. };
  2091. #if defined(USE_SERVER_STATS)
  2092. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2093. static struct mg_memory_stat *
  2094. get_memory_stat(struct mg_context *ctx)
  2095. {
  2096. if (ctx) {
  2097. return &(ctx->ctx_memory);
  2098. }
  2099. return &mg_common_memory;
  2100. }
  2101. #endif
  2102. enum {
  2103. CONNECTION_TYPE_INVALID,
  2104. CONNECTION_TYPE_REQUEST,
  2105. CONNECTION_TYPE_RESPONSE
  2106. };
  2107. struct mg_connection {
  2108. int connection_type; /* see CONNECTION_TYPE_* above */
  2109. struct mg_request_info request_info;
  2110. struct mg_response_info response_info;
  2111. struct mg_context *phys_ctx;
  2112. struct mg_domain_context *dom_ctx;
  2113. #if defined(USE_SERVER_STATS)
  2114. int conn_state; /* 0 = undef, numerical value may change in different
  2115. * versions. For the current definition, see
  2116. * mg_get_connection_info_impl */
  2117. #endif
  2118. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2119. SSL *ssl; /* SSL descriptor */
  2120. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2121. struct socket client; /* Connected client */
  2122. time_t conn_birth_time; /* Time (wall clock) when connection was
  2123. * established */
  2124. struct timespec req_time; /* Time (since system start) when the request
  2125. * was received */
  2126. int64_t num_bytes_sent; /* Total bytes sent to client */
  2127. int64_t content_len; /* Content-Length header value */
  2128. int64_t consumed_content; /* How many bytes of content have been read */
  2129. int is_chunked; /* Transfer-Encoding is chunked:
  2130. * 0 = not chunked,
  2131. * 1 = chunked, do data read yet,
  2132. * 2 = chunked, some data read,
  2133. * 3 = chunked, all data read
  2134. */
  2135. size_t chunk_remainder; /* Unread data from the last chunk */
  2136. char *buf; /* Buffer for received data */
  2137. char *path_info; /* PATH_INFO part of the URL */
  2138. int must_close; /* 1 if connection must be closed */
  2139. int accept_gzip; /* 1 if gzip encoding is accepted */
  2140. int in_error_handler; /* 1 if in handler for user defined error
  2141. * pages */
  2142. #if defined(USE_WEBSOCKET)
  2143. int in_websocket_handling; /* 1 if in read_websocket */
  2144. #endif
  2145. int handled_requests; /* Number of requests handled by this connection
  2146. */
  2147. int buf_size; /* Buffer size */
  2148. int request_len; /* Size of the request + headers in a buffer */
  2149. int data_len; /* Total size of data in a buffer */
  2150. int status_code; /* HTTP reply status code, e.g. 200 */
  2151. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2152. * throttle */
  2153. time_t last_throttle_time; /* Last time throttled data was sent */
  2154. int64_t last_throttle_bytes; /* Bytes sent this second */
  2155. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2156. * atomic transmissions for websockets */
  2157. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2158. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2159. #endif
  2160. int thread_index; /* Thread index within ctx */
  2161. };
  2162. /* Directory entry */
  2163. struct de {
  2164. struct mg_connection *conn;
  2165. char *file_name;
  2166. struct mg_file_stat file;
  2167. };
  2168. #if defined(USE_WEBSOCKET)
  2169. static int is_websocket_protocol(const struct mg_connection *conn);
  2170. #else
  2171. #define is_websocket_protocol(conn) (0)
  2172. #endif
  2173. #define mg_cry_internal(conn, fmt, ...) \
  2174. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2175. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2176. const char *func,
  2177. unsigned line,
  2178. const char *fmt,
  2179. ...) PRINTF_ARGS(4, 5);
  2180. #if !defined(NO_THREAD_NAME)
  2181. #if defined(_WIN32) && defined(_MSC_VER)
  2182. /* Set the thread name for debugging purposes in Visual Studio
  2183. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2184. */
  2185. #pragma pack(push, 8)
  2186. typedef struct tagTHREADNAME_INFO {
  2187. DWORD dwType; /* Must be 0x1000. */
  2188. LPCSTR szName; /* Pointer to name (in user addr space). */
  2189. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2190. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2191. } THREADNAME_INFO;
  2192. #pragma pack(pop)
  2193. #elif defined(__linux__)
  2194. #include <sys/prctl.h>
  2195. #include <sys/sendfile.h>
  2196. #ifdef ALTERNATIVE_QUEUE
  2197. #include <sys/eventfd.h>
  2198. #endif /* ALTERNATIVE_QUEUE */
  2199. #if defined(ALTERNATIVE_QUEUE)
  2200. #ifdef __clang__
  2201. #pragma clang diagnostic push
  2202. #pragma clang diagnostic ignored "-Wunreachable-code"
  2203. /* For every system, "(sizeof(int) == sizeof(void *))" is either always
  2204. * true or always false. One of the two branches is unreachable in any case.
  2205. * Unfortunately the C standard does not define a way to check this at
  2206. * compile time, since the #if preprocessor conditions can not use the sizeof
  2207. * operator as an argument. */
  2208. #endif
  2209. #if defined(__GNUC__) || defined(__MINGW32__)
  2210. /* GCC does not realize one branch is unreachable, so it raises some
  2211. * pointer cast warning within the unreachable branch.
  2212. */
  2213. #pragma GCC diagnostic push
  2214. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
  2215. #pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
  2216. #endif
  2217. static void *
  2218. event_create(void)
  2219. {
  2220. int evhdl = eventfd(0, EFD_CLOEXEC);
  2221. int *ret;
  2222. if (evhdl == -1) {
  2223. /* Linux uses -1 on error, Windows NULL. */
  2224. /* However, Linux does not return 0 on success either. */
  2225. return 0;
  2226. }
  2227. if (sizeof(int) == sizeof(void *)) {
  2228. ret = (void *)evhdl;
  2229. } else {
  2230. ret = (int *)mg_malloc(sizeof(int));
  2231. if (ret) {
  2232. *ret = evhdl;
  2233. } else {
  2234. (void)close(evhdl);
  2235. }
  2236. }
  2237. return (void *)ret;
  2238. }
  2239. static int
  2240. event_wait(void *eventhdl)
  2241. {
  2242. uint64_t u;
  2243. int evhdl, s;
  2244. if (sizeof(int) == sizeof(void *)) {
  2245. evhdl = (int)eventhdl;
  2246. } else {
  2247. if (!eventhdl) {
  2248. /* error */
  2249. return 0;
  2250. }
  2251. evhdl = *(int *)eventhdl;
  2252. }
  2253. s = (int)read(evhdl, &u, sizeof(u));
  2254. if (s != sizeof(uint64_t)) {
  2255. /* error */
  2256. return 0;
  2257. }
  2258. (void)u; /* the value is not required */
  2259. return 1;
  2260. }
  2261. static int
  2262. event_signal(void *eventhdl)
  2263. {
  2264. uint64_t u = 1;
  2265. int evhdl, s;
  2266. if (sizeof(int) == sizeof(void *)) {
  2267. evhdl = (int)eventhdl;
  2268. } else {
  2269. if (!eventhdl) {
  2270. /* error */
  2271. return 0;
  2272. }
  2273. evhdl = *(int *)eventhdl;
  2274. }
  2275. s = (int)write(evhdl, &u, sizeof(u));
  2276. if (s != sizeof(uint64_t)) {
  2277. /* error */
  2278. return 0;
  2279. }
  2280. return 1;
  2281. }
  2282. static void
  2283. event_destroy(void *eventhdl)
  2284. {
  2285. int evhdl;
  2286. if (sizeof(int) == sizeof(void *)) {
  2287. evhdl = (int)eventhdl;
  2288. close(evhdl);
  2289. } else {
  2290. if (!eventhdl) {
  2291. /* error */
  2292. return;
  2293. }
  2294. evhdl = *(int *)eventhdl;
  2295. close(evhdl);
  2296. mg_free(eventhdl);
  2297. }
  2298. }
  2299. #if defined(__GNUC__) || defined(__MINGW32__)
  2300. #pragma GCC diagnostic pop
  2301. #endif
  2302. #ifdef __clang__
  2303. #pragma clang diagnostic pop
  2304. #endif
  2305. #endif
  2306. #endif
  2307. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2308. struct posix_event {
  2309. pthread_mutex_t mutex;
  2310. pthread_cond_t cond;
  2311. };
  2312. static void *
  2313. event_create(void)
  2314. {
  2315. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2316. if (ret == 0) {
  2317. /* out of memory */
  2318. return 0;
  2319. }
  2320. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2321. /* pthread mutex not available */
  2322. mg_free(ret);
  2323. return 0;
  2324. }
  2325. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2326. /* pthread cond not available */
  2327. pthread_mutex_destroy(&(ret->mutex));
  2328. mg_free(ret);
  2329. return 0;
  2330. }
  2331. return (void *)ret;
  2332. }
  2333. static int
  2334. event_wait(void *eventhdl)
  2335. {
  2336. struct posix_event *ev = (struct posix_event *)eventhdl;
  2337. pthread_mutex_lock(&(ev->mutex));
  2338. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2339. pthread_mutex_unlock(&(ev->mutex));
  2340. return 1;
  2341. }
  2342. static int
  2343. event_signal(void *eventhdl)
  2344. {
  2345. struct posix_event *ev = (struct posix_event *)eventhdl;
  2346. pthread_mutex_lock(&(ev->mutex));
  2347. pthread_cond_signal(&(ev->cond));
  2348. pthread_mutex_unlock(&(ev->mutex));
  2349. return 1;
  2350. }
  2351. static void
  2352. event_destroy(void *eventhdl)
  2353. {
  2354. struct posix_event *ev = (struct posix_event *)eventhdl;
  2355. pthread_cond_destroy(&(ev->cond));
  2356. pthread_mutex_destroy(&(ev->mutex));
  2357. mg_free(ev);
  2358. }
  2359. #endif
  2360. static void
  2361. mg_set_thread_name(const char *name)
  2362. {
  2363. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2364. mg_snprintf(
  2365. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2366. #if defined(_WIN32)
  2367. #if defined(_MSC_VER)
  2368. /* Windows and Visual Studio Compiler */
  2369. __try
  2370. {
  2371. THREADNAME_INFO info;
  2372. info.dwType = 0x1000;
  2373. info.szName = threadName;
  2374. info.dwThreadID = ~0U;
  2375. info.dwFlags = 0;
  2376. RaiseException(0x406D1388,
  2377. 0,
  2378. sizeof(info) / sizeof(ULONG_PTR),
  2379. (ULONG_PTR *)&info);
  2380. }
  2381. __except(EXCEPTION_EXECUTE_HANDLER)
  2382. {
  2383. }
  2384. #elif defined(__MINGW32__)
  2385. /* No option known to set thread name for MinGW */
  2386. #endif
  2387. #elif defined(__GLIBC__) \
  2388. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2389. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2390. (void)pthread_setname_np(pthread_self(), threadName);
  2391. #elif defined(__linux__)
  2392. /* on linux we can use the old prctl function */
  2393. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2394. #endif
  2395. }
  2396. #else /* !defined(NO_THREAD_NAME) */
  2397. void
  2398. mg_set_thread_name(const char *threadName)
  2399. {
  2400. }
  2401. #endif
  2402. #if defined(MG_LEGACY_INTERFACE)
  2403. const char **
  2404. mg_get_valid_option_names(void)
  2405. {
  2406. /* This function is deprecated. Use mg_get_valid_options instead. */
  2407. static const char *
  2408. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2409. int i;
  2410. for (i = 0; config_options[i].name != NULL; i++) {
  2411. data[i * 2] = config_options[i].name;
  2412. data[i * 2 + 1] = config_options[i].default_value;
  2413. }
  2414. return data;
  2415. }
  2416. #endif
  2417. const struct mg_option *
  2418. mg_get_valid_options(void)
  2419. {
  2420. return config_options;
  2421. }
  2422. /* Do not open file (used in is_file_in_memory) */
  2423. #define MG_FOPEN_MODE_NONE (0)
  2424. /* Open file for read only access */
  2425. #define MG_FOPEN_MODE_READ (1)
  2426. /* Open file for writing, create and overwrite */
  2427. #define MG_FOPEN_MODE_WRITE (2)
  2428. /* Open file for writing, create and append */
  2429. #define MG_FOPEN_MODE_APPEND (4)
  2430. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2431. * output filep and return 1, otherwise return 0 and don't modify anything.
  2432. */
  2433. static int
  2434. open_file_in_memory(const struct mg_connection *conn,
  2435. const char *path,
  2436. struct mg_file *filep,
  2437. int mode)
  2438. {
  2439. #if defined(MG_USE_OPEN_FILE)
  2440. size_t size = 0;
  2441. const char *buf = NULL;
  2442. if (!conn) {
  2443. return 0;
  2444. }
  2445. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2446. return 0;
  2447. }
  2448. if (conn->phys_ctx->callbacks.open_file) {
  2449. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2450. if (buf != NULL) {
  2451. if (filep == NULL) {
  2452. /* This is a file in memory, but we cannot store the
  2453. * properties
  2454. * now.
  2455. * Called from "is_file_in_memory" function. */
  2456. return 1;
  2457. }
  2458. /* NOTE: override filep->size only on success. Otherwise, it
  2459. * might
  2460. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2461. filep->access.membuf = buf;
  2462. filep->access.fp = NULL;
  2463. /* Size was set by the callback */
  2464. filep->stat.size = size;
  2465. /* Assume the data may change during runtime by setting
  2466. * last_modified = now */
  2467. filep->stat.last_modified = time(NULL);
  2468. filep->stat.is_directory = 0;
  2469. filep->stat.is_gzipped = 0;
  2470. }
  2471. }
  2472. return (buf != NULL);
  2473. #else
  2474. (void)conn;
  2475. (void)path;
  2476. (void)filep;
  2477. (void)mode;
  2478. return 0;
  2479. #endif
  2480. }
  2481. static int
  2482. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2483. {
  2484. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2485. }
  2486. static int
  2487. is_file_opened(const struct mg_file_access *fileacc)
  2488. {
  2489. if (!fileacc) {
  2490. return 0;
  2491. }
  2492. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2493. }
  2494. static int mg_stat(const struct mg_connection *conn,
  2495. const char *path,
  2496. struct mg_file_stat *filep);
  2497. /* mg_fopen will open a file either in memory or on the disk.
  2498. * The input parameter path is a string in UTF-8 encoding.
  2499. * The input parameter mode is MG_FOPEN_MODE_*
  2500. * On success, either fp or membuf will be set in the output
  2501. * struct file. All status members will also be set.
  2502. * The function returns 1 on success, 0 on error. */
  2503. static int
  2504. mg_fopen(const struct mg_connection *conn,
  2505. const char *path,
  2506. int mode,
  2507. struct mg_file *filep)
  2508. {
  2509. int found;
  2510. if (!filep) {
  2511. return 0;
  2512. }
  2513. filep->access.fp = NULL;
  2514. filep->access.membuf = NULL;
  2515. if (!is_file_in_memory(conn, path)) {
  2516. /* filep is initialized in mg_stat: all fields with memset to,
  2517. * some fields like size and modification date with values */
  2518. found = mg_stat(conn, path, &(filep->stat));
  2519. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2520. /* file does not exist and will not be created */
  2521. return 0;
  2522. }
  2523. #ifdef _WIN32
  2524. {
  2525. wchar_t wbuf[W_PATH_MAX];
  2526. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2527. switch (mode) {
  2528. case MG_FOPEN_MODE_READ:
  2529. filep->access.fp = _wfopen(wbuf, L"rb");
  2530. break;
  2531. case MG_FOPEN_MODE_WRITE:
  2532. filep->access.fp = _wfopen(wbuf, L"wb");
  2533. break;
  2534. case MG_FOPEN_MODE_APPEND:
  2535. filep->access.fp = _wfopen(wbuf, L"ab");
  2536. break;
  2537. }
  2538. }
  2539. #else
  2540. /* Linux et al already use unicode. No need to convert. */
  2541. switch (mode) {
  2542. case MG_FOPEN_MODE_READ:
  2543. filep->access.fp = fopen(path, "r");
  2544. break;
  2545. case MG_FOPEN_MODE_WRITE:
  2546. filep->access.fp = fopen(path, "w");
  2547. break;
  2548. case MG_FOPEN_MODE_APPEND:
  2549. filep->access.fp = fopen(path, "a");
  2550. break;
  2551. }
  2552. #endif
  2553. if (!found) {
  2554. /* File did not exist before fopen was called.
  2555. * Maybe it has been created now. Get stat info
  2556. * like creation time now. */
  2557. found = mg_stat(conn, path, &(filep->stat));
  2558. (void)found;
  2559. }
  2560. /* file is on disk */
  2561. return (filep->access.fp != NULL);
  2562. } else {
  2563. /* is_file_in_memory returned true */
  2564. if (open_file_in_memory(conn, path, filep, mode)) {
  2565. /* file is in memory */
  2566. return (filep->access.membuf != NULL);
  2567. }
  2568. }
  2569. /* Open failed */
  2570. return 0;
  2571. }
  2572. /* return 0 on success, just like fclose */
  2573. static int
  2574. mg_fclose(struct mg_file_access *fileacc)
  2575. {
  2576. int ret = -1;
  2577. if (fileacc != NULL) {
  2578. if (fileacc->fp != NULL) {
  2579. ret = fclose(fileacc->fp);
  2580. } else if (fileacc->membuf != NULL) {
  2581. ret = 0;
  2582. }
  2583. /* reset all members of fileacc */
  2584. memset(fileacc, 0, sizeof(*fileacc));
  2585. }
  2586. return ret;
  2587. }
  2588. static void
  2589. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2590. {
  2591. for (; *src != '\0' && n > 1; n--) {
  2592. *dst++ = *src++;
  2593. }
  2594. *dst = '\0';
  2595. }
  2596. static int
  2597. lowercase(const char *s)
  2598. {
  2599. return tolower(*(const unsigned char *)s);
  2600. }
  2601. int
  2602. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2603. {
  2604. int diff = 0;
  2605. if (len > 0) {
  2606. do {
  2607. diff = lowercase(s1++) - lowercase(s2++);
  2608. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2609. }
  2610. return diff;
  2611. }
  2612. int
  2613. mg_strcasecmp(const char *s1, const char *s2)
  2614. {
  2615. int diff;
  2616. do {
  2617. diff = lowercase(s1++) - lowercase(s2++);
  2618. } while (diff == 0 && s1[-1] != '\0');
  2619. return diff;
  2620. }
  2621. static char *
  2622. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2623. {
  2624. char *p;
  2625. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2626. * defined */
  2627. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2628. mg_strlcpy(p, ptr, len + 1);
  2629. }
  2630. return p;
  2631. }
  2632. static char *
  2633. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2634. {
  2635. return mg_strndup_ctx(str, strlen(str), ctx);
  2636. }
  2637. static char *
  2638. mg_strdup(const char *str)
  2639. {
  2640. return mg_strndup_ctx(str, strlen(str), NULL);
  2641. }
  2642. static const char *
  2643. mg_strcasestr(const char *big_str, const char *small_str)
  2644. {
  2645. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2646. if (big_len >= small_len) {
  2647. for (i = 0; i <= (big_len - small_len); i++) {
  2648. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2649. return big_str + i;
  2650. }
  2651. }
  2652. }
  2653. return NULL;
  2654. }
  2655. /* Return null terminated string of given maximum length.
  2656. * Report errors if length is exceeded. */
  2657. static void
  2658. mg_vsnprintf(const struct mg_connection *conn,
  2659. int *truncated,
  2660. char *buf,
  2661. size_t buflen,
  2662. const char *fmt,
  2663. va_list ap)
  2664. {
  2665. int n, ok;
  2666. if (buflen == 0) {
  2667. if (truncated) {
  2668. *truncated = 1;
  2669. }
  2670. return;
  2671. }
  2672. #ifdef __clang__
  2673. #pragma clang diagnostic push
  2674. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2675. /* Using fmt as a non-literal is intended here, since it is mostly called
  2676. * indirectly by mg_snprintf */
  2677. #endif
  2678. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2679. ok = (n >= 0) && ((size_t)n < buflen);
  2680. #ifdef __clang__
  2681. #pragma clang diagnostic pop
  2682. #endif
  2683. if (ok) {
  2684. if (truncated) {
  2685. *truncated = 0;
  2686. }
  2687. } else {
  2688. if (truncated) {
  2689. *truncated = 1;
  2690. }
  2691. mg_cry_internal(conn,
  2692. "truncating vsnprintf buffer: [%.*s]",
  2693. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2694. buf);
  2695. n = (int)buflen - 1;
  2696. }
  2697. buf[n] = '\0';
  2698. }
  2699. static void
  2700. mg_snprintf(const struct mg_connection *conn,
  2701. int *truncated,
  2702. char *buf,
  2703. size_t buflen,
  2704. const char *fmt,
  2705. ...)
  2706. {
  2707. va_list ap;
  2708. va_start(ap, fmt);
  2709. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2710. va_end(ap);
  2711. }
  2712. static int
  2713. get_option_index(const char *name)
  2714. {
  2715. int i;
  2716. for (i = 0; config_options[i].name != NULL; i++) {
  2717. if (strcmp(config_options[i].name, name) == 0) {
  2718. return i;
  2719. }
  2720. }
  2721. return -1;
  2722. }
  2723. const char *
  2724. mg_get_option(const struct mg_context *ctx, const char *name)
  2725. {
  2726. int i;
  2727. if ((i = get_option_index(name)) == -1) {
  2728. return NULL;
  2729. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2730. return "";
  2731. } else {
  2732. return ctx->dd.config[i];
  2733. }
  2734. }
  2735. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2736. struct mg_context *
  2737. mg_get_context(const struct mg_connection *conn)
  2738. {
  2739. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2740. }
  2741. void *
  2742. mg_get_user_data(const struct mg_context *ctx)
  2743. {
  2744. return (ctx == NULL) ? NULL : ctx->user_data;
  2745. }
  2746. void
  2747. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2748. {
  2749. if (conn != NULL) {
  2750. conn->request_info.conn_data = data;
  2751. }
  2752. }
  2753. void *
  2754. mg_get_user_connection_data(const struct mg_connection *conn)
  2755. {
  2756. if (conn != NULL) {
  2757. return conn->request_info.conn_data;
  2758. }
  2759. return NULL;
  2760. }
  2761. #if defined(MG_LEGACY_INTERFACE)
  2762. /* Deprecated: Use mg_get_server_ports instead. */
  2763. size_t
  2764. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2765. {
  2766. size_t i;
  2767. if (!ctx) {
  2768. return 0;
  2769. }
  2770. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2771. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2772. ports[i] =
  2773. #if defined(USE_IPV6)
  2774. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2775. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2776. :
  2777. #endif
  2778. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2779. }
  2780. return i;
  2781. }
  2782. #endif
  2783. int
  2784. mg_get_server_ports(const struct mg_context *ctx,
  2785. int size,
  2786. struct mg_server_ports *ports)
  2787. {
  2788. int i, cnt = 0;
  2789. if (size <= 0) {
  2790. return -1;
  2791. }
  2792. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2793. if (!ctx) {
  2794. return -1;
  2795. }
  2796. if (!ctx->listening_sockets) {
  2797. return -1;
  2798. }
  2799. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2800. ports[cnt].port =
  2801. #if defined(USE_IPV6)
  2802. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2803. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2804. :
  2805. #endif
  2806. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2807. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2808. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2809. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2810. /* IPv4 */
  2811. ports[cnt].protocol = 1;
  2812. cnt++;
  2813. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2814. /* IPv6 */
  2815. ports[cnt].protocol = 3;
  2816. cnt++;
  2817. }
  2818. }
  2819. return cnt;
  2820. }
  2821. static void
  2822. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2823. {
  2824. buf[0] = '\0';
  2825. if (!usa) {
  2826. return;
  2827. }
  2828. if (usa->sa.sa_family == AF_INET) {
  2829. getnameinfo(&usa->sa,
  2830. sizeof(usa->sin),
  2831. buf,
  2832. (unsigned)len,
  2833. NULL,
  2834. 0,
  2835. NI_NUMERICHOST);
  2836. }
  2837. #if defined(USE_IPV6)
  2838. else if (usa->sa.sa_family == AF_INET6) {
  2839. getnameinfo(&usa->sa,
  2840. sizeof(usa->sin6),
  2841. buf,
  2842. (unsigned)len,
  2843. NULL,
  2844. 0,
  2845. NI_NUMERICHOST);
  2846. }
  2847. #endif
  2848. }
  2849. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2850. * included in all responses other than 100, 101, 5xx. */
  2851. static void
  2852. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2853. {
  2854. #ifndef REENTRANT_TIME
  2855. struct tm *tm;
  2856. tm = ((t != NULL) ? gmtime(t) : NULL);
  2857. if (tm != NULL) {
  2858. #else
  2859. struct tm _tm;
  2860. struct tm *tm = &_tm;
  2861. if (t != NULL) {
  2862. gmtime_r(t, tm);
  2863. #endif
  2864. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2865. } else {
  2866. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2867. buf[buf_len - 1] = '\0';
  2868. }
  2869. }
  2870. /* difftime for struct timespec. Return value is in seconds. */
  2871. static double
  2872. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2873. {
  2874. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2875. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2876. }
  2877. /* Print error message to the opened error log stream. */
  2878. static void
  2879. mg_cry_internal_impl(const struct mg_connection *conn,
  2880. const char *func,
  2881. unsigned line,
  2882. const char *fmt,
  2883. va_list ap)
  2884. {
  2885. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2886. struct mg_file fi;
  2887. time_t timestamp;
  2888. /* Unused, in the RELEASE build */
  2889. (void)func;
  2890. (void)line;
  2891. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2892. buf[sizeof(buf) - 1] = 0;
  2893. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2894. if (!conn) {
  2895. puts(buf);
  2896. return;
  2897. }
  2898. /* Do not lock when getting the callback value, here and below.
  2899. * I suppose this is fine, since function cannot disappear in the
  2900. * same way string option can. */
  2901. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2902. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2903. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2904. if (mg_fopen(conn,
  2905. conn->dom_ctx->config[ERROR_LOG_FILE],
  2906. MG_FOPEN_MODE_APPEND,
  2907. &fi) == 0) {
  2908. fi.access.fp = NULL;
  2909. }
  2910. } else {
  2911. fi.access.fp = NULL;
  2912. }
  2913. if (fi.access.fp != NULL) {
  2914. flockfile(fi.access.fp);
  2915. timestamp = time(NULL);
  2916. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2917. fprintf(fi.access.fp,
  2918. "[%010lu] [error] [client %s] ",
  2919. (unsigned long)timestamp,
  2920. src_addr);
  2921. if (conn->request_info.request_method != NULL) {
  2922. fprintf(fi.access.fp,
  2923. "%s %s: ",
  2924. conn->request_info.request_method,
  2925. conn->request_info.request_uri
  2926. ? conn->request_info.request_uri
  2927. : "");
  2928. }
  2929. fprintf(fi.access.fp, "%s", buf);
  2930. fputc('\n', fi.access.fp);
  2931. fflush(fi.access.fp);
  2932. funlockfile(fi.access.fp);
  2933. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2934. * mg_cry here anyway ;-) */
  2935. }
  2936. }
  2937. }
  2938. static void
  2939. mg_cry_internal_wrap(const struct mg_connection *conn,
  2940. const char *func,
  2941. unsigned line,
  2942. const char *fmt,
  2943. ...)
  2944. {
  2945. va_list ap;
  2946. va_start(ap, fmt);
  2947. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2948. va_end(ap);
  2949. }
  2950. void
  2951. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2952. {
  2953. va_list ap;
  2954. va_start(ap, fmt);
  2955. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2956. va_end(ap);
  2957. }
  2958. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2959. /* Return fake connection structure. Used for logging, if connection
  2960. * is not applicable at the moment of logging. */
  2961. static struct mg_connection *
  2962. fc(struct mg_context *ctx)
  2963. {
  2964. static struct mg_connection fake_connection;
  2965. fake_connection.phys_ctx = ctx;
  2966. fake_connection.dom_ctx = &(ctx->dd);
  2967. return &fake_connection;
  2968. }
  2969. const char *
  2970. mg_version(void)
  2971. {
  2972. return CIVETWEB_VERSION;
  2973. }
  2974. const struct mg_request_info *
  2975. mg_get_request_info(const struct mg_connection *conn)
  2976. {
  2977. if (!conn) {
  2978. return NULL;
  2979. }
  2980. #if 1 /* TODO: deal with legacy */
  2981. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2982. static char txt[16];
  2983. sprintf(txt, "%03i", conn->response_info.status_code);
  2984. ((struct mg_connection *)conn)->request_info.local_uri =
  2985. ((struct mg_connection *)conn)->request_info.request_uri =
  2986. txt; /* TODO: not thread safe */
  2987. ((struct mg_connection *)conn)->request_info.num_headers =
  2988. conn->response_info.num_headers;
  2989. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2990. conn->response_info.http_headers,
  2991. sizeof(conn->response_info.http_headers));
  2992. } else
  2993. #endif
  2994. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2995. return NULL;
  2996. }
  2997. return &conn->request_info;
  2998. }
  2999. const struct mg_response_info *
  3000. mg_get_response_info(const struct mg_connection *conn)
  3001. {
  3002. if (!conn) {
  3003. return NULL;
  3004. }
  3005. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3006. return NULL;
  3007. }
  3008. return &conn->response_info;
  3009. }
  3010. static const char *
  3011. get_proto_name(const struct mg_connection *conn)
  3012. {
  3013. #ifdef __clang__
  3014. #pragma clang diagnostic push
  3015. #pragma clang diagnostic ignored "-Wunreachable-code"
  3016. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3017. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3018. * unreachable, but splitting into four different #ifdef clauses here is more
  3019. * complicated.
  3020. */
  3021. #endif
  3022. const struct mg_request_info *ri = &conn->request_info;
  3023. const char *proto =
  3024. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3025. : (ri->is_ssl ? "https" : "http"));
  3026. return proto;
  3027. #ifdef __clang__
  3028. #pragma clang diagnostic pop
  3029. #endif
  3030. }
  3031. int
  3032. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3033. {
  3034. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3035. return -1;
  3036. } else {
  3037. int truncated = 0;
  3038. const struct mg_request_info *ri = &conn->request_info;
  3039. const char *proto = get_proto_name(conn);
  3040. if (ri->local_uri == NULL) {
  3041. return -1;
  3042. }
  3043. if ((ri->request_uri != NULL)
  3044. && strcmp(ri->local_uri, ri->request_uri)) {
  3045. mg_snprintf(conn,
  3046. &truncated,
  3047. buf,
  3048. buflen,
  3049. "%s://%s",
  3050. proto,
  3051. ri->request_uri);
  3052. if (truncated) {
  3053. return -1;
  3054. }
  3055. return 0;
  3056. } else {
  3057. #if defined(USE_IPV6)
  3058. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3059. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3060. : htons(conn->client.lsa.sin.sin_port);
  3061. #else
  3062. int port = htons(conn->client.lsa.sin.sin_port);
  3063. #endif
  3064. int def_port = ri->is_ssl ? 443 : 80;
  3065. int auth_domain_check_enabled =
  3066. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3067. && (!mg_strcasecmp(
  3068. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  3069. "yes"));
  3070. const char *server_domain =
  3071. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3072. char portstr[16];
  3073. char server_ip[48];
  3074. if (port != def_port) {
  3075. sprintf(portstr, ":%u", (unsigned)port);
  3076. } else {
  3077. portstr[0] = 0;
  3078. }
  3079. if (!auth_domain_check_enabled || !server_domain) {
  3080. sockaddr_to_string(server_ip,
  3081. sizeof(server_ip),
  3082. &conn->client.lsa);
  3083. server_domain = server_ip;
  3084. }
  3085. mg_snprintf(conn,
  3086. &truncated,
  3087. buf,
  3088. buflen,
  3089. "%s://%s%s%s",
  3090. proto,
  3091. server_domain,
  3092. portstr,
  3093. ri->local_uri);
  3094. if (truncated) {
  3095. return -1;
  3096. }
  3097. return 0;
  3098. }
  3099. }
  3100. }
  3101. /* Skip the characters until one of the delimiters characters found.
  3102. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3103. * Advance pointer to buffer to the next word. Return found 0-terminated
  3104. * word.
  3105. * Delimiters can be quoted with quotechar. */
  3106. static char *
  3107. skip_quoted(char **buf,
  3108. const char *delimiters,
  3109. const char *whitespace,
  3110. char quotechar)
  3111. {
  3112. char *p, *begin_word, *end_word, *end_whitespace;
  3113. begin_word = *buf;
  3114. end_word = begin_word + strcspn(begin_word, delimiters);
  3115. /* Check for quotechar */
  3116. if (end_word > begin_word) {
  3117. p = end_word - 1;
  3118. while (*p == quotechar) {
  3119. /* While the delimiter is quoted, look for the next delimiter.
  3120. */
  3121. /* This happens, e.g., in calls from parse_auth_header,
  3122. * if the user name contains a " character. */
  3123. /* If there is anything beyond end_word, copy it. */
  3124. if (*end_word != '\0') {
  3125. size_t end_off = strcspn(end_word + 1, delimiters);
  3126. memmove(p, end_word, end_off + 1);
  3127. p += end_off; /* p must correspond to end_word - 1 */
  3128. end_word += end_off + 1;
  3129. } else {
  3130. *p = '\0';
  3131. break;
  3132. }
  3133. }
  3134. for (p++; p < end_word; p++) {
  3135. *p = '\0';
  3136. }
  3137. }
  3138. if (*end_word == '\0') {
  3139. *buf = end_word;
  3140. } else {
  3141. #if defined(__GNUC__) || defined(__MINGW32__)
  3142. /* Disable spurious conversion warning for GCC */
  3143. #if GCC_VERSION >= 40500
  3144. #pragma GCC diagnostic push
  3145. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3146. #endif /* GCC_VERSION >= 40500 */
  3147. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3148. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3149. #if defined(__GNUC__) || defined(__MINGW32__)
  3150. #if GCC_VERSION >= 40500
  3151. #pragma GCC diagnostic pop
  3152. #endif /* GCC_VERSION >= 40500 */
  3153. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3154. for (p = end_word; p < end_whitespace; p++) {
  3155. *p = '\0';
  3156. }
  3157. *buf = end_whitespace;
  3158. }
  3159. return begin_word;
  3160. }
  3161. /* Return HTTP header value, or NULL if not found. */
  3162. static const char *
  3163. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3164. {
  3165. int i;
  3166. for (i = 0; i < num_hdr; i++) {
  3167. if (!mg_strcasecmp(name, hdr[i].name)) {
  3168. return hdr[i].value;
  3169. }
  3170. }
  3171. return NULL;
  3172. }
  3173. #if defined(USE_WEBSOCKET)
  3174. /* Retrieve requested HTTP header multiple values, and return the number of
  3175. * found occurrences */
  3176. static int
  3177. get_req_headers(const struct mg_request_info *ri,
  3178. const char *name,
  3179. const char **output,
  3180. int output_max_size)
  3181. {
  3182. int i;
  3183. int cnt = 0;
  3184. if (ri) {
  3185. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3186. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3187. output[cnt++] = ri->http_headers[i].value;
  3188. }
  3189. }
  3190. }
  3191. return cnt;
  3192. }
  3193. #endif
  3194. const char *
  3195. mg_get_header(const struct mg_connection *conn, const char *name)
  3196. {
  3197. if (!conn) {
  3198. return NULL;
  3199. }
  3200. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3201. return get_header(conn->request_info.http_headers,
  3202. conn->request_info.num_headers,
  3203. name);
  3204. }
  3205. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3206. return get_header(conn->response_info.http_headers,
  3207. conn->response_info.num_headers,
  3208. name);
  3209. }
  3210. return NULL;
  3211. }
  3212. static const char *
  3213. get_http_version(const struct mg_connection *conn)
  3214. {
  3215. if (!conn) {
  3216. return NULL;
  3217. }
  3218. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3219. return conn->request_info.http_version;
  3220. }
  3221. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3222. return conn->response_info.http_version;
  3223. }
  3224. return NULL;
  3225. }
  3226. /* A helper function for traversing a comma separated list of values.
  3227. * It returns a list pointer shifted to the next value, or NULL if the end
  3228. * of the list found.
  3229. * Value is stored in val vector. If value has form "x=y", then eq_val
  3230. * vector is initialized to point to the "y" part, and val vector length
  3231. * is adjusted to point only to "x". */
  3232. static const char *
  3233. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3234. {
  3235. int end;
  3236. reparse:
  3237. if (val == NULL || list == NULL || *list == '\0') {
  3238. /* End of the list */
  3239. return NULL;
  3240. }
  3241. /* Skip over leading LWS */
  3242. while (*list == ' ' || *list == '\t')
  3243. list++;
  3244. val->ptr = list;
  3245. if ((list = strchr(val->ptr, ',')) != NULL) {
  3246. /* Comma found. Store length and shift the list ptr */
  3247. val->len = ((size_t)(list - val->ptr));
  3248. list++;
  3249. } else {
  3250. /* This value is the last one */
  3251. list = val->ptr + strlen(val->ptr);
  3252. val->len = ((size_t)(list - val->ptr));
  3253. }
  3254. /* Adjust length for trailing LWS */
  3255. end = (int)val->len - 1;
  3256. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3257. end--;
  3258. val->len = (size_t)(end + 1);
  3259. if (val->len == 0) {
  3260. /* Ignore any empty entries. */
  3261. goto reparse;
  3262. }
  3263. if (eq_val != NULL) {
  3264. /* Value has form "x=y", adjust pointers and lengths
  3265. * so that val points to "x", and eq_val points to "y". */
  3266. eq_val->len = 0;
  3267. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3268. if (eq_val->ptr != NULL) {
  3269. eq_val->ptr++; /* Skip over '=' character */
  3270. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3271. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3272. }
  3273. }
  3274. return list;
  3275. }
  3276. /* A helper function for checking if a comma separated list of values
  3277. * contains
  3278. * the given option (case insensitvely).
  3279. * 'header' can be NULL, in which case false is returned. */
  3280. static int
  3281. header_has_option(const char *header, const char *option)
  3282. {
  3283. struct vec opt_vec;
  3284. struct vec eq_vec;
  3285. DEBUG_ASSERT(option != NULL);
  3286. DEBUG_ASSERT(option[0] != '\0');
  3287. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3288. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3289. return 1;
  3290. }
  3291. return 0;
  3292. }
  3293. /* Perform case-insensitive match of string against pattern */
  3294. static int
  3295. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3296. {
  3297. const char *or_str;
  3298. size_t i;
  3299. int j, len, res;
  3300. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3301. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3302. return (res > 0) ? res : match_prefix(or_str + 1,
  3303. (size_t)((pattern + pattern_len)
  3304. - (or_str + 1)),
  3305. str);
  3306. }
  3307. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  3308. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3309. continue;
  3310. } else if (pattern[i] == '$') {
  3311. return (str[j] == '\0') ? j : -1;
  3312. } else if (pattern[i] == '*') {
  3313. i++;
  3314. if (pattern[i] == '*') {
  3315. i++;
  3316. len = (int)strlen(str + j);
  3317. } else {
  3318. len = (int)strcspn(str + j, "/");
  3319. }
  3320. if (i == pattern_len) {
  3321. return j + len;
  3322. }
  3323. do {
  3324. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3325. } while (res == -1 && len-- > 0);
  3326. return (res == -1) ? -1 : j + res + len;
  3327. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3328. return -1;
  3329. }
  3330. }
  3331. return j;
  3332. }
  3333. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3334. * This function must tolerate situations when connection info is not
  3335. * set up, for example if request parsing failed. */
  3336. static int
  3337. should_keep_alive(const struct mg_connection *conn)
  3338. {
  3339. const char *http_version;
  3340. const char *header;
  3341. /* First satisfy needs of the server */
  3342. if ((conn == NULL) || conn->must_close) {
  3343. /* Close, if civetweb framework needs to close */
  3344. return 0;
  3345. }
  3346. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3347. /* Close, if keep alive is not enabled */
  3348. return 0;
  3349. }
  3350. /* Check explicit wish of the client */
  3351. header = mg_get_header(conn, "Connection");
  3352. if (header) {
  3353. /* If there is a connection header from the client, obey */
  3354. if (header_has_option(header, "keep-alive")) {
  3355. return 1;
  3356. }
  3357. return 0;
  3358. }
  3359. /* Use default of the standard */
  3360. http_version = get_http_version(conn);
  3361. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3362. /* HTTP 1.1 default is keep alive */
  3363. return 1;
  3364. }
  3365. /* HTTP 1.0 (and earlier) default is to close the connection */
  3366. return 0;
  3367. }
  3368. static int
  3369. should_decode_url(const struct mg_connection *conn)
  3370. {
  3371. if (!conn || !conn->dom_ctx) {
  3372. return 0;
  3373. }
  3374. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3375. }
  3376. static const char *
  3377. suggest_connection_header(const struct mg_connection *conn)
  3378. {
  3379. return should_keep_alive(conn) ? "keep-alive" : "close";
  3380. }
  3381. static int
  3382. send_no_cache_header(struct mg_connection *conn)
  3383. {
  3384. /* Send all current and obsolete cache opt-out directives. */
  3385. return mg_printf(conn,
  3386. "Cache-Control: no-cache, no-store, "
  3387. "must-revalidate, private, max-age=0\r\n"
  3388. "Pragma: no-cache\r\n"
  3389. "Expires: 0\r\n");
  3390. }
  3391. static int
  3392. send_static_cache_header(struct mg_connection *conn)
  3393. {
  3394. #if !defined(NO_CACHING)
  3395. /* Read the server config to check how long a file may be cached.
  3396. * The configuration is in seconds. */
  3397. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3398. if (max_age <= 0) {
  3399. /* 0 means "do not cache". All values <0 are reserved
  3400. * and may be used differently in the future. */
  3401. /* If a file should not be cached, do not only send
  3402. * max-age=0, but also pragmas and Expires headers. */
  3403. return send_no_cache_header(conn);
  3404. }
  3405. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3406. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3407. /* See also https://www.mnot.net/cache_docs/ */
  3408. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3409. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3410. * leap
  3411. * year to 31622400 seconds. For the moment, we just send whatever has
  3412. * been configured, still the behavior for >1 year should be considered
  3413. * as undefined. */
  3414. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3415. #else /* NO_CACHING */
  3416. return send_no_cache_header(conn);
  3417. #endif /* !NO_CACHING */
  3418. }
  3419. static int
  3420. send_additional_header(struct mg_connection *conn)
  3421. {
  3422. int i = 0;
  3423. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3424. #if !defined(NO_SSL)
  3425. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3426. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3427. if (max_age >= 0) {
  3428. i += mg_printf(conn,
  3429. "Strict-Transport-Security: max-age=%u\r\n",
  3430. (unsigned)max_age);
  3431. }
  3432. }
  3433. #endif
  3434. if (header && header[0]) {
  3435. i += mg_printf(conn, "%s\r\n", header);
  3436. }
  3437. return i;
  3438. }
  3439. static void handle_file_based_request(struct mg_connection *conn,
  3440. const char *path,
  3441. struct mg_file *filep);
  3442. const char *
  3443. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3444. {
  3445. /* See IANA HTTP status code assignment:
  3446. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3447. */
  3448. switch (response_code) {
  3449. /* RFC2616 Section 10.1 - Informational 1xx */
  3450. case 100:
  3451. return "Continue"; /* RFC2616 Section 10.1.1 */
  3452. case 101:
  3453. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3454. case 102:
  3455. return "Processing"; /* RFC2518 Section 10.1 */
  3456. /* RFC2616 Section 10.2 - Successful 2xx */
  3457. case 200:
  3458. return "OK"; /* RFC2616 Section 10.2.1 */
  3459. case 201:
  3460. return "Created"; /* RFC2616 Section 10.2.2 */
  3461. case 202:
  3462. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3463. case 203:
  3464. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3465. case 204:
  3466. return "No Content"; /* RFC2616 Section 10.2.5 */
  3467. case 205:
  3468. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3469. case 206:
  3470. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3471. case 207:
  3472. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3473. */
  3474. case 208:
  3475. return "Already Reported"; /* RFC5842 Section 7.1 */
  3476. case 226:
  3477. return "IM used"; /* RFC3229 Section 10.4.1 */
  3478. /* RFC2616 Section 10.3 - Redirection 3xx */
  3479. case 300:
  3480. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3481. case 301:
  3482. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3483. case 302:
  3484. return "Found"; /* RFC2616 Section 10.3.3 */
  3485. case 303:
  3486. return "See Other"; /* RFC2616 Section 10.3.4 */
  3487. case 304:
  3488. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3489. case 305:
  3490. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3491. case 307:
  3492. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3493. case 308:
  3494. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3495. /* RFC2616 Section 10.4 - Client Error 4xx */
  3496. case 400:
  3497. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3498. case 401:
  3499. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3500. case 402:
  3501. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3502. case 403:
  3503. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3504. case 404:
  3505. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3506. case 405:
  3507. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3508. case 406:
  3509. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3510. case 407:
  3511. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3512. case 408:
  3513. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3514. case 409:
  3515. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3516. case 410:
  3517. return "Gone"; /* RFC2616 Section 10.4.11 */
  3518. case 411:
  3519. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3520. case 412:
  3521. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3522. case 413:
  3523. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3524. case 414:
  3525. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3526. case 415:
  3527. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3528. case 416:
  3529. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3530. */
  3531. case 417:
  3532. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3533. case 421:
  3534. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3535. case 422:
  3536. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3537. * Section 11.2 */
  3538. case 423:
  3539. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3540. case 424:
  3541. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3542. * Section 11.4 */
  3543. case 426:
  3544. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3545. case 428:
  3546. return "Precondition Required"; /* RFC 6585, Section 3 */
  3547. case 429:
  3548. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3549. case 431:
  3550. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3551. case 451:
  3552. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3553. * Section 3 */
  3554. /* RFC2616 Section 10.5 - Server Error 5xx */
  3555. case 500:
  3556. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3557. case 501:
  3558. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3559. case 502:
  3560. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3561. case 503:
  3562. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3563. case 504:
  3564. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3565. case 505:
  3566. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3567. case 506:
  3568. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3569. case 507:
  3570. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3571. * Section 11.5 */
  3572. case 508:
  3573. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3574. case 510:
  3575. return "Not Extended"; /* RFC 2774, Section 7 */
  3576. case 511:
  3577. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3578. /* Other status codes, not shown in the IANA HTTP status code
  3579. * assignment.
  3580. * E.g., "de facto" standards due to common use, ... */
  3581. case 418:
  3582. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3583. case 419:
  3584. return "Authentication Timeout"; /* common use */
  3585. case 420:
  3586. return "Enhance Your Calm"; /* common use */
  3587. case 440:
  3588. return "Login Timeout"; /* common use */
  3589. case 509:
  3590. return "Bandwidth Limit Exceeded"; /* common use */
  3591. default:
  3592. /* This error code is unknown. This should not happen. */
  3593. if (conn) {
  3594. mg_cry_internal(conn,
  3595. "Unknown HTTP response code: %u",
  3596. response_code);
  3597. }
  3598. /* Return at least a category according to RFC 2616 Section 10. */
  3599. if (response_code >= 100 && response_code < 200) {
  3600. /* Unknown informational status code */
  3601. return "Information";
  3602. }
  3603. if (response_code >= 200 && response_code < 300) {
  3604. /* Unknown success code */
  3605. return "Success";
  3606. }
  3607. if (response_code >= 300 && response_code < 400) {
  3608. /* Unknown redirection code */
  3609. return "Redirection";
  3610. }
  3611. if (response_code >= 400 && response_code < 500) {
  3612. /* Unknown request error code */
  3613. return "Client Error";
  3614. }
  3615. if (response_code >= 500 && response_code < 600) {
  3616. /* Unknown server error code */
  3617. return "Server Error";
  3618. }
  3619. /* Response code not even within reasonable range */
  3620. return "";
  3621. }
  3622. }
  3623. static void
  3624. mg_send_http_error_impl(struct mg_connection *conn,
  3625. int status,
  3626. const char *fmt,
  3627. va_list args)
  3628. {
  3629. char errmsg_buf[MG_BUF_LEN];
  3630. char path_buf[PATH_MAX];
  3631. va_list ap;
  3632. int len, i, page_handler_found, scope, truncated, has_body;
  3633. char date[64];
  3634. time_t curtime = time(NULL);
  3635. const char *error_handler = NULL;
  3636. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3637. const char *error_page_file_ext, *tstr;
  3638. int handled_by_callback = 0;
  3639. const char *status_text = mg_get_response_code_text(conn, status);
  3640. if (conn == NULL) {
  3641. return;
  3642. }
  3643. /* Set status (for log) */
  3644. conn->status_code = status;
  3645. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3646. has_body = ((status > 199) && (status != 204) && (status != 304));
  3647. /* Prepare message in buf, if required */
  3648. if ((has_body && (fmt != NULL))
  3649. || (!conn->in_error_handler
  3650. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3651. /* Store error message in errmsg_buf */
  3652. va_copy(ap, args);
  3653. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3654. va_end(ap);
  3655. /* In a debug build, print all html errors */
  3656. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3657. }
  3658. /* If there is a http_error callback, call it.
  3659. * But don't do it recursively, if callback calls mg_send_http_error again.
  3660. */
  3661. if (!conn->in_error_handler
  3662. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3663. /* Mark in_error_handler to avoid recursion and call user callback. */
  3664. conn->in_error_handler = 1;
  3665. handled_by_callback =
  3666. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3667. == 0);
  3668. conn->in_error_handler = 0;
  3669. }
  3670. if (!handled_by_callback) {
  3671. /* Check for recursion */
  3672. if (conn->in_error_handler) {
  3673. DEBUG_TRACE(
  3674. "Recursion when handling error %u - fall back to default",
  3675. status);
  3676. } else {
  3677. /* Send user defined error pages, if defined */
  3678. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3679. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3680. page_handler_found = 0;
  3681. if (error_handler != NULL) {
  3682. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3683. switch (scope) {
  3684. case 1: /* Handler for specific error, e.g. 404 error */
  3685. mg_snprintf(conn,
  3686. &truncated,
  3687. path_buf,
  3688. sizeof(path_buf) - 32,
  3689. "%serror%03u.",
  3690. error_handler,
  3691. status);
  3692. break;
  3693. case 2: /* Handler for error group, e.g., 5xx error
  3694. * handler
  3695. * for all server errors (500-599) */
  3696. mg_snprintf(conn,
  3697. &truncated,
  3698. path_buf,
  3699. sizeof(path_buf) - 32,
  3700. "%serror%01uxx.",
  3701. error_handler,
  3702. status / 100);
  3703. break;
  3704. default: /* Handler for all errors */
  3705. mg_snprintf(conn,
  3706. &truncated,
  3707. path_buf,
  3708. sizeof(path_buf) - 32,
  3709. "%serror.",
  3710. error_handler);
  3711. break;
  3712. }
  3713. /* String truncation in buf may only occur if
  3714. * error_handler is too long. This string is
  3715. * from the config, not from a client. */
  3716. (void)truncated;
  3717. len = (int)strlen(path_buf);
  3718. tstr = strchr(error_page_file_ext, '.');
  3719. while (tstr) {
  3720. for (i = 1;
  3721. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3722. i++)
  3723. path_buf[len + i - 1] = tstr[i];
  3724. path_buf[len + i - 1] = 0;
  3725. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3726. DEBUG_TRACE("Check error page %s - found",
  3727. path_buf);
  3728. page_handler_found = 1;
  3729. break;
  3730. }
  3731. DEBUG_TRACE("Check error page %s - not found",
  3732. path_buf);
  3733. tstr = strchr(tstr + i, '.');
  3734. }
  3735. }
  3736. }
  3737. if (page_handler_found) {
  3738. conn->in_error_handler = 1;
  3739. handle_file_based_request(conn, path_buf, &error_page_file);
  3740. conn->in_error_handler = 0;
  3741. return;
  3742. }
  3743. }
  3744. /* No custom error page. Send default error page. */
  3745. gmt_time_string(date, sizeof(date), &curtime);
  3746. conn->must_close = 1;
  3747. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3748. send_no_cache_header(conn);
  3749. send_additional_header(conn);
  3750. if (has_body) {
  3751. mg_printf(conn,
  3752. "%s",
  3753. "Content-Type: text/plain; charset=utf-8\r\n");
  3754. }
  3755. mg_printf(conn,
  3756. "Date: %s\r\n"
  3757. "Connection: close\r\n\r\n",
  3758. date);
  3759. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3760. if (has_body) {
  3761. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3762. if (fmt != NULL) {
  3763. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3764. }
  3765. } else {
  3766. /* No body allowed. Close the connection. */
  3767. DEBUG_TRACE("Error %i", status);
  3768. }
  3769. }
  3770. }
  3771. void
  3772. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3773. {
  3774. va_list ap;
  3775. va_start(ap, fmt);
  3776. mg_send_http_error_impl(conn, status, fmt, ap);
  3777. va_end(ap);
  3778. }
  3779. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3780. /* Create substitutes for POSIX functions in Win32. */
  3781. #if defined(__MINGW32__)
  3782. /* Show no warning in case system functions are not used. */
  3783. #pragma GCC diagnostic push
  3784. #pragma GCC diagnostic ignored "-Wunused-function"
  3785. #endif
  3786. FUNCTION_MAY_BE_UNUSED
  3787. static int
  3788. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3789. {
  3790. (void)unused;
  3791. *mutex = CreateMutex(NULL, FALSE, NULL);
  3792. return (*mutex == NULL) ? -1 : 0;
  3793. }
  3794. FUNCTION_MAY_BE_UNUSED
  3795. static int
  3796. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3797. {
  3798. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3799. }
  3800. FUNCTION_MAY_BE_UNUSED
  3801. static int
  3802. pthread_mutex_lock(pthread_mutex_t *mutex)
  3803. {
  3804. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  3805. : -1;
  3806. }
  3807. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3808. FUNCTION_MAY_BE_UNUSED
  3809. static int
  3810. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3811. {
  3812. switch (WaitForSingleObject(*mutex, 0)) {
  3813. case WAIT_OBJECT_0:
  3814. return 0;
  3815. case WAIT_TIMEOUT:
  3816. return -2; /* EBUSY */
  3817. }
  3818. return -1;
  3819. }
  3820. #endif
  3821. FUNCTION_MAY_BE_UNUSED
  3822. static int
  3823. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3824. {
  3825. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3826. }
  3827. FUNCTION_MAY_BE_UNUSED
  3828. static int
  3829. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3830. {
  3831. (void)unused;
  3832. InitializeCriticalSection(&cv->threadIdSec);
  3833. cv->waiting_thread = NULL;
  3834. return 0;
  3835. }
  3836. FUNCTION_MAY_BE_UNUSED
  3837. static int
  3838. pthread_cond_timedwait(pthread_cond_t *cv,
  3839. pthread_mutex_t *mutex,
  3840. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  3841. {
  3842. struct mg_workerTLS **ptls,
  3843. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3844. int ok;
  3845. int64_t nsnow, nswaitabs, nswaitrel;
  3846. DWORD mswaitrel;
  3847. EnterCriticalSection(&cv->threadIdSec);
  3848. /* Add this thread to cv's waiting list */
  3849. ptls = &cv->waiting_thread;
  3850. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3851. ;
  3852. tls->next_waiting_thread = NULL;
  3853. *ptls = tls;
  3854. LeaveCriticalSection(&cv->threadIdSec);
  3855. if (abstime) {
  3856. nsnow = mg_get_current_time_ns();
  3857. nswaitabs =
  3858. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3859. nswaitrel = nswaitabs - nsnow;
  3860. if (nswaitrel < 0) {
  3861. nswaitrel = 0;
  3862. }
  3863. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3864. } else {
  3865. mswaitrel = (DWORD)INFINITE;
  3866. }
  3867. pthread_mutex_unlock(mutex);
  3868. ok = (WAIT_OBJECT_0
  3869. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3870. if (!ok) {
  3871. ok = 1;
  3872. EnterCriticalSection(&cv->threadIdSec);
  3873. ptls = &cv->waiting_thread;
  3874. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3875. if (*ptls == tls) {
  3876. *ptls = tls->next_waiting_thread;
  3877. ok = 0;
  3878. break;
  3879. }
  3880. }
  3881. LeaveCriticalSection(&cv->threadIdSec);
  3882. if (ok) {
  3883. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  3884. (DWORD)INFINITE);
  3885. }
  3886. }
  3887. /* This thread has been removed from cv's waiting list */
  3888. pthread_mutex_lock(mutex);
  3889. return ok ? 0 : -1;
  3890. }
  3891. FUNCTION_MAY_BE_UNUSED
  3892. static int
  3893. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3894. {
  3895. return pthread_cond_timedwait(cv, mutex, NULL);
  3896. }
  3897. FUNCTION_MAY_BE_UNUSED
  3898. static int
  3899. pthread_cond_signal(pthread_cond_t *cv)
  3900. {
  3901. HANDLE wkup = NULL;
  3902. BOOL ok = FALSE;
  3903. EnterCriticalSection(&cv->threadIdSec);
  3904. if (cv->waiting_thread) {
  3905. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3906. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3907. ok = SetEvent(wkup);
  3908. DEBUG_ASSERT(ok);
  3909. }
  3910. LeaveCriticalSection(&cv->threadIdSec);
  3911. return ok ? 0 : 1;
  3912. }
  3913. FUNCTION_MAY_BE_UNUSED
  3914. static int
  3915. pthread_cond_broadcast(pthread_cond_t *cv)
  3916. {
  3917. EnterCriticalSection(&cv->threadIdSec);
  3918. while (cv->waiting_thread) {
  3919. pthread_cond_signal(cv);
  3920. }
  3921. LeaveCriticalSection(&cv->threadIdSec);
  3922. return 0;
  3923. }
  3924. FUNCTION_MAY_BE_UNUSED
  3925. static int
  3926. pthread_cond_destroy(pthread_cond_t *cv)
  3927. {
  3928. EnterCriticalSection(&cv->threadIdSec);
  3929. DEBUG_ASSERT(cv->waiting_thread == NULL);
  3930. LeaveCriticalSection(&cv->threadIdSec);
  3931. DeleteCriticalSection(&cv->threadIdSec);
  3932. return 0;
  3933. }
  3934. #ifdef ALTERNATIVE_QUEUE
  3935. FUNCTION_MAY_BE_UNUSED
  3936. static void *
  3937. event_create(void)
  3938. {
  3939. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3940. }
  3941. FUNCTION_MAY_BE_UNUSED
  3942. static int
  3943. event_wait(void *eventhdl)
  3944. {
  3945. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  3946. return (res == WAIT_OBJECT_0);
  3947. }
  3948. FUNCTION_MAY_BE_UNUSED
  3949. static int
  3950. event_signal(void *eventhdl)
  3951. {
  3952. return (int)SetEvent((HANDLE)eventhdl);
  3953. }
  3954. FUNCTION_MAY_BE_UNUSED
  3955. static void
  3956. event_destroy(void *eventhdl)
  3957. {
  3958. CloseHandle((HANDLE)eventhdl);
  3959. }
  3960. #endif
  3961. #if defined(__MINGW32__)
  3962. /* Enable unused function warning again */
  3963. #pragma GCC diagnostic pop
  3964. #endif
  3965. /* For Windows, change all slashes to backslashes in path names. */
  3966. static void
  3967. change_slashes_to_backslashes(char *path)
  3968. {
  3969. int i;
  3970. for (i = 0; path[i] != '\0'; i++) {
  3971. if (path[i] == '/') {
  3972. path[i] = '\\';
  3973. }
  3974. /* remove double backslash (check i > 0 to preserve UNC paths,
  3975. * like \\server\file.txt) */
  3976. if ((path[i] == '\\') && (i > 0)) {
  3977. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3978. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3979. }
  3980. }
  3981. }
  3982. }
  3983. static int
  3984. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3985. {
  3986. int diff;
  3987. do {
  3988. diff = tolower(*s1) - tolower(*s2);
  3989. s1++;
  3990. s2++;
  3991. } while ((diff == 0) && (s1[-1] != '\0'));
  3992. return diff;
  3993. }
  3994. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3995. * wbuf and wbuf_len is a target buffer and its length. */
  3996. static void
  3997. path_to_unicode(const struct mg_connection *conn,
  3998. const char *path,
  3999. wchar_t *wbuf,
  4000. size_t wbuf_len)
  4001. {
  4002. char buf[PATH_MAX], buf2[PATH_MAX];
  4003. wchar_t wbuf2[W_PATH_MAX + 1];
  4004. DWORD long_len, err;
  4005. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4006. mg_strlcpy(buf, path, sizeof(buf));
  4007. change_slashes_to_backslashes(buf);
  4008. /* Convert to Unicode and back. If doubly-converted string does not
  4009. * match the original, something is fishy, reject. */
  4010. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4011. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4012. WideCharToMultiByte(
  4013. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4014. if (strcmp(buf, buf2) != 0) {
  4015. wbuf[0] = L'\0';
  4016. }
  4017. /* Windows file systems are not case sensitive, but you can still use
  4018. * uppercase and lowercase letters (on all modern file systems).
  4019. * The server can check if the URI uses the same upper/lowercase
  4020. * letters an the file system, effectively making Windows servers
  4021. * case sensitive (like Linux servers are). It is still not possible
  4022. * to use two files with the same name in different cases on Windows
  4023. * (like /a and /A) - this would be possible in Linux.
  4024. * As a default, Windows is not case sensitive, but the case sensitive
  4025. * file name check can be activated by an additional configuration. */
  4026. if (conn) {
  4027. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4028. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4029. "yes")) {
  4030. /* Use case sensitive compare function */
  4031. fcompare = wcscmp;
  4032. }
  4033. }
  4034. (void)conn; /* conn is currently unused */
  4035. #if !defined(_WIN32_WCE)
  4036. /* Only accept a full file path, not a Windows short (8.3) path. */
  4037. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4038. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4039. if (long_len == 0) {
  4040. err = GetLastError();
  4041. if (err == ERROR_FILE_NOT_FOUND) {
  4042. /* File does not exist. This is not always a problem here. */
  4043. return;
  4044. }
  4045. }
  4046. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4047. /* Short name is used. */
  4048. wbuf[0] = L'\0';
  4049. }
  4050. #else
  4051. (void)long_len;
  4052. (void)wbuf2;
  4053. (void)err;
  4054. if (strchr(path, '~')) {
  4055. wbuf[0] = L'\0';
  4056. }
  4057. #endif
  4058. }
  4059. /* Windows happily opens files with some garbage at the end of file name.
  4060. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4061. * "a.cgi", despite one would expect an error back.
  4062. * This function returns non-0 if path ends with some garbage. */
  4063. static int
  4064. path_cannot_disclose_cgi(const char *path)
  4065. {
  4066. static const char *allowed_last_characters = "_-";
  4067. int last = path[strlen(path) - 1];
  4068. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  4069. }
  4070. static int
  4071. mg_stat(const struct mg_connection *conn,
  4072. const char *path,
  4073. struct mg_file_stat *filep)
  4074. {
  4075. wchar_t wbuf[W_PATH_MAX];
  4076. WIN32_FILE_ATTRIBUTE_DATA info;
  4077. time_t creation_time;
  4078. if (!filep) {
  4079. return 0;
  4080. }
  4081. memset(filep, 0, sizeof(*filep));
  4082. if (conn && is_file_in_memory(conn, path)) {
  4083. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4084. * memset */
  4085. /* Quick fix (for 1.9.x): */
  4086. /* mg_stat must fill all fields, also for files in memory */
  4087. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4088. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4089. filep->size = tmp_file.stat.size;
  4090. filep->location = 2;
  4091. /* TODO: for 1.10: restructure how files in memory are handled */
  4092. /* The "file in memory" feature is a candidate for deletion.
  4093. * Please join the discussion at
  4094. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4095. */
  4096. filep->last_modified = time(NULL); /* TODO */
  4097. /* last_modified = now ... assumes the file may change during
  4098. * runtime,
  4099. * so every mg_fopen call may return different data */
  4100. /* last_modified = conn->phys_ctx.start_time;
  4101. * May be used it the data does not change during runtime. This
  4102. * allows
  4103. * browser caching. Since we do not know, we have to assume the file
  4104. * in memory may change. */
  4105. return 1;
  4106. }
  4107. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4108. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4109. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4110. filep->last_modified =
  4111. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4112. info.ftLastWriteTime.dwHighDateTime);
  4113. /* On Windows, the file creation time can be higher than the
  4114. * modification time, e.g. when a file is copied.
  4115. * Since the Last-Modified timestamp is used for caching
  4116. * it should be based on the most recent timestamp. */
  4117. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4118. info.ftCreationTime.dwHighDateTime);
  4119. if (creation_time > filep->last_modified) {
  4120. filep->last_modified = creation_time;
  4121. }
  4122. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4123. /* If file name is fishy, reset the file structure and return
  4124. * error.
  4125. * Note it is important to reset, not just return the error, cause
  4126. * functions like is_file_opened() check the struct. */
  4127. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4128. memset(filep, 0, sizeof(*filep));
  4129. return 0;
  4130. }
  4131. return 1;
  4132. }
  4133. return 0;
  4134. }
  4135. static int
  4136. mg_remove(const struct mg_connection *conn, const char *path)
  4137. {
  4138. wchar_t wbuf[W_PATH_MAX];
  4139. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4140. return DeleteFileW(wbuf) ? 0 : -1;
  4141. }
  4142. static int
  4143. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4144. {
  4145. wchar_t wbuf[W_PATH_MAX];
  4146. (void)mode;
  4147. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4148. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4149. }
  4150. /* Create substitutes for POSIX functions in Win32. */
  4151. #if defined(__MINGW32__)
  4152. /* Show no warning in case system functions are not used. */
  4153. #pragma GCC diagnostic push
  4154. #pragma GCC diagnostic ignored "-Wunused-function"
  4155. #endif
  4156. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4157. FUNCTION_MAY_BE_UNUSED
  4158. static DIR *
  4159. mg_opendir(const struct mg_connection *conn, const char *name)
  4160. {
  4161. DIR *dir = NULL;
  4162. wchar_t wpath[W_PATH_MAX];
  4163. DWORD attrs;
  4164. if (name == NULL) {
  4165. SetLastError(ERROR_BAD_ARGUMENTS);
  4166. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4167. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4168. } else {
  4169. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4170. attrs = GetFileAttributesW(wpath);
  4171. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4172. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4173. (void)wcscat(wpath, L"\\*");
  4174. dir->handle = FindFirstFileW(wpath, &dir->info);
  4175. dir->result.d_name[0] = '\0';
  4176. } else {
  4177. mg_free(dir);
  4178. dir = NULL;
  4179. }
  4180. }
  4181. return dir;
  4182. }
  4183. FUNCTION_MAY_BE_UNUSED
  4184. static int
  4185. mg_closedir(DIR *dir)
  4186. {
  4187. int result = 0;
  4188. if (dir != NULL) {
  4189. if (dir->handle != INVALID_HANDLE_VALUE)
  4190. result = FindClose(dir->handle) ? 0 : -1;
  4191. mg_free(dir);
  4192. } else {
  4193. result = -1;
  4194. SetLastError(ERROR_BAD_ARGUMENTS);
  4195. }
  4196. return result;
  4197. }
  4198. FUNCTION_MAY_BE_UNUSED
  4199. static struct dirent *
  4200. mg_readdir(DIR *dir)
  4201. {
  4202. struct dirent *result = 0;
  4203. if (dir) {
  4204. if (dir->handle != INVALID_HANDLE_VALUE) {
  4205. result = &dir->result;
  4206. (void)WideCharToMultiByte(CP_UTF8,
  4207. 0,
  4208. dir->info.cFileName,
  4209. -1,
  4210. result->d_name,
  4211. sizeof(result->d_name),
  4212. NULL,
  4213. NULL);
  4214. if (!FindNextFileW(dir->handle, &dir->info)) {
  4215. (void)FindClose(dir->handle);
  4216. dir->handle = INVALID_HANDLE_VALUE;
  4217. }
  4218. } else {
  4219. SetLastError(ERROR_FILE_NOT_FOUND);
  4220. }
  4221. } else {
  4222. SetLastError(ERROR_BAD_ARGUMENTS);
  4223. }
  4224. return result;
  4225. }
  4226. #ifndef HAVE_POLL
  4227. FUNCTION_MAY_BE_UNUSED
  4228. static int
  4229. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4230. {
  4231. struct timeval tv;
  4232. fd_set set;
  4233. unsigned int i;
  4234. int result;
  4235. SOCKET maxfd = 0;
  4236. memset(&tv, 0, sizeof(tv));
  4237. tv.tv_sec = milliseconds / 1000;
  4238. tv.tv_usec = (milliseconds % 1000) * 1000;
  4239. FD_ZERO(&set);
  4240. for (i = 0; i < n; i++) {
  4241. FD_SET((SOCKET)pfd[i].fd, &set);
  4242. pfd[i].revents = 0;
  4243. if (pfd[i].fd > maxfd) {
  4244. maxfd = pfd[i].fd;
  4245. }
  4246. }
  4247. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4248. for (i = 0; i < n; i++) {
  4249. if (FD_ISSET(pfd[i].fd, &set)) {
  4250. pfd[i].revents = POLLIN;
  4251. }
  4252. }
  4253. }
  4254. /* We should subtract the time used in select from remaining
  4255. * "milliseconds", in particular if called from mg_poll with a
  4256. * timeout quantum.
  4257. * Unfortunately, the remaining time is not stored in "tv" in all
  4258. * implementations, so the result in "tv" must be considered undefined.
  4259. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4260. return result;
  4261. }
  4262. #endif /* HAVE_POLL */
  4263. #if defined(__MINGW32__)
  4264. /* Enable unused function warning again */
  4265. #pragma GCC diagnostic pop
  4266. #endif
  4267. static void
  4268. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4269. {
  4270. (void)conn; /* Unused. */
  4271. #if defined(_WIN32_WCE)
  4272. (void)sock;
  4273. #else
  4274. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4275. #endif
  4276. }
  4277. int
  4278. mg_start_thread(mg_thread_func_t f, void *p)
  4279. {
  4280. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4281. /* Compile-time option to control stack size, e.g.
  4282. * -DUSE_STACK_SIZE=16384
  4283. */
  4284. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4285. == ((uintptr_t)(-1L)))
  4286. ? -1
  4287. : 0);
  4288. #else
  4289. return (
  4290. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4291. ? -1
  4292. : 0);
  4293. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4294. }
  4295. /* Start a thread storing the thread context. */
  4296. static int
  4297. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4298. void *p,
  4299. pthread_t *threadidptr)
  4300. {
  4301. uintptr_t uip;
  4302. HANDLE threadhandle;
  4303. int result = -1;
  4304. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4305. threadhandle = (HANDLE)uip;
  4306. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4307. *threadidptr = threadhandle;
  4308. result = 0;
  4309. }
  4310. return result;
  4311. }
  4312. /* Wait for a thread to finish. */
  4313. static int
  4314. mg_join_thread(pthread_t threadid)
  4315. {
  4316. int result;
  4317. DWORD dwevent;
  4318. result = -1;
  4319. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4320. if (dwevent == WAIT_FAILED) {
  4321. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4322. } else {
  4323. if (dwevent == WAIT_OBJECT_0) {
  4324. CloseHandle(threadid);
  4325. result = 0;
  4326. }
  4327. }
  4328. return result;
  4329. }
  4330. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4331. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4332. /* Create substitutes for POSIX functions in Win32. */
  4333. #if defined(__MINGW32__)
  4334. /* Show no warning in case system functions are not used. */
  4335. #pragma GCC diagnostic push
  4336. #pragma GCC diagnostic ignored "-Wunused-function"
  4337. #endif
  4338. FUNCTION_MAY_BE_UNUSED
  4339. static HANDLE
  4340. dlopen(const char *dll_name, int flags)
  4341. {
  4342. wchar_t wbuf[W_PATH_MAX];
  4343. (void)flags;
  4344. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4345. return LoadLibraryW(wbuf);
  4346. }
  4347. FUNCTION_MAY_BE_UNUSED
  4348. static int
  4349. dlclose(void *handle)
  4350. {
  4351. int result;
  4352. if (FreeLibrary((HMODULE)handle) != 0) {
  4353. result = 0;
  4354. } else {
  4355. result = -1;
  4356. }
  4357. return result;
  4358. }
  4359. #if defined(__MINGW32__)
  4360. /* Enable unused function warning again */
  4361. #pragma GCC diagnostic pop
  4362. #endif
  4363. #endif
  4364. #if !defined(NO_CGI)
  4365. #define SIGKILL (0)
  4366. static int
  4367. kill(pid_t pid, int sig_num)
  4368. {
  4369. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4370. (void)CloseHandle((HANDLE)pid);
  4371. return 0;
  4372. }
  4373. static void
  4374. trim_trailing_whitespaces(char *s)
  4375. {
  4376. char *e = s + strlen(s) - 1;
  4377. while ((e > s) && isspace(*(unsigned char *)e)) {
  4378. *e-- = '\0';
  4379. }
  4380. }
  4381. static pid_t
  4382. spawn_process(struct mg_connection *conn,
  4383. const char *prog,
  4384. char *envblk,
  4385. char *envp[],
  4386. int fdin[2],
  4387. int fdout[2],
  4388. int fderr[2],
  4389. const char *dir)
  4390. {
  4391. HANDLE me;
  4392. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4393. cmdline[PATH_MAX], buf[PATH_MAX];
  4394. int truncated;
  4395. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4396. STARTUPINFOA si;
  4397. PROCESS_INFORMATION pi = {0};
  4398. (void)envp;
  4399. memset(&si, 0, sizeof(si));
  4400. si.cb = sizeof(si);
  4401. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4402. si.wShowWindow = SW_HIDE;
  4403. me = GetCurrentProcess();
  4404. DuplicateHandle(me,
  4405. (HANDLE)_get_osfhandle(fdin[0]),
  4406. me,
  4407. &si.hStdInput,
  4408. 0,
  4409. TRUE,
  4410. DUPLICATE_SAME_ACCESS);
  4411. DuplicateHandle(me,
  4412. (HANDLE)_get_osfhandle(fdout[1]),
  4413. me,
  4414. &si.hStdOutput,
  4415. 0,
  4416. TRUE,
  4417. DUPLICATE_SAME_ACCESS);
  4418. DuplicateHandle(me,
  4419. (HANDLE)_get_osfhandle(fderr[1]),
  4420. me,
  4421. &si.hStdError,
  4422. 0,
  4423. TRUE,
  4424. DUPLICATE_SAME_ACCESS);
  4425. /* Mark handles that should not be inherited. See
  4426. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4427. */
  4428. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4429. HANDLE_FLAG_INHERIT,
  4430. 0);
  4431. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4432. HANDLE_FLAG_INHERIT,
  4433. 0);
  4434. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4435. HANDLE_FLAG_INHERIT,
  4436. 0);
  4437. /* If CGI file is a script, try to read the interpreter line */
  4438. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4439. if (interp == NULL) {
  4440. buf[0] = buf[1] = '\0';
  4441. /* Read the first line of the script into the buffer */
  4442. mg_snprintf(
  4443. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4444. if (truncated) {
  4445. pi.hProcess = (pid_t)-1;
  4446. goto spawn_cleanup;
  4447. }
  4448. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4449. p = (char *)file.access.membuf;
  4450. mg_fgets(buf, sizeof(buf), &file, &p);
  4451. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4452. buf[sizeof(buf) - 1] = '\0';
  4453. }
  4454. if ((buf[0] == '#') && (buf[1] == '!')) {
  4455. trim_trailing_whitespaces(buf + 2);
  4456. } else {
  4457. buf[2] = '\0';
  4458. }
  4459. interp = buf + 2;
  4460. }
  4461. if (interp[0] != '\0') {
  4462. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4463. interp = full_interp;
  4464. }
  4465. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4466. if (interp[0] != '\0') {
  4467. mg_snprintf(conn,
  4468. &truncated,
  4469. cmdline,
  4470. sizeof(cmdline),
  4471. "\"%s\" \"%s\\%s\"",
  4472. interp,
  4473. full_dir,
  4474. prog);
  4475. } else {
  4476. mg_snprintf(conn,
  4477. &truncated,
  4478. cmdline,
  4479. sizeof(cmdline),
  4480. "\"%s\\%s\"",
  4481. full_dir,
  4482. prog);
  4483. }
  4484. if (truncated) {
  4485. pi.hProcess = (pid_t)-1;
  4486. goto spawn_cleanup;
  4487. }
  4488. DEBUG_TRACE("Running [%s]", cmdline);
  4489. if (CreateProcessA(NULL,
  4490. cmdline,
  4491. NULL,
  4492. NULL,
  4493. TRUE,
  4494. CREATE_NEW_PROCESS_GROUP,
  4495. envblk,
  4496. NULL,
  4497. &si,
  4498. &pi) == 0) {
  4499. mg_cry_internal(
  4500. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4501. pi.hProcess = (pid_t)-1;
  4502. /* goto spawn_cleanup; */
  4503. }
  4504. spawn_cleanup:
  4505. (void)CloseHandle(si.hStdOutput);
  4506. (void)CloseHandle(si.hStdError);
  4507. (void)CloseHandle(si.hStdInput);
  4508. if (pi.hThread != NULL) {
  4509. (void)CloseHandle(pi.hThread);
  4510. }
  4511. return (pid_t)pi.hProcess;
  4512. }
  4513. #endif /* !NO_CGI */
  4514. static int
  4515. set_blocking_mode(SOCKET sock)
  4516. {
  4517. unsigned long non_blocking = 0;
  4518. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4519. }
  4520. static int
  4521. set_non_blocking_mode(SOCKET sock)
  4522. {
  4523. unsigned long non_blocking = 1;
  4524. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4525. }
  4526. #else
  4527. static int
  4528. mg_stat(const struct mg_connection *conn,
  4529. const char *path,
  4530. struct mg_file_stat *filep)
  4531. {
  4532. struct stat st;
  4533. if (!filep) {
  4534. return 0;
  4535. }
  4536. memset(filep, 0, sizeof(*filep));
  4537. if (conn && is_file_in_memory(conn, path)) {
  4538. /* Quick fix (for 1.9.x): */
  4539. /* mg_stat must fill all fields, also for files in memory */
  4540. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4541. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4542. filep->size = tmp_file.stat.size;
  4543. filep->last_modified = time(NULL);
  4544. filep->location = 2;
  4545. /* TODO: for 1.10: restructure how files in memory are handled */
  4546. return 1;
  4547. }
  4548. if (0 == stat(path, &st)) {
  4549. filep->size = (uint64_t)(st.st_size);
  4550. filep->last_modified = st.st_mtime;
  4551. filep->is_directory = S_ISDIR(st.st_mode);
  4552. return 1;
  4553. }
  4554. return 0;
  4555. }
  4556. static void
  4557. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4558. {
  4559. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4560. if (conn) {
  4561. mg_cry_internal(conn,
  4562. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4563. __func__,
  4564. strerror(ERRNO));
  4565. }
  4566. }
  4567. }
  4568. int
  4569. mg_start_thread(mg_thread_func_t func, void *param)
  4570. {
  4571. pthread_t thread_id;
  4572. pthread_attr_t attr;
  4573. int result;
  4574. (void)pthread_attr_init(&attr);
  4575. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4576. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4577. /* Compile-time option to control stack size,
  4578. * e.g. -DUSE_STACK_SIZE=16384 */
  4579. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4580. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4581. result = pthread_create(&thread_id, &attr, func, param);
  4582. pthread_attr_destroy(&attr);
  4583. return result;
  4584. }
  4585. /* Start a thread storing the thread context. */
  4586. static int
  4587. mg_start_thread_with_id(mg_thread_func_t func,
  4588. void *param,
  4589. pthread_t *threadidptr)
  4590. {
  4591. pthread_t thread_id;
  4592. pthread_attr_t attr;
  4593. int result;
  4594. (void)pthread_attr_init(&attr);
  4595. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4596. /* Compile-time option to control stack size,
  4597. * e.g. -DUSE_STACK_SIZE=16384 */
  4598. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4599. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4600. result = pthread_create(&thread_id, &attr, func, param);
  4601. pthread_attr_destroy(&attr);
  4602. if ((result == 0) && (threadidptr != NULL)) {
  4603. *threadidptr = thread_id;
  4604. }
  4605. return result;
  4606. }
  4607. /* Wait for a thread to finish. */
  4608. static int
  4609. mg_join_thread(pthread_t threadid)
  4610. {
  4611. int result;
  4612. result = pthread_join(threadid, NULL);
  4613. return result;
  4614. }
  4615. #ifndef NO_CGI
  4616. static pid_t
  4617. spawn_process(struct mg_connection *conn,
  4618. const char *prog,
  4619. char *envblk,
  4620. char *envp[],
  4621. int fdin[2],
  4622. int fdout[2],
  4623. int fderr[2],
  4624. const char *dir)
  4625. {
  4626. pid_t pid;
  4627. const char *interp;
  4628. (void)envblk;
  4629. if (conn == NULL) {
  4630. return 0;
  4631. }
  4632. if ((pid = fork()) == -1) {
  4633. /* Parent */
  4634. mg_send_http_error(conn,
  4635. 500,
  4636. "Error: Creating CGI process\nfork(): %s",
  4637. strerror(ERRNO));
  4638. } else if (pid == 0) {
  4639. /* Child */
  4640. if (chdir(dir) != 0) {
  4641. mg_cry_internal(
  4642. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4643. } else if (dup2(fdin[0], 0) == -1) {
  4644. mg_cry_internal(conn,
  4645. "%s: dup2(%d, 0): %s",
  4646. __func__,
  4647. fdin[0],
  4648. strerror(ERRNO));
  4649. } else if (dup2(fdout[1], 1) == -1) {
  4650. mg_cry_internal(conn,
  4651. "%s: dup2(%d, 1): %s",
  4652. __func__,
  4653. fdout[1],
  4654. strerror(ERRNO));
  4655. } else if (dup2(fderr[1], 2) == -1) {
  4656. mg_cry_internal(conn,
  4657. "%s: dup2(%d, 2): %s",
  4658. __func__,
  4659. fderr[1],
  4660. strerror(ERRNO));
  4661. } else {
  4662. /* Keep stderr and stdout in two different pipes.
  4663. * Stdout will be sent back to the client,
  4664. * stderr should go into a server error log. */
  4665. (void)close(fdin[0]);
  4666. (void)close(fdout[1]);
  4667. (void)close(fderr[1]);
  4668. /* Close write end fdin and read end fdout and fderr */
  4669. (void)close(fdin[1]);
  4670. (void)close(fdout[0]);
  4671. (void)close(fderr[0]);
  4672. /* After exec, all signal handlers are restored to their default
  4673. * values, with one exception of SIGCHLD. According to
  4674. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4675. * will leave unchanged after exec if it was set to be ignored.
  4676. * Restore it to default action. */
  4677. signal(SIGCHLD, SIG_DFL);
  4678. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4679. if (interp == NULL) {
  4680. (void)execle(prog, prog, NULL, envp);
  4681. mg_cry_internal(conn,
  4682. "%s: execle(%s): %s",
  4683. __func__,
  4684. prog,
  4685. strerror(ERRNO));
  4686. } else {
  4687. (void)execle(interp, interp, prog, NULL, envp);
  4688. mg_cry_internal(conn,
  4689. "%s: execle(%s %s): %s",
  4690. __func__,
  4691. interp,
  4692. prog,
  4693. strerror(ERRNO));
  4694. }
  4695. }
  4696. exit(EXIT_FAILURE);
  4697. }
  4698. return pid;
  4699. }
  4700. #endif /* !NO_CGI */
  4701. static int
  4702. set_non_blocking_mode(SOCKET sock)
  4703. {
  4704. int flags = fcntl(sock, F_GETFL, 0);
  4705. if (flags < 0) {
  4706. return -1;
  4707. }
  4708. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4709. return -1;
  4710. }
  4711. return 0;
  4712. }
  4713. static int
  4714. set_blocking_mode(SOCKET sock)
  4715. {
  4716. int flags = fcntl(sock, F_GETFL, 0);
  4717. if (flags < 0) {
  4718. return -1;
  4719. }
  4720. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4721. return -1;
  4722. }
  4723. return 0;
  4724. }
  4725. #endif /* _WIN32 / else */
  4726. /* End of initial operating system specific define block. */
  4727. /* Get a random number (independent of C rand function) */
  4728. static uint64_t
  4729. get_random(void)
  4730. {
  4731. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4732. static uint64_t lcg = 0; /* Linear congruential generator */
  4733. uint64_t now = mg_get_current_time_ns();
  4734. if (lfsr == 0) {
  4735. /* lfsr will be only 0 if has not been initialized,
  4736. * so this code is called only once. */
  4737. lfsr = mg_get_current_time_ns();
  4738. lcg = mg_get_current_time_ns();
  4739. } else {
  4740. /* Get the next step of both random number generators. */
  4741. lfsr = (lfsr >> 1)
  4742. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4743. << 63);
  4744. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4745. }
  4746. /* Combining two pseudo-random number generators and a high resolution
  4747. * part
  4748. * of the current server time will make it hard (impossible?) to guess
  4749. * the
  4750. * next number. */
  4751. return (lfsr ^ lcg ^ now);
  4752. }
  4753. static int
  4754. mg_poll(struct pollfd *pfd,
  4755. unsigned int n,
  4756. int milliseconds,
  4757. volatile int *stop_server)
  4758. {
  4759. /* Call poll, but only for a maximum time of a few seconds.
  4760. * This will allow to stop the server after some seconds, instead
  4761. * of having to wait for a long socket timeout. */
  4762. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4763. do {
  4764. int result;
  4765. if (*stop_server) {
  4766. /* Shut down signal */
  4767. return -2;
  4768. }
  4769. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4770. ms_now = milliseconds;
  4771. }
  4772. result = poll(pfd, n, ms_now);
  4773. if (result != 0) {
  4774. /* Poll returned either success (1) or error (-1).
  4775. * Forward both to the caller. */
  4776. return result;
  4777. }
  4778. /* Poll returned timeout (0). */
  4779. if (milliseconds > 0) {
  4780. milliseconds -= ms_now;
  4781. }
  4782. } while (milliseconds != 0);
  4783. /* timeout: return 0 */
  4784. return 0;
  4785. }
  4786. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4787. * descriptor.
  4788. * Return value:
  4789. * >=0 .. number of bytes successfully written
  4790. * -1 .. timeout
  4791. * -2 .. error
  4792. */
  4793. static int
  4794. push_inner(struct mg_context *ctx,
  4795. FILE *fp,
  4796. SOCKET sock,
  4797. SSL *ssl,
  4798. const char *buf,
  4799. int len,
  4800. double timeout)
  4801. {
  4802. uint64_t start = 0, now = 0, timeout_ns = 0;
  4803. int n, err;
  4804. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4805. #ifdef _WIN32
  4806. typedef int len_t;
  4807. #else
  4808. typedef size_t len_t;
  4809. #endif
  4810. if (timeout > 0) {
  4811. now = mg_get_current_time_ns();
  4812. start = now;
  4813. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4814. }
  4815. if (ctx == NULL) {
  4816. return -2;
  4817. }
  4818. #ifdef NO_SSL
  4819. if (ssl) {
  4820. return -2;
  4821. }
  4822. #endif
  4823. /* Try to read until it succeeds, fails, times out, or the server
  4824. * shuts down. */
  4825. for (;;) {
  4826. #ifndef NO_SSL
  4827. if (ssl != NULL) {
  4828. n = SSL_write(ssl, buf, len);
  4829. if (n <= 0) {
  4830. err = SSL_get_error(ssl, n);
  4831. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4832. err = ERRNO;
  4833. } else if ((err == SSL_ERROR_WANT_READ)
  4834. || (err == SSL_ERROR_WANT_WRITE)) {
  4835. n = 0;
  4836. } else {
  4837. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4838. return -2;
  4839. }
  4840. } else {
  4841. err = 0;
  4842. }
  4843. } else
  4844. #endif
  4845. if (fp != NULL) {
  4846. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4847. if (ferror(fp)) {
  4848. n = -1;
  4849. err = ERRNO;
  4850. } else {
  4851. err = 0;
  4852. }
  4853. } else {
  4854. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4855. err = (n < 0) ? ERRNO : 0;
  4856. #ifdef _WIN32
  4857. if (err == WSAEWOULDBLOCK) {
  4858. err = 0;
  4859. n = 0;
  4860. }
  4861. #else
  4862. if (err == EWOULDBLOCK) {
  4863. err = 0;
  4864. n = 0;
  4865. }
  4866. #endif
  4867. if (n < 0) {
  4868. /* shutdown of the socket at client side */
  4869. return -2;
  4870. }
  4871. }
  4872. if (ctx->stop_flag) {
  4873. return -2;
  4874. }
  4875. if ((n > 0) || ((n == 0) && (len == 0))) {
  4876. /* some data has been read, or no data was requested */
  4877. return n;
  4878. }
  4879. if (n < 0) {
  4880. /* socket error - check errno */
  4881. DEBUG_TRACE("send() failed, error %d", err);
  4882. /* TODO (mid): error handling depending on the error code.
  4883. * These codes are different between Windows and Linux.
  4884. * Currently there is no problem with failing send calls,
  4885. * if there is a reproducible situation, it should be
  4886. * investigated in detail.
  4887. */
  4888. return -2;
  4889. }
  4890. /* Only in case n=0 (timeout), repeat calling the write function */
  4891. /* If send failed, wait before retry */
  4892. if (fp != NULL) {
  4893. /* For files, just wait a fixed time,
  4894. * maybe an average disk seek time. */
  4895. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4896. } else {
  4897. /* For sockets, wait for the socket using select */
  4898. fd_set wfds;
  4899. struct timeval tv;
  4900. int sret;
  4901. #if defined(__GNUC__) || defined(__MINGW32__)
  4902. /* GCC seems to have a flaw with it's own socket macros:
  4903. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4904. */
  4905. #pragma GCC diagnostic push
  4906. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4907. #endif
  4908. FD_ZERO(&wfds);
  4909. FD_SET(sock, &wfds);
  4910. tv.tv_sec = (time_t)(ms_wait / 1000);
  4911. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4912. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4913. #if defined(__GNUC__) || defined(__MINGW32__)
  4914. #pragma GCC diagnostic pop
  4915. #endif
  4916. if (sret > 0) {
  4917. /* We got ready to write. Don't check the timeout
  4918. * but directly go back to write again. */
  4919. continue;
  4920. }
  4921. }
  4922. if (timeout > 0) {
  4923. now = mg_get_current_time_ns();
  4924. if ((now - start) > timeout_ns) {
  4925. /* Timeout */
  4926. break;
  4927. }
  4928. }
  4929. }
  4930. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4931. used */
  4932. return -1;
  4933. }
  4934. static int64_t
  4935. push_all(struct mg_context *ctx,
  4936. FILE *fp,
  4937. SOCKET sock,
  4938. SSL *ssl,
  4939. const char *buf,
  4940. int64_t len)
  4941. {
  4942. double timeout = -1.0;
  4943. int64_t n, nwritten = 0;
  4944. if (ctx == NULL) {
  4945. return -1;
  4946. }
  4947. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  4948. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  4949. }
  4950. while ((len > 0) && (ctx->stop_flag == 0)) {
  4951. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4952. if (n < 0) {
  4953. if (nwritten == 0) {
  4954. nwritten = n; /* Propagate the error */
  4955. }
  4956. break;
  4957. } else if (n == 0) {
  4958. break; /* No more data to write */
  4959. } else {
  4960. nwritten += n;
  4961. len -= n;
  4962. }
  4963. }
  4964. return nwritten;
  4965. }
  4966. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4967. * Return value:
  4968. * >=0 .. number of bytes successfully read
  4969. * -1 .. timeout
  4970. * -2 .. error
  4971. */
  4972. static int
  4973. pull_inner(FILE *fp,
  4974. struct mg_connection *conn,
  4975. char *buf,
  4976. int len,
  4977. double timeout)
  4978. {
  4979. int nread, err = 0;
  4980. #ifdef _WIN32
  4981. typedef int len_t;
  4982. #else
  4983. typedef size_t len_t;
  4984. #endif
  4985. #ifndef NO_SSL
  4986. int ssl_pending;
  4987. #endif
  4988. /* We need an additional wait loop around this, because in some cases
  4989. * with TLSwe may get data from the socket but not from SSL_read.
  4990. * In this case we need to repeat at least once.
  4991. */
  4992. if (fp != NULL) {
  4993. #if !defined(_WIN32_WCE)
  4994. /* Use read() instead of fread(), because if we're reading from the
  4995. * CGI pipe, fread() may block until IO buffer is filled up. We
  4996. * cannot afford to block and must pass all read bytes immediately
  4997. * to the client. */
  4998. nread = (int)read(fileno(fp), buf, (size_t)len);
  4999. #else
  5000. /* WinCE does not support CGI pipes */
  5001. nread = (int)fread(buf, 1, (size_t)len, fp);
  5002. #endif
  5003. err = (nread < 0) ? ERRNO : 0;
  5004. if ((nread == 0) && (len > 0)) {
  5005. /* Should get data, but got EOL */
  5006. return -2;
  5007. }
  5008. #ifndef NO_SSL
  5009. } else if ((conn->ssl != NULL)
  5010. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5011. /* We already know there is no more data buffered in conn->buf
  5012. * but there is more available in the SSL layer. So don't poll
  5013. * conn->client.sock yet. */
  5014. if (ssl_pending > len) {
  5015. ssl_pending = len;
  5016. }
  5017. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5018. if (nread <= 0) {
  5019. err = SSL_get_error(conn->ssl, nread);
  5020. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5021. err = ERRNO;
  5022. } else if ((err == SSL_ERROR_WANT_READ)
  5023. || (err == SSL_ERROR_WANT_WRITE)) {
  5024. nread = 0;
  5025. } else {
  5026. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5027. return -1;
  5028. }
  5029. } else {
  5030. err = 0;
  5031. }
  5032. } else if (conn->ssl != NULL) {
  5033. struct pollfd pfd[1];
  5034. int pollres;
  5035. pfd[0].fd = conn->client.sock;
  5036. pfd[0].events = POLLIN;
  5037. pollres = mg_poll(pfd,
  5038. 1,
  5039. (int)(timeout * 1000.0),
  5040. &(conn->phys_ctx->stop_flag));
  5041. if (conn->phys_ctx->stop_flag) {
  5042. return -2;
  5043. }
  5044. if (pollres > 0) {
  5045. nread = SSL_read(conn->ssl, buf, len);
  5046. if (nread <= 0) {
  5047. err = SSL_get_error(conn->ssl, nread);
  5048. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5049. err = ERRNO;
  5050. } else if ((err == SSL_ERROR_WANT_READ)
  5051. || (err == SSL_ERROR_WANT_WRITE)) {
  5052. nread = 0;
  5053. } else {
  5054. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5055. return -2;
  5056. }
  5057. } else {
  5058. err = 0;
  5059. }
  5060. } else if (pollres < 0) {
  5061. /* Error */
  5062. return -2;
  5063. } else {
  5064. /* pollres = 0 means timeout */
  5065. nread = 0;
  5066. }
  5067. #endif
  5068. } else {
  5069. struct pollfd pfd[1];
  5070. int pollres;
  5071. pfd[0].fd = conn->client.sock;
  5072. pfd[0].events = POLLIN;
  5073. pollres = mg_poll(pfd,
  5074. 1,
  5075. (int)(timeout * 1000.0),
  5076. &(conn->phys_ctx->stop_flag));
  5077. if (conn->phys_ctx->stop_flag) {
  5078. return -2;
  5079. }
  5080. if (pollres > 0) {
  5081. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5082. err = (nread < 0) ? ERRNO : 0;
  5083. if (nread <= 0) {
  5084. /* shutdown of the socket at client side */
  5085. return -2;
  5086. }
  5087. } else if (pollres < 0) {
  5088. /* error callint poll */
  5089. return -2;
  5090. } else {
  5091. /* pollres = 0 means timeout */
  5092. nread = 0;
  5093. }
  5094. }
  5095. if (conn->phys_ctx->stop_flag) {
  5096. return -2;
  5097. }
  5098. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5099. /* some data has been read, or no data was requested */
  5100. return nread;
  5101. }
  5102. if (nread < 0) {
  5103. /* socket error - check errno */
  5104. #ifdef _WIN32
  5105. if (err == WSAEWOULDBLOCK) {
  5106. /* TODO (low): check if this is still required */
  5107. /* standard case if called from close_socket_gracefully */
  5108. return -2;
  5109. } else if (err == WSAETIMEDOUT) {
  5110. /* TODO (low): check if this is still required */
  5111. /* timeout is handled by the while loop */
  5112. return 0;
  5113. } else if (err == WSAECONNABORTED) {
  5114. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5115. return -2;
  5116. } else {
  5117. DEBUG_TRACE("recv() failed, error %d", err);
  5118. return -2;
  5119. }
  5120. #else
  5121. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5122. * if the timeout is reached and if the socket was set to non-
  5123. * blocking in close_socket_gracefully, so we can not distinguish
  5124. * here. We have to wait for the timeout in both cases for now.
  5125. */
  5126. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5127. /* TODO (low): check if this is still required */
  5128. /* EAGAIN/EWOULDBLOCK:
  5129. * standard case if called from close_socket_gracefully
  5130. * => should return -1 */
  5131. /* or timeout occurred
  5132. * => the code must stay in the while loop */
  5133. /* EINTR can be generated on a socket with a timeout set even
  5134. * when SA_RESTART is effective for all relevant signals
  5135. * (see signal(7)).
  5136. * => stay in the while loop */
  5137. } else {
  5138. DEBUG_TRACE("recv() failed, error %d", err);
  5139. return -2;
  5140. }
  5141. #endif
  5142. }
  5143. /* Timeout occurred, but no data available. */
  5144. return -1;
  5145. }
  5146. static int
  5147. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5148. {
  5149. int n, nread = 0;
  5150. double timeout = -1.0;
  5151. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5152. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5153. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5154. }
  5155. if (timeout >= 0.0) {
  5156. start_time = mg_get_current_time_ns();
  5157. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5158. }
  5159. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5160. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5161. if (n == -2) {
  5162. if (nread == 0) {
  5163. nread = -1; /* Propagate the error */
  5164. }
  5165. break;
  5166. } else if (n == -1) {
  5167. /* timeout */
  5168. if (timeout >= 0.0) {
  5169. now = mg_get_current_time_ns();
  5170. if ((now - start_time) <= timeout_ns) {
  5171. continue;
  5172. }
  5173. }
  5174. break;
  5175. } else if (n == 0) {
  5176. break; /* No more data to read */
  5177. } else {
  5178. conn->consumed_content += n;
  5179. nread += n;
  5180. len -= n;
  5181. }
  5182. }
  5183. return nread;
  5184. }
  5185. static void
  5186. discard_unread_request_data(struct mg_connection *conn)
  5187. {
  5188. char buf[MG_BUF_LEN];
  5189. size_t to_read;
  5190. int nread;
  5191. if (conn == NULL) {
  5192. return;
  5193. }
  5194. to_read = sizeof(buf);
  5195. if (conn->is_chunked) {
  5196. /* Chunked encoding: 3=chunk read completely
  5197. * completely */
  5198. while (conn->is_chunked != 3) {
  5199. nread = mg_read(conn, buf, to_read);
  5200. if (nread <= 0) {
  5201. break;
  5202. }
  5203. }
  5204. } else {
  5205. /* Not chunked: content length is known */
  5206. while (conn->consumed_content < conn->content_len) {
  5207. if (to_read
  5208. > (size_t)(conn->content_len - conn->consumed_content)) {
  5209. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5210. }
  5211. nread = mg_read(conn, buf, to_read);
  5212. if (nread <= 0) {
  5213. break;
  5214. }
  5215. }
  5216. }
  5217. }
  5218. static int
  5219. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5220. {
  5221. int64_t n, buffered_len, nread;
  5222. int64_t len64 =
  5223. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5224. * int, we may not read more
  5225. * bytes */
  5226. const char *body;
  5227. if (conn == NULL) {
  5228. return 0;
  5229. }
  5230. /* If Content-Length is not set for a request with body data
  5231. * (e.g., a PUT or POST request), we do not know in advance
  5232. * how much data should be read. */
  5233. if (conn->consumed_content == 0) {
  5234. if (conn->is_chunked == 1) {
  5235. conn->content_len = len64;
  5236. conn->is_chunked = 2;
  5237. } else if (conn->content_len == -1) {
  5238. /* The body data is completed when the connection
  5239. * is closed. */
  5240. conn->content_len = INT64_MAX;
  5241. conn->must_close = 1;
  5242. }
  5243. }
  5244. nread = 0;
  5245. if (conn->consumed_content < conn->content_len) {
  5246. /* Adjust number of bytes to read. */
  5247. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5248. if (left_to_read < len64) {
  5249. /* Do not read more than the total content length of the
  5250. * request.
  5251. */
  5252. len64 = left_to_read;
  5253. }
  5254. /* Return buffered data */
  5255. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5256. - conn->consumed_content;
  5257. if (buffered_len > 0) {
  5258. if (len64 < buffered_len) {
  5259. buffered_len = len64;
  5260. }
  5261. body = conn->buf + conn->request_len + conn->consumed_content;
  5262. memcpy(buf, body, (size_t)buffered_len);
  5263. len64 -= buffered_len;
  5264. conn->consumed_content += buffered_len;
  5265. nread += buffered_len;
  5266. buf = (char *)buf + buffered_len;
  5267. }
  5268. /* We have returned all buffered data. Read new data from the remote
  5269. * socket.
  5270. */
  5271. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5272. nread += n;
  5273. } else {
  5274. nread = ((nread > 0) ? nread : n);
  5275. }
  5276. }
  5277. return (int)nread;
  5278. }
  5279. static char
  5280. mg_getc(struct mg_connection *conn)
  5281. {
  5282. char c;
  5283. if (conn == NULL) {
  5284. return 0;
  5285. }
  5286. if (mg_read_inner(conn, &c, 1) <= 0) {
  5287. return (char)0;
  5288. }
  5289. return c;
  5290. }
  5291. int
  5292. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5293. {
  5294. if (len > INT_MAX) {
  5295. len = INT_MAX;
  5296. }
  5297. if (conn == NULL) {
  5298. return 0;
  5299. }
  5300. if (conn->is_chunked) {
  5301. size_t all_read = 0;
  5302. while (len > 0) {
  5303. if (conn->is_chunked == 3) {
  5304. /* No more data left to read */
  5305. return 0;
  5306. }
  5307. if (conn->chunk_remainder) {
  5308. /* copy from the remainder of the last received chunk */
  5309. long read_ret;
  5310. size_t read_now =
  5311. ((conn->chunk_remainder > len) ? (len)
  5312. : (conn->chunk_remainder));
  5313. conn->content_len += (int)read_now;
  5314. read_ret =
  5315. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5316. if (read_ret < 1) {
  5317. /* read error */
  5318. return -1;
  5319. }
  5320. all_read += (size_t)read_ret;
  5321. conn->chunk_remainder -= (size_t)read_ret;
  5322. len -= (size_t)read_ret;
  5323. if (conn->chunk_remainder == 0) {
  5324. /* Add data bytes in the current chunk have been read,
  5325. * so we are expecting \r\n now. */
  5326. char x1, x2;
  5327. conn->content_len += 2;
  5328. x1 = mg_getc(conn);
  5329. x2 = mg_getc(conn);
  5330. if ((x1 != '\r') || (x2 != '\n')) {
  5331. /* Protocol violation */
  5332. return -1;
  5333. }
  5334. }
  5335. } else {
  5336. /* fetch a new chunk */
  5337. int i = 0;
  5338. char lenbuf[64];
  5339. char *end = 0;
  5340. unsigned long chunkSize = 0;
  5341. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5342. conn->content_len++;
  5343. lenbuf[i] = mg_getc(conn);
  5344. if ((i > 0) && (lenbuf[i] == '\r')
  5345. && (lenbuf[i - 1] != '\r')) {
  5346. continue;
  5347. }
  5348. if ((i > 1) && (lenbuf[i] == '\n')
  5349. && (lenbuf[i - 1] == '\r')) {
  5350. lenbuf[i + 1] = 0;
  5351. chunkSize = strtoul(lenbuf, &end, 16);
  5352. if (chunkSize == 0) {
  5353. /* regular end of content */
  5354. conn->is_chunked = 3;
  5355. }
  5356. break;
  5357. }
  5358. if (!isxdigit(lenbuf[i])) {
  5359. /* illegal character for chunk length */
  5360. return -1;
  5361. }
  5362. }
  5363. if ((end == NULL) || (*end != '\r')) {
  5364. /* chunksize not set correctly */
  5365. return -1;
  5366. }
  5367. if (chunkSize == 0) {
  5368. break;
  5369. }
  5370. conn->chunk_remainder = chunkSize;
  5371. }
  5372. }
  5373. return (int)all_read;
  5374. }
  5375. return mg_read_inner(conn, buf, len);
  5376. }
  5377. int
  5378. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5379. {
  5380. time_t now;
  5381. int64_t n, total, allowed;
  5382. if (conn == NULL) {
  5383. return 0;
  5384. }
  5385. if (conn->throttle > 0) {
  5386. if ((now = time(NULL)) != conn->last_throttle_time) {
  5387. conn->last_throttle_time = now;
  5388. conn->last_throttle_bytes = 0;
  5389. }
  5390. allowed = conn->throttle - conn->last_throttle_bytes;
  5391. if (allowed > (int64_t)len) {
  5392. allowed = (int64_t)len;
  5393. }
  5394. if ((total = push_all(conn->phys_ctx,
  5395. NULL,
  5396. conn->client.sock,
  5397. conn->ssl,
  5398. (const char *)buf,
  5399. (int64_t)allowed)) == allowed) {
  5400. buf = (const char *)buf + total;
  5401. conn->last_throttle_bytes += total;
  5402. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5403. allowed = (conn->throttle > ((int64_t)len - total))
  5404. ? (int64_t)len - total
  5405. : conn->throttle;
  5406. if ((n = push_all(conn->phys_ctx,
  5407. NULL,
  5408. conn->client.sock,
  5409. conn->ssl,
  5410. (const char *)buf,
  5411. (int64_t)allowed)) != allowed) {
  5412. break;
  5413. }
  5414. sleep(1);
  5415. conn->last_throttle_bytes = allowed;
  5416. conn->last_throttle_time = time(NULL);
  5417. buf = (const char *)buf + n;
  5418. total += n;
  5419. }
  5420. }
  5421. } else {
  5422. total = push_all(conn->phys_ctx,
  5423. NULL,
  5424. conn->client.sock,
  5425. conn->ssl,
  5426. (const char *)buf,
  5427. (int64_t)len);
  5428. }
  5429. if (total > 0) {
  5430. conn->num_bytes_sent += total;
  5431. }
  5432. return (int)total;
  5433. }
  5434. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5435. int
  5436. mg_send_chunk(struct mg_connection *conn,
  5437. const char *chunk,
  5438. unsigned int chunk_len)
  5439. {
  5440. char lenbuf[16];
  5441. size_t lenbuf_len;
  5442. int ret;
  5443. int t;
  5444. /* First store the length information in a text buffer. */
  5445. sprintf(lenbuf, "%x\r\n", chunk_len);
  5446. lenbuf_len = strlen(lenbuf);
  5447. /* Then send length information, chunk and terminating \r\n. */
  5448. ret = mg_write(conn, lenbuf, lenbuf_len);
  5449. if (ret != (int)lenbuf_len) {
  5450. return -1;
  5451. }
  5452. t = ret;
  5453. ret = mg_write(conn, chunk, chunk_len);
  5454. if (ret != (int)chunk_len) {
  5455. return -1;
  5456. }
  5457. t += ret;
  5458. ret = mg_write(conn, "\r\n", 2);
  5459. if (ret != 2) {
  5460. return -1;
  5461. }
  5462. t += ret;
  5463. return t;
  5464. }
  5465. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5466. static int
  5467. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5468. {
  5469. va_list ap_copy;
  5470. size_t size = MG_BUF_LEN / 4;
  5471. int len = -1;
  5472. *buf = NULL;
  5473. while (len < 0) {
  5474. if (*buf) {
  5475. mg_free(*buf);
  5476. }
  5477. size *= 4;
  5478. *buf = (char *)mg_malloc(size);
  5479. if (!*buf) {
  5480. break;
  5481. }
  5482. va_copy(ap_copy, ap);
  5483. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5484. va_end(ap_copy);
  5485. (*buf)[size - 1] = 0;
  5486. }
  5487. return len;
  5488. }
  5489. /* Print message to buffer. If buffer is large enough to hold the message,
  5490. * return buffer. If buffer is to small, allocate large enough buffer on
  5491. * heap,
  5492. * and return allocated buffer. */
  5493. static int
  5494. alloc_vprintf(char **out_buf,
  5495. char *prealloc_buf,
  5496. size_t prealloc_size,
  5497. const char *fmt,
  5498. va_list ap)
  5499. {
  5500. va_list ap_copy;
  5501. int len;
  5502. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5503. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5504. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5505. * Therefore, we make two passes: on first pass, get required message
  5506. * length.
  5507. * On second pass, actually print the message. */
  5508. va_copy(ap_copy, ap);
  5509. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5510. va_end(ap_copy);
  5511. if (len < 0) {
  5512. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5513. * Switch to alternative code path that uses incremental
  5514. * allocations.
  5515. */
  5516. va_copy(ap_copy, ap);
  5517. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5518. va_end(ap_copy);
  5519. } else if ((size_t)(len) >= prealloc_size) {
  5520. /* The pre-allocated buffer not large enough. */
  5521. /* Allocate a new buffer. */
  5522. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5523. if (!*out_buf) {
  5524. /* Allocation failed. Return -1 as "out of memory" error. */
  5525. return -1;
  5526. }
  5527. /* Buffer allocation successful. Store the string there. */
  5528. va_copy(ap_copy, ap);
  5529. IGNORE_UNUSED_RESULT(
  5530. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5531. va_end(ap_copy);
  5532. } else {
  5533. /* The pre-allocated buffer is large enough.
  5534. * Use it to store the string and return the address. */
  5535. va_copy(ap_copy, ap);
  5536. IGNORE_UNUSED_RESULT(
  5537. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5538. va_end(ap_copy);
  5539. *out_buf = prealloc_buf;
  5540. }
  5541. return len;
  5542. }
  5543. static int
  5544. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5545. {
  5546. char mem[MG_BUF_LEN];
  5547. char *buf = NULL;
  5548. int len;
  5549. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5550. len = mg_write(conn, buf, (size_t)len);
  5551. }
  5552. if ((buf != mem) && (buf != NULL)) {
  5553. mg_free(buf);
  5554. }
  5555. return len;
  5556. }
  5557. int
  5558. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5559. {
  5560. va_list ap;
  5561. int result;
  5562. va_start(ap, fmt);
  5563. result = mg_vprintf(conn, fmt, ap);
  5564. va_end(ap);
  5565. return result;
  5566. }
  5567. int
  5568. mg_url_decode(const char *src,
  5569. int src_len,
  5570. char *dst,
  5571. int dst_len,
  5572. int is_form_url_encoded)
  5573. {
  5574. int i, j, a, b;
  5575. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5576. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5577. if ((i < src_len - 2) && (src[i] == '%')
  5578. && isxdigit(*(const unsigned char *)(src + i + 1))
  5579. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5580. a = tolower(*(const unsigned char *)(src + i + 1));
  5581. b = tolower(*(const unsigned char *)(src + i + 2));
  5582. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5583. i += 2;
  5584. } else if (is_form_url_encoded && (src[i] == '+')) {
  5585. dst[j] = ' ';
  5586. } else {
  5587. dst[j] = src[i];
  5588. }
  5589. }
  5590. dst[j] = '\0'; /* Null-terminate the destination */
  5591. return (i >= src_len) ? j : -1;
  5592. }
  5593. int
  5594. mg_get_var(const char *data,
  5595. size_t data_len,
  5596. const char *name,
  5597. char *dst,
  5598. size_t dst_len)
  5599. {
  5600. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5601. }
  5602. int
  5603. mg_get_var2(const char *data,
  5604. size_t data_len,
  5605. const char *name,
  5606. char *dst,
  5607. size_t dst_len,
  5608. size_t occurrence)
  5609. {
  5610. const char *p, *e, *s;
  5611. size_t name_len;
  5612. int len;
  5613. if ((dst == NULL) || (dst_len == 0)) {
  5614. len = -2;
  5615. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5616. len = -1;
  5617. dst[0] = '\0';
  5618. } else {
  5619. name_len = strlen(name);
  5620. e = data + data_len;
  5621. len = -1;
  5622. dst[0] = '\0';
  5623. /* data is "var1=val1&var2=val2...". Find variable first */
  5624. for (p = data; p + name_len < e; p++) {
  5625. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5626. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5627. /* Point p to variable value */
  5628. p += name_len + 1;
  5629. /* Point s to the end of the value */
  5630. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5631. if (s == NULL) {
  5632. s = e;
  5633. }
  5634. DEBUG_ASSERT(s >= p);
  5635. if (s < p) {
  5636. return -3;
  5637. }
  5638. /* Decode variable into destination buffer */
  5639. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5640. /* Redirect error code from -1 to -2 (destination buffer too
  5641. * small). */
  5642. if (len == -1) {
  5643. len = -2;
  5644. }
  5645. break;
  5646. }
  5647. }
  5648. }
  5649. return len;
  5650. }
  5651. /* HCP24: some changes to compare hole var_name */
  5652. int
  5653. mg_get_cookie(const char *cookie_header,
  5654. const char *var_name,
  5655. char *dst,
  5656. size_t dst_size)
  5657. {
  5658. const char *s, *p, *end;
  5659. int name_len, len = -1;
  5660. if ((dst == NULL) || (dst_size == 0)) {
  5661. return -2;
  5662. }
  5663. dst[0] = '\0';
  5664. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5665. return -1;
  5666. }
  5667. name_len = (int)strlen(var_name);
  5668. end = s + strlen(s);
  5669. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5670. if (s[name_len] == '=') {
  5671. /* HCP24: now check is it a substring or a full cookie name */
  5672. if ((s == cookie_header) || (s[-1] == ' ')) {
  5673. s += name_len + 1;
  5674. if ((p = strchr(s, ' ')) == NULL) {
  5675. p = end;
  5676. }
  5677. if (p[-1] == ';') {
  5678. p--;
  5679. }
  5680. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5681. s++;
  5682. p--;
  5683. }
  5684. if ((size_t)(p - s) < dst_size) {
  5685. len = (int)(p - s);
  5686. mg_strlcpy(dst, s, (size_t)len + 1);
  5687. } else {
  5688. len = -3;
  5689. }
  5690. break;
  5691. }
  5692. }
  5693. }
  5694. return len;
  5695. }
  5696. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5697. static void
  5698. base64_encode(const unsigned char *src, int src_len, char *dst)
  5699. {
  5700. static const char *b64 =
  5701. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5702. int i, j, a, b, c;
  5703. for (i = j = 0; i < src_len; i += 3) {
  5704. a = src[i];
  5705. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5706. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5707. dst[j++] = b64[a >> 2];
  5708. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5709. if (i + 1 < src_len) {
  5710. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5711. }
  5712. if (i + 2 < src_len) {
  5713. dst[j++] = b64[c & 63];
  5714. }
  5715. }
  5716. while (j % 4 != 0) {
  5717. dst[j++] = '=';
  5718. }
  5719. dst[j++] = '\0';
  5720. }
  5721. #endif
  5722. #if defined(USE_LUA)
  5723. static unsigned char
  5724. b64reverse(char letter)
  5725. {
  5726. if ((letter >= 'A') && (letter <= 'Z')) {
  5727. return letter - 'A';
  5728. }
  5729. if ((letter >= 'a') && (letter <= 'z')) {
  5730. return letter - 'a' + 26;
  5731. }
  5732. if ((letter >= '0') && (letter <= '9')) {
  5733. return letter - '0' + 52;
  5734. }
  5735. if (letter == '+') {
  5736. return 62;
  5737. }
  5738. if (letter == '/') {
  5739. return 63;
  5740. }
  5741. if (letter == '=') {
  5742. return 255; /* normal end */
  5743. }
  5744. return 254; /* error */
  5745. }
  5746. static int
  5747. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5748. {
  5749. int i;
  5750. unsigned char a, b, c, d;
  5751. *dst_len = 0;
  5752. for (i = 0; i < src_len; i += 4) {
  5753. a = b64reverse(src[i]);
  5754. if (a >= 254) {
  5755. return i;
  5756. }
  5757. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5758. if (b >= 254) {
  5759. return i + 1;
  5760. }
  5761. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5762. if (c == 254) {
  5763. return i + 2;
  5764. }
  5765. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5766. if (d == 254) {
  5767. return i + 3;
  5768. }
  5769. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5770. if (c != 255) {
  5771. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5772. if (d != 255) {
  5773. dst[(*dst_len)++] = (c << 6) + d;
  5774. }
  5775. }
  5776. }
  5777. return -1;
  5778. }
  5779. #endif
  5780. static int
  5781. is_put_or_delete_method(const struct mg_connection *conn)
  5782. {
  5783. if (conn) {
  5784. const char *s = conn->request_info.request_method;
  5785. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5786. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5787. }
  5788. return 0;
  5789. }
  5790. #if !defined(NO_FILES)
  5791. static int
  5792. extention_matches_script(
  5793. struct mg_connection *conn, /* in: request (must be valid) */
  5794. const char *filename /* in: filename (must be valid) */
  5795. )
  5796. {
  5797. #if !defined(NO_CGI)
  5798. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  5799. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  5800. filename) > 0) {
  5801. return 1;
  5802. }
  5803. #endif
  5804. #if defined(USE_LUA)
  5805. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  5806. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5807. filename) > 0) {
  5808. return 1;
  5809. }
  5810. #endif
  5811. #if defined(USE_DUKTAPE)
  5812. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5813. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5814. filename) > 0) {
  5815. return 1;
  5816. }
  5817. #endif
  5818. /* filename and conn could be unused, if all preocessor conditions
  5819. * are false (no script language supported). */
  5820. (void)filename;
  5821. (void)conn;
  5822. return 0;
  5823. }
  5824. /* For given directory path, substitute it to valid index file.
  5825. * Return 1 if index file has been found, 0 if not found.
  5826. * If the file is found, it's stats is returned in stp. */
  5827. static int
  5828. substitute_index_file(struct mg_connection *conn,
  5829. char *path,
  5830. size_t path_len,
  5831. struct mg_file_stat *filestat)
  5832. {
  5833. const char *list = conn->dom_ctx->config[INDEX_FILES];
  5834. struct vec filename_vec;
  5835. size_t n = strlen(path);
  5836. int found = 0;
  5837. /* The 'path' given to us points to the directory. Remove all trailing
  5838. * directory separator characters from the end of the path, and
  5839. * then append single directory separator character. */
  5840. while ((n > 0) && (path[n - 1] == '/')) {
  5841. n--;
  5842. }
  5843. path[n] = '/';
  5844. /* Traverse index files list. For each entry, append it to the given
  5845. * path and see if the file exists. If it exists, break the loop */
  5846. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5847. /* Ignore too long entries that may overflow path buffer */
  5848. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  5849. continue;
  5850. }
  5851. /* Prepare full path to the index file */
  5852. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5853. /* Does it exist? */
  5854. if (mg_stat(conn, path, filestat)) {
  5855. /* Yes it does, break the loop */
  5856. found = 1;
  5857. break;
  5858. }
  5859. }
  5860. /* If no index file exists, restore directory path */
  5861. if (!found) {
  5862. path[n] = '\0';
  5863. }
  5864. return found;
  5865. }
  5866. #endif
  5867. static void
  5868. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  5869. char *filename, /* out: filename */
  5870. size_t filename_buf_len, /* in: size of filename buffer */
  5871. struct mg_file_stat *filestat, /* out: file status structure */
  5872. int *is_found, /* out: file found (directly) */
  5873. int *is_script_resource, /* out: handled by a script? */
  5874. int *is_websocket_request, /* out: websocket connetion? */
  5875. int *is_put_or_delete_request /* out: put/delete a file? */
  5876. )
  5877. {
  5878. char const *accept_encoding;
  5879. #if !defined(NO_FILES)
  5880. const char *uri = conn->request_info.local_uri;
  5881. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  5882. const char *rewrite;
  5883. struct vec a, b;
  5884. int match_len;
  5885. char gz_path[PATH_MAX];
  5886. int truncated;
  5887. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5888. char *tmp_str;
  5889. size_t tmp_str_len, sep_pos;
  5890. int allow_substitute_script_subresources;
  5891. #endif
  5892. #else
  5893. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5894. #endif
  5895. /* Step 1: Set all initially unknown outputs to zero */
  5896. memset(filestat, 0, sizeof(*filestat));
  5897. *filename = 0;
  5898. *is_found = 0;
  5899. *is_script_resource = 0;
  5900. /* Step 2: Check if the request attempts to modify the file system */
  5901. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5902. /* Step 3: Check if it is a websocket request, and modify the document
  5903. * root if required */
  5904. #if defined(USE_WEBSOCKET)
  5905. *is_websocket_request = is_websocket_protocol(conn);
  5906. #if !defined(NO_FILES)
  5907. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  5908. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  5909. }
  5910. #endif /* !NO_FILES */
  5911. #else /* USE_WEBSOCKET */
  5912. *is_websocket_request = 0;
  5913. #endif /* USE_WEBSOCKET */
  5914. /* Step 4: Check if gzip encoded response is allowed */
  5915. conn->accept_gzip = 0;
  5916. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5917. if (strstr(accept_encoding, "gzip") != NULL) {
  5918. conn->accept_gzip = 1;
  5919. }
  5920. }
  5921. #if !defined(NO_FILES)
  5922. /* Step 5: If there is no root directory, don't look for files. */
  5923. /* Note that root == NULL is a regular use case here. This occurs,
  5924. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5925. * config is not required. */
  5926. if (root == NULL) {
  5927. /* all file related outputs have already been set to 0, just return
  5928. */
  5929. return;
  5930. }
  5931. /* Step 6: Determine the local file path from the root path and the
  5932. * request uri. */
  5933. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5934. * part of the path one byte on the right. */
  5935. mg_snprintf(
  5936. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5937. if (truncated) {
  5938. goto interpret_cleanup;
  5939. }
  5940. /* Step 7: URI rewriting */
  5941. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  5942. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5943. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5944. mg_snprintf(conn,
  5945. &truncated,
  5946. filename,
  5947. filename_buf_len - 1,
  5948. "%.*s%s",
  5949. (int)b.len,
  5950. b.ptr,
  5951. uri + match_len);
  5952. break;
  5953. }
  5954. }
  5955. if (truncated) {
  5956. goto interpret_cleanup;
  5957. }
  5958. /* Step 8: Check if the file exists at the server */
  5959. /* Local file path and name, corresponding to requested URI
  5960. * is now stored in "filename" variable. */
  5961. if (mg_stat(conn, filename, filestat)) {
  5962. int uri_len = (int)strlen(uri);
  5963. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  5964. /* 8.1: File exists. */
  5965. *is_found = 1;
  5966. /* 8.2: Check if it is a script type. */
  5967. if (extention_matches_script(conn, filename)) {
  5968. /* The request addresses a CGI resource, Lua script or
  5969. * server-side javascript.
  5970. * The URI corresponds to the script itself (like
  5971. * /path/script.cgi), and there is no additional resource
  5972. * path (like /path/script.cgi/something).
  5973. * Requests that modify (replace or delete) a resource, like
  5974. * PUT and DELETE requests, should replace/delete the script
  5975. * file.
  5976. * Requests that read or write from/to a resource, like GET and
  5977. * POST requests, should call the script and return the
  5978. * generated response. */
  5979. *is_script_resource = (!*is_put_or_delete_request);
  5980. }
  5981. /* 8.3: If the request target is a directory, there could be
  5982. * a substitute file (index.html, index.cgi, ...). */
  5983. if (filestat->is_directory && is_uri_end_slash) {
  5984. /* Use a local copy here, since substitute_index_file will
  5985. * change the content of the file status */
  5986. struct mg_file_stat tmp_filestat;
  5987. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5988. if (substitute_index_file(
  5989. conn, filename, filename_buf_len, &tmp_filestat)) {
  5990. /* Substitute file found. Copy stat to the output, then
  5991. * check if the file is a script file */
  5992. *filestat = tmp_filestat;
  5993. if (extention_matches_script(conn, filename)) {
  5994. /* Substitute file is a script file */
  5995. *is_script_resource = 1;
  5996. } else {
  5997. /* Substitute file is a regular file */
  5998. *is_script_resource = 0;
  5999. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6000. }
  6001. }
  6002. /* If there is no substitute file, the server could return
  6003. * a directory listing in a later step */
  6004. }
  6005. return;
  6006. }
  6007. /* Step 9: Check for zipped files: */
  6008. /* If we can't find the actual file, look for the file
  6009. * with the same name but a .gz extension. If we find it,
  6010. * use that and set the gzipped flag in the file struct
  6011. * to indicate that the response need to have the content-
  6012. * encoding: gzip header.
  6013. * We can only do this if the browser declares support. */
  6014. if (conn->accept_gzip) {
  6015. mg_snprintf(
  6016. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6017. if (truncated) {
  6018. goto interpret_cleanup;
  6019. }
  6020. if (mg_stat(conn, gz_path, filestat)) {
  6021. if (filestat) {
  6022. filestat->is_gzipped = 1;
  6023. *is_found = 1;
  6024. }
  6025. /* Currently gz files can not be scripts. */
  6026. return;
  6027. }
  6028. }
  6029. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6030. /* Step 10: Script resources may handle sub-resources */
  6031. /* Support PATH_INFO for CGI scripts. */
  6032. tmp_str_len = strlen(filename);
  6033. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6034. if (!tmp_str) {
  6035. /* Out of memory */
  6036. goto interpret_cleanup;
  6037. }
  6038. memcpy(tmp_str, filename, tmp_str_len + 1);
  6039. /* Check config, if index scripts may have sub-resources */
  6040. allow_substitute_script_subresources =
  6041. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6042. "yes");
  6043. sep_pos = tmp_str_len;
  6044. while (sep_pos > 0) {
  6045. sep_pos--;
  6046. if (tmp_str[sep_pos] == '/') {
  6047. int is_script = 0, does_exist = 0;
  6048. tmp_str[sep_pos] = 0;
  6049. if (tmp_str[0]) {
  6050. is_script = extention_matches_script(conn, tmp_str);
  6051. does_exist = mg_stat(conn, tmp_str, filestat);
  6052. }
  6053. if (does_exist && is_script) {
  6054. filename[sep_pos] = 0;
  6055. memmove(filename + sep_pos + 2,
  6056. filename + sep_pos + 1,
  6057. strlen(filename + sep_pos + 1) + 1);
  6058. conn->path_info = filename + sep_pos + 1;
  6059. filename[sep_pos + 1] = '/';
  6060. *is_script_resource = 1;
  6061. *is_found = 1;
  6062. break;
  6063. }
  6064. if (allow_substitute_script_subresources) {
  6065. if (substitute_index_file(
  6066. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6067. /* some intermediate directory has an index file */
  6068. if (extention_matches_script(conn, tmp_str)) {
  6069. char *tmp_str2;
  6070. DEBUG_TRACE("Substitute script %s serving path %s",
  6071. tmp_str,
  6072. filename);
  6073. /* this index file is a script */
  6074. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6075. conn->phys_ctx);
  6076. mg_snprintf(conn,
  6077. &truncated,
  6078. filename,
  6079. filename_buf_len,
  6080. "%s//%s",
  6081. tmp_str,
  6082. tmp_str2);
  6083. mg_free(tmp_str2);
  6084. if (truncated) {
  6085. mg_free(tmp_str);
  6086. goto interpret_cleanup;
  6087. }
  6088. sep_pos = strlen(tmp_str);
  6089. filename[sep_pos] = 0;
  6090. conn->path_info = filename + sep_pos + 1;
  6091. *is_script_resource = 1;
  6092. *is_found = 1;
  6093. break;
  6094. } else {
  6095. DEBUG_TRACE("Substitute file %s serving path %s",
  6096. tmp_str,
  6097. filename);
  6098. /* non-script files will not have sub-resources */
  6099. filename[sep_pos] = 0;
  6100. conn->path_info = 0;
  6101. *is_script_resource = 0;
  6102. *is_found = 0;
  6103. break;
  6104. }
  6105. }
  6106. }
  6107. tmp_str[sep_pos] = '/';
  6108. }
  6109. }
  6110. mg_free(tmp_str);
  6111. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6112. #endif /* !defined(NO_FILES) */
  6113. return;
  6114. #if !defined(NO_FILES)
  6115. /* Reset all outputs */
  6116. interpret_cleanup:
  6117. memset(filestat, 0, sizeof(*filestat));
  6118. *filename = 0;
  6119. *is_found = 0;
  6120. *is_script_resource = 0;
  6121. *is_websocket_request = 0;
  6122. *is_put_or_delete_request = 0;
  6123. #endif /* !defined(NO_FILES) */
  6124. }
  6125. /* Check whether full request is buffered. Return:
  6126. * -1 if request or response is malformed
  6127. * 0 if request or response is not yet fully buffered
  6128. * >0 actual request length, including last \r\n\r\n */
  6129. static int
  6130. get_http_header_len(const char *buf, int buflen)
  6131. {
  6132. int i;
  6133. for (i = 0; i < buflen; i++) {
  6134. /* Do an unsigned comparison in some conditions below */
  6135. const unsigned char c = ((const unsigned char *)buf)[i];
  6136. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6137. && !isprint(c)) {
  6138. /* abort scan as soon as one malformed character is found */
  6139. return -1;
  6140. }
  6141. if (i < buflen - 1) {
  6142. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6143. /* Two newline, no carriage return - not standard compliant,
  6144. * but
  6145. * it
  6146. * should be accepted */
  6147. return i + 2;
  6148. }
  6149. }
  6150. if (i < buflen - 3) {
  6151. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6152. && (buf[i + 3] == '\n')) {
  6153. /* Two \r\n - standard compliant */
  6154. return i + 4;
  6155. }
  6156. }
  6157. }
  6158. return 0;
  6159. }
  6160. #if !defined(NO_CACHING)
  6161. /* Convert month to the month number. Return -1 on error, or month number */
  6162. static int
  6163. get_month_index(const char *s)
  6164. {
  6165. size_t i;
  6166. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6167. if (!strcmp(s, month_names[i])) {
  6168. return (int)i;
  6169. }
  6170. }
  6171. return -1;
  6172. }
  6173. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6174. static time_t
  6175. parse_date_string(const char *datetime)
  6176. {
  6177. char month_str[32] = {0};
  6178. int second, minute, hour, day, month, year;
  6179. time_t result = (time_t)0;
  6180. struct tm tm;
  6181. if ((sscanf(datetime,
  6182. "%d/%3s/%d %d:%d:%d",
  6183. &day,
  6184. month_str,
  6185. &year,
  6186. &hour,
  6187. &minute,
  6188. &second) == 6) || (sscanf(datetime,
  6189. "%d %3s %d %d:%d:%d",
  6190. &day,
  6191. month_str,
  6192. &year,
  6193. &hour,
  6194. &minute,
  6195. &second) == 6)
  6196. || (sscanf(datetime,
  6197. "%*3s, %d %3s %d %d:%d:%d",
  6198. &day,
  6199. month_str,
  6200. &year,
  6201. &hour,
  6202. &minute,
  6203. &second) == 6) || (sscanf(datetime,
  6204. "%d-%3s-%d %d:%d:%d",
  6205. &day,
  6206. month_str,
  6207. &year,
  6208. &hour,
  6209. &minute,
  6210. &second) == 6)) {
  6211. month = get_month_index(month_str);
  6212. if ((month >= 0) && (year >= 1970)) {
  6213. memset(&tm, 0, sizeof(tm));
  6214. tm.tm_year = year - 1900;
  6215. tm.tm_mon = month;
  6216. tm.tm_mday = day;
  6217. tm.tm_hour = hour;
  6218. tm.tm_min = minute;
  6219. tm.tm_sec = second;
  6220. result = timegm(&tm);
  6221. }
  6222. }
  6223. return result;
  6224. }
  6225. #endif /* !NO_CACHING */
  6226. /* Protect against directory disclosure attack by removing '..',
  6227. * excessive '/' and '\' characters */
  6228. static void
  6229. remove_double_dots_and_double_slashes(char *s)
  6230. {
  6231. char *p = s;
  6232. while ((s[0] == '.') && (s[1] == '.')) {
  6233. s++;
  6234. }
  6235. while (*s != '\0') {
  6236. *p++ = *s++;
  6237. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6238. /* Skip all following slashes, backslashes and double-dots */
  6239. while (s[0] != '\0') {
  6240. if ((s[0] == '/') || (s[0] == '\\')) {
  6241. s++;
  6242. } else if ((s[0] == '.') && (s[1] == '.')) {
  6243. s += 2;
  6244. } else {
  6245. break;
  6246. }
  6247. }
  6248. }
  6249. }
  6250. *p = '\0';
  6251. }
  6252. static const struct {
  6253. const char *extension;
  6254. size_t ext_len;
  6255. const char *mime_type;
  6256. } builtin_mime_types[] = {
  6257. /* IANA registered MIME types
  6258. * (http://www.iana.org/assignments/media-types)
  6259. * application types */
  6260. {".doc", 4, "application/msword"},
  6261. {".eps", 4, "application/postscript"},
  6262. {".exe", 4, "application/octet-stream"},
  6263. {".js", 3, "application/javascript"},
  6264. {".json", 5, "application/json"},
  6265. {".pdf", 4, "application/pdf"},
  6266. {".ps", 3, "application/postscript"},
  6267. {".rtf", 4, "application/rtf"},
  6268. {".xhtml", 6, "application/xhtml+xml"},
  6269. {".xsl", 4, "application/xml"},
  6270. {".xslt", 5, "application/xml"},
  6271. /* fonts */
  6272. {".ttf", 4, "application/font-sfnt"},
  6273. {".cff", 4, "application/font-sfnt"},
  6274. {".otf", 4, "application/font-sfnt"},
  6275. {".aat", 4, "application/font-sfnt"},
  6276. {".sil", 4, "application/font-sfnt"},
  6277. {".pfr", 4, "application/font-tdpfr"},
  6278. {".woff", 5, "application/font-woff"},
  6279. /* audio */
  6280. {".mp3", 4, "audio/mpeg"},
  6281. {".oga", 4, "audio/ogg"},
  6282. {".ogg", 4, "audio/ogg"},
  6283. /* image */
  6284. {".gif", 4, "image/gif"},
  6285. {".ief", 4, "image/ief"},
  6286. {".jpeg", 5, "image/jpeg"},
  6287. {".jpg", 4, "image/jpeg"},
  6288. {".jpm", 4, "image/jpm"},
  6289. {".jpx", 4, "image/jpx"},
  6290. {".png", 4, "image/png"},
  6291. {".svg", 4, "image/svg+xml"},
  6292. {".tif", 4, "image/tiff"},
  6293. {".tiff", 5, "image/tiff"},
  6294. /* model */
  6295. {".wrl", 4, "model/vrml"},
  6296. /* text */
  6297. {".css", 4, "text/css"},
  6298. {".csv", 4, "text/csv"},
  6299. {".htm", 4, "text/html"},
  6300. {".html", 5, "text/html"},
  6301. {".sgm", 4, "text/sgml"},
  6302. {".shtm", 5, "text/html"},
  6303. {".shtml", 6, "text/html"},
  6304. {".txt", 4, "text/plain"},
  6305. {".xml", 4, "text/xml"},
  6306. /* video */
  6307. {".mov", 4, "video/quicktime"},
  6308. {".mp4", 4, "video/mp4"},
  6309. {".mpeg", 5, "video/mpeg"},
  6310. {".mpg", 4, "video/mpeg"},
  6311. {".ogv", 4, "video/ogg"},
  6312. {".qt", 3, "video/quicktime"},
  6313. /* not registered types
  6314. * (http://reference.sitepoint.com/html/mime-types-full,
  6315. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6316. {".arj", 4, "application/x-arj-compressed"},
  6317. {".gz", 3, "application/x-gunzip"},
  6318. {".rar", 4, "application/x-arj-compressed"},
  6319. {".swf", 4, "application/x-shockwave-flash"},
  6320. {".tar", 4, "application/x-tar"},
  6321. {".tgz", 4, "application/x-tar-gz"},
  6322. {".torrent", 8, "application/x-bittorrent"},
  6323. {".ppt", 4, "application/x-mspowerpoint"},
  6324. {".xls", 4, "application/x-msexcel"},
  6325. {".zip", 4, "application/x-zip-compressed"},
  6326. {".aac",
  6327. 4,
  6328. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6329. {".aif", 4, "audio/x-aif"},
  6330. {".m3u", 4, "audio/x-mpegurl"},
  6331. {".mid", 4, "audio/x-midi"},
  6332. {".ra", 3, "audio/x-pn-realaudio"},
  6333. {".ram", 4, "audio/x-pn-realaudio"},
  6334. {".wav", 4, "audio/x-wav"},
  6335. {".bmp", 4, "image/bmp"},
  6336. {".ico", 4, "image/x-icon"},
  6337. {".pct", 4, "image/x-pct"},
  6338. {".pict", 5, "image/pict"},
  6339. {".rgb", 4, "image/x-rgb"},
  6340. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6341. {".asf", 4, "video/x-ms-asf"},
  6342. {".avi", 4, "video/x-msvideo"},
  6343. {".m4v", 4, "video/x-m4v"},
  6344. {NULL, 0, NULL}};
  6345. const char *
  6346. mg_get_builtin_mime_type(const char *path)
  6347. {
  6348. const char *ext;
  6349. size_t i, path_len;
  6350. path_len = strlen(path);
  6351. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6352. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6353. if ((path_len > builtin_mime_types[i].ext_len)
  6354. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6355. return builtin_mime_types[i].mime_type;
  6356. }
  6357. }
  6358. return "text/plain";
  6359. }
  6360. /* Look at the "path" extension and figure what mime type it has.
  6361. * Store mime type in the vector. */
  6362. static void
  6363. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6364. {
  6365. struct vec ext_vec, mime_vec;
  6366. const char *list, *ext;
  6367. size_t path_len;
  6368. path_len = strlen(path);
  6369. if ((conn == NULL) || (vec == NULL)) {
  6370. if (vec != NULL) {
  6371. memset(vec, '\0', sizeof(struct vec));
  6372. }
  6373. return;
  6374. }
  6375. /* Scan user-defined mime types first, in case user wants to
  6376. * override default mime types. */
  6377. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6378. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6379. /* ext now points to the path suffix */
  6380. ext = path + path_len - ext_vec.len;
  6381. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6382. *vec = mime_vec;
  6383. return;
  6384. }
  6385. }
  6386. vec->ptr = mg_get_builtin_mime_type(path);
  6387. vec->len = strlen(vec->ptr);
  6388. }
  6389. /* Stringify binary data. Output buffer must be twice as big as input,
  6390. * because each byte takes 2 bytes in string representation */
  6391. static void
  6392. bin2str(char *to, const unsigned char *p, size_t len)
  6393. {
  6394. static const char *hex = "0123456789abcdef";
  6395. for (; len--; p++) {
  6396. *to++ = hex[p[0] >> 4];
  6397. *to++ = hex[p[0] & 0x0f];
  6398. }
  6399. *to = '\0';
  6400. }
  6401. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6402. */
  6403. char *
  6404. mg_md5(char buf[33], ...)
  6405. {
  6406. md5_byte_t hash[16];
  6407. const char *p;
  6408. va_list ap;
  6409. md5_state_t ctx;
  6410. md5_init(&ctx);
  6411. va_start(ap, buf);
  6412. while ((p = va_arg(ap, const char *)) != NULL) {
  6413. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6414. }
  6415. va_end(ap);
  6416. md5_finish(&ctx, hash);
  6417. bin2str(buf, hash, sizeof(hash));
  6418. return buf;
  6419. }
  6420. /* Check the user's password, return 1 if OK */
  6421. static int
  6422. check_password(const char *method,
  6423. const char *ha1,
  6424. const char *uri,
  6425. const char *nonce,
  6426. const char *nc,
  6427. const char *cnonce,
  6428. const char *qop,
  6429. const char *response)
  6430. {
  6431. char ha2[32 + 1], expected_response[32 + 1];
  6432. /* Some of the parameters may be NULL */
  6433. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6434. || (qop == NULL) || (response == NULL)) {
  6435. return 0;
  6436. }
  6437. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6438. if (strlen(response) != 32) {
  6439. return 0;
  6440. }
  6441. mg_md5(ha2, method, ":", uri, NULL);
  6442. mg_md5(expected_response,
  6443. ha1,
  6444. ":",
  6445. nonce,
  6446. ":",
  6447. nc,
  6448. ":",
  6449. cnonce,
  6450. ":",
  6451. qop,
  6452. ":",
  6453. ha2,
  6454. NULL);
  6455. return mg_strcasecmp(response, expected_response) == 0;
  6456. }
  6457. /* Use the global passwords file, if specified by auth_gpass option,
  6458. * or search for .htpasswd in the requested directory. */
  6459. static void
  6460. open_auth_file(struct mg_connection *conn,
  6461. const char *path,
  6462. struct mg_file *filep)
  6463. {
  6464. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6465. char name[PATH_MAX];
  6466. const char *p, *e,
  6467. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6468. int truncated;
  6469. if (gpass != NULL) {
  6470. /* Use global passwords file */
  6471. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6472. #ifdef DEBUG
  6473. /* Use mg_cry_internal here, since gpass has been configured. */
  6474. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6475. #endif
  6476. }
  6477. /* Important: using local struct mg_file to test path for
  6478. * is_directory flag. If filep is used, mg_stat() makes it
  6479. * appear as if auth file was opened.
  6480. * TODO(mid): Check if this is still required after rewriting
  6481. * mg_stat */
  6482. } else if (mg_stat(conn, path, &filep->stat)
  6483. && filep->stat.is_directory) {
  6484. mg_snprintf(conn,
  6485. &truncated,
  6486. name,
  6487. sizeof(name),
  6488. "%s/%s",
  6489. path,
  6490. PASSWORDS_FILE_NAME);
  6491. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6492. #ifdef DEBUG
  6493. /* Don't use mg_cry_internal here, but only a trace, since this
  6494. * is
  6495. * a typical case. It will occur for every directory
  6496. * without a password file. */
  6497. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6498. #endif
  6499. }
  6500. } else {
  6501. /* Try to find .htpasswd in requested directory. */
  6502. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6503. if (e[0] == '/') {
  6504. break;
  6505. }
  6506. }
  6507. mg_snprintf(conn,
  6508. &truncated,
  6509. name,
  6510. sizeof(name),
  6511. "%.*s/%s",
  6512. (int)(e - p),
  6513. p,
  6514. PASSWORDS_FILE_NAME);
  6515. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6516. #ifdef DEBUG
  6517. /* Don't use mg_cry_internal here, but only a trace, since this
  6518. * is
  6519. * a typical case. It will occur for every directory
  6520. * without a password file. */
  6521. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6522. #endif
  6523. }
  6524. }
  6525. }
  6526. }
  6527. /* Parsed Authorization header */
  6528. struct ah {
  6529. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6530. };
  6531. /* Return 1 on success. Always initializes the ah structure. */
  6532. static int
  6533. parse_auth_header(struct mg_connection *conn,
  6534. char *buf,
  6535. size_t buf_size,
  6536. struct ah *ah)
  6537. {
  6538. char *name, *value, *s;
  6539. const char *auth_header;
  6540. uint64_t nonce;
  6541. if (!ah || !conn) {
  6542. return 0;
  6543. }
  6544. (void)memset(ah, 0, sizeof(*ah));
  6545. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6546. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6547. return 0;
  6548. }
  6549. /* Make modifiable copy of the auth header */
  6550. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6551. s = buf;
  6552. /* Parse authorization header */
  6553. for (;;) {
  6554. /* Gobble initial spaces */
  6555. while (isspace(*(unsigned char *)s)) {
  6556. s++;
  6557. }
  6558. name = skip_quoted(&s, "=", " ", 0);
  6559. /* Value is either quote-delimited, or ends at first comma or space.
  6560. */
  6561. if (s[0] == '\"') {
  6562. s++;
  6563. value = skip_quoted(&s, "\"", " ", '\\');
  6564. if (s[0] == ',') {
  6565. s++;
  6566. }
  6567. } else {
  6568. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6569. * spaces */
  6570. }
  6571. if (*name == '\0') {
  6572. break;
  6573. }
  6574. if (!strcmp(name, "username")) {
  6575. ah->user = value;
  6576. } else if (!strcmp(name, "cnonce")) {
  6577. ah->cnonce = value;
  6578. } else if (!strcmp(name, "response")) {
  6579. ah->response = value;
  6580. } else if (!strcmp(name, "uri")) {
  6581. ah->uri = value;
  6582. } else if (!strcmp(name, "qop")) {
  6583. ah->qop = value;
  6584. } else if (!strcmp(name, "nc")) {
  6585. ah->nc = value;
  6586. } else if (!strcmp(name, "nonce")) {
  6587. ah->nonce = value;
  6588. }
  6589. }
  6590. #ifndef NO_NONCE_CHECK
  6591. /* Read the nonce from the response. */
  6592. if (ah->nonce == NULL) {
  6593. return 0;
  6594. }
  6595. s = NULL;
  6596. nonce = strtoull(ah->nonce, &s, 10);
  6597. if ((s == NULL) || (*s != 0)) {
  6598. return 0;
  6599. }
  6600. /* Convert the nonce from the client to a number. */
  6601. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6602. /* The converted number corresponds to the time the nounce has been
  6603. * created. This should not be earlier than the server start. */
  6604. /* Server side nonce check is valuable in all situations but one:
  6605. * if the server restarts frequently, but the client should not see
  6606. * that, so the server should accept nonces from previous starts. */
  6607. /* However, the reasonable default is to not accept a nonce from a
  6608. * previous start, so if anyone changed the access rights between
  6609. * two restarts, a new login is required. */
  6610. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6611. /* nonce is from a previous start of the server and no longer valid
  6612. * (replay attack?) */
  6613. return 0;
  6614. }
  6615. /* Check if the nonce is too high, so it has not (yet) been used by the
  6616. * server. */
  6617. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6618. + conn->dom_ctx->nonce_count)) {
  6619. return 0;
  6620. }
  6621. #else
  6622. (void)nonce;
  6623. #endif
  6624. /* CGI needs it as REMOTE_USER */
  6625. if (ah->user != NULL) {
  6626. conn->request_info.remote_user =
  6627. mg_strdup_ctx(ah->user, conn->phys_ctx);
  6628. } else {
  6629. return 0;
  6630. }
  6631. return 1;
  6632. }
  6633. static const char *
  6634. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6635. {
  6636. const char *eof;
  6637. size_t len;
  6638. const char *memend;
  6639. if (!filep) {
  6640. return NULL;
  6641. }
  6642. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6643. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6644. /* Search for \n from p till the end of stream */
  6645. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6646. if (eof != NULL) {
  6647. eof += 1; /* Include \n */
  6648. } else {
  6649. eof = memend; /* Copy remaining data */
  6650. }
  6651. len =
  6652. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6653. memcpy(buf, *p, len);
  6654. buf[len] = '\0';
  6655. *p += len;
  6656. return len ? eof : NULL;
  6657. } else if (filep->access.fp != NULL) {
  6658. return fgets(buf, (int)size, filep->access.fp);
  6659. } else {
  6660. return NULL;
  6661. }
  6662. }
  6663. /* Define the initial recursion depth for procesesing htpasswd files that
  6664. * include other htpasswd
  6665. * (or even the same) files. It is not difficult to provide a file or files
  6666. * s.t. they force civetweb
  6667. * to infinitely recurse and then crash.
  6668. */
  6669. #define INITIAL_DEPTH 9
  6670. #if INITIAL_DEPTH <= 0
  6671. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6672. #endif
  6673. struct read_auth_file_struct {
  6674. struct mg_connection *conn;
  6675. struct ah ah;
  6676. const char *domain;
  6677. char buf[256 + 256 + 40];
  6678. const char *f_user;
  6679. const char *f_domain;
  6680. const char *f_ha1;
  6681. };
  6682. static int
  6683. read_auth_file(struct mg_file *filep,
  6684. struct read_auth_file_struct *workdata,
  6685. int depth)
  6686. {
  6687. char *p;
  6688. int is_authorized = 0;
  6689. struct mg_file fp;
  6690. size_t l;
  6691. if (!filep || !workdata || (0 == depth)) {
  6692. return 0;
  6693. }
  6694. /* Loop over passwords file */
  6695. p = (char *)filep->access.membuf;
  6696. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6697. l = strlen(workdata->buf);
  6698. while (l > 0) {
  6699. if (isspace(workdata->buf[l - 1])
  6700. || iscntrl(workdata->buf[l - 1])) {
  6701. l--;
  6702. workdata->buf[l] = 0;
  6703. } else
  6704. break;
  6705. }
  6706. if (l < 1) {
  6707. continue;
  6708. }
  6709. workdata->f_user = workdata->buf;
  6710. if (workdata->f_user[0] == ':') {
  6711. /* user names may not contain a ':' and may not be empty,
  6712. * so lines starting with ':' may be used for a special purpose
  6713. */
  6714. if (workdata->f_user[1] == '#') {
  6715. /* :# is a comment */
  6716. continue;
  6717. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6718. if (mg_fopen(workdata->conn,
  6719. workdata->f_user + 9,
  6720. MG_FOPEN_MODE_READ,
  6721. &fp)) {
  6722. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6723. (void)mg_fclose(
  6724. &fp.access); /* ignore error on read only file */
  6725. /* No need to continue processing files once we have a
  6726. * match, since nothing will reset it back
  6727. * to 0.
  6728. */
  6729. if (is_authorized) {
  6730. return is_authorized;
  6731. }
  6732. } else {
  6733. mg_cry_internal(workdata->conn,
  6734. "%s: cannot open authorization file: %s",
  6735. __func__,
  6736. workdata->buf);
  6737. }
  6738. continue;
  6739. }
  6740. /* everything is invalid for the moment (might change in the
  6741. * future) */
  6742. mg_cry_internal(workdata->conn,
  6743. "%s: syntax error in authorization file: %s",
  6744. __func__,
  6745. workdata->buf);
  6746. continue;
  6747. }
  6748. workdata->f_domain = strchr(workdata->f_user, ':');
  6749. if (workdata->f_domain == NULL) {
  6750. mg_cry_internal(workdata->conn,
  6751. "%s: syntax error in authorization file: %s",
  6752. __func__,
  6753. workdata->buf);
  6754. continue;
  6755. }
  6756. *(char *)(workdata->f_domain) = 0;
  6757. (workdata->f_domain)++;
  6758. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6759. if (workdata->f_ha1 == NULL) {
  6760. mg_cry_internal(workdata->conn,
  6761. "%s: syntax error in authorization file: %s",
  6762. __func__,
  6763. workdata->buf);
  6764. continue;
  6765. }
  6766. *(char *)(workdata->f_ha1) = 0;
  6767. (workdata->f_ha1)++;
  6768. if (!strcmp(workdata->ah.user, workdata->f_user)
  6769. && !strcmp(workdata->domain, workdata->f_domain)) {
  6770. return check_password(workdata->conn->request_info.request_method,
  6771. workdata->f_ha1,
  6772. workdata->ah.uri,
  6773. workdata->ah.nonce,
  6774. workdata->ah.nc,
  6775. workdata->ah.cnonce,
  6776. workdata->ah.qop,
  6777. workdata->ah.response);
  6778. }
  6779. }
  6780. return is_authorized;
  6781. }
  6782. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6783. static int
  6784. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  6785. {
  6786. struct read_auth_file_struct workdata;
  6787. char buf[MG_BUF_LEN];
  6788. if (!conn || !conn->dom_ctx) {
  6789. return 0;
  6790. }
  6791. memset(&workdata, 0, sizeof(workdata));
  6792. workdata.conn = conn;
  6793. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6794. return 0;
  6795. }
  6796. if (realm) {
  6797. workdata.domain = realm;
  6798. } else {
  6799. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6800. }
  6801. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6802. }
  6803. /* Public function to check http digest authentication header */
  6804. int
  6805. mg_check_digest_access_authentication(struct mg_connection *conn,
  6806. const char *realm,
  6807. const char *filename)
  6808. {
  6809. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6810. int auth;
  6811. if (!conn || !filename) {
  6812. return -1;
  6813. }
  6814. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  6815. return -2;
  6816. }
  6817. auth = authorize(conn, &file, realm);
  6818. mg_fclose(&file.access);
  6819. return auth;
  6820. }
  6821. /* Return 1 if request is authorised, 0 otherwise. */
  6822. static int
  6823. check_authorization(struct mg_connection *conn, const char *path)
  6824. {
  6825. char fname[PATH_MAX];
  6826. struct vec uri_vec, filename_vec;
  6827. const char *list;
  6828. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6829. int authorized = 1, truncated;
  6830. if (!conn || !conn->dom_ctx) {
  6831. return 0;
  6832. }
  6833. list = conn->dom_ctx->config[PROTECT_URI];
  6834. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6835. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6836. mg_snprintf(conn,
  6837. &truncated,
  6838. fname,
  6839. sizeof(fname),
  6840. "%.*s",
  6841. (int)filename_vec.len,
  6842. filename_vec.ptr);
  6843. if (truncated
  6844. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6845. mg_cry_internal(conn,
  6846. "%s: cannot open %s: %s",
  6847. __func__,
  6848. fname,
  6849. strerror(errno));
  6850. }
  6851. break;
  6852. }
  6853. }
  6854. if (!is_file_opened(&file.access)) {
  6855. open_auth_file(conn, path, &file);
  6856. }
  6857. if (is_file_opened(&file.access)) {
  6858. authorized = authorize(conn, &file, NULL);
  6859. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6860. }
  6861. return authorized;
  6862. }
  6863. /* Internal function. Assumes conn is valid */
  6864. static void
  6865. send_authorization_request(struct mg_connection *conn, const char *realm)
  6866. {
  6867. char date[64];
  6868. time_t curtime = time(NULL);
  6869. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  6870. if (!realm) {
  6871. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6872. }
  6873. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  6874. nonce += conn->dom_ctx->nonce_count;
  6875. ++conn->dom_ctx->nonce_count;
  6876. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  6877. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6878. conn->status_code = 401;
  6879. conn->must_close = 1;
  6880. gmt_time_string(date, sizeof(date), &curtime);
  6881. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6882. send_no_cache_header(conn);
  6883. send_additional_header(conn);
  6884. mg_printf(conn,
  6885. "Date: %s\r\n"
  6886. "Connection: %s\r\n"
  6887. "Content-Length: 0\r\n"
  6888. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6889. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6890. date,
  6891. suggest_connection_header(conn),
  6892. realm,
  6893. nonce);
  6894. }
  6895. /* Interface function. Parameters are provided by the user, so do
  6896. * at least some basic checks.
  6897. */
  6898. int
  6899. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  6900. const char *realm)
  6901. {
  6902. if (conn && conn->dom_ctx) {
  6903. send_authorization_request(conn, realm);
  6904. return 0;
  6905. }
  6906. return -1;
  6907. }
  6908. #if !defined(NO_FILES)
  6909. static int
  6910. is_authorized_for_put(struct mg_connection *conn)
  6911. {
  6912. if (conn) {
  6913. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6914. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6915. int ret = 0;
  6916. if (passfile != NULL
  6917. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6918. ret = authorize(conn, &file, NULL);
  6919. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6920. }
  6921. return ret;
  6922. }
  6923. return 0;
  6924. }
  6925. #endif
  6926. int
  6927. mg_modify_passwords_file(const char *fname,
  6928. const char *domain,
  6929. const char *user,
  6930. const char *pass)
  6931. {
  6932. int found, i;
  6933. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6934. FILE *fp, *fp2;
  6935. found = 0;
  6936. fp = fp2 = NULL;
  6937. /* Regard empty password as no password - remove user record. */
  6938. if ((pass != NULL) && (pass[0] == '\0')) {
  6939. pass = NULL;
  6940. }
  6941. /* Other arguments must not be empty */
  6942. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6943. return 0;
  6944. }
  6945. /* Using the given file format, user name and domain must not contain
  6946. * ':'
  6947. */
  6948. if (strchr(user, ':') != NULL) {
  6949. return 0;
  6950. }
  6951. if (strchr(domain, ':') != NULL) {
  6952. return 0;
  6953. }
  6954. /* Do not allow control characters like newline in user name and domain.
  6955. * Do not allow excessively long names either. */
  6956. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6957. if (iscntrl(user[i])) {
  6958. return 0;
  6959. }
  6960. }
  6961. if (user[i]) {
  6962. return 0;
  6963. }
  6964. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6965. if (iscntrl(domain[i])) {
  6966. return 0;
  6967. }
  6968. }
  6969. if (domain[i]) {
  6970. return 0;
  6971. }
  6972. /* The maximum length of the path to the password file is limited */
  6973. if ((strlen(fname) + 4) >= PATH_MAX) {
  6974. return 0;
  6975. }
  6976. /* Create a temporary file name. Length has been checked before. */
  6977. strcpy(tmp, fname);
  6978. strcat(tmp, ".tmp");
  6979. /* Create the file if does not exist */
  6980. /* Use of fopen here is OK, since fname is only ASCII */
  6981. if ((fp = fopen(fname, "a+")) != NULL) {
  6982. (void)fclose(fp);
  6983. }
  6984. /* Open the given file and temporary file */
  6985. if ((fp = fopen(fname, "r")) == NULL) {
  6986. return 0;
  6987. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6988. fclose(fp);
  6989. return 0;
  6990. }
  6991. /* Copy the stuff to temporary file */
  6992. while (fgets(line, sizeof(line), fp) != NULL) {
  6993. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6994. continue;
  6995. }
  6996. u[255] = 0;
  6997. d[255] = 0;
  6998. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6999. found++;
  7000. if (pass != NULL) {
  7001. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7002. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7003. }
  7004. } else {
  7005. fprintf(fp2, "%s", line);
  7006. }
  7007. }
  7008. /* If new user, just add it */
  7009. if (!found && (pass != NULL)) {
  7010. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7011. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7012. }
  7013. /* Close files */
  7014. fclose(fp);
  7015. fclose(fp2);
  7016. /* Put the temp file in place of real file */
  7017. IGNORE_UNUSED_RESULT(remove(fname));
  7018. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7019. return 1;
  7020. }
  7021. static int
  7022. is_valid_port(unsigned long port)
  7023. {
  7024. return (port <= 0xffff);
  7025. }
  7026. static int
  7027. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7028. {
  7029. struct addrinfo hints, *res, *ressave;
  7030. int func_ret = 0;
  7031. int gai_ret;
  7032. memset(&hints, 0, sizeof(struct addrinfo));
  7033. hints.ai_family = af;
  7034. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7035. if (gai_ret != 0) {
  7036. /* gai_strerror could be used to convert gai_ret to a string */
  7037. /* POSIX return values: see
  7038. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7039. */
  7040. /* Windows return values: see
  7041. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7042. */
  7043. return 0;
  7044. }
  7045. ressave = res;
  7046. while (res) {
  7047. if (dstlen >= (size_t)res->ai_addrlen) {
  7048. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7049. func_ret = 1;
  7050. }
  7051. res = res->ai_next;
  7052. }
  7053. freeaddrinfo(ressave);
  7054. return func_ret;
  7055. }
  7056. static int
  7057. connect_socket(struct mg_context *ctx /* may be NULL */,
  7058. const char *host,
  7059. int port,
  7060. int use_ssl,
  7061. char *ebuf,
  7062. size_t ebuf_len,
  7063. SOCKET *sock /* output: socket, must not be NULL */,
  7064. union usa *sa /* output: socket address, must not be NULL */
  7065. )
  7066. {
  7067. int ip_ver = 0;
  7068. int conn_ret = -1;
  7069. *sock = INVALID_SOCKET;
  7070. memset(sa, 0, sizeof(*sa));
  7071. if (ebuf_len > 0) {
  7072. *ebuf = 0;
  7073. }
  7074. if (host == NULL) {
  7075. mg_snprintf(NULL,
  7076. NULL, /* No truncation check for ebuf */
  7077. ebuf,
  7078. ebuf_len,
  7079. "%s",
  7080. "NULL host");
  7081. return 0;
  7082. }
  7083. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7084. mg_snprintf(NULL,
  7085. NULL, /* No truncation check for ebuf */
  7086. ebuf,
  7087. ebuf_len,
  7088. "%s",
  7089. "invalid port");
  7090. return 0;
  7091. }
  7092. #if !defined(NO_SSL)
  7093. #if !defined(NO_SSL_DL)
  7094. #ifdef OPENSSL_API_1_1
  7095. if (use_ssl && (TLS_client_method == NULL)) {
  7096. mg_snprintf(NULL,
  7097. NULL, /* No truncation check for ebuf */
  7098. ebuf,
  7099. ebuf_len,
  7100. "%s",
  7101. "SSL is not initialized");
  7102. return 0;
  7103. }
  7104. #else
  7105. if (use_ssl && (SSLv23_client_method == NULL)) {
  7106. mg_snprintf(NULL,
  7107. NULL, /* No truncation check for ebuf */
  7108. ebuf,
  7109. ebuf_len,
  7110. "%s",
  7111. "SSL is not initialized");
  7112. return 0;
  7113. }
  7114. #endif /* OPENSSL_API_1_1 */
  7115. #else
  7116. (void)use_ssl;
  7117. #endif /* NO_SSL_DL */
  7118. #else
  7119. (void)use_ssl;
  7120. #endif /* !defined(NO_SSL) */
  7121. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7122. sa->sin.sin_family = AF_INET;
  7123. sa->sin.sin_port = htons((uint16_t)port);
  7124. ip_ver = 4;
  7125. #ifdef USE_IPV6
  7126. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7127. sa->sin6.sin6_family = AF_INET6;
  7128. sa->sin6.sin6_port = htons((uint16_t)port);
  7129. ip_ver = 6;
  7130. } else if (host[0] == '[') {
  7131. /* While getaddrinfo on Windows will work with [::1],
  7132. * getaddrinfo on Linux only works with ::1 (without []). */
  7133. size_t l = strlen(host + 1);
  7134. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7135. if (h) {
  7136. h[l - 1] = 0;
  7137. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7138. sa->sin6.sin6_family = AF_INET6;
  7139. sa->sin6.sin6_port = htons((uint16_t)port);
  7140. ip_ver = 6;
  7141. }
  7142. mg_free(h);
  7143. }
  7144. #endif
  7145. }
  7146. if (ip_ver == 0) {
  7147. mg_snprintf(NULL,
  7148. NULL, /* No truncation check for ebuf */
  7149. ebuf,
  7150. ebuf_len,
  7151. "%s",
  7152. "host not found");
  7153. return 0;
  7154. }
  7155. if (ip_ver == 4) {
  7156. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7157. }
  7158. #ifdef USE_IPV6
  7159. else if (ip_ver == 6) {
  7160. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7161. }
  7162. #endif
  7163. if (*sock == INVALID_SOCKET) {
  7164. mg_snprintf(NULL,
  7165. NULL, /* No truncation check for ebuf */
  7166. ebuf,
  7167. ebuf_len,
  7168. "socket(): %s",
  7169. strerror(ERRNO));
  7170. return 0;
  7171. }
  7172. if (0 != set_non_blocking_mode(*sock)) {
  7173. mg_snprintf(NULL,
  7174. NULL, /* No truncation check for ebuf */
  7175. ebuf,
  7176. ebuf_len,
  7177. "Cannot set socket to non-blocking: %s",
  7178. strerror(ERRNO));
  7179. closesocket(*sock);
  7180. *sock = INVALID_SOCKET;
  7181. return 0;
  7182. }
  7183. set_close_on_exec(*sock, fc(ctx));
  7184. if (ip_ver == 4) {
  7185. /* connected with IPv4 */
  7186. conn_ret = connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin));
  7187. }
  7188. #ifdef USE_IPV6
  7189. else if (ip_ver == 6) {
  7190. /* connected with IPv6 */
  7191. conn_ret =
  7192. connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6));
  7193. }
  7194. #endif
  7195. if (conn_ret != 0) {
  7196. fd_set fdset;
  7197. struct timeval timeout;
  7198. int sockerr = -1;
  7199. #if defined(_WIN32)
  7200. int len = (int)sizeof(sockerr);
  7201. #else
  7202. socklen_t len = (socklen_t)sizeof(sockerr);
  7203. #endif
  7204. FD_ZERO(&fdset);
  7205. FD_SET(*sock, &fdset);
  7206. timeout.tv_sec = 10; /* 10 second timeout */
  7207. timeout.tv_usec = 0;
  7208. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7209. /* Not connected */
  7210. mg_snprintf(NULL,
  7211. NULL, /* No truncation check for ebuf */
  7212. ebuf,
  7213. ebuf_len,
  7214. "connect(%s:%d): timeout",
  7215. host,
  7216. port);
  7217. closesocket(*sock);
  7218. *sock = INVALID_SOCKET;
  7219. return 0;
  7220. }
  7221. #if defined(_WIN32)
  7222. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)&sockerr, &len);
  7223. #else
  7224. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &len);
  7225. #endif
  7226. if (sockerr != 0) {
  7227. /* Not connected */
  7228. mg_snprintf(NULL,
  7229. NULL, /* No truncation check for ebuf */
  7230. ebuf,
  7231. ebuf_len,
  7232. "connect(%s:%d): error %s",
  7233. host,
  7234. port,
  7235. strerror(sockerr));
  7236. closesocket(*sock);
  7237. *sock = INVALID_SOCKET;
  7238. return 0;
  7239. }
  7240. }
  7241. return 1;
  7242. }
  7243. int
  7244. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7245. {
  7246. static const char *dont_escape = "._-$,;~()";
  7247. static const char *hex = "0123456789abcdef";
  7248. char *pos = dst;
  7249. const char *end = dst + dst_len - 1;
  7250. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7251. if (isalnum(*(const unsigned char *)src)
  7252. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7253. *pos = *src;
  7254. } else if (pos + 2 < end) {
  7255. pos[0] = '%';
  7256. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7257. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7258. pos += 2;
  7259. } else {
  7260. break;
  7261. }
  7262. }
  7263. *pos = '\0';
  7264. return (*src == '\0') ? (int)(pos - dst) : -1;
  7265. }
  7266. /* Return 0 on success, non-zero if an error occurs. */
  7267. static int
  7268. print_dir_entry(struct de *de)
  7269. {
  7270. size_t hrefsize;
  7271. char *href;
  7272. char size[64], mod[64];
  7273. #ifdef REENTRANT_TIME
  7274. struct tm _tm;
  7275. struct tm *tm = &_tm;
  7276. #else
  7277. struct tm *tm;
  7278. #endif
  7279. hrefsize = PATH_MAX * 3; /* worst case */
  7280. href = (char *)mg_malloc(hrefsize);
  7281. if (href == NULL) {
  7282. return -1;
  7283. }
  7284. if (de->file.is_directory) {
  7285. mg_snprintf(de->conn,
  7286. NULL, /* Buffer is big enough */
  7287. size,
  7288. sizeof(size),
  7289. "%s",
  7290. "[DIRECTORY]");
  7291. } else {
  7292. /* We use (signed) cast below because MSVC 6 compiler cannot
  7293. * convert unsigned __int64 to double. Sigh. */
  7294. if (de->file.size < 1024) {
  7295. mg_snprintf(de->conn,
  7296. NULL, /* Buffer is big enough */
  7297. size,
  7298. sizeof(size),
  7299. "%d",
  7300. (int)de->file.size);
  7301. } else if (de->file.size < 0x100000) {
  7302. mg_snprintf(de->conn,
  7303. NULL, /* Buffer is big enough */
  7304. size,
  7305. sizeof(size),
  7306. "%.1fk",
  7307. (double)de->file.size / 1024.0);
  7308. } else if (de->file.size < 0x40000000) {
  7309. mg_snprintf(de->conn,
  7310. NULL, /* Buffer is big enough */
  7311. size,
  7312. sizeof(size),
  7313. "%.1fM",
  7314. (double)de->file.size / 1048576);
  7315. } else {
  7316. mg_snprintf(de->conn,
  7317. NULL, /* Buffer is big enough */
  7318. size,
  7319. sizeof(size),
  7320. "%.1fG",
  7321. (double)de->file.size / 1073741824);
  7322. }
  7323. }
  7324. /* Note: mg_snprintf will not cause a buffer overflow above.
  7325. * So, string truncation checks are not required here. */
  7326. #ifdef REENTRANT_TIME
  7327. localtime_r(&de->file.last_modified, tm);
  7328. #else
  7329. tm = localtime(&de->file.last_modified);
  7330. #endif
  7331. if (tm != NULL) {
  7332. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7333. } else {
  7334. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7335. mod[sizeof(mod) - 1] = '\0';
  7336. }
  7337. mg_url_encode(de->file_name, href, hrefsize);
  7338. mg_printf(de->conn,
  7339. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7340. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7341. de->conn->request_info.local_uri,
  7342. href,
  7343. de->file.is_directory ? "/" : "",
  7344. de->file_name,
  7345. de->file.is_directory ? "/" : "",
  7346. mod,
  7347. size);
  7348. mg_free(href);
  7349. return 0;
  7350. }
  7351. /* This function is called from send_directory() and used for
  7352. * sorting directory entries by size, or name, or modification time.
  7353. * On windows, __cdecl specification is needed in case if project is built
  7354. * with __stdcall convention. qsort always requires __cdels callback. */
  7355. static int WINCDECL
  7356. compare_dir_entries(const void *p1, const void *p2)
  7357. {
  7358. if (p1 && p2) {
  7359. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7360. const char *query_string = a->conn->request_info.query_string;
  7361. int cmp_result = 0;
  7362. if (query_string == NULL) {
  7363. query_string = "na";
  7364. }
  7365. if (a->file.is_directory && !b->file.is_directory) {
  7366. return -1; /* Always put directories on top */
  7367. } else if (!a->file.is_directory && b->file.is_directory) {
  7368. return 1; /* Always put directories on top */
  7369. } else if (*query_string == 'n') {
  7370. cmp_result = strcmp(a->file_name, b->file_name);
  7371. } else if (*query_string == 's') {
  7372. cmp_result = (a->file.size == b->file.size)
  7373. ? 0
  7374. : ((a->file.size > b->file.size) ? 1 : -1);
  7375. } else if (*query_string == 'd') {
  7376. cmp_result =
  7377. (a->file.last_modified == b->file.last_modified)
  7378. ? 0
  7379. : ((a->file.last_modified > b->file.last_modified) ? 1
  7380. : -1);
  7381. }
  7382. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7383. }
  7384. return 0;
  7385. }
  7386. static int
  7387. must_hide_file(struct mg_connection *conn, const char *path)
  7388. {
  7389. if (conn && conn->dom_ctx) {
  7390. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7391. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7392. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7393. || ((pattern != NULL)
  7394. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7395. }
  7396. return 0;
  7397. }
  7398. static int
  7399. scan_directory(struct mg_connection *conn,
  7400. const char *dir,
  7401. void *data,
  7402. int (*cb)(struct de *, void *))
  7403. {
  7404. char path[PATH_MAX];
  7405. struct dirent *dp;
  7406. DIR *dirp;
  7407. struct de de;
  7408. int truncated;
  7409. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7410. return 0;
  7411. } else {
  7412. de.conn = conn;
  7413. while ((dp = mg_readdir(dirp)) != NULL) {
  7414. /* Do not show current dir and hidden files */
  7415. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7416. || must_hide_file(conn, dp->d_name)) {
  7417. continue;
  7418. }
  7419. mg_snprintf(
  7420. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7421. /* If we don't memset stat structure to zero, mtime will have
  7422. * garbage and strftime() will segfault later on in
  7423. * print_dir_entry(). memset is required only if mg_stat()
  7424. * fails. For more details, see
  7425. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7426. memset(&de.file, 0, sizeof(de.file));
  7427. if (truncated) {
  7428. /* If the path is not complete, skip processing. */
  7429. continue;
  7430. }
  7431. if (!mg_stat(conn, path, &de.file)) {
  7432. mg_cry_internal(conn,
  7433. "%s: mg_stat(%s) failed: %s",
  7434. __func__,
  7435. path,
  7436. strerror(ERRNO));
  7437. }
  7438. de.file_name = dp->d_name;
  7439. cb(&de, data);
  7440. }
  7441. (void)mg_closedir(dirp);
  7442. }
  7443. return 1;
  7444. }
  7445. #if !defined(NO_FILES)
  7446. static int
  7447. remove_directory(struct mg_connection *conn, const char *dir)
  7448. {
  7449. char path[PATH_MAX];
  7450. struct dirent *dp;
  7451. DIR *dirp;
  7452. struct de de;
  7453. int truncated;
  7454. int ok = 1;
  7455. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7456. return 0;
  7457. } else {
  7458. de.conn = conn;
  7459. while ((dp = mg_readdir(dirp)) != NULL) {
  7460. /* Do not show current dir (but show hidden files as they will
  7461. * also be removed) */
  7462. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7463. continue;
  7464. }
  7465. mg_snprintf(
  7466. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7467. /* If we don't memset stat structure to zero, mtime will have
  7468. * garbage and strftime() will segfault later on in
  7469. * print_dir_entry(). memset is required only if mg_stat()
  7470. * fails. For more details, see
  7471. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7472. memset(&de.file, 0, sizeof(de.file));
  7473. if (truncated) {
  7474. /* Do not delete anything shorter */
  7475. ok = 0;
  7476. continue;
  7477. }
  7478. if (!mg_stat(conn, path, &de.file)) {
  7479. mg_cry_internal(conn,
  7480. "%s: mg_stat(%s) failed: %s",
  7481. __func__,
  7482. path,
  7483. strerror(ERRNO));
  7484. ok = 0;
  7485. }
  7486. if (de.file.is_directory) {
  7487. if (remove_directory(conn, path) == 0) {
  7488. ok = 0;
  7489. }
  7490. } else {
  7491. /* This will fail file is the file is in memory */
  7492. if (mg_remove(conn, path) == 0) {
  7493. ok = 0;
  7494. }
  7495. }
  7496. }
  7497. (void)mg_closedir(dirp);
  7498. IGNORE_UNUSED_RESULT(rmdir(dir));
  7499. }
  7500. return ok;
  7501. }
  7502. #endif
  7503. struct dir_scan_data {
  7504. struct de *entries;
  7505. unsigned int num_entries;
  7506. unsigned int arr_size;
  7507. };
  7508. /* Behaves like realloc(), but frees original pointer on failure */
  7509. static void *
  7510. realloc2(void *ptr, size_t size)
  7511. {
  7512. void *new_ptr = mg_realloc(ptr, size);
  7513. if (new_ptr == NULL) {
  7514. mg_free(ptr);
  7515. }
  7516. return new_ptr;
  7517. }
  7518. static int
  7519. dir_scan_callback(struct de *de, void *data)
  7520. {
  7521. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7522. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7523. dsd->arr_size *= 2;
  7524. dsd->entries =
  7525. (struct de *)realloc2(dsd->entries,
  7526. dsd->arr_size * sizeof(dsd->entries[0]));
  7527. }
  7528. if (dsd->entries == NULL) {
  7529. /* TODO(lsm, low): propagate an error to the caller */
  7530. dsd->num_entries = 0;
  7531. } else {
  7532. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7533. dsd->entries[dsd->num_entries].file = de->file;
  7534. dsd->entries[dsd->num_entries].conn = de->conn;
  7535. dsd->num_entries++;
  7536. }
  7537. return 0;
  7538. }
  7539. static void
  7540. handle_directory_request(struct mg_connection *conn, const char *dir)
  7541. {
  7542. unsigned int i;
  7543. int sort_direction;
  7544. struct dir_scan_data data = {NULL, 0, 128};
  7545. char date[64];
  7546. time_t curtime = time(NULL);
  7547. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7548. mg_send_http_error(conn,
  7549. 500,
  7550. "Error: Cannot open directory\nopendir(%s): %s",
  7551. dir,
  7552. strerror(ERRNO));
  7553. return;
  7554. }
  7555. gmt_time_string(date, sizeof(date), &curtime);
  7556. if (!conn) {
  7557. return;
  7558. }
  7559. sort_direction = ((conn->request_info.query_string != NULL)
  7560. && (conn->request_info.query_string[1] == 'd'))
  7561. ? 'a'
  7562. : 'd';
  7563. conn->must_close = 1;
  7564. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7565. send_static_cache_header(conn);
  7566. send_additional_header(conn);
  7567. mg_printf(conn,
  7568. "Date: %s\r\n"
  7569. "Connection: close\r\n"
  7570. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7571. date);
  7572. mg_printf(conn,
  7573. "<html><head><title>Index of %s</title>"
  7574. "<style>th {text-align: left;}</style></head>"
  7575. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7576. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7577. "<th><a href=\"?d%c\">Modified</a></th>"
  7578. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7579. "<tr><td colspan=\"3\"><hr></td></tr>",
  7580. conn->request_info.local_uri,
  7581. conn->request_info.local_uri,
  7582. sort_direction,
  7583. sort_direction,
  7584. sort_direction);
  7585. /* Print first entry - link to a parent directory */
  7586. mg_printf(conn,
  7587. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7588. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7589. conn->request_info.local_uri,
  7590. "..",
  7591. "Parent directory",
  7592. "-",
  7593. "-");
  7594. /* Sort and print directory entries */
  7595. if (data.entries != NULL) {
  7596. qsort(data.entries,
  7597. (size_t)data.num_entries,
  7598. sizeof(data.entries[0]),
  7599. compare_dir_entries);
  7600. for (i = 0; i < data.num_entries; i++) {
  7601. print_dir_entry(&data.entries[i]);
  7602. mg_free(data.entries[i].file_name);
  7603. }
  7604. mg_free(data.entries);
  7605. }
  7606. mg_printf(conn, "%s", "</table></body></html>");
  7607. conn->status_code = 200;
  7608. }
  7609. /* Send len bytes from the opened file to the client. */
  7610. static void
  7611. send_file_data(struct mg_connection *conn,
  7612. struct mg_file *filep,
  7613. int64_t offset,
  7614. int64_t len)
  7615. {
  7616. char buf[MG_BUF_LEN];
  7617. int to_read, num_read, num_written;
  7618. int64_t size;
  7619. if (!filep || !conn) {
  7620. return;
  7621. }
  7622. /* Sanity check the offset */
  7623. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7624. : (int64_t)(filep->stat.size);
  7625. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7626. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7627. /* file stored in memory */
  7628. if (len > size - offset) {
  7629. len = size - offset;
  7630. }
  7631. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7632. } else if (len > 0 && filep->access.fp != NULL) {
  7633. /* file stored on disk */
  7634. #if defined(__linux__)
  7635. /* sendfile is only available for Linux */
  7636. if ((conn->ssl == 0) && (conn->throttle == 0)
  7637. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  7638. "yes"))) {
  7639. off_t sf_offs = (off_t)offset;
  7640. ssize_t sf_sent;
  7641. int sf_file = fileno(filep->access.fp);
  7642. int loop_cnt = 0;
  7643. do {
  7644. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7645. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7646. size_t sf_tosend =
  7647. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7648. sf_sent =
  7649. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7650. if (sf_sent > 0) {
  7651. len -= sf_sent;
  7652. offset += sf_sent;
  7653. } else if (loop_cnt == 0) {
  7654. /* This file can not be sent using sendfile.
  7655. * This might be the case for pseudo-files in the
  7656. * /sys/ and /proc/ file system.
  7657. * Use the regular user mode copy code instead. */
  7658. break;
  7659. } else if (sf_sent == 0) {
  7660. /* No error, but 0 bytes sent. May be EOF? */
  7661. return;
  7662. }
  7663. loop_cnt++;
  7664. } while ((len > 0) && (sf_sent >= 0));
  7665. if (sf_sent > 0) {
  7666. return; /* OK */
  7667. }
  7668. /* sf_sent<0 means error, thus fall back to the classic way */
  7669. /* This is always the case, if sf_file is not a "normal" file,
  7670. * e.g., for sending data from the output of a CGI process. */
  7671. offset = (int64_t)sf_offs;
  7672. }
  7673. #endif
  7674. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7675. mg_cry_internal(conn,
  7676. "%s: fseeko() failed: %s",
  7677. __func__,
  7678. strerror(ERRNO));
  7679. mg_send_http_error(
  7680. conn,
  7681. 500,
  7682. "%s",
  7683. "Error: Unable to access file at requested position.");
  7684. } else {
  7685. while (len > 0) {
  7686. /* Calculate how much to read from the file in the buffer */
  7687. to_read = sizeof(buf);
  7688. if ((int64_t)to_read > len) {
  7689. to_read = (int)len;
  7690. }
  7691. /* Read from file, exit the loop on error */
  7692. if ((num_read =
  7693. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7694. <= 0) {
  7695. break;
  7696. }
  7697. /* Send read bytes to the client, exit the loop on error */
  7698. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7699. != num_read) {
  7700. break;
  7701. }
  7702. /* Both read and were successful, adjust counters */
  7703. len -= num_written;
  7704. }
  7705. }
  7706. }
  7707. }
  7708. static int
  7709. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7710. {
  7711. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7712. }
  7713. static void
  7714. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7715. {
  7716. if ((filestat != NULL) && (buf != NULL)) {
  7717. mg_snprintf(NULL,
  7718. NULL, /* All calls to construct_etag use 64 byte buffer */
  7719. buf,
  7720. buf_len,
  7721. "\"%lx.%" INT64_FMT "\"",
  7722. (unsigned long)filestat->last_modified,
  7723. filestat->size);
  7724. }
  7725. }
  7726. static void
  7727. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7728. {
  7729. if (filep != NULL && filep->fp != NULL) {
  7730. #ifdef _WIN32
  7731. (void)conn; /* Unused. */
  7732. #else
  7733. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7734. mg_cry_internal(conn,
  7735. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7736. __func__,
  7737. strerror(ERRNO));
  7738. }
  7739. #endif
  7740. }
  7741. }
  7742. static void
  7743. handle_static_file_request(struct mg_connection *conn,
  7744. const char *path,
  7745. struct mg_file *filep,
  7746. const char *mime_type,
  7747. const char *additional_headers)
  7748. {
  7749. char date[64], lm[64], etag[64];
  7750. char range[128]; /* large enough, so there will be no overflow */
  7751. const char *msg = "OK", *hdr;
  7752. time_t curtime = time(NULL);
  7753. int64_t cl, r1, r2;
  7754. struct vec mime_vec;
  7755. int n, truncated;
  7756. char gz_path[PATH_MAX];
  7757. const char *encoding = "";
  7758. const char *cors1, *cors2, *cors3;
  7759. int allow_on_the_fly_compression;
  7760. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  7761. return;
  7762. }
  7763. if (mime_type == NULL) {
  7764. get_mime_type(conn, path, &mime_vec);
  7765. } else {
  7766. mime_vec.ptr = mime_type;
  7767. mime_vec.len = strlen(mime_type);
  7768. }
  7769. if (filep->stat.size > INT64_MAX) {
  7770. mg_send_http_error(conn,
  7771. 500,
  7772. "Error: File size is too large to send\n%" INT64_FMT,
  7773. filep->stat.size);
  7774. return;
  7775. }
  7776. cl = (int64_t)filep->stat.size;
  7777. conn->status_code = 200;
  7778. range[0] = '\0';
  7779. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7780. * it's important to rewrite the filename after resolving
  7781. * the mime type from it, to preserve the actual file's type */
  7782. allow_on_the_fly_compression = conn->accept_gzip;
  7783. if (filep->stat.is_gzipped) {
  7784. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7785. if (truncated) {
  7786. mg_send_http_error(conn,
  7787. 500,
  7788. "Error: Path of zipped file too long (%s)",
  7789. path);
  7790. return;
  7791. }
  7792. path = gz_path;
  7793. encoding = "Content-Encoding: gzip\r\n";
  7794. /* File is already compressed. No "on the fly" compression. */
  7795. allow_on_the_fly_compression = 0;
  7796. }
  7797. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7798. mg_send_http_error(conn,
  7799. 500,
  7800. "Error: Cannot open file\nfopen(%s): %s",
  7801. path,
  7802. strerror(ERRNO));
  7803. return;
  7804. }
  7805. fclose_on_exec(&filep->access, conn);
  7806. /* If Range: header specified, act accordingly */
  7807. r1 = r2 = 0;
  7808. hdr = mg_get_header(conn, "Range");
  7809. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7810. && (r1 >= 0) && (r2 >= 0)) {
  7811. /* actually, range requests don't play well with a pre-gzipped
  7812. * file (since the range is specified in the uncompressed space) */
  7813. if (filep->stat.is_gzipped) {
  7814. mg_send_http_error(
  7815. conn,
  7816. 416, /* 416 = Range Not Satisfiable */
  7817. "%s",
  7818. "Error: Range requests in gzipped files are not supported");
  7819. (void)mg_fclose(
  7820. &filep->access); /* ignore error on read only file */
  7821. return;
  7822. }
  7823. conn->status_code = 206;
  7824. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7825. mg_snprintf(conn,
  7826. NULL, /* range buffer is big enough */
  7827. range,
  7828. sizeof(range),
  7829. "Content-Range: bytes "
  7830. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7831. r1,
  7832. r1 + cl - 1,
  7833. filep->stat.size);
  7834. msg = "Partial Content";
  7835. /* Do not compress ranges. */
  7836. allow_on_the_fly_compression = 0;
  7837. }
  7838. hdr = mg_get_header(conn, "Origin");
  7839. if (hdr) {
  7840. /* Cross-origin resource sharing (CORS), see
  7841. * http://www.html5rocks.com/en/tutorials/cors/,
  7842. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7843. * -
  7844. * preflight is not supported for files. */
  7845. cors1 = "Access-Control-Allow-Origin: ";
  7846. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7847. cors3 = "\r\n";
  7848. } else {
  7849. cors1 = cors2 = cors3 = "";
  7850. }
  7851. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  7852. * according to
  7853. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7854. gmt_time_string(date, sizeof(date), &curtime);
  7855. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7856. construct_etag(etag, sizeof(etag), &filep->stat);
  7857. /* On the fly compression allowed */
  7858. if (allow_on_the_fly_compression) {
  7859. ;
  7860. /* TODO: add interface to compression module */
  7861. /* e.g., def from https://zlib.net/zlib_how.html */
  7862. /* Check license (zlib has a permissive license, but */
  7863. /* is still not MIT) and use dynamic binding like */
  7864. /* done with OpenSSL */
  7865. /* See #199 (https://github.com/civetweb/civetweb/issues/199) */
  7866. }
  7867. /* Send header */
  7868. (void)mg_printf(conn,
  7869. "HTTP/1.1 %d %s\r\n"
  7870. "%s%s%s"
  7871. "Date: %s\r\n",
  7872. conn->status_code,
  7873. msg,
  7874. cors1,
  7875. cors2,
  7876. cors3,
  7877. date);
  7878. send_static_cache_header(conn);
  7879. send_additional_header(conn);
  7880. (void)mg_printf(conn,
  7881. "Last-Modified: %s\r\n"
  7882. "Etag: %s\r\n"
  7883. "Content-Type: %.*s\r\n"
  7884. "Content-Length: %" INT64_FMT "\r\n"
  7885. "Connection: %s\r\n"
  7886. "Accept-Ranges: bytes\r\n"
  7887. "%s%s",
  7888. lm,
  7889. etag,
  7890. (int)mime_vec.len,
  7891. mime_vec.ptr,
  7892. cl,
  7893. suggest_connection_header(conn),
  7894. range,
  7895. encoding);
  7896. /* The previous code must not add any header starting with X- to make
  7897. * sure no one of the additional_headers is included twice */
  7898. if (additional_headers != NULL) {
  7899. (void)mg_printf(conn,
  7900. "%.*s\r\n\r\n",
  7901. (int)strlen(additional_headers),
  7902. additional_headers);
  7903. } else {
  7904. (void)mg_printf(conn, "\r\n");
  7905. }
  7906. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7907. send_file_data(conn, filep, r1, cl);
  7908. }
  7909. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7910. }
  7911. #if !defined(NO_CACHING)
  7912. /* Return True if we should reply 304 Not Modified. */
  7913. static int
  7914. is_not_modified(const struct mg_connection *conn,
  7915. const struct mg_file_stat *filestat)
  7916. {
  7917. char etag[64];
  7918. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7919. const char *inm = mg_get_header(conn, "If-None-Match");
  7920. construct_etag(etag, sizeof(etag), filestat);
  7921. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  7922. || ((ims != NULL)
  7923. && (filestat->last_modified <= parse_date_string(ims)));
  7924. }
  7925. static void
  7926. handle_not_modified_static_file_request(struct mg_connection *conn,
  7927. struct mg_file *filep)
  7928. {
  7929. char date[64], lm[64], etag[64];
  7930. time_t curtime = time(NULL);
  7931. if ((conn == NULL) || (filep == NULL)) {
  7932. return;
  7933. }
  7934. conn->status_code = 304;
  7935. gmt_time_string(date, sizeof(date), &curtime);
  7936. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7937. construct_etag(etag, sizeof(etag), &filep->stat);
  7938. (void)mg_printf(conn,
  7939. "HTTP/1.1 %d %s\r\n"
  7940. "Date: %s\r\n",
  7941. conn->status_code,
  7942. mg_get_response_code_text(conn, conn->status_code),
  7943. date);
  7944. send_static_cache_header(conn);
  7945. send_additional_header(conn);
  7946. (void)mg_printf(conn,
  7947. "Last-Modified: %s\r\n"
  7948. "Etag: %s\r\n"
  7949. "Connection: %s\r\n"
  7950. "\r\n",
  7951. lm,
  7952. etag,
  7953. suggest_connection_header(conn));
  7954. }
  7955. #endif
  7956. void
  7957. mg_send_file(struct mg_connection *conn, const char *path)
  7958. {
  7959. mg_send_mime_file(conn, path, NULL);
  7960. }
  7961. void
  7962. mg_send_mime_file(struct mg_connection *conn,
  7963. const char *path,
  7964. const char *mime_type)
  7965. {
  7966. mg_send_mime_file2(conn, path, mime_type, NULL);
  7967. }
  7968. void
  7969. mg_send_mime_file2(struct mg_connection *conn,
  7970. const char *path,
  7971. const char *mime_type,
  7972. const char *additional_headers)
  7973. {
  7974. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7975. if (!conn) {
  7976. /* No conn */
  7977. return;
  7978. }
  7979. if (mg_stat(conn, path, &file.stat)) {
  7980. #if !defined(NO_CACHING)
  7981. if (is_not_modified(conn, &file.stat)) {
  7982. /* Send 304 "Not Modified" - this must not send any body data */
  7983. handle_not_modified_static_file_request(conn, &file);
  7984. } else
  7985. #endif /* NO_CACHING */
  7986. if (file.stat.is_directory) {
  7987. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  7988. "yes")) {
  7989. handle_directory_request(conn, path);
  7990. } else {
  7991. mg_send_http_error(conn,
  7992. 403,
  7993. "%s",
  7994. "Error: Directory listing denied");
  7995. }
  7996. } else {
  7997. handle_static_file_request(
  7998. conn, path, &file, mime_type, additional_headers);
  7999. }
  8000. } else {
  8001. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8002. }
  8003. }
  8004. /* For a given PUT path, create all intermediate subdirectories.
  8005. * Return 0 if the path itself is a directory.
  8006. * Return 1 if the path leads to a file.
  8007. * Return -1 for if the path is too long.
  8008. * Return -2 if path can not be created.
  8009. */
  8010. static int
  8011. put_dir(struct mg_connection *conn, const char *path)
  8012. {
  8013. char buf[PATH_MAX];
  8014. const char *s, *p;
  8015. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8016. size_t len;
  8017. int res = 1;
  8018. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8019. len = (size_t)(p - path);
  8020. if (len >= sizeof(buf)) {
  8021. /* path too long */
  8022. res = -1;
  8023. break;
  8024. }
  8025. memcpy(buf, path, len);
  8026. buf[len] = '\0';
  8027. /* Try to create intermediate directory */
  8028. DEBUG_TRACE("mkdir(%s)", buf);
  8029. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8030. /* path does not exixt and can not be created */
  8031. res = -2;
  8032. break;
  8033. }
  8034. /* Is path itself a directory? */
  8035. if (p[1] == '\0') {
  8036. res = 0;
  8037. }
  8038. }
  8039. return res;
  8040. }
  8041. static void
  8042. remove_bad_file(const struct mg_connection *conn, const char *path)
  8043. {
  8044. int r = mg_remove(conn, path);
  8045. if (r != 0) {
  8046. mg_cry_internal(conn,
  8047. "%s: Cannot remove invalid file %s",
  8048. __func__,
  8049. path);
  8050. }
  8051. }
  8052. long long
  8053. mg_store_body(struct mg_connection *conn, const char *path)
  8054. {
  8055. char buf[MG_BUF_LEN];
  8056. long long len = 0;
  8057. int ret, n;
  8058. struct mg_file fi;
  8059. if (conn->consumed_content != 0) {
  8060. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8061. return -11;
  8062. }
  8063. ret = put_dir(conn, path);
  8064. if (ret < 0) {
  8065. /* -1 for path too long,
  8066. * -2 for path can not be created. */
  8067. return ret;
  8068. }
  8069. if (ret != 1) {
  8070. /* Return 0 means, path itself is a directory. */
  8071. return 0;
  8072. }
  8073. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8074. return -12;
  8075. }
  8076. ret = mg_read(conn, buf, sizeof(buf));
  8077. while (ret > 0) {
  8078. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8079. if (n != ret) {
  8080. (void)mg_fclose(
  8081. &fi.access); /* File is bad and will be removed anyway. */
  8082. remove_bad_file(conn, path);
  8083. return -13;
  8084. }
  8085. len += ret;
  8086. ret = mg_read(conn, buf, sizeof(buf));
  8087. }
  8088. /* File is open for writing. If fclose fails, there was probably an
  8089. * error flushing the buffer to disk, so the file on disk might be
  8090. * broken. Delete it and return an error to the caller. */
  8091. if (mg_fclose(&fi.access) != 0) {
  8092. remove_bad_file(conn, path);
  8093. return -14;
  8094. }
  8095. return len;
  8096. }
  8097. /* Parse a buffer:
  8098. * Forward the string pointer till the end of a word, then
  8099. * terminate it and forward till the begin of the next word.
  8100. */
  8101. static int
  8102. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8103. {
  8104. /* Forward until a space is found - use isgraph here */
  8105. /* See http://www.cplusplus.com/reference/cctype/ */
  8106. while (isgraph(**ppw)) {
  8107. (*ppw)++;
  8108. }
  8109. /* Check end of word */
  8110. if (eol) {
  8111. /* must be a end of line */
  8112. if ((**ppw != '\r') && (**ppw != '\n')) {
  8113. return -1;
  8114. }
  8115. } else {
  8116. /* must be a end of a word, but not a line */
  8117. if (**ppw != ' ') {
  8118. return -1;
  8119. }
  8120. }
  8121. /* Terminate and forward to the next word */
  8122. do {
  8123. **ppw = 0;
  8124. (*ppw)++;
  8125. } while ((**ppw) && isspace(**ppw));
  8126. /* Check after term */
  8127. if (!eol) {
  8128. /* if it's not the end of line, there must be a next word */
  8129. if (!isgraph(**ppw)) {
  8130. return -1;
  8131. }
  8132. }
  8133. /* ok */
  8134. return 1;
  8135. }
  8136. /* Parse HTTP headers from the given buffer, advance buf pointer
  8137. * to the point where parsing stopped.
  8138. * All parameters must be valid pointers (not NULL).
  8139. * Return <0 on error. */
  8140. static int
  8141. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8142. {
  8143. int i;
  8144. int num_headers = 0;
  8145. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8146. char *dp = *buf;
  8147. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8148. dp++;
  8149. }
  8150. if (dp == *buf) {
  8151. /* End of headers reached. */
  8152. break;
  8153. }
  8154. if (*dp != ':') {
  8155. /* This is not a valid field. */
  8156. return -1;
  8157. }
  8158. /* End of header key (*dp == ':') */
  8159. /* Truncate here and set the key name */
  8160. *dp = 0;
  8161. hdr[i].name = *buf;
  8162. do {
  8163. dp++;
  8164. } while (*dp == ' ');
  8165. /* The rest of the line is the value */
  8166. hdr[i].value = dp;
  8167. *buf = dp + strcspn(dp, "\r\n");
  8168. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8169. *buf = NULL;
  8170. }
  8171. num_headers = i + 1;
  8172. if (*buf) {
  8173. (*buf)[0] = 0;
  8174. (*buf)[1] = 0;
  8175. *buf += 2;
  8176. } else {
  8177. *buf = dp;
  8178. break;
  8179. }
  8180. if ((*buf)[0] == '\r') {
  8181. /* This is the end of the header */
  8182. break;
  8183. }
  8184. }
  8185. return num_headers;
  8186. }
  8187. struct mg_http_method_info {
  8188. const char *name;
  8189. int request_has_body;
  8190. int response_has_body;
  8191. int is_safe;
  8192. int is_idempotent;
  8193. int is_cacheable;
  8194. };
  8195. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8196. static struct mg_http_method_info http_methods[] = {
  8197. /* HTTP (RFC 2616) */
  8198. {"GET", 0, 1, 1, 1, 1},
  8199. {"POST", 1, 1, 0, 0, 0},
  8200. {"PUT", 1, 0, 0, 1, 0},
  8201. {"DELETE", 0, 0, 0, 1, 0},
  8202. {"HEAD", 0, 0, 1, 1, 1},
  8203. {"OPTIONS", 0, 0, 1, 1, 0},
  8204. {"CONNECT", 1, 1, 0, 0, 0},
  8205. /* TRACE method (RFC 2616) is not supported for security reasons */
  8206. /* PATCH method (RFC 5789) */
  8207. {"PATCH", 1, 0, 0, 0, 0},
  8208. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8209. /* WEBDAV (RFC 2518) */
  8210. {"PROPFIND", 0, 1, 1, 1, 0},
  8211. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8212. * Some PROPFIND results MAY be cached, with care,
  8213. * as there is no cache validation mechanism for
  8214. * most properties. This method is both safe and
  8215. * idempotent (see Section 9.1 of [RFC2616]). */
  8216. {"MKCOL", 0, 0, 0, 1, 0},
  8217. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8218. * When MKCOL is invoked without a request body,
  8219. * the newly created collection SHOULD have no
  8220. * members. A MKCOL request message may contain
  8221. * a message body. The precise behavior of a MKCOL
  8222. * request when the body is present is undefined,
  8223. * ... ==> We do not support MKCOL with body data.
  8224. * This method is idempotent, but not safe (see
  8225. * Section 9.1 of [RFC2616]). Responses to this
  8226. * method MUST NOT be cached. */
  8227. /* Unsupported WEBDAV Methods: */
  8228. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8229. /* + 11 methods from RFC 3253 */
  8230. /* ORDERPATCH (RFC 3648) */
  8231. /* ACL (RFC 3744) */
  8232. /* SEARCH (RFC 5323) */
  8233. /* + MicroSoft extensions
  8234. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8235. /* REPORT method (RFC 3253) */
  8236. {"REPORT", 1, 1, 1, 1, 1},
  8237. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8238. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8239. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8240. * to be useful for REST in case a "GET request with body" is
  8241. * required. */
  8242. {NULL, 0, 0, 0, 0, 0}
  8243. /* end of list */
  8244. };
  8245. static const struct mg_http_method_info *
  8246. get_http_method_info(const char *method)
  8247. {
  8248. /* Check if the method is known to the server. The list of all known
  8249. * HTTP methods can be found here at
  8250. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8251. */
  8252. const struct mg_http_method_info *m = http_methods;
  8253. while (m->name) {
  8254. if (!strcmp(m->name, method)) {
  8255. return m;
  8256. }
  8257. m++;
  8258. }
  8259. return NULL;
  8260. }
  8261. static int
  8262. is_valid_http_method(const char *method)
  8263. {
  8264. return (get_http_method_info(method) != NULL);
  8265. }
  8266. /* Parse HTTP request, fill in mg_request_info structure.
  8267. * This function modifies the buffer by NUL-terminating
  8268. * HTTP request components, header names and header values.
  8269. * Parameters:
  8270. * buf (in/out): pointer to the HTTP header to parse and split
  8271. * len (in): length of HTTP header buffer
  8272. * re (out): parsed header as mg_request_info
  8273. * buf and ri must be valid pointers (not NULL), len>0.
  8274. * Returns <0 on error. */
  8275. static int
  8276. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8277. {
  8278. int request_length;
  8279. int init_skip = 0;
  8280. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8281. * remote_port */
  8282. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8283. NULL;
  8284. ri->num_headers = 0;
  8285. /* RFC says that all initial whitespaces should be ingored */
  8286. /* This included all leading \r and \n (isspace) */
  8287. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8288. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8289. buf++;
  8290. len--;
  8291. init_skip++;
  8292. }
  8293. if (len == 0) {
  8294. /* Incomplete request */
  8295. return 0;
  8296. }
  8297. /* Control characters are not allowed, including zero */
  8298. if (iscntrl(*(unsigned char *)buf)) {
  8299. return -1;
  8300. }
  8301. /* Find end of HTTP header */
  8302. request_length = get_http_header_len(buf, len);
  8303. if (request_length <= 0) {
  8304. return request_length;
  8305. }
  8306. buf[request_length - 1] = '\0';
  8307. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8308. return -1;
  8309. }
  8310. /* The first word has to be the HTTP method */
  8311. ri->request_method = buf;
  8312. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8313. return -1;
  8314. }
  8315. /* Check for a valid http method */
  8316. if (!is_valid_http_method(ri->request_method)) {
  8317. return -1;
  8318. }
  8319. /* The second word is the URI */
  8320. ri->request_uri = buf;
  8321. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8322. return -1;
  8323. }
  8324. /* Next would be the HTTP version */
  8325. ri->http_version = buf;
  8326. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8327. return -1;
  8328. }
  8329. /* Check for a valid HTTP version key */
  8330. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8331. /* Invalid request */
  8332. return -1;
  8333. }
  8334. ri->http_version += 5;
  8335. /* Parse all HTTP headers */
  8336. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8337. if (ri->num_headers < 0) {
  8338. /* Error while parsing headers */
  8339. return -1;
  8340. }
  8341. return request_length + init_skip;
  8342. }
  8343. static int
  8344. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8345. {
  8346. int response_length;
  8347. int init_skip = 0;
  8348. char *tmp, *tmp2;
  8349. long l;
  8350. /* Initialize elements. */
  8351. ri->http_version = ri->status_text = NULL;
  8352. ri->num_headers = ri->status_code = 0;
  8353. /* RFC says that all initial whitespaces should be ingored */
  8354. /* This included all leading \r and \n (isspace) */
  8355. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8356. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8357. buf++;
  8358. len--;
  8359. init_skip++;
  8360. }
  8361. if (len == 0) {
  8362. /* Incomplete request */
  8363. return 0;
  8364. }
  8365. /* Control characters are not allowed, including zero */
  8366. if (iscntrl(*(unsigned char *)buf)) {
  8367. return -1;
  8368. }
  8369. /* Find end of HTTP header */
  8370. response_length = get_http_header_len(buf, len);
  8371. if (response_length <= 0) {
  8372. return response_length;
  8373. }
  8374. buf[response_length - 1] = '\0';
  8375. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8376. return -1;
  8377. }
  8378. /* The first word is the HTTP version */
  8379. /* Check for a valid HTTP version key */
  8380. if (strncmp(buf, "HTTP/", 5) != 0) {
  8381. /* Invalid request */
  8382. return -1;
  8383. }
  8384. buf += 5;
  8385. if (!isgraph(buf[0])) {
  8386. /* Invalid request */
  8387. return -1;
  8388. }
  8389. ri->http_version = buf;
  8390. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8391. return -1;
  8392. }
  8393. /* The second word is the status as a number */
  8394. tmp = buf;
  8395. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8396. return -1;
  8397. }
  8398. l = strtol(tmp, &tmp2, 10);
  8399. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8400. /* Everything else but a 3 digit code is invalid */
  8401. return -1;
  8402. }
  8403. ri->status_code = (int)l;
  8404. /* The rest of the line is the status text */
  8405. ri->status_text = buf;
  8406. /* Find end of status text */
  8407. /* isgraph or isspace = isprint */
  8408. while (isprint(*buf)) {
  8409. buf++;
  8410. }
  8411. if ((*buf != '\r') && (*buf != '\n')) {
  8412. return -1;
  8413. }
  8414. /* Terminate string and forward buf to next line */
  8415. do {
  8416. *buf = 0;
  8417. buf++;
  8418. } while ((*buf) && isspace(*buf));
  8419. /* Parse all HTTP headers */
  8420. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8421. if (ri->num_headers < 0) {
  8422. /* Error while parsing headers */
  8423. return -1;
  8424. }
  8425. return response_length + init_skip;
  8426. }
  8427. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8428. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8429. * buffer (which marks the end of HTTP request). Buffer buf may already
  8430. * have some data. The length of the data is stored in nread.
  8431. * Upon every read operation, increase nread by the number of bytes read. */
  8432. static int
  8433. read_message(FILE *fp,
  8434. struct mg_connection *conn,
  8435. char *buf,
  8436. int bufsiz,
  8437. int *nread)
  8438. {
  8439. int request_len, n = 0;
  8440. struct timespec last_action_time;
  8441. double request_timeout;
  8442. if (!conn) {
  8443. return 0;
  8444. }
  8445. memset(&last_action_time, 0, sizeof(last_action_time));
  8446. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8447. /* value of request_timeout is in seconds, config in milliseconds */
  8448. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8449. } else {
  8450. request_timeout = -1.0;
  8451. }
  8452. if (conn->handled_requests > 0) {
  8453. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8454. request_timeout =
  8455. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8456. }
  8457. }
  8458. request_len = get_http_header_len(buf, *nread);
  8459. /* first time reading from this connection */
  8460. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8461. while (request_len == 0) {
  8462. /* Full request not yet received */
  8463. if (conn->phys_ctx->stop_flag != 0) {
  8464. /* Server is to be stopped. */
  8465. return -1;
  8466. }
  8467. if (*nread >= bufsiz) {
  8468. /* Request too long */
  8469. return -2;
  8470. }
  8471. n = pull_inner(
  8472. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8473. if (n == -2) {
  8474. /* Receive error */
  8475. return -1;
  8476. }
  8477. if (n > 0) {
  8478. *nread += n;
  8479. request_len = get_http_header_len(buf, *nread);
  8480. } else {
  8481. request_len = 0;
  8482. }
  8483. if ((request_len == 0) && (request_timeout >= 0)) {
  8484. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8485. > request_timeout) {
  8486. /* Timeout */
  8487. return -1;
  8488. }
  8489. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8490. }
  8491. }
  8492. return request_len;
  8493. }
  8494. #if !defined(NO_CGI) || !defined(NO_FILES)
  8495. static int
  8496. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8497. {
  8498. const char *expect, *body;
  8499. char buf[MG_BUF_LEN];
  8500. int to_read, nread, success = 0;
  8501. int64_t buffered_len;
  8502. double timeout = -1.0;
  8503. if (!conn) {
  8504. return 0;
  8505. }
  8506. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8507. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8508. }
  8509. expect = mg_get_header(conn, "Expect");
  8510. DEBUG_ASSERT(fp != NULL);
  8511. if (!fp) {
  8512. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8513. return 0;
  8514. }
  8515. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8516. /* Content length is not specified by the client. */
  8517. mg_send_http_error(conn,
  8518. 411,
  8519. "%s",
  8520. "Error: Client did not specify content length");
  8521. } else if ((expect != NULL)
  8522. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8523. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8524. */
  8525. mg_send_http_error(conn,
  8526. 417,
  8527. "Error: Can not fulfill expectation %s",
  8528. expect);
  8529. } else {
  8530. if (expect != NULL) {
  8531. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8532. conn->status_code = 100;
  8533. } else {
  8534. conn->status_code = 200;
  8535. }
  8536. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8537. - conn->consumed_content;
  8538. DEBUG_ASSERT(buffered_len >= 0);
  8539. DEBUG_ASSERT(conn->consumed_content == 0);
  8540. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8541. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8542. return 0;
  8543. }
  8544. if (buffered_len > 0) {
  8545. if ((int64_t)buffered_len > conn->content_len) {
  8546. buffered_len = (int)conn->content_len;
  8547. }
  8548. body = conn->buf + conn->request_len + conn->consumed_content;
  8549. push_all(
  8550. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8551. conn->consumed_content += buffered_len;
  8552. }
  8553. nread = 0;
  8554. while (conn->consumed_content < conn->content_len) {
  8555. to_read = sizeof(buf);
  8556. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8557. to_read = (int)(conn->content_len - conn->consumed_content);
  8558. }
  8559. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8560. if (nread == -2) {
  8561. /* error */
  8562. break;
  8563. }
  8564. if (nread > 0) {
  8565. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  8566. != nread) {
  8567. break;
  8568. }
  8569. }
  8570. conn->consumed_content += nread;
  8571. }
  8572. if (conn->consumed_content == conn->content_len) {
  8573. success = (nread >= 0);
  8574. }
  8575. /* Each error code path in this function must send an error */
  8576. if (!success) {
  8577. /* NOTE: Maybe some data has already been sent. */
  8578. /* TODO (low): If some data has been sent, a correct error
  8579. * reply can no longer be sent, so just close the connection */
  8580. mg_send_http_error(conn, 500, "%s", "");
  8581. }
  8582. }
  8583. return success;
  8584. }
  8585. #endif
  8586. #if !defined(NO_CGI)
  8587. /* This structure helps to create an environment for the spawned CGI
  8588. * program.
  8589. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8590. * last element must be NULL.
  8591. * However, on Windows there is a requirement that all these
  8592. * VARIABLE=VALUE\0
  8593. * strings must reside in a contiguous buffer. The end of the buffer is
  8594. * marked by two '\0' characters.
  8595. * We satisfy both worlds: we create an envp array (which is vars), all
  8596. * entries are actually pointers inside buf. */
  8597. struct cgi_environment {
  8598. struct mg_connection *conn;
  8599. /* Data block */
  8600. char *buf; /* Environment buffer */
  8601. size_t buflen; /* Space available in buf */
  8602. size_t bufused; /* Space taken in buf */
  8603. /* Index block */
  8604. char **var; /* char **envp */
  8605. size_t varlen; /* Number of variables available in var */
  8606. size_t varused; /* Number of variables stored in var */
  8607. };
  8608. static void addenv(struct cgi_environment *env,
  8609. PRINTF_FORMAT_STRING(const char *fmt),
  8610. ...) PRINTF_ARGS(2, 3);
  8611. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8612. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8613. static void
  8614. addenv(struct cgi_environment *env, const char *fmt, ...)
  8615. {
  8616. size_t n, space;
  8617. int truncated = 0;
  8618. char *added;
  8619. va_list ap;
  8620. /* Calculate how much space is left in the buffer */
  8621. space = (env->buflen - env->bufused);
  8622. /* Calculate an estimate for the required space */
  8623. n = strlen(fmt) + 2 + 128;
  8624. do {
  8625. if (space <= n) {
  8626. /* Allocate new buffer */
  8627. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8628. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  8629. if (!added) {
  8630. /* Out of memory */
  8631. mg_cry_internal(
  8632. env->conn,
  8633. "%s: Cannot allocate memory for CGI variable [%s]",
  8634. __func__,
  8635. fmt);
  8636. return;
  8637. }
  8638. env->buf = added;
  8639. env->buflen = n;
  8640. space = (env->buflen - env->bufused);
  8641. }
  8642. /* Make a pointer to the free space int the buffer */
  8643. added = env->buf + env->bufused;
  8644. /* Copy VARIABLE=VALUE\0 string into the free space */
  8645. va_start(ap, fmt);
  8646. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8647. va_end(ap);
  8648. /* Do not add truncated strings to the environment */
  8649. if (truncated) {
  8650. /* Reallocate the buffer */
  8651. space = 0;
  8652. n = 1;
  8653. }
  8654. } while (truncated);
  8655. /* Calculate number of bytes added to the environment */
  8656. n = strlen(added) + 1;
  8657. env->bufused += n;
  8658. /* Now update the variable index */
  8659. space = (env->varlen - env->varused);
  8660. if (space < 2) {
  8661. mg_cry_internal(env->conn,
  8662. "%s: Cannot register CGI variable [%s]",
  8663. __func__,
  8664. fmt);
  8665. return;
  8666. }
  8667. /* Append a pointer to the added string into the envp array */
  8668. env->var[env->varused] = added;
  8669. env->varused++;
  8670. }
  8671. /* Return 0 on success, non-zero if an error occurs. */
  8672. static int
  8673. prepare_cgi_environment(struct mg_connection *conn,
  8674. const char *prog,
  8675. struct cgi_environment *env)
  8676. {
  8677. const char *s;
  8678. struct vec var_vec;
  8679. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8680. int i, truncated, uri_len;
  8681. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8682. return -1;
  8683. }
  8684. env->conn = conn;
  8685. env->buflen = CGI_ENVIRONMENT_SIZE;
  8686. env->bufused = 0;
  8687. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  8688. if (env->buf == NULL) {
  8689. mg_cry_internal(conn,
  8690. "%s: Not enough memory for environmental buffer",
  8691. __func__);
  8692. return -1;
  8693. }
  8694. env->varlen = MAX_CGI_ENVIR_VARS;
  8695. env->varused = 0;
  8696. env->var =
  8697. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  8698. if (env->var == NULL) {
  8699. mg_cry_internal(conn,
  8700. "%s: Not enough memory for environmental variables",
  8701. __func__);
  8702. mg_free(env->buf);
  8703. return -1;
  8704. }
  8705. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  8706. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8707. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8708. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8709. /* Prepare the environment block */
  8710. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8711. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8712. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8713. #if defined(USE_IPV6)
  8714. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8715. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8716. } else
  8717. #endif
  8718. {
  8719. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8720. }
  8721. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8722. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8723. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8724. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8725. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8726. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8727. /* SCRIPT_NAME */
  8728. uri_len = (int)strlen(conn->request_info.local_uri);
  8729. if (conn->path_info == NULL) {
  8730. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8731. /* URI: /path_to_script/script.cgi */
  8732. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8733. } else {
  8734. /* URI: /path_to_script/ ... using index.cgi */
  8735. const char *index_file = strrchr(prog, '/');
  8736. if (index_file) {
  8737. addenv(env,
  8738. "SCRIPT_NAME=%s%s",
  8739. conn->request_info.local_uri,
  8740. index_file + 1);
  8741. }
  8742. }
  8743. } else {
  8744. /* URI: /path_to_script/script.cgi/path_info */
  8745. addenv(env,
  8746. "SCRIPT_NAME=%.*s",
  8747. uri_len - (int)strlen(conn->path_info),
  8748. conn->request_info.local_uri);
  8749. }
  8750. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8751. if (conn->path_info == NULL) {
  8752. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8753. } else {
  8754. addenv(env,
  8755. "PATH_TRANSLATED=%s%s",
  8756. conn->dom_ctx->config[DOCUMENT_ROOT],
  8757. conn->path_info);
  8758. }
  8759. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8760. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8761. addenv(env, "CONTENT_TYPE=%s", s);
  8762. }
  8763. if (conn->request_info.query_string != NULL) {
  8764. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8765. }
  8766. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8767. addenv(env, "CONTENT_LENGTH=%s", s);
  8768. }
  8769. if ((s = getenv("PATH")) != NULL) {
  8770. addenv(env, "PATH=%s", s);
  8771. }
  8772. if (conn->path_info != NULL) {
  8773. addenv(env, "PATH_INFO=%s", conn->path_info);
  8774. }
  8775. if (conn->status_code > 0) {
  8776. /* CGI error handler should show the status code */
  8777. addenv(env, "STATUS=%d", conn->status_code);
  8778. }
  8779. #if defined(_WIN32)
  8780. if ((s = getenv("COMSPEC")) != NULL) {
  8781. addenv(env, "COMSPEC=%s", s);
  8782. }
  8783. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8784. addenv(env, "SYSTEMROOT=%s", s);
  8785. }
  8786. if ((s = getenv("SystemDrive")) != NULL) {
  8787. addenv(env, "SystemDrive=%s", s);
  8788. }
  8789. if ((s = getenv("ProgramFiles")) != NULL) {
  8790. addenv(env, "ProgramFiles=%s", s);
  8791. }
  8792. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8793. addenv(env, "ProgramFiles(x86)=%s", s);
  8794. }
  8795. #else
  8796. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8797. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8798. }
  8799. #endif /* _WIN32 */
  8800. if ((s = getenv("PERLLIB")) != NULL) {
  8801. addenv(env, "PERLLIB=%s", s);
  8802. }
  8803. if (conn->request_info.remote_user != NULL) {
  8804. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8805. addenv(env, "%s", "AUTH_TYPE=Digest");
  8806. }
  8807. /* Add all headers as HTTP_* variables */
  8808. for (i = 0; i < conn->request_info.num_headers; i++) {
  8809. (void)mg_snprintf(conn,
  8810. &truncated,
  8811. http_var_name,
  8812. sizeof(http_var_name),
  8813. "HTTP_%s",
  8814. conn->request_info.http_headers[i].name);
  8815. if (truncated) {
  8816. mg_cry_internal(conn,
  8817. "%s: HTTP header variable too long [%s]",
  8818. __func__,
  8819. conn->request_info.http_headers[i].name);
  8820. continue;
  8821. }
  8822. /* Convert variable name into uppercase, and change - to _ */
  8823. for (p = http_var_name; *p != '\0'; p++) {
  8824. if (*p == '-') {
  8825. *p = '_';
  8826. }
  8827. *p = (char)toupper(*(unsigned char *)p);
  8828. }
  8829. addenv(env,
  8830. "%s=%s",
  8831. http_var_name,
  8832. conn->request_info.http_headers[i].value);
  8833. }
  8834. /* Add user-specified variables */
  8835. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  8836. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8837. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8838. }
  8839. env->var[env->varused] = NULL;
  8840. env->buf[env->bufused] = '\0';
  8841. return 0;
  8842. }
  8843. static void
  8844. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8845. {
  8846. char *buf;
  8847. size_t buflen;
  8848. int headers_len, data_len, i, truncated;
  8849. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8850. const char *status, *status_text, *connection_state;
  8851. char *pbuf, dir[PATH_MAX], *p;
  8852. struct mg_request_info ri;
  8853. struct cgi_environment blk;
  8854. FILE *in = NULL, *out = NULL, *err = NULL;
  8855. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8856. pid_t pid = (pid_t)-1;
  8857. if (conn == NULL) {
  8858. return;
  8859. }
  8860. buf = NULL;
  8861. buflen = 16384;
  8862. i = prepare_cgi_environment(conn, prog, &blk);
  8863. if (i != 0) {
  8864. blk.buf = NULL;
  8865. blk.var = NULL;
  8866. goto done;
  8867. }
  8868. /* CGI must be executed in its own directory. 'dir' must point to the
  8869. * directory containing executable program, 'p' must point to the
  8870. * executable program name relative to 'dir'. */
  8871. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8872. if (truncated) {
  8873. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  8874. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8875. goto done;
  8876. }
  8877. if ((p = strrchr(dir, '/')) != NULL) {
  8878. *p++ = '\0';
  8879. } else {
  8880. dir[0] = '.';
  8881. dir[1] = '\0';
  8882. p = (char *)prog;
  8883. }
  8884. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8885. status = strerror(ERRNO);
  8886. mg_cry_internal(
  8887. conn,
  8888. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8889. prog,
  8890. status);
  8891. mg_send_http_error(conn,
  8892. 500,
  8893. "Error: Cannot create CGI pipe: %s",
  8894. status);
  8895. goto done;
  8896. }
  8897. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  8898. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8899. if (pid == (pid_t)-1) {
  8900. status = strerror(ERRNO);
  8901. mg_cry_internal(
  8902. conn,
  8903. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8904. prog,
  8905. status);
  8906. mg_send_http_error(conn,
  8907. 500,
  8908. "Error: Cannot spawn CGI process [%s]: %s",
  8909. prog,
  8910. status);
  8911. goto done;
  8912. }
  8913. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  8914. */
  8915. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8916. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8917. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8918. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8919. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8920. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8921. /* Parent closes only one side of the pipes.
  8922. * If we don't mark them as closed, close() attempt before
  8923. * return from this function throws an exception on Windows.
  8924. * Windows does not like when closed descriptor is closed again. */
  8925. (void)close(fdin[0]);
  8926. (void)close(fdout[1]);
  8927. (void)close(fderr[1]);
  8928. fdin[0] = fdout[1] = fderr[1] = -1;
  8929. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8930. status = strerror(ERRNO);
  8931. mg_cry_internal(conn,
  8932. "Error: CGI program \"%s\": Can not open stdin: %s",
  8933. prog,
  8934. status);
  8935. mg_send_http_error(conn,
  8936. 500,
  8937. "Error: CGI can not open fdin\nfopen: %s",
  8938. status);
  8939. goto done;
  8940. }
  8941. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8942. status = strerror(ERRNO);
  8943. mg_cry_internal(conn,
  8944. "Error: CGI program \"%s\": Can not open stdout: %s",
  8945. prog,
  8946. status);
  8947. mg_send_http_error(conn,
  8948. 500,
  8949. "Error: CGI can not open fdout\nfopen: %s",
  8950. status);
  8951. goto done;
  8952. }
  8953. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8954. status = strerror(ERRNO);
  8955. mg_cry_internal(conn,
  8956. "Error: CGI program \"%s\": Can not open stderr: %s",
  8957. prog,
  8958. status);
  8959. mg_send_http_error(conn,
  8960. 500,
  8961. "Error: CGI can not open fdout\nfopen: %s",
  8962. status);
  8963. goto done;
  8964. }
  8965. setbuf(in, NULL);
  8966. setbuf(out, NULL);
  8967. setbuf(err, NULL);
  8968. fout.access.fp = out;
  8969. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  8970. DEBUG_TRACE("CGI: send body data (%lli)\n",
  8971. (signed long long)conn->request_info.content_length);
  8972. /* This is a POST/PUT request, or another request with body data. */
  8973. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8974. /* Error sending the body data */
  8975. mg_cry_internal(
  8976. conn,
  8977. "Error: CGI program \"%s\": Forward body data failed",
  8978. prog);
  8979. goto done;
  8980. }
  8981. }
  8982. /* Close so child gets an EOF. */
  8983. fclose(in);
  8984. in = NULL;
  8985. fdin[1] = -1;
  8986. /* Now read CGI reply into a buffer. We need to set correct
  8987. * status code, thus we need to see all HTTP headers first.
  8988. * Do not send anything back to client, until we buffer in all
  8989. * HTTP headers. */
  8990. data_len = 0;
  8991. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  8992. if (buf == NULL) {
  8993. mg_send_http_error(conn,
  8994. 500,
  8995. "Error: Not enough memory for CGI buffer (%u bytes)",
  8996. (unsigned int)buflen);
  8997. mg_cry_internal(
  8998. conn,
  8999. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9000. "bytes)",
  9001. prog,
  9002. (unsigned int)buflen);
  9003. goto done;
  9004. }
  9005. DEBUG_TRACE("CGI: %s", "wait for response");
  9006. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9007. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9008. if (headers_len <= 0) {
  9009. /* Could not parse the CGI response. Check if some error message on
  9010. * stderr. */
  9011. i = pull_all(err, conn, buf, (int)buflen);
  9012. if (i > 0) {
  9013. mg_cry_internal(conn,
  9014. "Error: CGI program \"%s\" sent error "
  9015. "message: [%.*s]",
  9016. prog,
  9017. i,
  9018. buf);
  9019. mg_send_http_error(conn,
  9020. 500,
  9021. "Error: CGI program \"%s\" sent error "
  9022. "message: [%.*s]",
  9023. prog,
  9024. i,
  9025. buf);
  9026. } else {
  9027. mg_cry_internal(conn,
  9028. "Error: CGI program sent malformed or too big "
  9029. "(>%u bytes) HTTP headers: [%.*s]",
  9030. (unsigned)buflen,
  9031. data_len,
  9032. buf);
  9033. mg_send_http_error(conn,
  9034. 500,
  9035. "Error: CGI program sent malformed or too big "
  9036. "(>%u bytes) HTTP headers: [%.*s]",
  9037. (unsigned)buflen,
  9038. data_len,
  9039. buf);
  9040. }
  9041. goto done;
  9042. }
  9043. pbuf = buf;
  9044. buf[headers_len - 1] = '\0';
  9045. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9046. /* Make up and send the status line */
  9047. status_text = "OK";
  9048. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9049. != NULL) {
  9050. conn->status_code = atoi(status);
  9051. status_text = status;
  9052. while (isdigit(*(const unsigned char *)status_text)
  9053. || *status_text == ' ') {
  9054. status_text++;
  9055. }
  9056. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9057. != NULL) {
  9058. conn->status_code = 302;
  9059. } else {
  9060. conn->status_code = 200;
  9061. }
  9062. connection_state =
  9063. get_header(ri.http_headers, ri.num_headers, "Connection");
  9064. if (!header_has_option(connection_state, "keep-alive")) {
  9065. conn->must_close = 1;
  9066. }
  9067. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9068. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9069. /* Send headers */
  9070. for (i = 0; i < ri.num_headers; i++) {
  9071. mg_printf(conn,
  9072. "%s: %s\r\n",
  9073. ri.http_headers[i].name,
  9074. ri.http_headers[i].value);
  9075. }
  9076. mg_write(conn, "\r\n", 2);
  9077. /* Send chunk of data that may have been read after the headers */
  9078. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9079. /* Read the rest of CGI output and send to the client */
  9080. send_file_data(conn, &fout, 0, INT64_MAX);
  9081. DEBUG_TRACE("CGI: %s", "all data sent");
  9082. done:
  9083. mg_free(blk.var);
  9084. mg_free(blk.buf);
  9085. if (pid != (pid_t)-1) {
  9086. kill(pid, SIGKILL);
  9087. #if !defined(_WIN32)
  9088. {
  9089. int st;
  9090. while (waitpid(pid, &st, 0) != -1)
  9091. ; /* clean zombies */
  9092. }
  9093. #endif
  9094. }
  9095. if (fdin[0] != -1) {
  9096. close(fdin[0]);
  9097. }
  9098. if (fdout[1] != -1) {
  9099. close(fdout[1]);
  9100. }
  9101. if (in != NULL) {
  9102. fclose(in);
  9103. } else if (fdin[1] != -1) {
  9104. close(fdin[1]);
  9105. }
  9106. if (out != NULL) {
  9107. fclose(out);
  9108. } else if (fdout[0] != -1) {
  9109. close(fdout[0]);
  9110. }
  9111. if (err != NULL) {
  9112. fclose(err);
  9113. } else if (fderr[0] != -1) {
  9114. close(fderr[0]);
  9115. }
  9116. if (buf != NULL) {
  9117. mg_free(buf);
  9118. }
  9119. }
  9120. #endif /* !NO_CGI */
  9121. #if !defined(NO_FILES)
  9122. static void
  9123. mkcol(struct mg_connection *conn, const char *path)
  9124. {
  9125. int rc, body_len;
  9126. struct de de;
  9127. char date[64];
  9128. time_t curtime = time(NULL);
  9129. if (conn == NULL) {
  9130. return;
  9131. }
  9132. /* TODO (mid): Check the mg_send_http_error situations in this function
  9133. */
  9134. memset(&de.file, 0, sizeof(de.file));
  9135. if (!mg_stat(conn, path, &de.file)) {
  9136. mg_cry_internal(conn,
  9137. "%s: mg_stat(%s) failed: %s",
  9138. __func__,
  9139. path,
  9140. strerror(ERRNO));
  9141. }
  9142. if (de.file.last_modified) {
  9143. /* TODO (mid): This check does not seem to make any sense ! */
  9144. /* TODO (mid): Add a webdav unit test first, before changing
  9145. * anything here. */
  9146. mg_send_http_error(
  9147. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9148. return;
  9149. }
  9150. body_len = conn->data_len - conn->request_len;
  9151. if (body_len > 0) {
  9152. mg_send_http_error(
  9153. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9154. return;
  9155. }
  9156. rc = mg_mkdir(conn, path, 0755);
  9157. if (rc == 0) {
  9158. conn->status_code = 201;
  9159. gmt_time_string(date, sizeof(date), &curtime);
  9160. mg_printf(conn,
  9161. "HTTP/1.1 %d Created\r\n"
  9162. "Date: %s\r\n",
  9163. conn->status_code,
  9164. date);
  9165. send_static_cache_header(conn);
  9166. send_additional_header(conn);
  9167. mg_printf(conn,
  9168. "Content-Length: 0\r\n"
  9169. "Connection: %s\r\n\r\n",
  9170. suggest_connection_header(conn));
  9171. } else if (rc == -1) {
  9172. if (errno == EEXIST) {
  9173. mg_send_http_error(
  9174. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9175. } else if (errno == EACCES) {
  9176. mg_send_http_error(
  9177. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9178. } else if (errno == ENOENT) {
  9179. mg_send_http_error(
  9180. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9181. } else {
  9182. mg_send_http_error(
  9183. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9184. }
  9185. }
  9186. }
  9187. static void
  9188. put_file(struct mg_connection *conn, const char *path)
  9189. {
  9190. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9191. const char *range;
  9192. int64_t r1, r2;
  9193. int rc;
  9194. char date[64];
  9195. time_t curtime = time(NULL);
  9196. if (conn == NULL) {
  9197. return;
  9198. }
  9199. if (mg_stat(conn, path, &file.stat)) {
  9200. /* File already exists */
  9201. conn->status_code = 200;
  9202. if (file.stat.is_directory) {
  9203. /* This is an already existing directory,
  9204. * so there is nothing to do for the server. */
  9205. rc = 0;
  9206. } else {
  9207. /* File exists and is not a directory. */
  9208. /* Can it be replaced? */
  9209. if (file.access.membuf != NULL) {
  9210. /* This is an "in-memory" file, that can not be replaced */
  9211. mg_send_http_error(conn,
  9212. 405,
  9213. "Error: Put not possible\nReplacing %s "
  9214. "is not supported",
  9215. path);
  9216. return;
  9217. }
  9218. /* Check if the server may write this file */
  9219. if (access(path, W_OK) == 0) {
  9220. /* Access granted */
  9221. conn->status_code = 200;
  9222. rc = 1;
  9223. } else {
  9224. mg_send_http_error(
  9225. conn,
  9226. 403,
  9227. "Error: Put not possible\nReplacing %s is not allowed",
  9228. path);
  9229. return;
  9230. }
  9231. }
  9232. } else {
  9233. /* File should be created */
  9234. conn->status_code = 201;
  9235. rc = put_dir(conn, path);
  9236. }
  9237. if (rc == 0) {
  9238. /* put_dir returns 0 if path is a directory */
  9239. gmt_time_string(date, sizeof(date), &curtime);
  9240. mg_printf(conn,
  9241. "HTTP/1.1 %d %s\r\n",
  9242. conn->status_code,
  9243. mg_get_response_code_text(NULL, conn->status_code));
  9244. send_no_cache_header(conn);
  9245. send_additional_header(conn);
  9246. mg_printf(conn,
  9247. "Date: %s\r\n"
  9248. "Content-Length: 0\r\n"
  9249. "Connection: %s\r\n\r\n",
  9250. date,
  9251. suggest_connection_header(conn));
  9252. /* Request to create a directory has been fulfilled successfully.
  9253. * No need to put a file. */
  9254. return;
  9255. }
  9256. if (rc == -1) {
  9257. /* put_dir returns -1 if the path is too long */
  9258. mg_send_http_error(conn,
  9259. 414,
  9260. "Error: Path too long\nput_dir(%s): %s",
  9261. path,
  9262. strerror(ERRNO));
  9263. return;
  9264. }
  9265. if (rc == -2) {
  9266. /* put_dir returns -2 if the directory can not be created */
  9267. mg_send_http_error(conn,
  9268. 500,
  9269. "Error: Can not create directory\nput_dir(%s): %s",
  9270. path,
  9271. strerror(ERRNO));
  9272. return;
  9273. }
  9274. /* A file should be created or overwritten. */
  9275. /* Currently CivetWeb does not nead read+write access. */
  9276. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9277. || file.access.fp == NULL) {
  9278. (void)mg_fclose(&file.access);
  9279. mg_send_http_error(conn,
  9280. 500,
  9281. "Error: Can not create file\nfopen(%s): %s",
  9282. path,
  9283. strerror(ERRNO));
  9284. return;
  9285. }
  9286. fclose_on_exec(&file.access, conn);
  9287. range = mg_get_header(conn, "Content-Range");
  9288. r1 = r2 = 0;
  9289. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9290. conn->status_code = 206; /* Partial content */
  9291. fseeko(file.access.fp, r1, SEEK_SET);
  9292. }
  9293. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9294. /* forward_body_data failed.
  9295. * The error code has already been sent to the client,
  9296. * and conn->status_code is already set. */
  9297. (void)mg_fclose(&file.access);
  9298. return;
  9299. }
  9300. if (mg_fclose(&file.access) != 0) {
  9301. /* fclose failed. This might have different reasons, but a likely
  9302. * one is "no space on disk", http 507. */
  9303. conn->status_code = 507;
  9304. }
  9305. gmt_time_string(date, sizeof(date), &curtime);
  9306. mg_printf(conn,
  9307. "HTTP/1.1 %d %s\r\n",
  9308. conn->status_code,
  9309. mg_get_response_code_text(NULL, conn->status_code));
  9310. send_no_cache_header(conn);
  9311. send_additional_header(conn);
  9312. mg_printf(conn,
  9313. "Date: %s\r\n"
  9314. "Content-Length: 0\r\n"
  9315. "Connection: %s\r\n\r\n",
  9316. date,
  9317. suggest_connection_header(conn));
  9318. }
  9319. static void
  9320. delete_file(struct mg_connection *conn, const char *path)
  9321. {
  9322. struct de de;
  9323. memset(&de.file, 0, sizeof(de.file));
  9324. if (!mg_stat(conn, path, &de.file)) {
  9325. /* mg_stat returns 0 if the file does not exist */
  9326. mg_send_http_error(conn,
  9327. 404,
  9328. "Error: Cannot delete file\nFile %s not found",
  9329. path);
  9330. return;
  9331. }
  9332. #if 0 /* Ignore if a file in memory is inside a folder */
  9333. if (de.access.membuf != NULL) {
  9334. /* the file is cached in memory */
  9335. mg_send_http_error(
  9336. conn,
  9337. 405,
  9338. "Error: Delete not possible\nDeleting %s is not supported",
  9339. path);
  9340. return;
  9341. }
  9342. #endif
  9343. if (de.file.is_directory) {
  9344. if (remove_directory(conn, path)) {
  9345. /* Delete is successful: Return 204 without content. */
  9346. mg_send_http_error(conn, 204, "%s", "");
  9347. } else {
  9348. /* Delete is not successful: Return 500 (Server error). */
  9349. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9350. }
  9351. return;
  9352. }
  9353. /* This is an existing file (not a directory).
  9354. * Check if write permission is granted. */
  9355. if (access(path, W_OK) != 0) {
  9356. /* File is read only */
  9357. mg_send_http_error(
  9358. conn,
  9359. 403,
  9360. "Error: Delete not possible\nDeleting %s is not allowed",
  9361. path);
  9362. return;
  9363. }
  9364. /* Try to delete it. */
  9365. if (mg_remove(conn, path) == 0) {
  9366. /* Delete was successful: Return 204 without content. */
  9367. mg_send_http_error(conn, 204, "%s", "");
  9368. } else {
  9369. /* Delete not successful (file locked). */
  9370. mg_send_http_error(conn,
  9371. 423,
  9372. "Error: Cannot delete file\nremove(%s): %s",
  9373. path,
  9374. strerror(ERRNO));
  9375. }
  9376. }
  9377. #endif /* !NO_FILES */
  9378. static void
  9379. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9380. static void
  9381. do_ssi_include(struct mg_connection *conn,
  9382. const char *ssi,
  9383. char *tag,
  9384. int include_level)
  9385. {
  9386. char file_name[MG_BUF_LEN], path[512], *p;
  9387. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9388. size_t len;
  9389. int truncated = 0;
  9390. if (conn == NULL) {
  9391. return;
  9392. }
  9393. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9394. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9395. * always < MG_BUF_LEN. */
  9396. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9397. /* File name is relative to the webserver root */
  9398. file_name[511] = 0;
  9399. (void)mg_snprintf(conn,
  9400. &truncated,
  9401. path,
  9402. sizeof(path),
  9403. "%s/%s",
  9404. conn->dom_ctx->config[DOCUMENT_ROOT],
  9405. file_name);
  9406. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9407. /* File name is relative to the webserver working directory
  9408. * or it is absolute system path */
  9409. file_name[511] = 0;
  9410. (void)
  9411. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9412. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9413. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9414. /* File name is relative to the currect document */
  9415. file_name[511] = 0;
  9416. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9417. if (!truncated) {
  9418. if ((p = strrchr(path, '/')) != NULL) {
  9419. p[1] = '\0';
  9420. }
  9421. len = strlen(path);
  9422. (void)mg_snprintf(conn,
  9423. &truncated,
  9424. path + len,
  9425. sizeof(path) - len,
  9426. "%s",
  9427. file_name);
  9428. }
  9429. } else {
  9430. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9431. return;
  9432. }
  9433. if (truncated) {
  9434. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9435. return;
  9436. }
  9437. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9438. mg_cry_internal(conn,
  9439. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9440. tag,
  9441. path,
  9442. strerror(ERRNO));
  9443. } else {
  9444. fclose_on_exec(&file.access, conn);
  9445. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9446. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9447. path) > 0) {
  9448. send_ssi_file(conn, path, &file, include_level + 1);
  9449. } else {
  9450. send_file_data(conn, &file, 0, INT64_MAX);
  9451. }
  9452. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9453. }
  9454. }
  9455. #if !defined(NO_POPEN)
  9456. static void
  9457. do_ssi_exec(struct mg_connection *conn, char *tag)
  9458. {
  9459. char cmd[1024] = "";
  9460. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9461. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9462. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9463. } else {
  9464. cmd[1023] = 0;
  9465. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9466. mg_cry_internal(conn,
  9467. "Cannot SSI #exec: [%s]: %s",
  9468. cmd,
  9469. strerror(ERRNO));
  9470. } else {
  9471. send_file_data(conn, &file, 0, INT64_MAX);
  9472. pclose(file.access.fp);
  9473. }
  9474. }
  9475. }
  9476. #endif /* !NO_POPEN */
  9477. static int
  9478. mg_fgetc(struct mg_file *filep, int offset)
  9479. {
  9480. if (filep == NULL) {
  9481. return EOF;
  9482. }
  9483. if ((filep->access.membuf != NULL) && (offset >= 0)
  9484. && (((unsigned int)(offset)) < filep->stat.size)) {
  9485. return ((const unsigned char *)filep->access.membuf)[offset];
  9486. } else if (filep->access.fp != NULL) {
  9487. return fgetc(filep->access.fp);
  9488. } else {
  9489. return EOF;
  9490. }
  9491. }
  9492. static void
  9493. send_ssi_file(struct mg_connection *conn,
  9494. const char *path,
  9495. struct mg_file *filep,
  9496. int include_level)
  9497. {
  9498. char buf[MG_BUF_LEN];
  9499. int ch, offset, len, in_tag, in_ssi_tag;
  9500. if (include_level > 10) {
  9501. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  9502. return;
  9503. }
  9504. in_tag = in_ssi_tag = len = offset = 0;
  9505. /* Read file, byte by byte, and look for SSI include tags */
  9506. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9507. if (in_tag) {
  9508. /* We are in a tag, either SSI tag or html tag */
  9509. if (ch == '>') {
  9510. /* Tag is closing */
  9511. buf[len++] = '>';
  9512. if (in_ssi_tag) {
  9513. /* Handle SSI tag */
  9514. buf[len] = 0;
  9515. if (!memcmp(buf + 5, "include", 7)) {
  9516. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9517. #if !defined(NO_POPEN)
  9518. } else if (!memcmp(buf + 5, "exec", 4)) {
  9519. do_ssi_exec(conn, buf + 9);
  9520. #endif /* !NO_POPEN */
  9521. } else {
  9522. mg_cry_internal(conn,
  9523. "%s: unknown SSI "
  9524. "command: \"%s\"",
  9525. path,
  9526. buf);
  9527. }
  9528. len = 0;
  9529. in_ssi_tag = in_tag = 0;
  9530. } else {
  9531. /* Not an SSI tag */
  9532. /* Flush buffer */
  9533. (void)mg_write(conn, buf, (size_t)len);
  9534. len = 0;
  9535. in_tag = 0;
  9536. }
  9537. } else {
  9538. /* Tag is still open */
  9539. buf[len++] = (char)(ch & 0xff);
  9540. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9541. /* All SSI tags start with <!--# */
  9542. in_ssi_tag = 1;
  9543. }
  9544. if ((len + 2) > (int)sizeof(buf)) {
  9545. /* Tag to long for buffer */
  9546. mg_cry_internal(conn, "%s: tag is too large", path);
  9547. return;
  9548. }
  9549. }
  9550. } else {
  9551. /* We are not in a tag yet. */
  9552. if (ch == '<') {
  9553. /* Tag is opening */
  9554. in_tag = 1;
  9555. /* Flush current buffer */
  9556. (void)mg_write(conn, buf, (size_t)len);
  9557. /* Store the < */
  9558. len = 1;
  9559. buf[0] = '<';
  9560. } else {
  9561. /* No Tag */
  9562. /* Add data to buffer */
  9563. buf[len++] = (char)(ch & 0xff);
  9564. /* Flush if buffer is full */
  9565. if (len == (int)sizeof(buf)) {
  9566. mg_write(conn, buf, (size_t)len);
  9567. len = 0;
  9568. }
  9569. }
  9570. }
  9571. }
  9572. /* Send the rest of buffered data */
  9573. if (len > 0) {
  9574. mg_write(conn, buf, (size_t)len);
  9575. }
  9576. }
  9577. static void
  9578. handle_ssi_file_request(struct mg_connection *conn,
  9579. const char *path,
  9580. struct mg_file *filep)
  9581. {
  9582. char date[64];
  9583. time_t curtime = time(NULL);
  9584. const char *cors1, *cors2, *cors3;
  9585. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9586. return;
  9587. }
  9588. if (mg_get_header(conn, "Origin")) {
  9589. /* Cross-origin resource sharing (CORS). */
  9590. cors1 = "Access-Control-Allow-Origin: ";
  9591. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9592. cors3 = "\r\n";
  9593. } else {
  9594. cors1 = cors2 = cors3 = "";
  9595. }
  9596. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9597. /* File exists (precondition for calling this function),
  9598. * but can not be opened by the server. */
  9599. mg_send_http_error(conn,
  9600. 500,
  9601. "Error: Cannot read file\nfopen(%s): %s",
  9602. path,
  9603. strerror(ERRNO));
  9604. } else {
  9605. conn->must_close = 1;
  9606. gmt_time_string(date, sizeof(date), &curtime);
  9607. fclose_on_exec(&filep->access, conn);
  9608. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9609. send_no_cache_header(conn);
  9610. send_additional_header(conn);
  9611. mg_printf(conn,
  9612. "%s%s%s"
  9613. "Date: %s\r\n"
  9614. "Content-Type: text/html\r\n"
  9615. "Connection: %s\r\n\r\n",
  9616. cors1,
  9617. cors2,
  9618. cors3,
  9619. date,
  9620. suggest_connection_header(conn));
  9621. send_ssi_file(conn, path, filep, 0);
  9622. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9623. }
  9624. }
  9625. #if !defined(NO_FILES)
  9626. static void
  9627. send_options(struct mg_connection *conn)
  9628. {
  9629. char date[64];
  9630. time_t curtime = time(NULL);
  9631. if (!conn) {
  9632. return;
  9633. }
  9634. conn->status_code = 200;
  9635. conn->must_close = 1;
  9636. gmt_time_string(date, sizeof(date), &curtime);
  9637. /* We do not set a "Cache-Control" header here, but leave the default.
  9638. * Since browsers do not send an OPTIONS request, we can not test the
  9639. * effect anyway. */
  9640. mg_printf(conn,
  9641. "HTTP/1.1 200 OK\r\n"
  9642. "Date: %s\r\n"
  9643. "Connection: %s\r\n"
  9644. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9645. "PROPFIND, MKCOL\r\n"
  9646. "DAV: 1\r\n",
  9647. date,
  9648. suggest_connection_header(conn));
  9649. send_additional_header(conn);
  9650. mg_printf(conn, "\r\n");
  9651. }
  9652. /* Writes PROPFIND properties for a collection element */
  9653. static void
  9654. print_props(struct mg_connection *conn,
  9655. const char *uri,
  9656. struct mg_file_stat *filep)
  9657. {
  9658. char mtime[64];
  9659. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9660. return;
  9661. }
  9662. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9663. mg_printf(conn,
  9664. "<d:response>"
  9665. "<d:href>%s</d:href>"
  9666. "<d:propstat>"
  9667. "<d:prop>"
  9668. "<d:resourcetype>%s</d:resourcetype>"
  9669. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9670. "<d:getlastmodified>%s</d:getlastmodified>"
  9671. "</d:prop>"
  9672. "<d:status>HTTP/1.1 200 OK</d:status>"
  9673. "</d:propstat>"
  9674. "</d:response>\n",
  9675. uri,
  9676. filep->is_directory ? "<d:collection/>" : "",
  9677. filep->size,
  9678. mtime);
  9679. }
  9680. static int
  9681. print_dav_dir_entry(struct de *de, void *data)
  9682. {
  9683. char href[PATH_MAX];
  9684. int truncated;
  9685. struct mg_connection *conn = (struct mg_connection *)data;
  9686. if (!de || !conn) {
  9687. return -1;
  9688. }
  9689. mg_snprintf(conn,
  9690. &truncated,
  9691. href,
  9692. sizeof(href),
  9693. "%s%s",
  9694. conn->request_info.local_uri,
  9695. de->file_name);
  9696. if (!truncated) {
  9697. size_t href_encoded_size;
  9698. char *href_encoded;
  9699. href_encoded_size = PATH_MAX * 3; /* worst case */
  9700. href_encoded = (char *)mg_malloc(href_encoded_size);
  9701. if (href_encoded == NULL) {
  9702. return -1;
  9703. }
  9704. mg_url_encode(href, href_encoded, href_encoded_size);
  9705. print_props(conn, href_encoded, &de->file);
  9706. mg_free(href_encoded);
  9707. }
  9708. return 0;
  9709. }
  9710. static void
  9711. handle_propfind(struct mg_connection *conn,
  9712. const char *path,
  9713. struct mg_file_stat *filep)
  9714. {
  9715. const char *depth = mg_get_header(conn, "Depth");
  9716. char date[64];
  9717. time_t curtime = time(NULL);
  9718. gmt_time_string(date, sizeof(date), &curtime);
  9719. if (!conn || !path || !filep || !conn->dom_ctx) {
  9720. return;
  9721. }
  9722. conn->must_close = 1;
  9723. conn->status_code = 207;
  9724. mg_printf(conn,
  9725. "HTTP/1.1 207 Multi-Status\r\n"
  9726. "Date: %s\r\n",
  9727. date);
  9728. send_static_cache_header(conn);
  9729. send_additional_header(conn);
  9730. mg_printf(conn,
  9731. "Connection: %s\r\n"
  9732. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9733. suggest_connection_header(conn));
  9734. mg_printf(conn,
  9735. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9736. "<d:multistatus xmlns:d='DAV:'>\n");
  9737. /* Print properties for the requested resource itself */
  9738. print_props(conn, conn->request_info.local_uri, filep);
  9739. /* If it is a directory, print directory entries too if Depth is not 0
  9740. */
  9741. if (filep && filep->is_directory
  9742. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9743. "yes")
  9744. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9745. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9746. }
  9747. mg_printf(conn, "%s\n", "</d:multistatus>");
  9748. }
  9749. #endif
  9750. void
  9751. mg_lock_connection(struct mg_connection *conn)
  9752. {
  9753. if (conn) {
  9754. (void)pthread_mutex_lock(&conn->mutex);
  9755. }
  9756. }
  9757. void
  9758. mg_unlock_connection(struct mg_connection *conn)
  9759. {
  9760. if (conn) {
  9761. (void)pthread_mutex_unlock(&conn->mutex);
  9762. }
  9763. }
  9764. void
  9765. mg_lock_context(struct mg_context *ctx)
  9766. {
  9767. if (ctx) {
  9768. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9769. }
  9770. }
  9771. void
  9772. mg_unlock_context(struct mg_context *ctx)
  9773. {
  9774. if (ctx) {
  9775. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9776. }
  9777. }
  9778. #if defined(USE_TIMERS)
  9779. #define TIMER_API static
  9780. #include "timer.inl"
  9781. #endif /* USE_TIMERS */
  9782. #ifdef USE_LUA
  9783. #include "mod_lua.inl"
  9784. #endif /* USE_LUA */
  9785. #ifdef USE_DUKTAPE
  9786. #include "mod_duktape.inl"
  9787. #endif /* USE_DUKTAPE */
  9788. #if defined(USE_WEBSOCKET)
  9789. #if !defined(NO_SSL_DL)
  9790. #define SHA_API static
  9791. #include "sha1.inl"
  9792. #endif
  9793. static int
  9794. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9795. {
  9796. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9797. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9798. SHA_CTX sha_ctx;
  9799. int truncated;
  9800. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9801. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9802. if (truncated) {
  9803. conn->must_close = 1;
  9804. return 0;
  9805. }
  9806. DEBUG_TRACE("%s", "Send websocket handshake");
  9807. SHA1_Init(&sha_ctx);
  9808. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9809. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9810. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9811. mg_printf(conn,
  9812. "HTTP/1.1 101 Switching Protocols\r\n"
  9813. "Upgrade: websocket\r\n"
  9814. "Connection: Upgrade\r\n"
  9815. "Sec-WebSocket-Accept: %s\r\n",
  9816. b64_sha);
  9817. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9818. mg_printf(conn,
  9819. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9820. conn->request_info.acceptedWebSocketSubprotocol);
  9821. } else {
  9822. mg_printf(conn, "%s", "\r\n");
  9823. }
  9824. return 1;
  9825. }
  9826. static void
  9827. read_websocket(struct mg_connection *conn,
  9828. mg_websocket_data_handler ws_data_handler,
  9829. void *callback_data)
  9830. {
  9831. /* Pointer to the beginning of the portion of the incoming websocket
  9832. * message queue.
  9833. * The original websocket upgrade request is never removed, so the queue
  9834. * begins after it. */
  9835. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9836. int n, error, exit_by_callback;
  9837. /* body_len is the length of the entire queue in bytes
  9838. * len is the length of the current message
  9839. * data_len is the length of the current message's data payload
  9840. * header_len is the length of the current message's header */
  9841. size_t i, len, mask_len = 0, header_len, body_len;
  9842. uint64_t data_len = 0;
  9843. /* "The masking key is a 32-bit value chosen at random by the client."
  9844. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9845. */
  9846. unsigned char mask[4];
  9847. /* data points to the place where the message is stored when passed to
  9848. * the
  9849. * websocket_data callback. This is either mem on the stack, or a
  9850. * dynamically allocated buffer if it is too large. */
  9851. unsigned char mem[4096];
  9852. unsigned char mop; /* mask flag and opcode */
  9853. double timeout = -1.0;
  9854. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  9855. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9856. }
  9857. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  9858. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9859. }
  9860. conn->in_websocket_handling = 1;
  9861. mg_set_thread_name("wsock");
  9862. /* Loop continuously, reading messages from the socket, invoking the
  9863. * callback, and waiting repeatedly until an error occurs. */
  9864. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  9865. header_len = 0;
  9866. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  9867. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9868. len = buf[1] & 127;
  9869. mask_len = (buf[1] & 128) ? 4 : 0;
  9870. if ((len < 126) && (body_len >= mask_len)) {
  9871. /* inline 7-bit length field */
  9872. data_len = len;
  9873. header_len = 2 + mask_len;
  9874. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9875. /* 16-bit length field */
  9876. header_len = 4 + mask_len;
  9877. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9878. } else if (body_len >= (10 + mask_len)) {
  9879. /* 64-bit length field */
  9880. uint32_t l1, l2;
  9881. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9882. memcpy(&l2, &buf[6], 4);
  9883. header_len = 10 + mask_len;
  9884. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9885. if (data_len > (uint64_t)0x7FFF0000ul) {
  9886. /* no can do */
  9887. mg_cry_internal(
  9888. conn,
  9889. "%s",
  9890. "websocket out of memory; closing connection");
  9891. break;
  9892. }
  9893. }
  9894. }
  9895. if ((header_len > 0) && (body_len >= header_len)) {
  9896. /* Allocate space to hold websocket payload */
  9897. unsigned char *data = mem;
  9898. if ((size_t)data_len > (size_t)sizeof(mem)) {
  9899. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  9900. conn->phys_ctx);
  9901. if (data == NULL) {
  9902. /* Allocation failed, exit the loop and then close the
  9903. * connection */
  9904. mg_cry_internal(
  9905. conn,
  9906. "%s",
  9907. "websocket out of memory; closing connection");
  9908. break;
  9909. }
  9910. }
  9911. /* Copy the mask before we shift the queue and destroy it */
  9912. if (mask_len > 0) {
  9913. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9914. } else {
  9915. memset(mask, 0, sizeof(mask));
  9916. }
  9917. /* Read frame payload from the first message in the queue into
  9918. * data and advance the queue by moving the memory in place. */
  9919. DEBUG_ASSERT(body_len >= header_len);
  9920. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  9921. mop = buf[0]; /* current mask and opcode */
  9922. /* Overflow case */
  9923. len = body_len - header_len;
  9924. memcpy(data, buf + header_len, len);
  9925. error = 0;
  9926. while ((uint64_t)len < data_len) {
  9927. n = pull_inner(NULL,
  9928. conn,
  9929. (char *)(data + len),
  9930. (int)(data_len - len),
  9931. timeout);
  9932. if (n <= -2) {
  9933. error = 1;
  9934. break;
  9935. } else if (n > 0) {
  9936. len += (size_t)n;
  9937. } else {
  9938. /* Timeout: should retry */
  9939. /* TODO: retry condition */
  9940. }
  9941. }
  9942. if (error) {
  9943. mg_cry_internal(
  9944. conn,
  9945. "%s",
  9946. "Websocket pull failed; closing connection");
  9947. if (data != mem) {
  9948. mg_free(data);
  9949. }
  9950. break;
  9951. }
  9952. conn->data_len = conn->request_len;
  9953. } else {
  9954. mop = buf[0]; /* current mask and opcode, overwritten by
  9955. * memmove() */
  9956. /* Length of the message being read at the front of the
  9957. * queue. Cast to 31 bit is OK, since we limited
  9958. * data_len before. */
  9959. len = (size_t)data_len + header_len;
  9960. /* Copy the data payload into the data pointer for the
  9961. * callback. Cast to 31 bit is OK, since we
  9962. * limited data_len */
  9963. memcpy(data, buf + header_len, (size_t)data_len);
  9964. /* Move the queue forward len bytes */
  9965. memmove(buf, buf + len, body_len - len);
  9966. /* Mark the queue as advanced */
  9967. conn->data_len -= (int)len;
  9968. }
  9969. /* Apply mask if necessary */
  9970. if (mask_len > 0) {
  9971. for (i = 0; i < (size_t)data_len; i++) {
  9972. data[i] ^= mask[i & 3];
  9973. }
  9974. }
  9975. /* Exit the loop if callback signals to exit (server side),
  9976. * or "connection close" opcode received (client side). */
  9977. exit_by_callback = 0;
  9978. if ((ws_data_handler != NULL)
  9979. && !ws_data_handler(conn,
  9980. mop,
  9981. (char *)data,
  9982. (size_t)data_len,
  9983. callback_data)) {
  9984. exit_by_callback = 1;
  9985. }
  9986. if (data != mem) {
  9987. mg_free(data);
  9988. }
  9989. if (exit_by_callback
  9990. || ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9991. /* Opcode == 8, connection close */
  9992. break;
  9993. }
  9994. /* Not breaking the loop, process next websocket frame. */
  9995. } else {
  9996. /* Read from the socket into the next available location in the
  9997. * message queue. */
  9998. n = pull_inner(NULL,
  9999. conn,
  10000. conn->buf + conn->data_len,
  10001. conn->buf_size - conn->data_len,
  10002. timeout);
  10003. if (n <= -2) {
  10004. /* Error, no bytes read */
  10005. break;
  10006. }
  10007. if (n > 0) {
  10008. conn->data_len += n;
  10009. } else {
  10010. /* Timeout: should retry */
  10011. /* TODO: get timeout def */
  10012. }
  10013. }
  10014. }
  10015. mg_set_thread_name("worker");
  10016. conn->in_websocket_handling = 0;
  10017. }
  10018. static int
  10019. mg_websocket_write_exec(struct mg_connection *conn,
  10020. int opcode,
  10021. const char *data,
  10022. size_t dataLen,
  10023. uint32_t masking_key)
  10024. {
  10025. unsigned char header[14];
  10026. size_t headerLen = 1;
  10027. int retval = -1;
  10028. #if defined(__GNUC__) || defined(__MINGW32__)
  10029. /* Disable spurious conversion warning for GCC */
  10030. #pragma GCC diagnostic push
  10031. #pragma GCC diagnostic ignored "-Wconversion"
  10032. #endif
  10033. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10034. #if defined(__GNUC__) || defined(__MINGW32__)
  10035. #pragma GCC diagnostic pop
  10036. #endif
  10037. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10038. if (dataLen < 126) {
  10039. /* inline 7-bit length field */
  10040. header[1] = (unsigned char)dataLen;
  10041. headerLen = 2;
  10042. } else if (dataLen <= 0xFFFF) {
  10043. /* 16-bit length field */
  10044. uint16_t len = htons((uint16_t)dataLen);
  10045. header[1] = 126;
  10046. memcpy(header + 2, &len, 2);
  10047. headerLen = 4;
  10048. } else {
  10049. /* 64-bit length field */
  10050. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10051. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10052. header[1] = 127;
  10053. memcpy(header + 2, &len1, 4);
  10054. memcpy(header + 6, &len2, 4);
  10055. headerLen = 10;
  10056. }
  10057. if (masking_key) {
  10058. /* add mask */
  10059. header[1] |= 0x80;
  10060. memcpy(header + headerLen, &masking_key, 4);
  10061. headerLen += 4;
  10062. }
  10063. /* Note that POSIX/Winsock's send() is threadsafe
  10064. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10065. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10066. * push(), although that is only a problem if the packet is large or
  10067. * outgoing buffer is full). */
  10068. /* TODO: Check if this lock should be moved to user land.
  10069. * Currently the server sets this lock for websockets, but
  10070. * not for any other connection. It must be set for every
  10071. * conn read/written by more than one thread, no matter if
  10072. * it is a websocket or regular connection. */
  10073. (void)mg_lock_connection(conn);
  10074. retval = mg_write(conn, header, headerLen);
  10075. if (dataLen > 0) {
  10076. retval = mg_write(conn, data, dataLen);
  10077. }
  10078. /* TODO: Remove this unlock as well, when lock is moved. */
  10079. mg_unlock_connection(conn);
  10080. return retval;
  10081. }
  10082. int
  10083. mg_websocket_write(struct mg_connection *conn,
  10084. int opcode,
  10085. const char *data,
  10086. size_t dataLen)
  10087. {
  10088. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10089. }
  10090. static void
  10091. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10092. {
  10093. size_t i = 0;
  10094. i = 0;
  10095. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10096. /* Convert in 32 bit words, if data is 4 byte aligned */
  10097. while (i < (in_len - 3)) {
  10098. *(uint32_t *)(void *)(out + i) =
  10099. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10100. i += 4;
  10101. }
  10102. }
  10103. if (i != in_len) {
  10104. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10105. while (i < in_len) {
  10106. *(uint8_t *)(void *)(out + i) =
  10107. *(uint8_t *)(void *)(in + i)
  10108. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10109. i++;
  10110. }
  10111. }
  10112. }
  10113. int
  10114. mg_websocket_client_write(struct mg_connection *conn,
  10115. int opcode,
  10116. const char *data,
  10117. size_t dataLen)
  10118. {
  10119. int retval = -1;
  10120. char *masked_data =
  10121. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10122. uint32_t masking_key = (uint32_t)get_random();
  10123. if (masked_data == NULL) {
  10124. /* Return -1 in an error case */
  10125. mg_cry_internal(conn,
  10126. "%s",
  10127. "Cannot allocate buffer for masked websocket response: "
  10128. "Out of memory");
  10129. return -1;
  10130. }
  10131. mask_data(data, dataLen, masking_key, masked_data);
  10132. retval = mg_websocket_write_exec(
  10133. conn, opcode, masked_data, dataLen, masking_key);
  10134. mg_free(masked_data);
  10135. return retval;
  10136. }
  10137. static void
  10138. handle_websocket_request(struct mg_connection *conn,
  10139. const char *path,
  10140. int is_callback_resource,
  10141. struct mg_websocket_subprotocols *subprotocols,
  10142. mg_websocket_connect_handler ws_connect_handler,
  10143. mg_websocket_ready_handler ws_ready_handler,
  10144. mg_websocket_data_handler ws_data_handler,
  10145. mg_websocket_close_handler ws_close_handler,
  10146. void *cbData)
  10147. {
  10148. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10149. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10150. int lua_websock = 0;
  10151. #if !defined(USE_LUA)
  10152. (void)path;
  10153. #endif
  10154. /* Step 1: Check websocket protocol version. */
  10155. /* Step 1.1: Check Sec-WebSocket-Key. */
  10156. if (!websock_key) {
  10157. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10158. * requires a Sec-WebSocket-Key header.
  10159. */
  10160. /* It could be the hixie draft version
  10161. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10162. */
  10163. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10164. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10165. char key3[8];
  10166. if ((key1 != NULL) && (key2 != NULL)) {
  10167. /* This version uses 8 byte body data in a GET request */
  10168. conn->content_len = 8;
  10169. if (8 == mg_read(conn, key3, 8)) {
  10170. /* This is the hixie version */
  10171. mg_send_http_error(conn,
  10172. 426,
  10173. "%s",
  10174. "Protocol upgrade to RFC 6455 required");
  10175. return;
  10176. }
  10177. }
  10178. /* This is an unknown version */
  10179. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10180. return;
  10181. }
  10182. /* Step 1.2: Check websocket protocol version. */
  10183. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10184. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10185. /* Reject wrong versions */
  10186. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10187. return;
  10188. }
  10189. /* Step 1.3: Could check for "Host", but we do not really nead this
  10190. * value for anything, so just ignore it. */
  10191. /* Step 2: If a callback is responsible, call it. */
  10192. if (is_callback_resource) {
  10193. /* Step 2.1 check and select subprotocol */
  10194. const char *protocols[64]; // max 64 headers
  10195. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10196. "Sec-WebSocket-Protocol",
  10197. protocols,
  10198. 64);
  10199. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10200. int cnt = 0;
  10201. int idx;
  10202. unsigned long len;
  10203. const char *sep, *curSubProtocol,
  10204. *acceptedWebSocketSubprotocol = NULL;
  10205. /* look for matching subprotocol */
  10206. do {
  10207. const char *protocol = protocols[cnt];
  10208. do {
  10209. sep = strchr(protocol, ',');
  10210. curSubProtocol = protocol;
  10211. len = sep ? (unsigned long)(sep - protocol)
  10212. : (unsigned long)strlen(protocol);
  10213. while (sep && isspace(*++sep))
  10214. ; // ignore leading whitespaces
  10215. protocol = sep;
  10216. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10217. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10218. && (strncmp(curSubProtocol,
  10219. subprotocols->subprotocols[idx],
  10220. len) == 0)) {
  10221. acceptedWebSocketSubprotocol =
  10222. subprotocols->subprotocols[idx];
  10223. break;
  10224. }
  10225. }
  10226. } while (sep && !acceptedWebSocketSubprotocol);
  10227. } while (++cnt < nbSubprotocolHeader
  10228. && !acceptedWebSocketSubprotocol);
  10229. conn->request_info.acceptedWebSocketSubprotocol =
  10230. acceptedWebSocketSubprotocol;
  10231. } else if (nbSubprotocolHeader > 0) {
  10232. /* keep legacy behavior */
  10233. const char *protocol = protocols[0];
  10234. /* The protocol is a comma separated list of names. */
  10235. /* The server must only return one value from this list. */
  10236. /* First check if it is a list or just a single value. */
  10237. const char *sep = strrchr(protocol, ',');
  10238. if (sep == NULL) {
  10239. /* Just a single protocol -> accept it. */
  10240. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10241. } else {
  10242. /* Multiple protocols -> accept the last one. */
  10243. /* This is just a quick fix if the client offers multiple
  10244. * protocols. The handler should have a list of accepted
  10245. * protocols on his own
  10246. * and use it to select one protocol among those the client
  10247. * has
  10248. * offered.
  10249. */
  10250. while (isspace(*++sep)) {
  10251. ; /* ignore leading whitespaces */
  10252. }
  10253. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10254. }
  10255. }
  10256. if ((ws_connect_handler != NULL)
  10257. && (ws_connect_handler(conn, cbData) != 0)) {
  10258. /* C callback has returned non-zero, do not proceed with
  10259. * handshake.
  10260. */
  10261. /* Note that C callbacks are no longer called when Lua is
  10262. * responsible, so C can no longer filter callbacks for Lua. */
  10263. return;
  10264. }
  10265. }
  10266. #if defined(USE_LUA)
  10267. /* Step 3: No callback. Check if Lua is responsible. */
  10268. else {
  10269. /* Step 3.1: Check if Lua is responsible. */
  10270. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10271. lua_websock = match_prefix(
  10272. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10273. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10274. path);
  10275. }
  10276. if (lua_websock) {
  10277. /* Step 3.2: Lua is responsible: call it. */
  10278. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10279. if (!conn->lua_websocket_state) {
  10280. /* Lua rejected the new client */
  10281. return;
  10282. }
  10283. }
  10284. }
  10285. #endif
  10286. /* Step 4: Check if there is a responsible websocket handler. */
  10287. if (!is_callback_resource && !lua_websock) {
  10288. /* There is no callback, and Lua is not responsible either. */
  10289. /* Reply with a 404 Not Found. We are still at a standard
  10290. * HTTP request here, before the websocket handshake, so
  10291. * we can still send standard HTTP error replies. */
  10292. mg_send_http_error(conn, 404, "%s", "Not found");
  10293. return;
  10294. }
  10295. /* Step 5: The websocket connection has been accepted */
  10296. if (!send_websocket_handshake(conn, websock_key)) {
  10297. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10298. return;
  10299. }
  10300. /* Step 6: Call the ready handler */
  10301. if (is_callback_resource) {
  10302. if (ws_ready_handler != NULL) {
  10303. ws_ready_handler(conn, cbData);
  10304. }
  10305. #if defined(USE_LUA)
  10306. } else if (lua_websock) {
  10307. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10308. /* the ready handler returned false */
  10309. return;
  10310. }
  10311. #endif
  10312. }
  10313. /* Step 7: Enter the read loop */
  10314. if (is_callback_resource) {
  10315. read_websocket(conn, ws_data_handler, cbData);
  10316. #if defined(USE_LUA)
  10317. } else if (lua_websock) {
  10318. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10319. #endif
  10320. }
  10321. /* Step 8: Call the close handler */
  10322. if (ws_close_handler) {
  10323. ws_close_handler(conn, cbData);
  10324. }
  10325. }
  10326. static int
  10327. is_websocket_protocol(const struct mg_connection *conn)
  10328. {
  10329. const char *upgrade, *connection;
  10330. /* A websocket protocoll has the following HTTP headers:
  10331. *
  10332. * Connection: Upgrade
  10333. * Upgrade: Websocket
  10334. */
  10335. upgrade = mg_get_header(conn, "Upgrade");
  10336. if (upgrade == NULL) {
  10337. return 0; /* fail early, don't waste time checking other header
  10338. * fields
  10339. */
  10340. }
  10341. if (!mg_strcasestr(upgrade, "websocket")) {
  10342. return 0;
  10343. }
  10344. connection = mg_get_header(conn, "Connection");
  10345. if (connection == NULL) {
  10346. return 0;
  10347. }
  10348. if (!mg_strcasestr(connection, "upgrade")) {
  10349. return 0;
  10350. }
  10351. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10352. * "Sec-WebSocket-Version" are also required.
  10353. * Don't check them here, since even an unsupported websocket protocol
  10354. * request still IS a websocket request (in contrast to a standard HTTP
  10355. * request). It will fail later in handle_websocket_request.
  10356. */
  10357. return 1;
  10358. }
  10359. #endif /* !USE_WEBSOCKET */
  10360. static int
  10361. isbyte(int n)
  10362. {
  10363. return (n >= 0) && (n <= 255);
  10364. }
  10365. static int
  10366. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10367. {
  10368. int n, a, b, c, d, slash = 32, len = 0;
  10369. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10370. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10371. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10372. && (slash < 33)) {
  10373. len = n;
  10374. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10375. | (uint32_t)d;
  10376. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10377. }
  10378. return len;
  10379. }
  10380. static int
  10381. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10382. {
  10383. int throttle = 0;
  10384. struct vec vec, val;
  10385. uint32_t net, mask;
  10386. char mult;
  10387. double v;
  10388. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10389. mult = ',';
  10390. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10391. || (v < 0) || ((lowercase(&mult) != 'k')
  10392. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10393. continue;
  10394. }
  10395. v *= (lowercase(&mult) == 'k')
  10396. ? 1024
  10397. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10398. if (vec.len == 1 && vec.ptr[0] == '*') {
  10399. throttle = (int)v;
  10400. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10401. if ((remote_ip & mask) == net) {
  10402. throttle = (int)v;
  10403. }
  10404. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10405. throttle = (int)v;
  10406. }
  10407. }
  10408. return throttle;
  10409. }
  10410. static uint32_t
  10411. get_remote_ip(const struct mg_connection *conn)
  10412. {
  10413. if (!conn) {
  10414. return 0;
  10415. }
  10416. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10417. }
  10418. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10419. #include "handle_form.inl"
  10420. #if defined(MG_LEGACY_INTERFACE)
  10421. /* Implement the deprecated mg_upload function by calling the new
  10422. * mg_handle_form_request function. While mg_upload could only handle
  10423. * HTML forms sent as POST request in multipart/form-data format
  10424. * containing only file input elements, mg_handle_form_request can
  10425. * handle all form input elements and all standard request methods. */
  10426. struct mg_upload_user_data {
  10427. struct mg_connection *conn;
  10428. const char *destination_dir;
  10429. int num_uploaded_files;
  10430. };
  10431. /* Helper function for deprecated mg_upload. */
  10432. static int
  10433. mg_upload_field_found(const char *key,
  10434. const char *filename,
  10435. char *path,
  10436. size_t pathlen,
  10437. void *user_data)
  10438. {
  10439. int truncated = 0;
  10440. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10441. (void)key;
  10442. if (!filename) {
  10443. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  10444. return FORM_FIELD_STORAGE_ABORT;
  10445. }
  10446. mg_snprintf(fud->conn,
  10447. &truncated,
  10448. path,
  10449. pathlen - 1,
  10450. "%s/%s",
  10451. fud->destination_dir,
  10452. filename);
  10453. if (truncated) {
  10454. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  10455. return FORM_FIELD_STORAGE_ABORT;
  10456. }
  10457. return FORM_FIELD_STORAGE_STORE;
  10458. }
  10459. /* Helper function for deprecated mg_upload. */
  10460. static int
  10461. mg_upload_field_get(const char *key,
  10462. const char *value,
  10463. size_t value_size,
  10464. void *user_data)
  10465. {
  10466. /* Function should never be called */
  10467. (void)key;
  10468. (void)value;
  10469. (void)value_size;
  10470. (void)user_data;
  10471. return 0;
  10472. }
  10473. /* Helper function for deprecated mg_upload. */
  10474. static int
  10475. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10476. {
  10477. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10478. (void)file_size;
  10479. fud->num_uploaded_files++;
  10480. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  10481. return 0;
  10482. }
  10483. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10484. int
  10485. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10486. {
  10487. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10488. struct mg_form_data_handler fdh = {mg_upload_field_found,
  10489. mg_upload_field_get,
  10490. mg_upload_field_stored,
  10491. 0};
  10492. int ret;
  10493. fdh.user_data = (void *)&fud;
  10494. ret = mg_handle_form_request(conn, &fdh);
  10495. if (ret < 0) {
  10496. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  10497. }
  10498. return fud.num_uploaded_files;
  10499. }
  10500. #endif
  10501. static int
  10502. get_first_ssl_listener_index(const struct mg_context *ctx)
  10503. {
  10504. unsigned int i;
  10505. int idx = -1;
  10506. if (ctx) {
  10507. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  10508. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  10509. }
  10510. }
  10511. return idx;
  10512. }
  10513. /* Return host (without port) */
  10514. /* Use mg_free to free the result */
  10515. static const char *
  10516. alloc_get_host(struct mg_connection *conn)
  10517. {
  10518. char host[1025];
  10519. const char *host_header;
  10520. size_t hostlen;
  10521. host_header = get_header(conn->request_info.http_headers,
  10522. conn->request_info.num_headers,
  10523. "Host");
  10524. hostlen = sizeof(host);
  10525. if (host_header != NULL) {
  10526. char *pos;
  10527. mg_strlcpy(host, host_header, hostlen);
  10528. host[hostlen - 1] = '\0';
  10529. pos = strchr(host, ':');
  10530. if (pos != NULL) {
  10531. *pos = '\0';
  10532. }
  10533. if (conn->ssl) {
  10534. /* This is a HTTPS connection, maybe we have a hostname
  10535. * from SNI (set in ssl_servername_callback). */
  10536. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  10537. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  10538. /* We are not using the default domain */
  10539. if (mg_strcasecmp(host, sslhost)) {
  10540. /* Mismatch between SNI domain and HTTP domain */
  10541. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  10542. sslhost,
  10543. host);
  10544. return NULL;
  10545. }
  10546. }
  10547. DEBUG_TRACE("HTTPS Host: %s", host);
  10548. } else {
  10549. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  10550. while (dom) {
  10551. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  10552. /* Found matching domain */
  10553. DEBUG_TRACE("HTTP domain %s found",
  10554. dom->config[AUTHENTICATION_DOMAIN]);
  10555. /* TODO: Check if this is a HTTP or HTTPS domain */
  10556. conn->dom_ctx = dom;
  10557. break;
  10558. }
  10559. dom = dom->next;
  10560. }
  10561. DEBUG_TRACE("HTTP Host: %s", host);
  10562. }
  10563. } else {
  10564. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  10565. DEBUG_TRACE("IP: %s", host);
  10566. }
  10567. return mg_strdup_ctx(host, conn->phys_ctx);
  10568. }
  10569. static void
  10570. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  10571. {
  10572. conn->must_close = 1;
  10573. /* Send host, port, uri and (if it exists) ?query_string */
  10574. if (conn->host) {
  10575. mg_printf(conn,
  10576. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  10577. conn->host,
  10578. #if defined(USE_IPV6)
  10579. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  10580. == AF_INET6)
  10581. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10582. .lsa.sin6.sin6_port)
  10583. :
  10584. #endif
  10585. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10586. .lsa.sin.sin_port),
  10587. conn->request_info.local_uri,
  10588. (conn->request_info.query_string == NULL) ? "" : "?",
  10589. (conn->request_info.query_string == NULL)
  10590. ? ""
  10591. : conn->request_info.query_string);
  10592. }
  10593. }
  10594. static void
  10595. mg_set_handler_type(struct mg_context *phys_ctx,
  10596. struct mg_domain_context *dom_ctx,
  10597. const char *uri,
  10598. int handler_type,
  10599. int is_delete_request,
  10600. mg_request_handler handler,
  10601. struct mg_websocket_subprotocols *subprotocols,
  10602. mg_websocket_connect_handler connect_handler,
  10603. mg_websocket_ready_handler ready_handler,
  10604. mg_websocket_data_handler data_handler,
  10605. mg_websocket_close_handler close_handler,
  10606. mg_authorization_handler auth_handler,
  10607. void *cbdata)
  10608. {
  10609. struct mg_handler_info *tmp_rh, **lastref;
  10610. size_t urilen = strlen(uri);
  10611. if (handler_type == WEBSOCKET_HANDLER) {
  10612. DEBUG_ASSERT(handler == NULL);
  10613. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  10614. || ready_handler != NULL
  10615. || data_handler != NULL
  10616. || close_handler != NULL);
  10617. DEBUG_ASSERT(auth_handler == NULL);
  10618. if (handler != NULL) {
  10619. return;
  10620. }
  10621. if (!is_delete_request && (connect_handler == NULL)
  10622. && (ready_handler == NULL) && (data_handler == NULL)
  10623. && (close_handler == NULL)) {
  10624. return;
  10625. }
  10626. if (auth_handler != NULL) {
  10627. return;
  10628. }
  10629. } else if (handler_type == REQUEST_HANDLER) {
  10630. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  10631. && data_handler == NULL
  10632. && close_handler == NULL);
  10633. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  10634. DEBUG_ASSERT(auth_handler == NULL);
  10635. if ((connect_handler != NULL) || (ready_handler != NULL)
  10636. || (data_handler != NULL) || (close_handler != NULL)) {
  10637. return;
  10638. }
  10639. if (!is_delete_request && (handler == NULL)) {
  10640. return;
  10641. }
  10642. if (auth_handler != NULL) {
  10643. return;
  10644. }
  10645. } else { /* AUTH_HANDLER */
  10646. DEBUG_ASSERT(handler == NULL);
  10647. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  10648. && data_handler == NULL
  10649. && close_handler == NULL);
  10650. DEBUG_ASSERT(auth_handler != NULL);
  10651. if (handler != NULL) {
  10652. return;
  10653. }
  10654. if ((connect_handler != NULL) || (ready_handler != NULL)
  10655. || (data_handler != NULL) || (close_handler != NULL)) {
  10656. return;
  10657. }
  10658. if (!is_delete_request && (auth_handler == NULL)) {
  10659. return;
  10660. }
  10661. }
  10662. if (!phys_ctx || !dom_ctx) {
  10663. return;
  10664. }
  10665. mg_lock_context(phys_ctx);
  10666. /* first try to find an existing handler */
  10667. lastref = &(dom_ctx->handlers);
  10668. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10669. if (tmp_rh->handler_type == handler_type) {
  10670. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10671. if (!is_delete_request) {
  10672. /* update existing handler */
  10673. if (handler_type == REQUEST_HANDLER) {
  10674. tmp_rh->handler = handler;
  10675. } else if (handler_type == WEBSOCKET_HANDLER) {
  10676. tmp_rh->subprotocols = subprotocols;
  10677. tmp_rh->connect_handler = connect_handler;
  10678. tmp_rh->ready_handler = ready_handler;
  10679. tmp_rh->data_handler = data_handler;
  10680. tmp_rh->close_handler = close_handler;
  10681. } else { /* AUTH_HANDLER */
  10682. tmp_rh->auth_handler = auth_handler;
  10683. }
  10684. tmp_rh->cbdata = cbdata;
  10685. } else {
  10686. /* remove existing handler */
  10687. *lastref = tmp_rh->next;
  10688. mg_free(tmp_rh->uri);
  10689. mg_free(tmp_rh);
  10690. }
  10691. mg_unlock_context(phys_ctx);
  10692. return;
  10693. }
  10694. }
  10695. lastref = &(tmp_rh->next);
  10696. }
  10697. if (is_delete_request) {
  10698. /* no handler to set, this was a remove request to a non-existing
  10699. * handler */
  10700. mg_unlock_context(phys_ctx);
  10701. return;
  10702. }
  10703. tmp_rh =
  10704. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  10705. 1,
  10706. phys_ctx);
  10707. if (tmp_rh == NULL) {
  10708. mg_unlock_context(phys_ctx);
  10709. mg_cry_internal(fc(phys_ctx),
  10710. "%s",
  10711. "Cannot create new request handler struct, OOM");
  10712. return;
  10713. }
  10714. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  10715. if (!tmp_rh->uri) {
  10716. mg_unlock_context(phys_ctx);
  10717. mg_free(tmp_rh);
  10718. mg_cry_internal(fc(phys_ctx),
  10719. "%s",
  10720. "Cannot create new request handler struct, OOM");
  10721. return;
  10722. }
  10723. tmp_rh->uri_len = urilen;
  10724. if (handler_type == REQUEST_HANDLER) {
  10725. tmp_rh->handler = handler;
  10726. } else if (handler_type == WEBSOCKET_HANDLER) {
  10727. tmp_rh->subprotocols = subprotocols;
  10728. tmp_rh->connect_handler = connect_handler;
  10729. tmp_rh->ready_handler = ready_handler;
  10730. tmp_rh->data_handler = data_handler;
  10731. tmp_rh->close_handler = close_handler;
  10732. } else { /* AUTH_HANDLER */
  10733. tmp_rh->auth_handler = auth_handler;
  10734. }
  10735. tmp_rh->cbdata = cbdata;
  10736. tmp_rh->handler_type = handler_type;
  10737. tmp_rh->next = NULL;
  10738. *lastref = tmp_rh;
  10739. mg_unlock_context(phys_ctx);
  10740. }
  10741. void
  10742. mg_set_request_handler(struct mg_context *ctx,
  10743. const char *uri,
  10744. mg_request_handler handler,
  10745. void *cbdata)
  10746. {
  10747. mg_set_handler_type(ctx,
  10748. &(ctx->dd),
  10749. uri,
  10750. REQUEST_HANDLER,
  10751. handler == NULL,
  10752. handler,
  10753. NULL,
  10754. NULL,
  10755. NULL,
  10756. NULL,
  10757. NULL,
  10758. NULL,
  10759. cbdata);
  10760. }
  10761. void
  10762. mg_set_websocket_handler(struct mg_context *ctx,
  10763. const char *uri,
  10764. mg_websocket_connect_handler connect_handler,
  10765. mg_websocket_ready_handler ready_handler,
  10766. mg_websocket_data_handler data_handler,
  10767. mg_websocket_close_handler close_handler,
  10768. void *cbdata)
  10769. {
  10770. mg_set_websocket_handler_with_subprotocols(ctx,
  10771. uri,
  10772. NULL,
  10773. connect_handler,
  10774. ready_handler,
  10775. data_handler,
  10776. close_handler,
  10777. cbdata);
  10778. }
  10779. void
  10780. mg_set_websocket_handler_with_subprotocols(
  10781. struct mg_context *ctx,
  10782. const char *uri,
  10783. struct mg_websocket_subprotocols *subprotocols,
  10784. mg_websocket_connect_handler connect_handler,
  10785. mg_websocket_ready_handler ready_handler,
  10786. mg_websocket_data_handler data_handler,
  10787. mg_websocket_close_handler close_handler,
  10788. void *cbdata)
  10789. {
  10790. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  10791. && (data_handler == NULL)
  10792. && (close_handler == NULL);
  10793. mg_set_handler_type(ctx,
  10794. &(ctx->dd),
  10795. uri,
  10796. WEBSOCKET_HANDLER,
  10797. is_delete_request,
  10798. NULL,
  10799. subprotocols,
  10800. connect_handler,
  10801. ready_handler,
  10802. data_handler,
  10803. close_handler,
  10804. NULL,
  10805. cbdata);
  10806. }
  10807. void
  10808. mg_set_auth_handler(struct mg_context *ctx,
  10809. const char *uri,
  10810. mg_request_handler handler,
  10811. void *cbdata)
  10812. {
  10813. mg_set_handler_type(ctx,
  10814. &(ctx->dd),
  10815. uri,
  10816. AUTH_HANDLER,
  10817. handler == NULL,
  10818. NULL,
  10819. NULL,
  10820. NULL,
  10821. NULL,
  10822. NULL,
  10823. NULL,
  10824. handler,
  10825. cbdata);
  10826. }
  10827. static int
  10828. get_request_handler(struct mg_connection *conn,
  10829. int handler_type,
  10830. mg_request_handler *handler,
  10831. struct mg_websocket_subprotocols **subprotocols,
  10832. mg_websocket_connect_handler *connect_handler,
  10833. mg_websocket_ready_handler *ready_handler,
  10834. mg_websocket_data_handler *data_handler,
  10835. mg_websocket_close_handler *close_handler,
  10836. mg_authorization_handler *auth_handler,
  10837. void **cbdata)
  10838. {
  10839. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10840. if (request_info) {
  10841. const char *uri = request_info->local_uri;
  10842. size_t urilen = strlen(uri);
  10843. struct mg_handler_info *tmp_rh;
  10844. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  10845. return 0;
  10846. }
  10847. mg_lock_context(conn->phys_ctx);
  10848. /* first try for an exact match */
  10849. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10850. tmp_rh = tmp_rh->next) {
  10851. if (tmp_rh->handler_type == handler_type) {
  10852. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10853. if (handler_type == WEBSOCKET_HANDLER) {
  10854. *subprotocols = tmp_rh->subprotocols;
  10855. *connect_handler = tmp_rh->connect_handler;
  10856. *ready_handler = tmp_rh->ready_handler;
  10857. *data_handler = tmp_rh->data_handler;
  10858. *close_handler = tmp_rh->close_handler;
  10859. } else if (handler_type == REQUEST_HANDLER) {
  10860. *handler = tmp_rh->handler;
  10861. } else { /* AUTH_HANDLER */
  10862. *auth_handler = tmp_rh->auth_handler;
  10863. }
  10864. *cbdata = tmp_rh->cbdata;
  10865. mg_unlock_context(conn->phys_ctx);
  10866. return 1;
  10867. }
  10868. }
  10869. }
  10870. /* next try for a partial match, we will accept uri/something */
  10871. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10872. tmp_rh = tmp_rh->next) {
  10873. if (tmp_rh->handler_type == handler_type) {
  10874. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10875. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  10876. if (handler_type == WEBSOCKET_HANDLER) {
  10877. *subprotocols = tmp_rh->subprotocols;
  10878. *connect_handler = tmp_rh->connect_handler;
  10879. *ready_handler = tmp_rh->ready_handler;
  10880. *data_handler = tmp_rh->data_handler;
  10881. *close_handler = tmp_rh->close_handler;
  10882. } else if (handler_type == REQUEST_HANDLER) {
  10883. *handler = tmp_rh->handler;
  10884. } else { /* AUTH_HANDLER */
  10885. *auth_handler = tmp_rh->auth_handler;
  10886. }
  10887. *cbdata = tmp_rh->cbdata;
  10888. mg_unlock_context(conn->phys_ctx);
  10889. return 1;
  10890. }
  10891. }
  10892. }
  10893. /* finally try for pattern match */
  10894. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10895. tmp_rh = tmp_rh->next) {
  10896. if (tmp_rh->handler_type == handler_type) {
  10897. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10898. if (handler_type == WEBSOCKET_HANDLER) {
  10899. *subprotocols = tmp_rh->subprotocols;
  10900. *connect_handler = tmp_rh->connect_handler;
  10901. *ready_handler = tmp_rh->ready_handler;
  10902. *data_handler = tmp_rh->data_handler;
  10903. *close_handler = tmp_rh->close_handler;
  10904. } else if (handler_type == REQUEST_HANDLER) {
  10905. *handler = tmp_rh->handler;
  10906. } else { /* AUTH_HANDLER */
  10907. *auth_handler = tmp_rh->auth_handler;
  10908. }
  10909. *cbdata = tmp_rh->cbdata;
  10910. mg_unlock_context(conn->phys_ctx);
  10911. return 1;
  10912. }
  10913. }
  10914. }
  10915. mg_unlock_context(conn->phys_ctx);
  10916. }
  10917. return 0; /* none found */
  10918. }
  10919. /* Check if the script file is in a path, allowed for script files.
  10920. * This can be used if uploading files is possible not only for the server
  10921. * admin, and the upload mechanism does not check the file extension.
  10922. */
  10923. static int
  10924. is_in_script_path(const struct mg_connection *conn, const char *path)
  10925. {
  10926. /* TODO (Feature): Add config value for allowed script path.
  10927. * Default: All allowed. */
  10928. (void)conn;
  10929. (void)path;
  10930. return 1;
  10931. }
  10932. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10933. static int
  10934. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10935. void *cbdata)
  10936. {
  10937. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10938. if (pcallbacks->websocket_connect) {
  10939. return pcallbacks->websocket_connect(conn);
  10940. }
  10941. /* No handler set - assume "OK" */
  10942. return 0;
  10943. }
  10944. static void
  10945. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10946. {
  10947. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10948. if (pcallbacks->websocket_ready) {
  10949. pcallbacks->websocket_ready(conn);
  10950. }
  10951. }
  10952. static int
  10953. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10954. int bits,
  10955. char *data,
  10956. size_t len,
  10957. void *cbdata)
  10958. {
  10959. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10960. if (pcallbacks->websocket_data) {
  10961. return pcallbacks->websocket_data(conn, bits, data, len);
  10962. }
  10963. /* No handler set - assume "OK" */
  10964. return 1;
  10965. }
  10966. #endif
  10967. /* This is the heart of the Civetweb's logic.
  10968. * This function is called when the request is read, parsed and validated,
  10969. * and Civetweb must decide what action to take: serve a file, or
  10970. * a directory, or call embedded function, etcetera. */
  10971. static void
  10972. handle_request(struct mg_connection *conn)
  10973. {
  10974. struct mg_request_info *ri = &conn->request_info;
  10975. char path[PATH_MAX];
  10976. int uri_len, ssl_index;
  10977. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  10978. is_put_or_delete_request = 0, is_callback_resource = 0;
  10979. int i;
  10980. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10981. mg_request_handler callback_handler = NULL;
  10982. struct mg_websocket_subprotocols *subprotocols;
  10983. mg_websocket_connect_handler ws_connect_handler = NULL;
  10984. mg_websocket_ready_handler ws_ready_handler = NULL;
  10985. mg_websocket_data_handler ws_data_handler = NULL;
  10986. mg_websocket_close_handler ws_close_handler = NULL;
  10987. void *callback_data = NULL;
  10988. mg_authorization_handler auth_handler = NULL;
  10989. void *auth_callback_data = NULL;
  10990. int handler_type;
  10991. time_t curtime = time(NULL);
  10992. char date[64];
  10993. path[0] = 0;
  10994. /* 1. get the request url */
  10995. /* 1.1. split into url and query string */
  10996. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  10997. != NULL) {
  10998. *((char *)conn->request_info.query_string++) = '\0';
  10999. }
  11000. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11001. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11002. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11003. if (ssl_index >= 0) {
  11004. redirect_to_https_port(conn, ssl_index);
  11005. } else {
  11006. /* A http to https forward port has been specified,
  11007. * but no https port to forward to. */
  11008. mg_send_http_error(conn,
  11009. 503,
  11010. "%s",
  11011. "Error: SSL forward not configured properly");
  11012. mg_cry_internal(conn,
  11013. "%s",
  11014. "Can not redirect to SSL, no SSL port available");
  11015. }
  11016. return;
  11017. }
  11018. uri_len = (int)strlen(ri->local_uri);
  11019. /* 1.3. decode url (if config says so) */
  11020. if (should_decode_url(conn)) {
  11021. mg_url_decode(
  11022. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11023. }
  11024. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11025. * not possible */
  11026. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11027. /* step 1. completed, the url is known now */
  11028. uri_len = (int)strlen(ri->local_uri);
  11029. DEBUG_TRACE("URL: %s", ri->local_uri);
  11030. /* 2. if this ip has limited speed, set it for this connection */
  11031. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11032. get_remote_ip(conn),
  11033. ri->local_uri);
  11034. /* 3. call a "handle everything" callback, if registered */
  11035. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11036. /* Note that since V1.7 the "begin_request" function is called
  11037. * before an authorization check. If an authorization check is
  11038. * required, use a request_handler instead. */
  11039. i = conn->phys_ctx->callbacks.begin_request(conn);
  11040. if (i > 0) {
  11041. /* callback already processed the request. Store the
  11042. return value as a status code for the access log. */
  11043. conn->status_code = i;
  11044. discard_unread_request_data(conn);
  11045. return;
  11046. } else if (i == 0) {
  11047. /* civetweb should process the request */
  11048. } else {
  11049. /* unspecified - may change with the next version */
  11050. return;
  11051. }
  11052. }
  11053. /* request not yet handled by a handler or redirect, so the request
  11054. * is processed here */
  11055. /* 4. Check for CORS preflight requests and handle them (if configured).
  11056. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11057. */
  11058. if (!strcmp(ri->request_method, "OPTIONS")) {
  11059. /* Send a response to CORS preflights only if
  11060. * access_control_allow_methods is not NULL and not an empty string.
  11061. * In this case, scripts can still handle CORS. */
  11062. const char *cors_meth_cfg =
  11063. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11064. const char *cors_orig_cfg =
  11065. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11066. const char *cors_origin =
  11067. get_header(ri->http_headers, ri->num_headers, "Origin");
  11068. const char *cors_acrm = get_header(ri->http_headers,
  11069. ri->num_headers,
  11070. "Access-Control-Request-Method");
  11071. /* Todo: check if cors_origin is in cors_orig_cfg.
  11072. * Or, let the client check this. */
  11073. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11074. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11075. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11076. /* This is a valid CORS preflight, and the server is configured
  11077. * to
  11078. * handle it automatically. */
  11079. const char *cors_acrh =
  11080. get_header(ri->http_headers,
  11081. ri->num_headers,
  11082. "Access-Control-Request-Headers");
  11083. gmt_time_string(date, sizeof(date), &curtime);
  11084. mg_printf(conn,
  11085. "HTTP/1.1 200 OK\r\n"
  11086. "Date: %s\r\n"
  11087. "Access-Control-Allow-Origin: %s\r\n"
  11088. "Access-Control-Allow-Methods: %s\r\n"
  11089. "Content-Length: 0\r\n"
  11090. "Connection: %s\r\n",
  11091. date,
  11092. cors_orig_cfg,
  11093. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11094. suggest_connection_header(conn));
  11095. if (cors_acrh != NULL) {
  11096. /* CORS request is asking for additional headers */
  11097. const char *cors_hdr_cfg =
  11098. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11099. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11100. /* Allow only if access_control_allow_headers is
  11101. * not NULL and not an empty string. If this
  11102. * configuration is set to *, allow everything.
  11103. * Otherwise this configuration must be a list
  11104. * of allowed HTTP header names. */
  11105. mg_printf(conn,
  11106. "Access-Control-Allow-Headers: %s\r\n",
  11107. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11108. : cors_hdr_cfg));
  11109. }
  11110. }
  11111. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11112. mg_printf(conn, "\r\n");
  11113. return;
  11114. }
  11115. }
  11116. /* 5. interpret the url to find out how the request must be handled
  11117. */
  11118. /* 5.1. first test, if the request targets the regular http(s)://
  11119. * protocol namespace or the websocket ws(s):// protocol namespace.
  11120. */
  11121. is_websocket_request = is_websocket_protocol(conn);
  11122. #if defined(USE_WEBSOCKET)
  11123. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11124. #else
  11125. handler_type = REQUEST_HANDLER;
  11126. #endif /* defined(USE_WEBSOCKET) */
  11127. /* 5.2. check if the request will be handled by a callback */
  11128. if (get_request_handler(conn,
  11129. handler_type,
  11130. &callback_handler,
  11131. &subprotocols,
  11132. &ws_connect_handler,
  11133. &ws_ready_handler,
  11134. &ws_data_handler,
  11135. &ws_close_handler,
  11136. NULL,
  11137. &callback_data)) {
  11138. /* 5.2.1. A callback will handle this request. All requests
  11139. * handled
  11140. * by a callback have to be considered as requests to a script
  11141. * resource. */
  11142. is_callback_resource = 1;
  11143. is_script_resource = 1;
  11144. is_put_or_delete_request = is_put_or_delete_method(conn);
  11145. } else {
  11146. no_callback_resource:
  11147. /* 5.2.2. No callback is responsible for this request. The URI
  11148. * addresses a file based resource (static content or Lua/cgi
  11149. * scripts in the file system). */
  11150. is_callback_resource = 0;
  11151. interpret_uri(conn,
  11152. path,
  11153. sizeof(path),
  11154. &file.stat,
  11155. &is_found,
  11156. &is_script_resource,
  11157. &is_websocket_request,
  11158. &is_put_or_delete_request);
  11159. }
  11160. /* 6. authorization check */
  11161. /* 6.1. a custom authorization handler is installed */
  11162. if (get_request_handler(conn,
  11163. AUTH_HANDLER,
  11164. NULL,
  11165. NULL,
  11166. NULL,
  11167. NULL,
  11168. NULL,
  11169. NULL,
  11170. &auth_handler,
  11171. &auth_callback_data)) {
  11172. if (!auth_handler(conn, auth_callback_data)) {
  11173. return;
  11174. }
  11175. } else if (is_put_or_delete_request && !is_script_resource
  11176. && !is_callback_resource) {
  11177. /* 6.2. this request is a PUT/DELETE to a real file */
  11178. /* 6.2.1. thus, the server must have real files */
  11179. #if defined(NO_FILES)
  11180. if (1) {
  11181. #else
  11182. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11183. #endif
  11184. /* This server does not have any real files, thus the
  11185. * PUT/DELETE methods are not valid. */
  11186. mg_send_http_error(conn,
  11187. 405,
  11188. "%s method not allowed",
  11189. conn->request_info.request_method);
  11190. return;
  11191. }
  11192. #if !defined(NO_FILES)
  11193. /* 6.2.2. Check if put authorization for static files is
  11194. * available.
  11195. */
  11196. if (!is_authorized_for_put(conn)) {
  11197. send_authorization_request(conn, NULL);
  11198. return;
  11199. }
  11200. #endif
  11201. } else {
  11202. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11203. * or it is a PUT or DELETE request to a resource that does not
  11204. * correspond to a file. Check authorization. */
  11205. if (!check_authorization(conn, path)) {
  11206. send_authorization_request(conn, NULL);
  11207. return;
  11208. }
  11209. }
  11210. /* request is authorized or does not need authorization */
  11211. /* 7. check if there are request handlers for this uri */
  11212. if (is_callback_resource) {
  11213. if (!is_websocket_request) {
  11214. i = callback_handler(conn, callback_data);
  11215. if (i > 0) {
  11216. /* Do nothing, callback has served the request. Store
  11217. * then return value as status code for the log and discard
  11218. * all data from the client not used by the callback. */
  11219. conn->status_code = i;
  11220. discard_unread_request_data(conn);
  11221. } else {
  11222. /* The handler did NOT handle the request. */
  11223. /* Some proper reactions would be:
  11224. * a) close the connections without sending anything
  11225. * b) send a 404 not found
  11226. * c) try if there is a file matching the URI
  11227. * It would be possible to do a, b or c in the callback
  11228. * implementation, and return 1 - we cannot do anything
  11229. * here, that is not possible in the callback.
  11230. *
  11231. * TODO: What would be the best reaction here?
  11232. * (Note: The reaction may change, if there is a better
  11233. *idea.)
  11234. */
  11235. /* For the moment, use option c: We look for a proper file,
  11236. * but since a file request is not always a script resource,
  11237. * the authorization check might be different. */
  11238. interpret_uri(conn,
  11239. path,
  11240. sizeof(path),
  11241. &file.stat,
  11242. &is_found,
  11243. &is_script_resource,
  11244. &is_websocket_request,
  11245. &is_put_or_delete_request);
  11246. callback_handler = NULL;
  11247. /* Here we are at a dead end:
  11248. * According to URI matching, a callback should be
  11249. * responsible for handling the request,
  11250. * we called it, but the callback declared itself
  11251. * not responsible.
  11252. * We use a goto here, to get out of this dead end,
  11253. * and continue with the default handling.
  11254. * A goto here is simpler and better to understand
  11255. * than some curious loop. */
  11256. goto no_callback_resource;
  11257. }
  11258. } else {
  11259. #if defined(USE_WEBSOCKET)
  11260. handle_websocket_request(conn,
  11261. path,
  11262. is_callback_resource,
  11263. subprotocols,
  11264. ws_connect_handler,
  11265. ws_ready_handler,
  11266. ws_data_handler,
  11267. ws_close_handler,
  11268. callback_data);
  11269. #endif
  11270. }
  11271. return;
  11272. }
  11273. /* 8. handle websocket requests */
  11274. #if defined(USE_WEBSOCKET)
  11275. if (is_websocket_request) {
  11276. if (is_script_resource) {
  11277. if (is_in_script_path(conn, path)) {
  11278. /* Websocket Lua script */
  11279. handle_websocket_request(conn,
  11280. path,
  11281. 0 /* Lua Script */,
  11282. NULL,
  11283. NULL,
  11284. NULL,
  11285. NULL,
  11286. NULL,
  11287. conn->phys_ctx->user_data);
  11288. } else {
  11289. /* Script was in an illegal path */
  11290. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11291. }
  11292. } else {
  11293. #if defined(MG_LEGACY_INTERFACE)
  11294. handle_websocket_request(
  11295. conn,
  11296. path,
  11297. !is_script_resource /* could be deprecated global callback */,
  11298. NULL,
  11299. deprecated_websocket_connect_wrapper,
  11300. deprecated_websocket_ready_wrapper,
  11301. deprecated_websocket_data_wrapper,
  11302. NULL,
  11303. conn->phys_ctx->user_data);
  11304. #else
  11305. mg_send_http_error(conn, 404, "%s", "Not found");
  11306. #endif
  11307. }
  11308. return;
  11309. } else
  11310. #endif
  11311. #if defined(NO_FILES)
  11312. /* 9a. In case the server uses only callbacks, this uri is
  11313. * unknown.
  11314. * Then, all request handling ends here. */
  11315. mg_send_http_error(conn, 404, "%s", "Not Found");
  11316. #else
  11317. /* 9b. This request is either for a static file or resource handled
  11318. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11319. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11320. mg_send_http_error(conn, 404, "%s", "Not Found");
  11321. return;
  11322. }
  11323. /* 10. Request is handled by a script */
  11324. if (is_script_resource) {
  11325. handle_file_based_request(conn, path, &file);
  11326. return;
  11327. }
  11328. /* 11. Handle put/delete/mkcol requests */
  11329. if (is_put_or_delete_request) {
  11330. /* 11.1. PUT method */
  11331. if (!strcmp(ri->request_method, "PUT")) {
  11332. put_file(conn, path);
  11333. return;
  11334. }
  11335. /* 11.2. DELETE method */
  11336. if (!strcmp(ri->request_method, "DELETE")) {
  11337. delete_file(conn, path);
  11338. return;
  11339. }
  11340. /* 11.3. MKCOL method */
  11341. if (!strcmp(ri->request_method, "MKCOL")) {
  11342. mkcol(conn, path);
  11343. return;
  11344. }
  11345. /* 11.4. PATCH method
  11346. * This method is not supported for static resources,
  11347. * only for scripts (Lua, CGI) and callbacks. */
  11348. mg_send_http_error(conn,
  11349. 405,
  11350. "%s method not allowed",
  11351. conn->request_info.request_method);
  11352. return;
  11353. }
  11354. /* 11. File does not exist, or it was configured that it should be
  11355. * hidden */
  11356. if (!is_found || (must_hide_file(conn, path))) {
  11357. mg_send_http_error(conn, 404, "%s", "Not found");
  11358. return;
  11359. }
  11360. /* 12. Directory uris should end with a slash */
  11361. if (file.stat.is_directory && (uri_len > 0)
  11362. && (ri->local_uri[uri_len - 1] != '/')) {
  11363. gmt_time_string(date, sizeof(date), &curtime);
  11364. mg_printf(conn,
  11365. "HTTP/1.1 301 Moved Permanently\r\n"
  11366. "Location: %s/\r\n"
  11367. "Date: %s\r\n"
  11368. /* "Cache-Control: private\r\n" (= default) */
  11369. "Content-Length: 0\r\n"
  11370. "Connection: %s\r\n",
  11371. ri->request_uri,
  11372. date,
  11373. suggest_connection_header(conn));
  11374. send_additional_header(conn);
  11375. mg_printf(conn, "\r\n");
  11376. return;
  11377. }
  11378. /* 13. Handle other methods than GET/HEAD */
  11379. /* 13.1. Handle PROPFIND */
  11380. if (!strcmp(ri->request_method, "PROPFIND")) {
  11381. handle_propfind(conn, path, &file.stat);
  11382. return;
  11383. }
  11384. /* 13.2. Handle OPTIONS for files */
  11385. if (!strcmp(ri->request_method, "OPTIONS")) {
  11386. /* This standard handler is only used for real files.
  11387. * Scripts should support the OPTIONS method themselves, to allow a
  11388. * maximum flexibility.
  11389. * Lua and CGI scripts may fully support CORS this way (including
  11390. * preflights). */
  11391. send_options(conn);
  11392. return;
  11393. }
  11394. /* 13.3. everything but GET and HEAD (e.g. POST) */
  11395. if ((0 != strcmp(ri->request_method, "GET"))
  11396. && (0 != strcmp(ri->request_method, "HEAD"))) {
  11397. mg_send_http_error(conn,
  11398. 405,
  11399. "%s method not allowed",
  11400. conn->request_info.request_method);
  11401. return;
  11402. }
  11403. /* 14. directories */
  11404. if (file.stat.is_directory) {
  11405. /* Substitute files have already been handled above. */
  11406. /* Here we can either generate and send a directory listing,
  11407. * or send an "access denied" error. */
  11408. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11409. "yes")) {
  11410. handle_directory_request(conn, path);
  11411. } else {
  11412. mg_send_http_error(conn,
  11413. 403,
  11414. "%s",
  11415. "Error: Directory listing denied");
  11416. }
  11417. return;
  11418. }
  11419. handle_file_based_request(conn, path, &file);
  11420. #endif /* !defined(NO_FILES) */
  11421. #if 0
  11422. /* Perform redirect and auth checks before calling begin_request()
  11423. * handler.
  11424. * Otherwise, begin_request() would need to perform auth checks and
  11425. * redirects. */
  11426. #endif
  11427. }
  11428. static void
  11429. handle_file_based_request(struct mg_connection *conn,
  11430. const char *path,
  11431. struct mg_file *file)
  11432. {
  11433. if (!conn || !conn->dom_ctx) {
  11434. return;
  11435. }
  11436. if (0) {
  11437. #ifdef USE_LUA
  11438. } else if (match_prefix(
  11439. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  11440. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  11441. path) > 0) {
  11442. if (is_in_script_path(conn, path)) {
  11443. /* Lua server page: an SSI like page containing mostly plain
  11444. * html
  11445. * code
  11446. * plus some tags with server generated contents. */
  11447. handle_lsp_request(conn, path, file, NULL);
  11448. } else {
  11449. /* Script was in an illegal path */
  11450. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11451. }
  11452. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  11453. strlen(
  11454. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  11455. path) > 0) {
  11456. if (is_in_script_path(conn, path)) {
  11457. /* Lua in-server module script: a CGI like script used to
  11458. * generate
  11459. * the
  11460. * entire reply. */
  11461. mg_exec_lua_script(conn, path, NULL);
  11462. } else {
  11463. /* Script was in an illegal path */
  11464. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11465. }
  11466. #endif
  11467. #if defined(USE_DUKTAPE)
  11468. } else if (match_prefix(
  11469. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  11470. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  11471. path) > 0) {
  11472. if (is_in_script_path(conn, path)) {
  11473. /* Call duktape to generate the page */
  11474. mg_exec_duktape_script(conn, path);
  11475. } else {
  11476. /* Script was in an illegal path */
  11477. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11478. }
  11479. #endif
  11480. #if !defined(NO_CGI)
  11481. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  11482. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  11483. path) > 0) {
  11484. if (is_in_script_path(conn, path)) {
  11485. /* CGI scripts may support all HTTP methods */
  11486. handle_cgi_request(conn, path);
  11487. } else {
  11488. /* Script was in an illegal path */
  11489. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11490. }
  11491. #endif /* !NO_CGI */
  11492. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  11493. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  11494. path) > 0) {
  11495. if (is_in_script_path(conn, path)) {
  11496. handle_ssi_file_request(conn, path, file);
  11497. } else {
  11498. /* Script was in an illegal path */
  11499. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11500. }
  11501. #if !defined(NO_CACHING)
  11502. } else if ((!conn->in_error_handler)
  11503. && is_not_modified(conn, &file->stat)) {
  11504. /* Send 304 "Not Modified" - this must not send any body data */
  11505. handle_not_modified_static_file_request(conn, file);
  11506. #endif /* !NO_CACHING */
  11507. } else {
  11508. handle_static_file_request(conn, path, file, NULL, NULL);
  11509. }
  11510. }
  11511. static void
  11512. close_all_listening_sockets(struct mg_context *ctx)
  11513. {
  11514. unsigned int i;
  11515. if (!ctx) {
  11516. return;
  11517. }
  11518. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11519. closesocket(ctx->listening_sockets[i].sock);
  11520. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  11521. }
  11522. mg_free(ctx->listening_sockets);
  11523. ctx->listening_sockets = NULL;
  11524. mg_free(ctx->listening_socket_fds);
  11525. ctx->listening_socket_fds = NULL;
  11526. }
  11527. /* Valid listening port specification is: [ip_address:]port[s]
  11528. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  11529. * Examples for IPv6: [::]:80, [::1]:80,
  11530. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  11531. * see https://tools.ietf.org/html/rfc3513#section-2.2
  11532. * In order to bind to both, IPv4 and IPv6, you can either add
  11533. * both ports using 8080,[::]:8080, or the short form +8080.
  11534. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  11535. * one only accepting IPv4 the other only IPv6. +8080 creates
  11536. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  11537. * environment, they might work differently, or might not work
  11538. * at all - it must be tested what options work best in the
  11539. * relevant network environment.
  11540. */
  11541. static int
  11542. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  11543. {
  11544. unsigned int a, b, c, d, port;
  11545. int ch, len;
  11546. const char *cb;
  11547. #if defined(USE_IPV6)
  11548. char buf[100] = {0};
  11549. #endif
  11550. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  11551. * Also, all-zeroes in the socket address means binding to all addresses
  11552. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  11553. memset(so, 0, sizeof(*so));
  11554. so->lsa.sin.sin_family = AF_INET;
  11555. *ip_version = 0;
  11556. /* Initialize port and len as invalid. */
  11557. port = 0;
  11558. len = 0;
  11559. /* Test for different ways to format this string */
  11560. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  11561. == 5) {
  11562. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  11563. so->lsa.sin.sin_addr.s_addr =
  11564. htonl((a << 24) | (b << 16) | (c << 8) | d);
  11565. so->lsa.sin.sin_port = htons((uint16_t)port);
  11566. *ip_version = 4;
  11567. #if defined(USE_IPV6)
  11568. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  11569. && mg_inet_pton(
  11570. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  11571. /* IPv6 address, examples: see above */
  11572. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  11573. */
  11574. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11575. *ip_version = 6;
  11576. #endif
  11577. } else if ((vec->ptr[0] == '+')
  11578. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  11579. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  11580. /* Add 1 to len for the + character we skipped before */
  11581. len++;
  11582. #if defined(USE_IPV6)
  11583. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  11584. so->lsa.sin6.sin6_family = AF_INET6;
  11585. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11586. *ip_version = 4 + 6;
  11587. #else
  11588. /* Bind to IPv4 only, since IPv6 is not built in. */
  11589. so->lsa.sin.sin_port = htons((uint16_t)port);
  11590. *ip_version = 4;
  11591. #endif
  11592. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  11593. /* If only port is specified, bind to IPv4, INADDR_ANY */
  11594. so->lsa.sin.sin_port = htons((uint16_t)port);
  11595. *ip_version = 4;
  11596. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  11597. /* Could be a hostname */
  11598. /* Will only work for RFC 952 compliant hostnames,
  11599. * starting with a letter, containing only letters,
  11600. * digits and hyphen ('-'). Newer specs may allow
  11601. * more, but this is not guaranteed here, since it
  11602. * may interfere with rules for port option lists. */
  11603. *(char *)cb = 0; /* Use a const cast here and modify the string.
  11604. * We are going to restore the string later. */
  11605. if (mg_inet_pton(
  11606. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  11607. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11608. *ip_version = 4;
  11609. so->lsa.sin.sin_family = AF_INET;
  11610. so->lsa.sin.sin_port = htons((uint16_t)port);
  11611. len += (int)(cb - vec->ptr) + 1;
  11612. } else {
  11613. port = 0;
  11614. len = 0;
  11615. }
  11616. #if defined(USE_IPV6)
  11617. } else if (mg_inet_pton(AF_INET6,
  11618. vec->ptr,
  11619. &so->lsa.sin6,
  11620. sizeof(so->lsa.sin6))) {
  11621. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11622. *ip_version = 6;
  11623. so->lsa.sin6.sin6_family = AF_INET6;
  11624. so->lsa.sin.sin_port = htons((uint16_t)port);
  11625. len += (int)(cb - vec->ptr) + 1;
  11626. } else {
  11627. port = 0;
  11628. len = 0;
  11629. }
  11630. #endif
  11631. }
  11632. *(char *)cb = ':'; /* restore the string */
  11633. } else {
  11634. /* Parsing failure. */
  11635. }
  11636. /* sscanf and the option splitting code ensure the following condition
  11637. */
  11638. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11639. *ip_version = 0;
  11640. return 0;
  11641. }
  11642. ch = vec->ptr[len]; /* Next character after the port number */
  11643. so->is_ssl = (ch == 's');
  11644. so->ssl_redir = (ch == 'r');
  11645. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11646. if (is_valid_port(port)
  11647. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  11648. return 1;
  11649. }
  11650. /* Reset ip_version to 0 of there is an error */
  11651. *ip_version = 0;
  11652. return 0;
  11653. }
  11654. /* Is there any SSL port in use? */
  11655. static int
  11656. is_ssl_port_used(const char *ports)
  11657. {
  11658. if (ports) {
  11659. if (strchr(ports, 's')) {
  11660. return 1;
  11661. }
  11662. if (strchr(ports, 'r')) {
  11663. return 1;
  11664. }
  11665. }
  11666. return 0;
  11667. }
  11668. static int
  11669. set_ports_option(struct mg_context *phys_ctx)
  11670. {
  11671. const char *list;
  11672. int on = 1;
  11673. #if defined(USE_IPV6)
  11674. int off = 0;
  11675. #endif
  11676. struct vec vec;
  11677. struct socket so, *ptr;
  11678. struct pollfd *pfd;
  11679. union usa usa;
  11680. socklen_t len;
  11681. int ip_version;
  11682. int portsTotal = 0;
  11683. int portsOk = 0;
  11684. if (!phys_ctx) {
  11685. return 0;
  11686. }
  11687. memset(&so, 0, sizeof(so));
  11688. memset(&usa, 0, sizeof(usa));
  11689. len = sizeof(usa);
  11690. list = phys_ctx->dd.config[LISTENING_PORTS];
  11691. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11692. portsTotal++;
  11693. if (!parse_port_string(&vec, &so, &ip_version)) {
  11694. mg_cry_internal(
  11695. fc(phys_ctx),
  11696. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  11697. (int)vec.len,
  11698. vec.ptr,
  11699. portsTotal,
  11700. "[IP_ADDRESS:]PORT[s|r]");
  11701. continue;
  11702. }
  11703. #if !defined(NO_SSL)
  11704. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  11705. mg_cry_internal(fc(phys_ctx),
  11706. "Cannot add SSL socket (entry %i)",
  11707. portsTotal);
  11708. continue;
  11709. }
  11710. #endif
  11711. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  11712. == INVALID_SOCKET) {
  11713. mg_cry_internal(fc(phys_ctx),
  11714. "cannot create socket (entry %i)",
  11715. portsTotal);
  11716. continue;
  11717. }
  11718. #ifdef _WIN32
  11719. /* Windows SO_REUSEADDR lets many procs binds to a
  11720. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  11721. * if someone already has the socket -- DTL */
  11722. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  11723. * Windows might need a few seconds before
  11724. * the same port can be used again in the
  11725. * same process, so a short Sleep may be
  11726. * required between mg_stop and mg_start.
  11727. */
  11728. if (setsockopt(so.sock,
  11729. SOL_SOCKET,
  11730. SO_EXCLUSIVEADDRUSE,
  11731. (SOCK_OPT_TYPE)&on,
  11732. sizeof(on)) != 0) {
  11733. /* Set reuse option, but don't abort on errors. */
  11734. mg_cry_internal(
  11735. fc(phys_ctx),
  11736. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  11737. portsTotal);
  11738. }
  11739. #else
  11740. if (setsockopt(so.sock,
  11741. SOL_SOCKET,
  11742. SO_REUSEADDR,
  11743. (SOCK_OPT_TYPE)&on,
  11744. sizeof(on)) != 0) {
  11745. /* Set reuse option, but don't abort on errors. */
  11746. mg_cry_internal(fc(phys_ctx),
  11747. "cannot set socket option SO_REUSEADDR (entry %i)",
  11748. portsTotal);
  11749. }
  11750. #endif
  11751. if (ip_version > 4) {
  11752. #if defined(USE_IPV6)
  11753. if (ip_version == 6) {
  11754. if (so.lsa.sa.sa_family == AF_INET6
  11755. && setsockopt(so.sock,
  11756. IPPROTO_IPV6,
  11757. IPV6_V6ONLY,
  11758. (void *)&off,
  11759. sizeof(off)) != 0) {
  11760. /* Set IPv6 only option, but don't abort on errors. */
  11761. mg_cry_internal(
  11762. fc(phys_ctx),
  11763. "cannot set socket option IPV6_V6ONLY (entry %i)",
  11764. portsTotal);
  11765. }
  11766. }
  11767. #else
  11768. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  11769. closesocket(so.sock);
  11770. so.sock = INVALID_SOCKET;
  11771. continue;
  11772. #endif
  11773. }
  11774. if (so.lsa.sa.sa_family == AF_INET) {
  11775. len = sizeof(so.lsa.sin);
  11776. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11777. mg_cry_internal(fc(phys_ctx),
  11778. "cannot bind to %.*s: %d (%s)",
  11779. (int)vec.len,
  11780. vec.ptr,
  11781. (int)ERRNO,
  11782. strerror(errno));
  11783. closesocket(so.sock);
  11784. so.sock = INVALID_SOCKET;
  11785. continue;
  11786. }
  11787. }
  11788. #if defined(USE_IPV6)
  11789. else if (so.lsa.sa.sa_family == AF_INET6) {
  11790. len = sizeof(so.lsa.sin6);
  11791. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11792. mg_cry_internal(fc(phys_ctx),
  11793. "cannot bind to IPv6 %.*s: %d (%s)",
  11794. (int)vec.len,
  11795. vec.ptr,
  11796. (int)ERRNO,
  11797. strerror(errno));
  11798. closesocket(so.sock);
  11799. so.sock = INVALID_SOCKET;
  11800. continue;
  11801. }
  11802. }
  11803. #endif
  11804. else {
  11805. mg_cry_internal(
  11806. fc(phys_ctx),
  11807. "cannot bind: address family not supported (entry %i)",
  11808. portsTotal);
  11809. closesocket(so.sock);
  11810. so.sock = INVALID_SOCKET;
  11811. continue;
  11812. }
  11813. if (listen(so.sock, SOMAXCONN) != 0) {
  11814. mg_cry_internal(fc(phys_ctx),
  11815. "cannot listen to %.*s: %d (%s)",
  11816. (int)vec.len,
  11817. vec.ptr,
  11818. (int)ERRNO,
  11819. strerror(errno));
  11820. closesocket(so.sock);
  11821. so.sock = INVALID_SOCKET;
  11822. continue;
  11823. }
  11824. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  11825. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  11826. int err = (int)ERRNO;
  11827. mg_cry_internal(fc(phys_ctx),
  11828. "call to getsockname failed %.*s: %d (%s)",
  11829. (int)vec.len,
  11830. vec.ptr,
  11831. err,
  11832. strerror(errno));
  11833. closesocket(so.sock);
  11834. so.sock = INVALID_SOCKET;
  11835. continue;
  11836. }
  11837. /* Update lsa port in case of random free ports */
  11838. #if defined(USE_IPV6)
  11839. if (so.lsa.sa.sa_family == AF_INET6) {
  11840. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  11841. } else
  11842. #endif
  11843. {
  11844. so.lsa.sin.sin_port = usa.sin.sin_port;
  11845. }
  11846. if ((ptr = (struct socket *)
  11847. mg_realloc_ctx(phys_ctx->listening_sockets,
  11848. (phys_ctx->num_listening_sockets + 1)
  11849. * sizeof(phys_ctx->listening_sockets[0]),
  11850. phys_ctx)) == NULL) {
  11851. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  11852. closesocket(so.sock);
  11853. so.sock = INVALID_SOCKET;
  11854. continue;
  11855. }
  11856. if ((pfd = (struct pollfd *)
  11857. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  11858. (phys_ctx->num_listening_sockets + 1)
  11859. * sizeof(phys_ctx->listening_socket_fds[0]),
  11860. phys_ctx)) == NULL) {
  11861. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  11862. closesocket(so.sock);
  11863. so.sock = INVALID_SOCKET;
  11864. mg_free(ptr);
  11865. continue;
  11866. }
  11867. set_close_on_exec(so.sock, fc(phys_ctx));
  11868. phys_ctx->listening_sockets = ptr;
  11869. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  11870. phys_ctx->listening_socket_fds = pfd;
  11871. phys_ctx->num_listening_sockets++;
  11872. portsOk++;
  11873. }
  11874. if (portsOk != portsTotal) {
  11875. close_all_listening_sockets(phys_ctx);
  11876. portsOk = 0;
  11877. }
  11878. return portsOk;
  11879. }
  11880. static const char *
  11881. header_val(const struct mg_connection *conn, const char *header)
  11882. {
  11883. const char *header_value;
  11884. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11885. return "-";
  11886. } else {
  11887. return header_value;
  11888. }
  11889. }
  11890. static void
  11891. log_access(const struct mg_connection *conn)
  11892. {
  11893. const struct mg_request_info *ri;
  11894. struct mg_file fi;
  11895. char date[64], src_addr[IP_ADDR_STR_LEN];
  11896. struct tm *tm;
  11897. const char *referer;
  11898. const char *user_agent;
  11899. char buf[4096];
  11900. if (!conn || !conn->dom_ctx) {
  11901. return;
  11902. }
  11903. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  11904. if (mg_fopen(conn,
  11905. conn->dom_ctx->config[ACCESS_LOG_FILE],
  11906. MG_FOPEN_MODE_APPEND,
  11907. &fi) == 0) {
  11908. fi.access.fp = NULL;
  11909. }
  11910. } else {
  11911. fi.access.fp = NULL;
  11912. }
  11913. /* Log is written to a file and/or a callback. If both are not set,
  11914. * executing the rest of the function is pointless. */
  11915. if ((fi.access.fp == NULL)
  11916. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  11917. return;
  11918. }
  11919. tm = localtime(&conn->conn_birth_time);
  11920. if (tm != NULL) {
  11921. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11922. } else {
  11923. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11924. date[sizeof(date) - 1] = '\0';
  11925. }
  11926. ri = &conn->request_info;
  11927. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11928. referer = header_val(conn, "Referer");
  11929. user_agent = header_val(conn, "User-Agent");
  11930. mg_snprintf(conn,
  11931. NULL, /* Ignore truncation in access log */
  11932. buf,
  11933. sizeof(buf),
  11934. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11935. src_addr,
  11936. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11937. date,
  11938. ri->request_method ? ri->request_method : "-",
  11939. ri->request_uri ? ri->request_uri : "-",
  11940. ri->query_string ? "?" : "",
  11941. ri->query_string ? ri->query_string : "",
  11942. ri->http_version,
  11943. conn->status_code,
  11944. conn->num_bytes_sent,
  11945. referer,
  11946. user_agent);
  11947. if (conn->phys_ctx->callbacks.log_access) {
  11948. conn->phys_ctx->callbacks.log_access(conn, buf);
  11949. }
  11950. if (fi.access.fp) {
  11951. int ok = 1;
  11952. flockfile(fi.access.fp);
  11953. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11954. ok = 0;
  11955. }
  11956. if (fflush(fi.access.fp) != 0) {
  11957. ok = 0;
  11958. }
  11959. funlockfile(fi.access.fp);
  11960. if (mg_fclose(&fi.access) != 0) {
  11961. ok = 0;
  11962. }
  11963. if (!ok) {
  11964. mg_cry_internal(conn,
  11965. "Error writing log file %s",
  11966. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  11967. }
  11968. }
  11969. }
  11970. /* Verify given socket address against the ACL.
  11971. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  11972. */
  11973. static int
  11974. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  11975. {
  11976. int allowed, flag;
  11977. uint32_t net, mask;
  11978. struct vec vec;
  11979. if (phys_ctx) {
  11980. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  11981. /* If any ACL is set, deny by default */
  11982. allowed = (list == NULL) ? '+' : '-';
  11983. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11984. flag = vec.ptr[0];
  11985. if ((flag != '+' && flag != '-')
  11986. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  11987. mg_cry_internal(fc(phys_ctx),
  11988. "%s: subnet must be [+|-]x.x.x.x[/x]",
  11989. __func__);
  11990. return -1;
  11991. }
  11992. if (net == (remote_ip & mask)) {
  11993. allowed = flag;
  11994. }
  11995. }
  11996. return allowed == '+';
  11997. }
  11998. return -1;
  11999. }
  12000. #if !defined(_WIN32)
  12001. static int
  12002. set_uid_option(struct mg_context *phys_ctx)
  12003. {
  12004. int success = 0;
  12005. if (phys_ctx) {
  12006. /* We are currently running as curr_uid. */
  12007. const uid_t curr_uid = getuid();
  12008. /* If set, we want to run as run_as_user. */
  12009. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12010. const struct passwd *to_pw = NULL;
  12011. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12012. /* run_as_user does not exist on the system. We can't proceed
  12013. * further. */
  12014. mg_cry_internal(fc(phys_ctx),
  12015. "%s: unknown user [%s]",
  12016. __func__,
  12017. run_as_user);
  12018. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12019. /* There was either no request to change user, or we're already
  12020. * running as run_as_user. Nothing else to do.
  12021. */
  12022. success = 1;
  12023. } else {
  12024. /* Valid change request. */
  12025. if (setgid(to_pw->pw_gid) == -1) {
  12026. mg_cry_internal(fc(phys_ctx),
  12027. "%s: setgid(%s): %s",
  12028. __func__,
  12029. run_as_user,
  12030. strerror(errno));
  12031. } else if (setgroups(0, NULL) == -1) {
  12032. mg_cry_internal(fc(phys_ctx),
  12033. "%s: setgroups(): %s",
  12034. __func__,
  12035. strerror(errno));
  12036. } else if (setuid(to_pw->pw_uid) == -1) {
  12037. mg_cry_internal(fc(phys_ctx),
  12038. "%s: setuid(%s): %s",
  12039. __func__,
  12040. run_as_user,
  12041. strerror(errno));
  12042. } else {
  12043. success = 1;
  12044. }
  12045. }
  12046. }
  12047. return success;
  12048. }
  12049. #endif /* !_WIN32 */
  12050. static void
  12051. tls_dtor(void *key)
  12052. {
  12053. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12054. /* key == pthread_getspecific(sTlsKey); */
  12055. if (tls) {
  12056. if (tls->is_master == 2) {
  12057. tls->is_master = -3; /* Mark memory as dead */
  12058. mg_free(tls);
  12059. }
  12060. }
  12061. pthread_setspecific(sTlsKey, NULL);
  12062. }
  12063. #if !defined(NO_SSL)
  12064. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12065. struct mg_domain_context *dom_ctx,
  12066. const char *pem,
  12067. const char *chain);
  12068. static const char *ssl_error(void);
  12069. static int
  12070. refresh_trust(struct mg_connection *conn)
  12071. {
  12072. static int reload_lock = 0;
  12073. static long int data_check = 0;
  12074. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12075. struct stat cert_buf;
  12076. long int t;
  12077. const char *pem;
  12078. const char *chain;
  12079. int should_verify_peer;
  12080. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12081. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12082. * refresh_trust still can not work. */
  12083. return 0;
  12084. }
  12085. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12086. if (chain == NULL) {
  12087. /* pem is not NULL here */
  12088. chain = pem;
  12089. }
  12090. if (*chain == 0) {
  12091. chain = NULL;
  12092. }
  12093. t = data_check;
  12094. if (stat(pem, &cert_buf) != -1) {
  12095. t = (long int)cert_buf.st_mtime;
  12096. }
  12097. if (data_check != t) {
  12098. data_check = t;
  12099. should_verify_peer = 0;
  12100. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12101. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12102. == 0) {
  12103. should_verify_peer = 1;
  12104. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12105. "optional") == 0) {
  12106. should_verify_peer = 1;
  12107. }
  12108. }
  12109. if (should_verify_peer) {
  12110. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12111. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12112. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12113. ca_file,
  12114. ca_path) != 1) {
  12115. mg_cry_internal(
  12116. fc(conn->phys_ctx),
  12117. "SSL_CTX_load_verify_locations error: %s "
  12118. "ssl_verify_peer requires setting "
  12119. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12120. "present in "
  12121. "the .conf file?",
  12122. ssl_error());
  12123. return 0;
  12124. }
  12125. }
  12126. if (1 == mg_atomic_inc(p_reload_lock)) {
  12127. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12128. == 0) {
  12129. return 0;
  12130. }
  12131. *p_reload_lock = 0;
  12132. }
  12133. }
  12134. /* lock while cert is reloading */
  12135. while (*p_reload_lock) {
  12136. sleep(1);
  12137. }
  12138. return 1;
  12139. }
  12140. #ifdef OPENSSL_API_1_1
  12141. #else
  12142. static pthread_mutex_t *ssl_mutexes;
  12143. #endif /* OPENSSL_API_1_1 */
  12144. static int
  12145. sslize(struct mg_connection *conn,
  12146. SSL_CTX *s,
  12147. int (*func)(SSL *),
  12148. volatile int *stop_server)
  12149. {
  12150. int ret, err;
  12151. int short_trust;
  12152. unsigned i;
  12153. if (!conn) {
  12154. return 0;
  12155. }
  12156. short_trust =
  12157. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12158. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12159. if (short_trust) {
  12160. int trust_ret = refresh_trust(conn);
  12161. if (!trust_ret) {
  12162. return trust_ret;
  12163. }
  12164. }
  12165. conn->ssl = SSL_new(s);
  12166. if (conn->ssl == NULL) {
  12167. return 0;
  12168. }
  12169. SSL_set_app_data(conn->ssl, (char *)conn);
  12170. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12171. if (ret != 1) {
  12172. err = SSL_get_error(conn->ssl, ret);
  12173. (void)err; /* TODO: set some error message */
  12174. SSL_free(conn->ssl);
  12175. conn->ssl = NULL;
  12176. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12177. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12178. #ifndef OPENSSL_API_1_1
  12179. ERR_remove_state(0);
  12180. #endif
  12181. return 0;
  12182. }
  12183. /* SSL functions may fail and require to be called again:
  12184. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  12185. * Here "func" could be SSL_connect or SSL_accept. */
  12186. for (i = 16; i <= 1024; i *= 2) {
  12187. ret = func(conn->ssl);
  12188. if (ret != 1) {
  12189. err = SSL_get_error(conn->ssl, ret);
  12190. if ((err == SSL_ERROR_WANT_CONNECT)
  12191. || (err == SSL_ERROR_WANT_ACCEPT)
  12192. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  12193. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  12194. /* Need to retry the function call "later".
  12195. * See https://linux.die.net/man/3/ssl_get_error
  12196. * This is typical for non-blocking sockets. */
  12197. if (*stop_server) {
  12198. /* Don't wait if the server is going to be stopped. */
  12199. break;
  12200. }
  12201. mg_sleep(i);
  12202. } else if (err == SSL_ERROR_SYSCALL) {
  12203. /* This is an IO error. Look at errno. */
  12204. err = errno;
  12205. /* TODO: set some error message */
  12206. (void)err;
  12207. break;
  12208. } else {
  12209. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  12210. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  12211. break;
  12212. }
  12213. } else {
  12214. /* success */
  12215. break;
  12216. }
  12217. }
  12218. if (ret != 1) {
  12219. SSL_free(conn->ssl);
  12220. conn->ssl = NULL;
  12221. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12222. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12223. #ifndef OPENSSL_API_1_1
  12224. ERR_remove_state(0);
  12225. #endif
  12226. return 0;
  12227. }
  12228. return 1;
  12229. }
  12230. /* Return OpenSSL error message (from CRYPTO lib) */
  12231. static const char *
  12232. ssl_error(void)
  12233. {
  12234. unsigned long err;
  12235. err = ERR_get_error();
  12236. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  12237. }
  12238. static int
  12239. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  12240. {
  12241. int i;
  12242. const char hexdigit[] = "0123456789abcdef";
  12243. if ((memlen <= 0) || (buflen <= 0)) {
  12244. return 0;
  12245. }
  12246. if (buflen < (3 * memlen)) {
  12247. return 0;
  12248. }
  12249. for (i = 0; i < memlen; i++) {
  12250. if (i > 0) {
  12251. buf[3 * i - 1] = ' ';
  12252. }
  12253. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  12254. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  12255. }
  12256. buf[3 * memlen - 1] = 0;
  12257. return 1;
  12258. }
  12259. static void
  12260. ssl_get_client_cert_info(struct mg_connection *conn)
  12261. {
  12262. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  12263. if (cert) {
  12264. char str_subject[1024];
  12265. char str_issuer[1024];
  12266. char str_finger[1024];
  12267. unsigned char buf[256];
  12268. char *str_serial = NULL;
  12269. unsigned int ulen;
  12270. int ilen;
  12271. unsigned char *tmp_buf;
  12272. unsigned char *tmp_p;
  12273. /* Handle to algorithm used for fingerprint */
  12274. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  12275. /* Get Subject and issuer */
  12276. X509_NAME *subj = X509_get_subject_name(cert);
  12277. X509_NAME *iss = X509_get_issuer_name(cert);
  12278. /* Get serial number */
  12279. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  12280. /* Translate serial number to a hex string */
  12281. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12282. str_serial = BN_bn2hex(serial_bn);
  12283. BN_free(serial_bn);
  12284. /* Translate subject and issuer to a string */
  12285. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12286. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12287. /* Calculate SHA1 fingerprint and store as a hex string */
  12288. ulen = 0;
  12289. /* ASN1_digest is deprecated. Do the calculation manually,
  12290. * using EVP_Digest. */
  12291. ilen = i2d_X509(cert, NULL);
  12292. tmp_buf = (ilen > 0)
  12293. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  12294. conn->phys_ctx)
  12295. : NULL;
  12296. if (tmp_buf) {
  12297. tmp_p = tmp_buf;
  12298. (void)i2d_X509(cert, &tmp_p);
  12299. if (!EVP_Digest(
  12300. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12301. ulen = 0;
  12302. }
  12303. mg_free(tmp_buf);
  12304. }
  12305. if (!hexdump2string(
  12306. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12307. *str_finger = 0;
  12308. }
  12309. conn->request_info.client_cert = (struct mg_client_cert *)
  12310. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  12311. if (conn->request_info.client_cert) {
  12312. conn->request_info.client_cert->peer_cert = (void *)cert;
  12313. conn->request_info.client_cert->subject =
  12314. mg_strdup_ctx(str_subject, conn->phys_ctx);
  12315. conn->request_info.client_cert->issuer =
  12316. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  12317. conn->request_info.client_cert->serial =
  12318. mg_strdup_ctx(str_serial, conn->phys_ctx);
  12319. conn->request_info.client_cert->finger =
  12320. mg_strdup_ctx(str_finger, conn->phys_ctx);
  12321. } else {
  12322. mg_cry_internal(conn,
  12323. "%s",
  12324. "Out of memory: Cannot allocate memory for client "
  12325. "certificate");
  12326. }
  12327. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  12328. * see https://linux.die.net/man/3/bn_bn2hex */
  12329. OPENSSL_free(str_serial);
  12330. }
  12331. }
  12332. #ifdef OPENSSL_API_1_1
  12333. #else
  12334. static void
  12335. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  12336. {
  12337. (void)line;
  12338. (void)file;
  12339. if (mode & 1) {
  12340. /* 1 is CRYPTO_LOCK */
  12341. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  12342. } else {
  12343. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  12344. }
  12345. }
  12346. #endif /* OPENSSL_API_1_1 */
  12347. #if !defined(NO_SSL_DL)
  12348. static void *
  12349. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  12350. {
  12351. union {
  12352. void *p;
  12353. void (*fp)(void);
  12354. } u;
  12355. void *dll_handle;
  12356. struct ssl_func *fp;
  12357. int ok;
  12358. int truncated = 0;
  12359. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  12360. mg_snprintf(NULL,
  12361. NULL, /* No truncation check for ebuf */
  12362. ebuf,
  12363. ebuf_len,
  12364. "%s: cannot load %s",
  12365. __func__,
  12366. dll_name);
  12367. return NULL;
  12368. }
  12369. ok = 1;
  12370. for (fp = sw; fp->name != NULL; fp++) {
  12371. #ifdef _WIN32
  12372. /* GetProcAddress() returns pointer to function */
  12373. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  12374. #else
  12375. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  12376. * pointers to function pointers. We need to use a union to make a
  12377. * cast. */
  12378. u.p = dlsym(dll_handle, fp->name);
  12379. #endif /* _WIN32 */
  12380. if (u.fp == NULL) {
  12381. if (ok) {
  12382. mg_snprintf(NULL,
  12383. &truncated,
  12384. ebuf,
  12385. ebuf_len,
  12386. "%s: %s: cannot find %s",
  12387. __func__,
  12388. dll_name,
  12389. fp->name);
  12390. ok = 0;
  12391. } else {
  12392. size_t cur_len = strlen(ebuf);
  12393. if (!truncated) {
  12394. mg_snprintf(NULL,
  12395. &truncated,
  12396. ebuf + cur_len,
  12397. ebuf_len - cur_len - 3,
  12398. ", %s",
  12399. fp->name);
  12400. if (truncated) {
  12401. /* If truncated, add "..." */
  12402. strcat(ebuf, "...");
  12403. }
  12404. }
  12405. }
  12406. /* Debug:
  12407. * printf("Missing function: %s\n", fp->name); */
  12408. } else {
  12409. fp->ptr = u.fp;
  12410. }
  12411. }
  12412. if (!ok) {
  12413. (void)dlclose(dll_handle);
  12414. return NULL;
  12415. }
  12416. return dll_handle;
  12417. }
  12418. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  12419. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  12420. #endif /* NO_SSL_DL */
  12421. #if defined(SSL_ALREADY_INITIALIZED)
  12422. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  12423. #else
  12424. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  12425. #endif
  12426. static int
  12427. initialize_ssl(char *ebuf, size_t ebuf_len)
  12428. {
  12429. #ifdef OPENSSL_API_1_1
  12430. if (ebuf_len > 0) {
  12431. ebuf[0] = 0;
  12432. }
  12433. #if !defined(NO_SSL_DL)
  12434. if (!cryptolib_dll_handle) {
  12435. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12436. if (!cryptolib_dll_handle) {
  12437. mg_snprintf(NULL,
  12438. NULL, /* No truncation check for ebuf */
  12439. ebuf,
  12440. ebuf_len,
  12441. "%s: error loading library %s",
  12442. __func__,
  12443. CRYPTO_LIB);
  12444. DEBUG_TRACE("%s", ebuf);
  12445. return 0;
  12446. }
  12447. }
  12448. #endif /* NO_SSL_DL */
  12449. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12450. return 1;
  12451. }
  12452. #else /* not OPENSSL_API_1_1 */
  12453. int i;
  12454. size_t size;
  12455. if (ebuf_len > 0) {
  12456. ebuf[0] = 0;
  12457. }
  12458. #if !defined(NO_SSL_DL)
  12459. if (!cryptolib_dll_handle) {
  12460. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12461. if (!cryptolib_dll_handle) {
  12462. mg_snprintf(NULL,
  12463. NULL, /* No truncation check for ebuf */
  12464. ebuf,
  12465. ebuf_len,
  12466. "%s: error loading library %s",
  12467. __func__,
  12468. CRYPTO_LIB);
  12469. DEBUG_TRACE("%s", ebuf);
  12470. return 0;
  12471. }
  12472. }
  12473. #endif /* NO_SSL_DL */
  12474. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12475. return 1;
  12476. }
  12477. /* Initialize locking callbacks, needed for thread safety.
  12478. * http://www.openssl.org/support/faq.html#PROG1
  12479. */
  12480. i = CRYPTO_num_locks();
  12481. if (i < 0) {
  12482. i = 0;
  12483. }
  12484. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  12485. if (size == 0) {
  12486. ssl_mutexes = NULL;
  12487. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  12488. mg_snprintf(NULL,
  12489. NULL, /* No truncation check for ebuf */
  12490. ebuf,
  12491. ebuf_len,
  12492. "%s: cannot allocate mutexes: %s",
  12493. __func__,
  12494. ssl_error());
  12495. DEBUG_TRACE("%s", ebuf);
  12496. return 0;
  12497. }
  12498. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12499. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  12500. }
  12501. CRYPTO_set_locking_callback(&ssl_locking_callback);
  12502. CRYPTO_set_id_callback(&mg_current_thread_id);
  12503. #endif /* OPENSSL_API_1_1 */
  12504. #if !defined(NO_SSL_DL)
  12505. if (!ssllib_dll_handle) {
  12506. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  12507. if (!ssllib_dll_handle) {
  12508. DEBUG_TRACE("%s", ebuf);
  12509. return 0;
  12510. }
  12511. }
  12512. #endif /* NO_SSL_DL */
  12513. #ifdef OPENSSL_API_1_1
  12514. /* Initialize SSL library */
  12515. OPENSSL_init_ssl(0, NULL);
  12516. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  12517. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  12518. NULL);
  12519. #else
  12520. /* Initialize SSL library */
  12521. SSL_library_init();
  12522. SSL_load_error_strings();
  12523. #endif
  12524. return 1;
  12525. }
  12526. static int
  12527. ssl_use_pem_file(struct mg_context *phys_ctx,
  12528. struct mg_domain_context *dom_ctx,
  12529. const char *pem,
  12530. const char *chain)
  12531. {
  12532. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12533. mg_cry_internal(fc(phys_ctx),
  12534. "%s: cannot open certificate file %s: %s",
  12535. __func__,
  12536. pem,
  12537. ssl_error());
  12538. return 0;
  12539. }
  12540. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  12541. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12542. mg_cry_internal(fc(phys_ctx),
  12543. "%s: cannot open private key file %s: %s",
  12544. __func__,
  12545. pem,
  12546. ssl_error());
  12547. return 0;
  12548. }
  12549. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  12550. mg_cry_internal(fc(phys_ctx),
  12551. "%s: certificate and private key do not match: %s",
  12552. __func__,
  12553. pem);
  12554. return 0;
  12555. }
  12556. /* In contrast to OpenSSL, wolfSSL does not support certificate
  12557. * chain files that contain private keys and certificates in
  12558. * SSL_CTX_use_certificate_chain_file.
  12559. * The CivetWeb-Server used pem-Files that contained both information.
  12560. * In order to make wolfSSL work, it is split in two files.
  12561. * One file that contains key and certificate used by the server and
  12562. * an optional chain file for the ssl stack.
  12563. */
  12564. if (chain) {
  12565. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  12566. mg_cry_internal(fc(phys_ctx),
  12567. "%s: cannot use certificate chain file %s: %s",
  12568. __func__,
  12569. pem,
  12570. ssl_error());
  12571. return 0;
  12572. }
  12573. }
  12574. return 1;
  12575. }
  12576. #ifdef OPENSSL_API_1_1
  12577. static unsigned long
  12578. ssl_get_protocol(int version_id)
  12579. {
  12580. long unsigned ret = SSL_OP_ALL;
  12581. if (version_id > 0)
  12582. ret |= SSL_OP_NO_SSLv2;
  12583. if (version_id > 1)
  12584. ret |= SSL_OP_NO_SSLv3;
  12585. if (version_id > 2)
  12586. ret |= SSL_OP_NO_TLSv1;
  12587. if (version_id > 3)
  12588. ret |= SSL_OP_NO_TLSv1_1;
  12589. return ret;
  12590. }
  12591. #else
  12592. static long
  12593. ssl_get_protocol(int version_id)
  12594. {
  12595. long ret = SSL_OP_ALL;
  12596. if (version_id > 0)
  12597. ret |= SSL_OP_NO_SSLv2;
  12598. if (version_id > 1)
  12599. ret |= SSL_OP_NO_SSLv3;
  12600. if (version_id > 2)
  12601. ret |= SSL_OP_NO_TLSv1;
  12602. if (version_id > 3)
  12603. ret |= SSL_OP_NO_TLSv1_1;
  12604. return ret;
  12605. }
  12606. #endif /* OPENSSL_API_1_1 */
  12607. /* SSL callback documentation:
  12608. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  12609. * https://linux.die.net/man/3/ssl_set_info_callback */
  12610. static void
  12611. ssl_info_callback(SSL *ssl, int what, int ret)
  12612. {
  12613. (void)ret;
  12614. if (what & SSL_CB_HANDSHAKE_START) {
  12615. SSL_get_app_data(ssl);
  12616. }
  12617. if (what & SSL_CB_HANDSHAKE_DONE) {
  12618. /* TODO: check for openSSL 1.1 */
  12619. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  12620. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  12621. }
  12622. }
  12623. static int
  12624. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  12625. {
  12626. struct mg_context *ctx = (struct mg_context *)arg;
  12627. struct mg_domain_context *dom =
  12628. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  12629. #if defined(__GNUC__) || defined(__MINGW32__)
  12630. #pragma GCC diagnostic push
  12631. #pragma GCC diagnostic ignored "-Wcast-align"
  12632. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  12633. /* We used an aligned pointer in SSL_set_app_data */
  12634. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  12635. #if defined(__GNUC__) || defined(__MINGW32__)
  12636. #pragma GCC diagnostic pop
  12637. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  12638. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  12639. (void)ad;
  12640. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  12641. DEBUG_TRACE("%s", "internal error - assertion failed");
  12642. return SSL_TLSEXT_ERR_NOACK;
  12643. }
  12644. /* Old clients (Win XP) will not support SNI. Then, there
  12645. * is no server name available in the request - we can
  12646. * only work with the default certificate.
  12647. * Multiple HTTPS hosts on one IP+port are only possible
  12648. * with a certificate containing all alternative names.
  12649. */
  12650. if ((servername == NULL) || (*servername == 0)) {
  12651. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  12652. conn->dom_ctx = &(ctx->dd);
  12653. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  12654. return SSL_TLSEXT_ERR_NOACK;
  12655. }
  12656. DEBUG_TRACE("TLS connection to host %s", servername);
  12657. while (dom) {
  12658. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  12659. /* Found matching domain */
  12660. DEBUG_TRACE("TLS domain %s found",
  12661. dom->config[AUTHENTICATION_DOMAIN]);
  12662. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  12663. conn->dom_ctx = dom;
  12664. return SSL_TLSEXT_ERR_OK;
  12665. }
  12666. dom = dom->next;
  12667. }
  12668. /* Default domain */
  12669. DEBUG_TRACE("TLS default domain %s used",
  12670. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  12671. conn->dom_ctx = &(ctx->dd);
  12672. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  12673. return SSL_TLSEXT_ERR_OK;
  12674. }
  12675. /* Setup SSL CTX as required by CivetWeb */
  12676. static int
  12677. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  12678. struct mg_domain_context *dom_ctx,
  12679. const char *pem,
  12680. const char *chain)
  12681. {
  12682. int callback_ret;
  12683. int should_verify_peer;
  12684. int peer_certificate_optional;
  12685. const char *ca_path;
  12686. const char *ca_file;
  12687. int use_default_verify_paths;
  12688. int verify_depth;
  12689. time_t now_rt = time(NULL);
  12690. struct timespec now_mt;
  12691. md5_byte_t ssl_context_id[16];
  12692. md5_state_t md5state;
  12693. int protocol_ver;
  12694. #ifdef OPENSSL_API_1_1
  12695. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  12696. mg_cry_internal(fc(phys_ctx),
  12697. "SSL_CTX_new (server) error: %s",
  12698. ssl_error());
  12699. return 0;
  12700. }
  12701. #else
  12702. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  12703. mg_cry_internal(fc(phys_ctx),
  12704. "SSL_CTX_new (server) error: %s",
  12705. ssl_error());
  12706. return 0;
  12707. }
  12708. #endif /* OPENSSL_API_1_1 */
  12709. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  12710. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  12711. | SSL_OP_NO_TLSv1_1);
  12712. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  12713. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  12714. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  12715. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  12716. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  12717. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12718. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  12719. #if !defined(NO_SSL_DL)
  12720. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  12721. #endif /* NO_SSL_DL */
  12722. #ifdef __clang__
  12723. #pragma clang diagnostic push
  12724. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  12725. #endif
  12726. /* Depending on the OpenSSL version, the callback may be
  12727. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  12728. * yielding in an "incompatible-pointer-type" warning for the other
  12729. * version. It seems to be "unclear" what is correct:
  12730. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  12731. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  12732. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  12733. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  12734. * Disable this warning here.
  12735. * Alternative would be a version dependent ssl_info_callback and
  12736. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  12737. */
  12738. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  12739. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  12740. ssl_servername_callback);
  12741. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  12742. #ifdef __clang__
  12743. #pragma clang diagnostic pop
  12744. #endif
  12745. /* If a callback has been specified, call it. */
  12746. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  12747. ? 0
  12748. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  12749. phys_ctx->user_data));
  12750. /* If callback returns 0, civetweb sets up the SSL certificate.
  12751. * If it returns 1, civetweb assumes the calback already did this.
  12752. * If it returns -1, initializing ssl fails. */
  12753. if (callback_ret < 0) {
  12754. mg_cry_internal(fc(phys_ctx),
  12755. "SSL callback returned error: %i",
  12756. callback_ret);
  12757. return 0;
  12758. }
  12759. if (callback_ret > 0) {
  12760. /* Callback did everything. */
  12761. return 1;
  12762. }
  12763. /* Use some UID as session context ID. */
  12764. md5_init(&md5state);
  12765. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  12766. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  12767. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  12768. md5_append(&md5state,
  12769. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  12770. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  12771. md5_append(&md5state,
  12772. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  12773. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  12774. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  12775. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  12776. md5_finish(&md5state, ssl_context_id);
  12777. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  12778. (const unsigned char *)&ssl_context_id,
  12779. sizeof(ssl_context_id));
  12780. if (pem != NULL) {
  12781. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  12782. return 0;
  12783. }
  12784. }
  12785. /* Should we support client certificates? */
  12786. /* Default is "no". */
  12787. should_verify_peer = 0;
  12788. peer_certificate_optional = 0;
  12789. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12790. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  12791. /* Yes, they are mandatory */
  12792. should_verify_peer = 1;
  12793. peer_certificate_optional = 0;
  12794. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  12795. "optional") == 0) {
  12796. /* Yes, they are optional */
  12797. should_verify_peer = 1;
  12798. peer_certificate_optional = 1;
  12799. }
  12800. }
  12801. use_default_verify_paths =
  12802. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  12803. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  12804. == 0);
  12805. if (should_verify_peer) {
  12806. ca_path = dom_ctx->config[SSL_CA_PATH];
  12807. ca_file = dom_ctx->config[SSL_CA_FILE];
  12808. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  12809. != 1) {
  12810. mg_cry_internal(fc(phys_ctx),
  12811. "SSL_CTX_load_verify_locations error: %s "
  12812. "ssl_verify_peer requires setting "
  12813. "either ssl_ca_path or ssl_ca_file. "
  12814. "Is any of them present in the "
  12815. ".conf file?",
  12816. ssl_error());
  12817. return 0;
  12818. }
  12819. if (peer_certificate_optional) {
  12820. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  12821. } else {
  12822. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  12823. SSL_VERIFY_PEER
  12824. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  12825. NULL);
  12826. }
  12827. if (use_default_verify_paths
  12828. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  12829. mg_cry_internal(fc(phys_ctx),
  12830. "SSL_CTX_set_default_verify_paths error: %s",
  12831. ssl_error());
  12832. return 0;
  12833. }
  12834. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  12835. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  12836. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  12837. }
  12838. }
  12839. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  12840. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  12841. dom_ctx->config[SSL_CIPHER_LIST]) != 1) {
  12842. mg_cry_internal(fc(phys_ctx),
  12843. "SSL_CTX_set_cipher_list error: %s",
  12844. ssl_error());
  12845. }
  12846. }
  12847. return 1;
  12848. }
  12849. /* Check if SSL is required.
  12850. * If so, dynamically load SSL library
  12851. * and set up ctx->ssl_ctx pointer. */
  12852. static int
  12853. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  12854. {
  12855. void *ssl_ctx = 0;
  12856. int callback_ret;
  12857. const char *pem;
  12858. const char *chain;
  12859. char ebuf[128];
  12860. if (!phys_ctx) {
  12861. return 0;
  12862. }
  12863. if (!dom_ctx) {
  12864. dom_ctx = &(phys_ctx->dd);
  12865. }
  12866. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  12867. /* No SSL port is set. No need to setup SSL. */
  12868. return 1;
  12869. }
  12870. /* Check for external SSL_CTX */
  12871. callback_ret =
  12872. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  12873. ? 0
  12874. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  12875. phys_ctx->user_data));
  12876. if (callback_ret < 0) {
  12877. mg_cry_internal(fc(phys_ctx),
  12878. "external_ssl_ctx callback returned error: %i",
  12879. callback_ret);
  12880. return 0;
  12881. } else if (callback_ret > 0) {
  12882. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  12883. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12884. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  12885. return 0;
  12886. }
  12887. return 1;
  12888. }
  12889. /* else: external_ssl_ctx does not exist or returns 0,
  12890. * CivetWeb should continue initializing SSL */
  12891. /* If PEM file is not specified and the init_ssl callback
  12892. * is not specified, setup will fail. */
  12893. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  12894. && (phys_ctx->callbacks.init_ssl == NULL)) {
  12895. /* No certificate and no callback:
  12896. * Essential data to set up TLS is missing.
  12897. */
  12898. mg_cry_internal(fc(phys_ctx),
  12899. "Initializing SSL failed: -%s is not set",
  12900. config_options[SSL_CERTIFICATE].name);
  12901. return 0;
  12902. }
  12903. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12904. if (chain == NULL) {
  12905. chain = pem;
  12906. }
  12907. if ((chain != NULL) && (*chain == 0)) {
  12908. chain = NULL;
  12909. }
  12910. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12911. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  12912. return 0;
  12913. }
  12914. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  12915. }
  12916. static void
  12917. uninitialize_ssl(void)
  12918. {
  12919. #ifdef OPENSSL_API_1_1
  12920. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12921. /* Shutdown according to
  12922. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12923. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12924. */
  12925. CONF_modules_unload(1);
  12926. #else
  12927. int i;
  12928. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12929. /* Shutdown according to
  12930. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12931. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12932. */
  12933. CRYPTO_set_locking_callback(NULL);
  12934. CRYPTO_set_id_callback(NULL);
  12935. ENGINE_cleanup();
  12936. CONF_modules_unload(1);
  12937. ERR_free_strings();
  12938. EVP_cleanup();
  12939. CRYPTO_cleanup_all_ex_data();
  12940. ERR_remove_state(0);
  12941. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12942. pthread_mutex_destroy(&ssl_mutexes[i]);
  12943. }
  12944. mg_free(ssl_mutexes);
  12945. ssl_mutexes = NULL;
  12946. #endif /* OPENSSL_API_1_1 */
  12947. }
  12948. }
  12949. #endif /* !NO_SSL */
  12950. static int
  12951. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  12952. {
  12953. if (phys_ctx) {
  12954. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12955. const char *path;
  12956. if (!dom_ctx) {
  12957. dom_ctx = &(phys_ctx->dd);
  12958. }
  12959. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  12960. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  12961. mg_cry_internal(fc(phys_ctx),
  12962. "Cannot open %s: %s",
  12963. path,
  12964. strerror(ERRNO));
  12965. return 0;
  12966. }
  12967. return 1;
  12968. }
  12969. return 0;
  12970. }
  12971. static int
  12972. set_acl_option(struct mg_context *phys_ctx)
  12973. {
  12974. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  12975. }
  12976. static void
  12977. reset_per_request_attributes(struct mg_connection *conn)
  12978. {
  12979. if (!conn) {
  12980. return;
  12981. }
  12982. conn->connection_type =
  12983. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  12984. conn->num_bytes_sent = conn->consumed_content = 0;
  12985. conn->path_info = NULL;
  12986. conn->status_code = -1;
  12987. conn->content_len = -1;
  12988. conn->is_chunked = 0;
  12989. conn->must_close = 0;
  12990. conn->request_len = 0;
  12991. conn->throttle = 0;
  12992. conn->data_len = 0;
  12993. conn->chunk_remainder = 0;
  12994. conn->accept_gzip = 0;
  12995. conn->response_info.content_length = conn->request_info.content_length = -1;
  12996. conn->response_info.http_version = conn->request_info.http_version = NULL;
  12997. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  12998. conn->response_info.status_text = NULL;
  12999. conn->response_info.status_code = 0;
  13000. conn->request_info.remote_user = NULL;
  13001. conn->request_info.request_method = NULL;
  13002. conn->request_info.request_uri = NULL;
  13003. conn->request_info.local_uri = NULL;
  13004. #if defined(MG_LEGACY_INTERFACE)
  13005. /* Legacy before split into local_uri and request_uri */
  13006. conn->request_info.uri = NULL;
  13007. #endif
  13008. }
  13009. #if 0
  13010. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13011. * Leave this function here (commented out) for reference until
  13012. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13013. * no longer required.
  13014. */
  13015. static int
  13016. set_sock_timeout(SOCKET sock, int milliseconds)
  13017. {
  13018. int r0 = 0, r1, r2;
  13019. #ifdef _WIN32
  13020. /* Windows specific */
  13021. DWORD tv = (DWORD)milliseconds;
  13022. #else
  13023. /* Linux, ... (not Windows) */
  13024. struct timeval tv;
  13025. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13026. * max. time waiting for the acknowledged of TCP data before the connection
  13027. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13028. * If this option is not set, the default timeout of 20-30 minutes is used.
  13029. */
  13030. /* #define TCP_USER_TIMEOUT (18) */
  13031. #if defined(TCP_USER_TIMEOUT)
  13032. unsigned int uto = (unsigned int)milliseconds;
  13033. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13034. #endif
  13035. memset(&tv, 0, sizeof(tv));
  13036. tv.tv_sec = milliseconds / 1000;
  13037. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13038. #endif /* _WIN32 */
  13039. r1 = setsockopt(
  13040. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13041. r2 = setsockopt(
  13042. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13043. return r0 || r1 || r2;
  13044. }
  13045. #endif
  13046. static int
  13047. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13048. {
  13049. if (setsockopt(sock,
  13050. IPPROTO_TCP,
  13051. TCP_NODELAY,
  13052. (SOCK_OPT_TYPE)&nodelay_on,
  13053. sizeof(nodelay_on)) != 0) {
  13054. /* Error */
  13055. return 1;
  13056. }
  13057. /* OK */
  13058. return 0;
  13059. }
  13060. static void
  13061. close_socket_gracefully(struct mg_connection *conn)
  13062. {
  13063. #if defined(_WIN32)
  13064. char buf[MG_BUF_LEN];
  13065. int n;
  13066. #endif
  13067. struct linger linger;
  13068. int error_code = 0;
  13069. int linger_timeout = -2;
  13070. socklen_t opt_len = sizeof(error_code);
  13071. if (!conn) {
  13072. return;
  13073. }
  13074. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13075. * "Note that enabling a nonzero timeout on a nonblocking socket
  13076. * is not recommended.", so set it to blocking now */
  13077. set_blocking_mode(conn->client.sock);
  13078. /* Send FIN to the client */
  13079. shutdown(conn->client.sock, SHUTDOWN_WR);
  13080. #if defined(_WIN32)
  13081. /* Read and discard pending incoming data. If we do not do that and
  13082. * close
  13083. * the socket, the data in the send buffer may be discarded. This
  13084. * behaviour is seen on Windows, when client keeps sending data
  13085. * when server decides to close the connection; then when client
  13086. * does recv() it gets no data back. */
  13087. do {
  13088. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13089. } while (n > 0);
  13090. #endif
  13091. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13092. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13093. }
  13094. /* Set linger option according to configuration */
  13095. if (linger_timeout >= 0) {
  13096. /* Set linger option to avoid socket hanging out after close. This
  13097. * prevent ephemeral port exhaust problem under high QPS. */
  13098. linger.l_onoff = 1;
  13099. #if defined(_MSC_VER)
  13100. #pragma warning(push)
  13101. #pragma warning(disable : 4244)
  13102. #endif
  13103. #if defined(__GNUC__) || defined(__MINGW32__)
  13104. #pragma GCC diagnostic push
  13105. #pragma GCC diagnostic ignored "-Wconversion"
  13106. #endif
  13107. /* Data type of linger structure elements may differ,
  13108. * so we don't know what cast we need here.
  13109. * Disable type conversion warnings. */
  13110. linger.l_linger = (linger_timeout + 999) / 1000;
  13111. #if defined(__GNUC__) || defined(__MINGW32__)
  13112. #pragma GCC diagnostic pop
  13113. #endif
  13114. #if defined(_MSC_VER)
  13115. #pragma warning(pop)
  13116. #endif
  13117. } else {
  13118. linger.l_onoff = 0;
  13119. linger.l_linger = 0;
  13120. }
  13121. if (linger_timeout < -1) {
  13122. /* Default: don't configure any linger */
  13123. } else if (getsockopt(conn->client.sock,
  13124. SOL_SOCKET,
  13125. SO_ERROR,
  13126. (char *)&error_code,
  13127. &opt_len) != 0) {
  13128. /* Cannot determine if socket is already closed. This should
  13129. * not occur and never did in a test. Log an error message
  13130. * and continue. */
  13131. mg_cry_internal(conn,
  13132. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13133. __func__,
  13134. strerror(ERRNO));
  13135. } else if (error_code == ECONNRESET) {
  13136. /* Socket already closed by client/peer, close socket without linger
  13137. */
  13138. } else {
  13139. /* Set linger timeout */
  13140. if (setsockopt(conn->client.sock,
  13141. SOL_SOCKET,
  13142. SO_LINGER,
  13143. (char *)&linger,
  13144. sizeof(linger)) != 0) {
  13145. mg_cry_internal(
  13146. conn,
  13147. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  13148. __func__,
  13149. linger.l_onoff,
  13150. linger.l_linger,
  13151. strerror(ERRNO));
  13152. }
  13153. }
  13154. /* Now we know that our FIN is ACK-ed, safe to close */
  13155. closesocket(conn->client.sock);
  13156. conn->client.sock = INVALID_SOCKET;
  13157. }
  13158. static void
  13159. close_connection(struct mg_connection *conn)
  13160. {
  13161. #if defined(USE_SERVER_STATS)
  13162. conn->conn_state = 6; /* to close */
  13163. #endif
  13164. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13165. if (conn->lua_websocket_state) {
  13166. lua_websocket_close(conn, conn->lua_websocket_state);
  13167. conn->lua_websocket_state = NULL;
  13168. }
  13169. #endif
  13170. mg_lock_connection(conn);
  13171. /* Set close flag, so keep-alive loops will stop */
  13172. conn->must_close = 1;
  13173. /* call the connection_close callback if assigned */
  13174. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  13175. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13176. conn->phys_ctx->callbacks.connection_close(conn);
  13177. }
  13178. }
  13179. /* Reset user data, after close callback is called.
  13180. * Do not reuse it. If the user needs a destructor,
  13181. * it must be done in the connection_close callback. */
  13182. mg_set_user_connection_data(conn, NULL);
  13183. #if defined(USE_SERVER_STATS)
  13184. conn->conn_state = 7; /* closing */
  13185. #endif
  13186. #ifndef NO_SSL
  13187. if (conn->ssl != NULL) {
  13188. /* Run SSL_shutdown twice to ensure completely close SSL connection
  13189. */
  13190. SSL_shutdown(conn->ssl);
  13191. SSL_free(conn->ssl);
  13192. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  13193. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  13194. #ifndef OPENSSL_API_1_1
  13195. ERR_remove_state(0);
  13196. #endif
  13197. conn->ssl = NULL;
  13198. }
  13199. #endif
  13200. if (conn->client.sock != INVALID_SOCKET) {
  13201. close_socket_gracefully(conn);
  13202. conn->client.sock = INVALID_SOCKET;
  13203. }
  13204. if (conn->host) {
  13205. mg_free((void *)conn->host);
  13206. conn->host = NULL;
  13207. }
  13208. mg_unlock_connection(conn);
  13209. #if defined(USE_SERVER_STATS)
  13210. conn->conn_state = 8; /* closed */
  13211. #endif
  13212. }
  13213. void
  13214. mg_close_connection(struct mg_connection *conn)
  13215. {
  13216. #if defined(USE_WEBSOCKET)
  13217. struct mg_context *client_ctx = NULL;
  13218. #endif /* defined(USE_WEBSOCKET) */
  13219. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13220. return;
  13221. }
  13222. #if defined(USE_WEBSOCKET)
  13223. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13224. if (conn->in_websocket_handling) {
  13225. /* Set close flag, so the server thread can exit. */
  13226. conn->must_close = 1;
  13227. return;
  13228. }
  13229. }
  13230. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  13231. unsigned int i;
  13232. /* ws/wss client */
  13233. client_ctx = conn->phys_ctx;
  13234. /* client context: loops must end */
  13235. client_ctx->stop_flag = 1;
  13236. conn->must_close = 1;
  13237. /* We need to get the client thread out of the select/recv call
  13238. * here. */
  13239. /* Since we use a sleep quantum of some seconds to check for recv
  13240. * timeouts, we will just wait a few seconds in mg_join_thread. */
  13241. /* join worker thread */
  13242. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  13243. if (client_ctx->worker_threadids[i] != 0) {
  13244. mg_join_thread(client_ctx->worker_threadids[i]);
  13245. }
  13246. }
  13247. }
  13248. #endif /* defined(USE_WEBSOCKET) */
  13249. close_connection(conn);
  13250. #ifndef NO_SSL
  13251. if (conn->client_ssl_ctx != NULL) {
  13252. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  13253. }
  13254. #endif
  13255. #if defined(USE_WEBSOCKET)
  13256. if (client_ctx != NULL) {
  13257. /* free context */
  13258. mg_free(client_ctx->worker_threadids);
  13259. mg_free(client_ctx);
  13260. (void)pthread_mutex_destroy(&conn->mutex);
  13261. mg_free(conn);
  13262. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  13263. mg_free(conn);
  13264. }
  13265. #else
  13266. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  13267. mg_free(conn);
  13268. }
  13269. #endif /* defined(USE_WEBSOCKET) */
  13270. }
  13271. /* Only for memory statistics */
  13272. static struct mg_context common_client_context;
  13273. static struct mg_connection *
  13274. mg_connect_client_impl(const struct mg_client_options *client_options,
  13275. int use_ssl,
  13276. char *ebuf,
  13277. size_t ebuf_len)
  13278. {
  13279. struct mg_connection *conn = NULL;
  13280. SOCKET sock;
  13281. union usa sa;
  13282. struct sockaddr *psa;
  13283. socklen_t len;
  13284. unsigned max_req_size =
  13285. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  13286. /* Size of structures, aligned to 8 bytes */
  13287. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  13288. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  13289. conn = (struct mg_connection *)mg_calloc_ctx(1,
  13290. conn_size + ctx_size
  13291. + max_req_size,
  13292. &common_client_context);
  13293. if (conn == NULL) {
  13294. mg_snprintf(NULL,
  13295. NULL, /* No truncation check for ebuf */
  13296. ebuf,
  13297. ebuf_len,
  13298. "calloc(): %s",
  13299. strerror(ERRNO));
  13300. return NULL;
  13301. }
  13302. #if defined(__GNUC__) || defined(__MINGW32__)
  13303. #pragma GCC diagnostic push
  13304. #pragma GCC diagnostic ignored "-Wcast-align"
  13305. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13306. /* conn_size is aligned to 8 bytes */
  13307. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  13308. #if defined(__GNUC__) || defined(__MINGW32__)
  13309. #pragma GCC diagnostic pop
  13310. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13311. conn->buf = (((char *)conn) + conn_size + ctx_size);
  13312. conn->buf_size = (int)max_req_size;
  13313. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  13314. conn->dom_ctx = &(conn->phys_ctx->dd);
  13315. if (!connect_socket(&common_client_context,
  13316. client_options->host,
  13317. client_options->port,
  13318. use_ssl,
  13319. ebuf,
  13320. ebuf_len,
  13321. &sock,
  13322. &sa)) {
  13323. /* ebuf is set by connect_socket,
  13324. * free all memory and return NULL; */
  13325. mg_free(conn);
  13326. return NULL;
  13327. }
  13328. #ifndef NO_SSL
  13329. #ifdef OPENSSL_API_1_1
  13330. if (use_ssl
  13331. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  13332. mg_snprintf(NULL,
  13333. NULL, /* No truncation check for ebuf */
  13334. ebuf,
  13335. ebuf_len,
  13336. "SSL_CTX_new error");
  13337. closesocket(sock);
  13338. mg_free(conn);
  13339. return NULL;
  13340. }
  13341. #else
  13342. if (use_ssl
  13343. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  13344. == NULL) {
  13345. mg_snprintf(NULL,
  13346. NULL, /* No truncation check for ebuf */
  13347. ebuf,
  13348. ebuf_len,
  13349. "SSL_CTX_new error");
  13350. closesocket(sock);
  13351. mg_free(conn);
  13352. return NULL;
  13353. }
  13354. #endif /* OPENSSL_API_1_1 */
  13355. #endif /* NO_SSL */
  13356. #ifdef USE_IPV6
  13357. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  13358. : sizeof(conn->client.rsa.sin6);
  13359. psa = (sa.sa.sa_family == AF_INET)
  13360. ? (struct sockaddr *)&(conn->client.rsa.sin)
  13361. : (struct sockaddr *)&(conn->client.rsa.sin6);
  13362. #else
  13363. len = sizeof(conn->client.rsa.sin);
  13364. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  13365. #endif
  13366. conn->client.sock = sock;
  13367. conn->client.lsa = sa;
  13368. if (getsockname(sock, psa, &len) != 0) {
  13369. mg_cry_internal(conn,
  13370. "%s: getsockname() failed: %s",
  13371. __func__,
  13372. strerror(ERRNO));
  13373. }
  13374. conn->client.is_ssl = use_ssl ? 1 : 0;
  13375. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13376. #ifndef NO_SSL
  13377. if (use_ssl) {
  13378. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  13379. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  13380. * SSL_CTX_set_verify call is needed to switch off server
  13381. * certificate checking, which is off by default in OpenSSL and
  13382. * on in yaSSL. */
  13383. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  13384. * SSL_VERIFY_PEER, verify_ssl_server); */
  13385. if (client_options->client_cert) {
  13386. if (!ssl_use_pem_file(&common_client_context,
  13387. &(common_client_context.dd),
  13388. client_options->client_cert,
  13389. NULL)) {
  13390. mg_snprintf(NULL,
  13391. NULL, /* No truncation check for ebuf */
  13392. ebuf,
  13393. ebuf_len,
  13394. "Can not use SSL client certificate");
  13395. SSL_CTX_free(conn->client_ssl_ctx);
  13396. closesocket(sock);
  13397. mg_free(conn);
  13398. return NULL;
  13399. }
  13400. }
  13401. if (client_options->server_cert) {
  13402. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  13403. client_options->server_cert,
  13404. NULL);
  13405. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  13406. } else {
  13407. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  13408. }
  13409. if (!sslize(conn,
  13410. conn->client_ssl_ctx,
  13411. SSL_connect,
  13412. &(conn->phys_ctx->stop_flag))) {
  13413. mg_snprintf(NULL,
  13414. NULL, /* No truncation check for ebuf */
  13415. ebuf,
  13416. ebuf_len,
  13417. "SSL connection error");
  13418. SSL_CTX_free(conn->client_ssl_ctx);
  13419. closesocket(sock);
  13420. mg_free(conn);
  13421. return NULL;
  13422. }
  13423. }
  13424. #endif
  13425. if (0 != set_non_blocking_mode(sock)) {
  13426. /* TODO: handle error */
  13427. ;
  13428. }
  13429. return conn;
  13430. }
  13431. CIVETWEB_API struct mg_connection *
  13432. mg_connect_client_secure(const struct mg_client_options *client_options,
  13433. char *error_buffer,
  13434. size_t error_buffer_size)
  13435. {
  13436. return mg_connect_client_impl(client_options,
  13437. 1,
  13438. error_buffer,
  13439. error_buffer_size);
  13440. }
  13441. struct mg_connection *
  13442. mg_connect_client(const char *host,
  13443. int port,
  13444. int use_ssl,
  13445. char *error_buffer,
  13446. size_t error_buffer_size)
  13447. {
  13448. struct mg_client_options opts;
  13449. memset(&opts, 0, sizeof(opts));
  13450. opts.host = host;
  13451. opts.port = port;
  13452. return mg_connect_client_impl(&opts,
  13453. use_ssl,
  13454. error_buffer,
  13455. error_buffer_size);
  13456. }
  13457. static const struct {
  13458. const char *proto;
  13459. size_t proto_len;
  13460. unsigned default_port;
  13461. } abs_uri_protocols[] = {{"http://", 7, 80},
  13462. {"https://", 8, 443},
  13463. {"ws://", 5, 80},
  13464. {"wss://", 6, 443},
  13465. {NULL, 0, 0}};
  13466. /* Check if the uri is valid.
  13467. * return 0 for invalid uri,
  13468. * return 1 for *,
  13469. * return 2 for relative uri,
  13470. * return 3 for absolute uri without port,
  13471. * return 4 for absolute uri with port */
  13472. static int
  13473. get_uri_type(const char *uri)
  13474. {
  13475. int i;
  13476. const char *hostend, *portbegin;
  13477. char *portend;
  13478. unsigned long port;
  13479. /* According to the HTTP standard
  13480. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  13481. * URI can be an asterisk (*) or should start with slash (relative uri),
  13482. * or it should start with the protocol (absolute uri). */
  13483. if ((uri[0] == '*') && (uri[1] == '\0')) {
  13484. /* asterisk */
  13485. return 1;
  13486. }
  13487. /* Valid URIs according to RFC 3986
  13488. * (https://www.ietf.org/rfc/rfc3986.txt)
  13489. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  13490. * and unreserved characters A-Z a-z 0-9 and -._~
  13491. * and % encoded symbols.
  13492. */
  13493. for (i = 0; uri[i] != 0; i++) {
  13494. if (uri[i] < 33) {
  13495. /* control characters and spaces are invalid */
  13496. return 0;
  13497. }
  13498. if (uri[i] > 126) {
  13499. /* non-ascii characters must be % encoded */
  13500. return 0;
  13501. } else {
  13502. switch (uri[i]) {
  13503. case '"': /* 34 */
  13504. case '<': /* 60 */
  13505. case '>': /* 62 */
  13506. case '\\': /* 92 */
  13507. case '^': /* 94 */
  13508. case '`': /* 96 */
  13509. case '{': /* 123 */
  13510. case '|': /* 124 */
  13511. case '}': /* 125 */
  13512. return 0;
  13513. default:
  13514. /* character is ok */
  13515. break;
  13516. }
  13517. }
  13518. }
  13519. /* A relative uri starts with a / character */
  13520. if (uri[0] == '/') {
  13521. /* relative uri */
  13522. return 2;
  13523. }
  13524. /* It could be an absolute uri: */
  13525. /* This function only checks if the uri is valid, not if it is
  13526. * addressing the current server. So civetweb can also be used
  13527. * as a proxy server. */
  13528. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13529. if (mg_strncasecmp(uri,
  13530. abs_uri_protocols[i].proto,
  13531. abs_uri_protocols[i].proto_len) == 0) {
  13532. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  13533. if (!hostend) {
  13534. return 0;
  13535. }
  13536. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  13537. if (!portbegin) {
  13538. return 3;
  13539. }
  13540. port = strtoul(portbegin + 1, &portend, 10);
  13541. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  13542. return 0;
  13543. }
  13544. return 4;
  13545. }
  13546. }
  13547. return 0;
  13548. }
  13549. /* Return NULL or the relative uri at the current server */
  13550. static const char *
  13551. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  13552. {
  13553. const char *server_domain;
  13554. size_t server_domain_len;
  13555. size_t request_domain_len = 0;
  13556. unsigned long port = 0;
  13557. int i, auth_domain_check_enabled;
  13558. const char *hostbegin = NULL;
  13559. const char *hostend = NULL;
  13560. const char *portbegin;
  13561. char *portend;
  13562. auth_domain_check_enabled =
  13563. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  13564. /* DNS is case insensitive, so use case insensitive string compare here
  13565. */
  13566. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13567. if (mg_strncasecmp(uri,
  13568. abs_uri_protocols[i].proto,
  13569. abs_uri_protocols[i].proto_len) == 0) {
  13570. hostbegin = uri + abs_uri_protocols[i].proto_len;
  13571. hostend = strchr(hostbegin, '/');
  13572. if (!hostend) {
  13573. return 0;
  13574. }
  13575. portbegin = strchr(hostbegin, ':');
  13576. if ((!portbegin) || (portbegin > hostend)) {
  13577. port = abs_uri_protocols[i].default_port;
  13578. request_domain_len = (size_t)(hostend - hostbegin);
  13579. } else {
  13580. port = strtoul(portbegin + 1, &portend, 10);
  13581. if ((portend != hostend) || (port <= 0)
  13582. || !is_valid_port(port)) {
  13583. return 0;
  13584. }
  13585. request_domain_len = (size_t)(portbegin - hostbegin);
  13586. }
  13587. /* protocol found, port set */
  13588. break;
  13589. }
  13590. }
  13591. if (!port) {
  13592. /* port remains 0 if the protocol is not found */
  13593. return 0;
  13594. }
  13595. /* Check if the request is directed to a different server. */
  13596. /* First check if the port is the same (IPv4 and IPv6). */
  13597. #if defined(USE_IPV6)
  13598. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  13599. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  13600. /* Request is directed to a different port */
  13601. return 0;
  13602. }
  13603. } else
  13604. #endif
  13605. {
  13606. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  13607. /* Request is directed to a different port */
  13608. return 0;
  13609. }
  13610. }
  13611. /* Finally check if the server corresponds to the authentication
  13612. * domain of the server (the server domain).
  13613. * Allow full matches (like http://mydomain.com/path/file.ext), and
  13614. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  13615. * but do not allow substrings (like
  13616. * http://notmydomain.com/path/file.ext
  13617. * or http://mydomain.com.fake/path/file.ext).
  13618. */
  13619. if (auth_domain_check_enabled) {
  13620. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  13621. server_domain_len = strlen(server_domain);
  13622. if (!server_domain_len) {
  13623. return 0;
  13624. }
  13625. if ((request_domain_len == server_domain_len)
  13626. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  13627. /* Request is directed to this server - full name match. */
  13628. } else {
  13629. if (request_domain_len < (server_domain_len + 2)) {
  13630. /* Request is directed to another server: The server name is
  13631. * longer
  13632. * than
  13633. * the request name. Drop this case here to avoid overflows
  13634. * in
  13635. * the
  13636. * following checks. */
  13637. return 0;
  13638. }
  13639. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  13640. /* Request is directed to another server: It could be a
  13641. * substring
  13642. * like notmyserver.com */
  13643. return 0;
  13644. }
  13645. if (0 != memcmp(server_domain,
  13646. hostbegin + request_domain_len - server_domain_len,
  13647. server_domain_len)) {
  13648. /* Request is directed to another server:
  13649. * The server name is different. */
  13650. return 0;
  13651. }
  13652. }
  13653. }
  13654. return hostend;
  13655. }
  13656. static int
  13657. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13658. {
  13659. if (ebuf_len > 0) {
  13660. ebuf[0] = '\0';
  13661. }
  13662. *err = 0;
  13663. reset_per_request_attributes(conn);
  13664. if (!conn) {
  13665. mg_snprintf(conn,
  13666. NULL, /* No truncation check for ebuf */
  13667. ebuf,
  13668. ebuf_len,
  13669. "%s",
  13670. "Internal error");
  13671. *err = 500;
  13672. return 0;
  13673. }
  13674. /* Set the time the request was received. This value should be used for
  13675. * timeouts. */
  13676. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  13677. conn->request_len =
  13678. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  13679. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  13680. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  13681. mg_snprintf(conn,
  13682. NULL, /* No truncation check for ebuf */
  13683. ebuf,
  13684. ebuf_len,
  13685. "%s",
  13686. "Invalid message size");
  13687. *err = 500;
  13688. return 0;
  13689. }
  13690. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  13691. mg_snprintf(conn,
  13692. NULL, /* No truncation check for ebuf */
  13693. ebuf,
  13694. ebuf_len,
  13695. "%s",
  13696. "Message too large");
  13697. *err = 413;
  13698. return 0;
  13699. }
  13700. if (conn->request_len <= 0) {
  13701. if (conn->data_len > 0) {
  13702. mg_snprintf(conn,
  13703. NULL, /* No truncation check for ebuf */
  13704. ebuf,
  13705. ebuf_len,
  13706. "%s",
  13707. "Malformed message");
  13708. *err = 400;
  13709. } else {
  13710. /* Server did not recv anything -> just close the connection */
  13711. conn->must_close = 1;
  13712. mg_snprintf(conn,
  13713. NULL, /* No truncation check for ebuf */
  13714. ebuf,
  13715. ebuf_len,
  13716. "%s",
  13717. "No data received");
  13718. *err = 0;
  13719. }
  13720. return 0;
  13721. }
  13722. return 1;
  13723. }
  13724. static int
  13725. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13726. {
  13727. const char *cl;
  13728. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13729. return 0;
  13730. }
  13731. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  13732. <= 0) {
  13733. mg_snprintf(conn,
  13734. NULL, /* No truncation check for ebuf */
  13735. ebuf,
  13736. ebuf_len,
  13737. "%s",
  13738. "Bad request");
  13739. *err = 400;
  13740. return 0;
  13741. }
  13742. /* Message is a valid request */
  13743. /* Is there a "host" ? */
  13744. conn->host = alloc_get_host(conn);
  13745. if (!conn->host) {
  13746. mg_snprintf(conn,
  13747. NULL, /* No truncation check for ebuf */
  13748. ebuf,
  13749. ebuf_len,
  13750. "%s",
  13751. "Bad request: Host mismatch");
  13752. *err = 400;
  13753. return 0;
  13754. }
  13755. /* Do we know the content length? */
  13756. if ((cl = get_header(conn->request_info.http_headers,
  13757. conn->request_info.num_headers,
  13758. "Content-Length")) != NULL) {
  13759. /* Request/response has content length set */
  13760. char *endptr = NULL;
  13761. conn->content_len = strtoll(cl, &endptr, 10);
  13762. if (endptr == cl) {
  13763. mg_snprintf(conn,
  13764. NULL, /* No truncation check for ebuf */
  13765. ebuf,
  13766. ebuf_len,
  13767. "%s",
  13768. "Bad request");
  13769. *err = 411;
  13770. return 0;
  13771. }
  13772. /* Publish the content length back to the request info. */
  13773. conn->request_info.content_length = conn->content_len;
  13774. } else if ((cl = get_header(conn->request_info.http_headers,
  13775. conn->request_info.num_headers,
  13776. "Transfer-Encoding")) != NULL
  13777. && !mg_strcasecmp(cl, "chunked")) {
  13778. conn->is_chunked = 1;
  13779. conn->content_len = -1; /* unknown content length */
  13780. } else if (get_http_method_info(conn->request_info.request_method)
  13781. ->request_has_body) {
  13782. /* POST or PUT request without content length set */
  13783. conn->content_len = -1; /* unknown content length */
  13784. } else {
  13785. /* Other request */
  13786. conn->content_len = 0; /* No content */
  13787. }
  13788. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  13789. return 1;
  13790. }
  13791. /* conn is assumed to be valid in this internal function */
  13792. static int
  13793. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13794. {
  13795. const char *cl;
  13796. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13797. return 0;
  13798. }
  13799. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  13800. <= 0) {
  13801. mg_snprintf(conn,
  13802. NULL, /* No truncation check for ebuf */
  13803. ebuf,
  13804. ebuf_len,
  13805. "%s",
  13806. "Bad response");
  13807. *err = 400;
  13808. return 0;
  13809. }
  13810. /* Message is a valid response */
  13811. /* Do we know the content length? */
  13812. if ((cl = get_header(conn->response_info.http_headers,
  13813. conn->response_info.num_headers,
  13814. "Content-Length")) != NULL) {
  13815. /* Request/response has content length set */
  13816. char *endptr = NULL;
  13817. conn->content_len = strtoll(cl, &endptr, 10);
  13818. if (endptr == cl) {
  13819. mg_snprintf(conn,
  13820. NULL, /* No truncation check for ebuf */
  13821. ebuf,
  13822. ebuf_len,
  13823. "%s",
  13824. "Bad request");
  13825. *err = 411;
  13826. return 0;
  13827. }
  13828. /* Publish the content length back to the response info. */
  13829. conn->response_info.content_length = conn->content_len;
  13830. /* TODO: check if it is still used in response_info */
  13831. conn->request_info.content_length = conn->content_len;
  13832. } else if ((cl = get_header(conn->response_info.http_headers,
  13833. conn->response_info.num_headers,
  13834. "Transfer-Encoding")) != NULL
  13835. && !mg_strcasecmp(cl, "chunked")) {
  13836. conn->is_chunked = 1;
  13837. conn->content_len = -1; /* unknown content length */
  13838. } else {
  13839. conn->content_len = -1; /* unknown content length */
  13840. }
  13841. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  13842. return 1;
  13843. }
  13844. int
  13845. mg_get_response(struct mg_connection *conn,
  13846. char *ebuf,
  13847. size_t ebuf_len,
  13848. int timeout)
  13849. {
  13850. int err, ret;
  13851. char txt[32]; /* will not overflow */
  13852. char *save_timeout;
  13853. char *new_timeout;
  13854. if (ebuf_len > 0) {
  13855. ebuf[0] = '\0';
  13856. }
  13857. if (!conn) {
  13858. mg_snprintf(conn,
  13859. NULL, /* No truncation check for ebuf */
  13860. ebuf,
  13861. ebuf_len,
  13862. "%s",
  13863. "Parameter error");
  13864. return -1;
  13865. }
  13866. /* Implementation of API function for HTTP clients */
  13867. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  13868. if (timeout >= 0) {
  13869. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  13870. new_timeout = txt;
  13871. /* Not required for non-blocking sockets.
  13872. set_sock_timeout(conn->client.sock, timeout);
  13873. */
  13874. } else {
  13875. new_timeout = NULL;
  13876. }
  13877. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  13878. ret = get_response(conn, ebuf, ebuf_len, &err);
  13879. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  13880. #if defined(MG_LEGACY_INTERFACE)
  13881. /* TODO: 1) uri is deprecated;
  13882. * 2) here, ri.uri is the http response code */
  13883. conn->request_info.uri = conn->request_info.request_uri;
  13884. #endif
  13885. conn->request_info.local_uri = conn->request_info.request_uri;
  13886. /* TODO (mid): Define proper return values - maybe return length?
  13887. * For the first test use <0 for error and >0 for OK */
  13888. return (ret == 0) ? -1 : +1;
  13889. }
  13890. struct mg_connection *
  13891. mg_download(const char *host,
  13892. int port,
  13893. int use_ssl,
  13894. char *ebuf,
  13895. size_t ebuf_len,
  13896. const char *fmt,
  13897. ...)
  13898. {
  13899. struct mg_connection *conn;
  13900. va_list ap;
  13901. int i;
  13902. int reqerr;
  13903. if (ebuf_len > 0) {
  13904. ebuf[0] = '\0';
  13905. }
  13906. va_start(ap, fmt);
  13907. /* open a connection */
  13908. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  13909. if (conn != NULL) {
  13910. i = mg_vprintf(conn, fmt, ap);
  13911. if (i <= 0) {
  13912. mg_snprintf(conn,
  13913. NULL, /* No truncation check for ebuf */
  13914. ebuf,
  13915. ebuf_len,
  13916. "%s",
  13917. "Error sending request");
  13918. } else {
  13919. get_response(conn, ebuf, ebuf_len, &reqerr);
  13920. #if defined(MG_LEGACY_INTERFACE)
  13921. /* TODO: 1) uri is deprecated;
  13922. * 2) here, ri.uri is the http response code */
  13923. conn->request_info.uri = conn->request_info.request_uri;
  13924. #endif
  13925. conn->request_info.local_uri = conn->request_info.request_uri;
  13926. }
  13927. }
  13928. /* if an error occurred, close the connection */
  13929. if ((ebuf[0] != '\0') && (conn != NULL)) {
  13930. mg_close_connection(conn);
  13931. conn = NULL;
  13932. }
  13933. va_end(ap);
  13934. return conn;
  13935. }
  13936. struct websocket_client_thread_data {
  13937. struct mg_connection *conn;
  13938. mg_websocket_data_handler data_handler;
  13939. mg_websocket_close_handler close_handler;
  13940. void *callback_data;
  13941. };
  13942. #if defined(USE_WEBSOCKET)
  13943. #ifdef _WIN32
  13944. static unsigned __stdcall websocket_client_thread(void *data)
  13945. #else
  13946. static void *
  13947. websocket_client_thread(void *data)
  13948. #endif
  13949. {
  13950. struct websocket_client_thread_data *cdata =
  13951. (struct websocket_client_thread_data *)data;
  13952. #if !defined(_WIN32)
  13953. struct sigaction sa;
  13954. /* Ignore SIGPIPE */
  13955. memset(&sa, 0, sizeof(sa));
  13956. sa.sa_handler = SIG_IGN;
  13957. sigaction(SIGPIPE, &sa, NULL);
  13958. #endif
  13959. mg_set_thread_name("ws-clnt");
  13960. if (cdata->conn->phys_ctx) {
  13961. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  13962. /* 3 indicates a websocket client thread */
  13963. /* TODO: check if conn->phys_ctx can be set */
  13964. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  13965. 3);
  13966. }
  13967. }
  13968. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  13969. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  13970. if (cdata->close_handler != NULL) {
  13971. cdata->close_handler(cdata->conn, cdata->callback_data);
  13972. }
  13973. /* The websocket_client context has only this thread. If it runs out,
  13974. set the stop_flag to 2 (= "stopped"). */
  13975. cdata->conn->phys_ctx->stop_flag = 2;
  13976. mg_free((void *)cdata);
  13977. #ifdef _WIN32
  13978. return 0;
  13979. #else
  13980. return NULL;
  13981. #endif
  13982. }
  13983. #endif
  13984. struct mg_connection *
  13985. mg_connect_websocket_client(const char *host,
  13986. int port,
  13987. int use_ssl,
  13988. char *error_buffer,
  13989. size_t error_buffer_size,
  13990. const char *path,
  13991. const char *origin,
  13992. mg_websocket_data_handler data_func,
  13993. mg_websocket_close_handler close_func,
  13994. void *user_data)
  13995. {
  13996. struct mg_connection *conn = NULL;
  13997. #if defined(USE_WEBSOCKET)
  13998. struct mg_context *newctx = NULL;
  13999. struct websocket_client_thread_data *thread_data;
  14000. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14001. static const char *handshake_req;
  14002. if (origin != NULL) {
  14003. handshake_req = "GET %s HTTP/1.1\r\n"
  14004. "Host: %s\r\n"
  14005. "Upgrade: websocket\r\n"
  14006. "Connection: Upgrade\r\n"
  14007. "Sec-WebSocket-Key: %s\r\n"
  14008. "Sec-WebSocket-Version: 13\r\n"
  14009. "Origin: %s\r\n"
  14010. "\r\n";
  14011. } else {
  14012. handshake_req = "GET %s HTTP/1.1\r\n"
  14013. "Host: %s\r\n"
  14014. "Upgrade: websocket\r\n"
  14015. "Connection: Upgrade\r\n"
  14016. "Sec-WebSocket-Key: %s\r\n"
  14017. "Sec-WebSocket-Version: 13\r\n"
  14018. "\r\n";
  14019. }
  14020. /* Establish the client connection and request upgrade */
  14021. conn = mg_download(host,
  14022. port,
  14023. use_ssl,
  14024. error_buffer,
  14025. error_buffer_size,
  14026. handshake_req,
  14027. path,
  14028. host,
  14029. magic,
  14030. origin);
  14031. /* Connection object will be null if something goes wrong */
  14032. if (conn == NULL) {
  14033. if (!*error_buffer) {
  14034. /* There should be already an error message */
  14035. mg_snprintf(conn,
  14036. NULL, /* No truncation check for ebuf */
  14037. error_buffer,
  14038. error_buffer_size,
  14039. "Unexpected error");
  14040. }
  14041. return NULL;
  14042. }
  14043. if (conn->response_info.status_code != 101) {
  14044. /* We sent an "upgrade" request. For a correct websocket
  14045. * protocol handshake, we expect a "101 Continue" response.
  14046. * Otherwise it is a protocol violation. Maybe the HTTP
  14047. * Server does not know websockets. */
  14048. if (!*error_buffer) {
  14049. /* set an error, if not yet set */
  14050. mg_snprintf(conn,
  14051. NULL, /* No truncation check for ebuf */
  14052. error_buffer,
  14053. error_buffer_size,
  14054. "Unexpected server reply");
  14055. }
  14056. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14057. mg_free(conn);
  14058. return NULL;
  14059. }
  14060. /* For client connections, mg_context is fake. Since we need to set a
  14061. * callback function, we need to create a copy and modify it. */
  14062. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14063. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14064. newctx->user_data = user_data;
  14065. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14066. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14067. newctx->worker_threadids =
  14068. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14069. sizeof(pthread_t),
  14070. newctx);
  14071. conn->phys_ctx = newctx;
  14072. conn->dom_ctx = &(newctx->dd);
  14073. thread_data = (struct websocket_client_thread_data *)
  14074. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14075. thread_data->conn = conn;
  14076. thread_data->data_handler = data_func;
  14077. thread_data->close_handler = close_func;
  14078. thread_data->callback_data = user_data;
  14079. /* Start a thread to read the websocket client connection
  14080. * This thread will automatically stop when mg_disconnect is
  14081. * called on the client connection */
  14082. if (mg_start_thread_with_id(websocket_client_thread,
  14083. (void *)thread_data,
  14084. newctx->worker_threadids) != 0) {
  14085. mg_free((void *)thread_data);
  14086. mg_free((void *)newctx->worker_threadids);
  14087. mg_free((void *)newctx);
  14088. mg_free((void *)conn);
  14089. conn = NULL;
  14090. DEBUG_TRACE("%s",
  14091. "Websocket client connect thread could not be started\r\n");
  14092. }
  14093. #else
  14094. /* Appease "unused parameter" warnings */
  14095. (void)host;
  14096. (void)port;
  14097. (void)use_ssl;
  14098. (void)error_buffer;
  14099. (void)error_buffer_size;
  14100. (void)path;
  14101. (void)origin;
  14102. (void)user_data;
  14103. (void)data_func;
  14104. (void)close_func;
  14105. #endif
  14106. return conn;
  14107. }
  14108. /* Prepare connection data structure */
  14109. static void
  14110. init_connection(struct mg_connection *conn)
  14111. {
  14112. /* Is keep alive allowed by the server */
  14113. int keep_alive_enabled =
  14114. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  14115. if (!keep_alive_enabled) {
  14116. conn->must_close = 1;
  14117. }
  14118. /* Important: on new connection, reset the receiving buffer. Credit
  14119. * goes to crule42. */
  14120. conn->data_len = 0;
  14121. conn->handled_requests = 0;
  14122. mg_set_user_connection_data(conn, NULL);
  14123. #if defined(USE_SERVER_STATS)
  14124. conn->conn_state = 2; /* init */
  14125. #endif
  14126. /* call the init_connection callback if assigned */
  14127. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  14128. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14129. void *conn_data = NULL;
  14130. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  14131. mg_set_user_connection_data(conn, conn_data);
  14132. }
  14133. }
  14134. }
  14135. /* Process a connection - may handle multiple requests
  14136. * using the same connection.
  14137. * Must be called with a valid connection (conn and
  14138. * conn->phys_ctx must be valid).
  14139. */
  14140. static void
  14141. process_new_connection(struct mg_connection *conn)
  14142. {
  14143. struct mg_request_info *ri = &conn->request_info;
  14144. int keep_alive, discard_len;
  14145. char ebuf[100];
  14146. const char *hostend;
  14147. int reqerr, uri_type;
  14148. #if defined(USE_SERVER_STATS)
  14149. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  14150. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  14151. if (mcon > (conn->phys_ctx->max_connections)) {
  14152. /* could use atomic compare exchange, but this
  14153. * seems overkill for statistics data */
  14154. conn->phys_ctx->max_connections = mcon;
  14155. }
  14156. #endif
  14157. init_connection(conn);
  14158. DEBUG_TRACE("Start processing connection from %s",
  14159. conn->request_info.remote_addr);
  14160. /* Loop over multiple requests sent using the same connection
  14161. * (while "keep alive"). */
  14162. do {
  14163. DEBUG_TRACE("calling get_request (%i times for this connection)",
  14164. conn->handled_requests + 1);
  14165. #if defined(USE_SERVER_STATS)
  14166. conn->conn_state = 3; /* ready */
  14167. #endif
  14168. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  14169. /* The request sent by the client could not be understood by
  14170. * the server, or it was incomplete or a timeout. Send an
  14171. * error message and close the connection. */
  14172. if (reqerr > 0) {
  14173. DEBUG_ASSERT(ebuf[0] != '\0');
  14174. mg_send_http_error(conn, reqerr, "%s", ebuf);
  14175. }
  14176. } else if (strcmp(ri->http_version, "1.0")
  14177. && strcmp(ri->http_version, "1.1")) {
  14178. mg_snprintf(conn,
  14179. NULL, /* No truncation check for ebuf */
  14180. ebuf,
  14181. sizeof(ebuf),
  14182. "Bad HTTP version: [%s]",
  14183. ri->http_version);
  14184. mg_send_http_error(conn, 505, "%s", ebuf);
  14185. }
  14186. if (ebuf[0] == '\0') {
  14187. uri_type = get_uri_type(conn->request_info.request_uri);
  14188. switch (uri_type) {
  14189. case 1:
  14190. /* Asterisk */
  14191. conn->request_info.local_uri = NULL;
  14192. break;
  14193. case 2:
  14194. /* relative uri */
  14195. conn->request_info.local_uri = conn->request_info.request_uri;
  14196. break;
  14197. case 3:
  14198. case 4:
  14199. /* absolute uri (with/without port) */
  14200. hostend = get_rel_url_at_current_server(
  14201. conn->request_info.request_uri, conn);
  14202. if (hostend) {
  14203. conn->request_info.local_uri = hostend;
  14204. } else {
  14205. conn->request_info.local_uri = NULL;
  14206. }
  14207. break;
  14208. default:
  14209. mg_snprintf(conn,
  14210. NULL, /* No truncation check for ebuf */
  14211. ebuf,
  14212. sizeof(ebuf),
  14213. "Invalid URI");
  14214. mg_send_http_error(conn, 400, "%s", ebuf);
  14215. conn->request_info.local_uri = NULL;
  14216. break;
  14217. }
  14218. #if defined(MG_LEGACY_INTERFACE)
  14219. /* Legacy before split into local_uri and request_uri */
  14220. conn->request_info.uri = conn->request_info.local_uri;
  14221. #endif
  14222. }
  14223. DEBUG_TRACE("http: %s, error: %s",
  14224. (ri->http_version ? ri->http_version : "none"),
  14225. (ebuf[0] ? ebuf : "none"));
  14226. if (ebuf[0] == '\0') {
  14227. if (conn->request_info.local_uri) {
  14228. /* handle request to local server */
  14229. #if defined(USE_SERVER_STATS)
  14230. conn->conn_state = 4; /* processing */
  14231. #endif
  14232. handle_request(conn);
  14233. #if defined(USE_SERVER_STATS)
  14234. conn->conn_state = 5; /* processed */
  14235. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  14236. conn->consumed_content);
  14237. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  14238. conn->num_bytes_sent);
  14239. #endif
  14240. DEBUG_TRACE("%s", "handle_request done");
  14241. if (conn->phys_ctx->callbacks.end_request != NULL) {
  14242. conn->phys_ctx->callbacks.end_request(conn,
  14243. conn->status_code);
  14244. DEBUG_TRACE("%s", "end_request callback done");
  14245. }
  14246. log_access(conn);
  14247. } else {
  14248. /* TODO: handle non-local request (PROXY) */
  14249. conn->must_close = 1;
  14250. }
  14251. } else {
  14252. conn->must_close = 1;
  14253. }
  14254. if (ri->remote_user != NULL) {
  14255. mg_free((void *)ri->remote_user);
  14256. /* Important! When having connections with and without auth
  14257. * would cause double free and then crash */
  14258. ri->remote_user = NULL;
  14259. }
  14260. /* NOTE(lsm): order is important here. should_keep_alive() call
  14261. * is using parsed request, which will be invalid after
  14262. * memmove's below.
  14263. * Therefore, memorize should_keep_alive() result now for later
  14264. * use in loop exit condition. */
  14265. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  14266. && (conn->content_len >= 0);
  14267. /* Discard all buffered data for this request */
  14268. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  14269. && ((conn->request_len + conn->content_len)
  14270. < (int64_t)conn->data_len))
  14271. ? (int)(conn->request_len + conn->content_len)
  14272. : conn->data_len;
  14273. DEBUG_ASSERT(discard_len >= 0);
  14274. if (discard_len < 0) {
  14275. DEBUG_TRACE("internal error: discard_len = %li",
  14276. (long int)discard_len);
  14277. break;
  14278. }
  14279. conn->data_len -= discard_len;
  14280. if (conn->data_len > 0) {
  14281. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  14282. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  14283. }
  14284. DEBUG_ASSERT(conn->data_len >= 0);
  14285. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  14286. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  14287. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  14288. (long int)conn->data_len,
  14289. (long int)conn->buf_size);
  14290. break;
  14291. }
  14292. conn->handled_requests++;
  14293. } while (keep_alive);
  14294. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  14295. conn->request_info.remote_addr,
  14296. difftime(time(NULL), conn->conn_birth_time));
  14297. close_connection(conn);
  14298. #if defined(USE_SERVER_STATS)
  14299. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  14300. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  14301. #endif
  14302. }
  14303. #if defined(ALTERNATIVE_QUEUE)
  14304. static void
  14305. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14306. {
  14307. unsigned int i;
  14308. while (!ctx->stop_flag) {
  14309. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14310. /* find a free worker slot and signal it */
  14311. if (ctx->client_socks[i].in_use == 0) {
  14312. ctx->client_socks[i] = *sp;
  14313. ctx->client_socks[i].in_use = 1;
  14314. event_signal(ctx->client_wait_events[i]);
  14315. return;
  14316. }
  14317. }
  14318. /* queue is full */
  14319. mg_sleep(1);
  14320. }
  14321. }
  14322. static int
  14323. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14324. {
  14325. DEBUG_TRACE("%s", "going idle");
  14326. ctx->client_socks[thread_index].in_use = 0;
  14327. event_wait(ctx->client_wait_events[thread_index]);
  14328. *sp = ctx->client_socks[thread_index];
  14329. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14330. return !ctx->stop_flag;
  14331. }
  14332. #else /* ALTERNATIVE_QUEUE */
  14333. /* Worker threads take accepted socket from the queue */
  14334. static int
  14335. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14336. {
  14337. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14338. (void)thread_index;
  14339. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14340. DEBUG_TRACE("%s", "going idle");
  14341. /* If the queue is empty, wait. We're idle at this point. */
  14342. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  14343. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  14344. }
  14345. /* If we're stopping, sq_head may be equal to sq_tail. */
  14346. if (ctx->sq_head > ctx->sq_tail) {
  14347. /* Copy socket from the queue and increment tail */
  14348. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  14349. ctx->sq_tail++;
  14350. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14351. /* Wrap pointers if needed */
  14352. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  14353. ctx->sq_tail -= QUEUE_SIZE(ctx);
  14354. ctx->sq_head -= QUEUE_SIZE(ctx);
  14355. }
  14356. }
  14357. (void)pthread_cond_signal(&ctx->sq_empty);
  14358. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14359. return !ctx->stop_flag;
  14360. #undef QUEUE_SIZE
  14361. }
  14362. /* Master thread adds accepted socket to a queue */
  14363. static void
  14364. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14365. {
  14366. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14367. if (!ctx) {
  14368. return;
  14369. }
  14370. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14371. /* If the queue is full, wait */
  14372. while ((ctx->stop_flag == 0)
  14373. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  14374. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  14375. }
  14376. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  14377. /* Copy socket to the queue and increment head */
  14378. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  14379. ctx->sq_head++;
  14380. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  14381. }
  14382. (void)pthread_cond_signal(&ctx->sq_full);
  14383. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14384. #undef QUEUE_SIZE
  14385. }
  14386. #endif /* ALTERNATIVE_QUEUE */
  14387. struct worker_thread_args {
  14388. struct mg_context *ctx;
  14389. int index;
  14390. };
  14391. static void *
  14392. worker_thread_run(struct worker_thread_args *thread_args)
  14393. {
  14394. struct mg_context *ctx = thread_args->ctx;
  14395. struct mg_connection *conn;
  14396. struct mg_workerTLS tls;
  14397. #if defined(MG_LEGACY_INTERFACE)
  14398. uint32_t addr;
  14399. #endif
  14400. mg_set_thread_name("worker");
  14401. tls.is_master = 0;
  14402. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14403. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14404. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14405. #endif
  14406. /* Initialize thread local storage before calling any callback */
  14407. pthread_setspecific(sTlsKey, &tls);
  14408. if (ctx->callbacks.init_thread) {
  14409. /* call init_thread for a worker thread (type 1) */
  14410. ctx->callbacks.init_thread(ctx, 1);
  14411. }
  14412. /* Connection structure has been pre-allocated */
  14413. if (((int)thread_args->index < 0)
  14414. || ((unsigned)thread_args->index
  14415. >= (unsigned)ctx->cfg_worker_threads)) {
  14416. mg_cry_internal(fc(ctx),
  14417. "Internal error: Invalid worker index %i",
  14418. (int)thread_args->index);
  14419. return NULL;
  14420. }
  14421. conn = ctx->worker_connections + thread_args->index;
  14422. /* Request buffers are not pre-allocated. They are private to the
  14423. * request and do not contain any state information that might be
  14424. * of interest to anyone observing a server status. */
  14425. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  14426. if (conn->buf == NULL) {
  14427. mg_cry_internal(fc(ctx),
  14428. "Out of memory: Cannot allocate buffer for worker %i",
  14429. (int)thread_args->index);
  14430. return NULL;
  14431. }
  14432. conn->buf_size = (int)ctx->max_request_size;
  14433. conn->phys_ctx = ctx;
  14434. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  14435. conn->host = NULL; /* until we have more information. */
  14436. conn->thread_index = thread_args->index;
  14437. conn->request_info.user_data = ctx->user_data;
  14438. /* Allocate a mutex for this connection to allow communication both
  14439. * within the request handler and from elsewhere in the application
  14440. */
  14441. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  14442. #if defined(USE_SERVER_STATS)
  14443. conn->conn_state = 1; /* not consumed */
  14444. #endif
  14445. #if defined(ALTERNATIVE_QUEUE)
  14446. while ((ctx->stop_flag == 0)
  14447. && consume_socket(ctx, &conn->client, conn->thread_index)) {
  14448. #else
  14449. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  14450. * signal sq_empty condvar to wake up the master waiting in
  14451. * produce_socket() */
  14452. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  14453. #endif
  14454. conn->conn_birth_time = time(NULL);
  14455. /* Fill in IP, port info early so even if SSL setup below fails,
  14456. * error handler would have the corresponding info.
  14457. * Thanks to Johannes Winkelmann for the patch.
  14458. */
  14459. #if defined(USE_IPV6)
  14460. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  14461. conn->request_info.remote_port =
  14462. ntohs(conn->client.rsa.sin6.sin6_port);
  14463. } else
  14464. #endif
  14465. {
  14466. conn->request_info.remote_port =
  14467. ntohs(conn->client.rsa.sin.sin_port);
  14468. }
  14469. sockaddr_to_string(conn->request_info.remote_addr,
  14470. sizeof(conn->request_info.remote_addr),
  14471. &conn->client.rsa);
  14472. DEBUG_TRACE("Start processing connection from %s",
  14473. conn->request_info.remote_addr);
  14474. conn->request_info.is_ssl = conn->client.is_ssl;
  14475. if (conn->client.is_ssl) {
  14476. #ifndef NO_SSL
  14477. /* HTTPS connection */
  14478. if (sslize(conn,
  14479. conn->dom_ctx->ssl_ctx,
  14480. SSL_accept,
  14481. &(conn->phys_ctx->stop_flag))) {
  14482. /* conn->dom_ctx is set in get_request */
  14483. /* Get SSL client certificate information (if set) */
  14484. ssl_get_client_cert_info(conn);
  14485. /* process HTTPS connection */
  14486. process_new_connection(conn);
  14487. /* Free client certificate info */
  14488. if (conn->request_info.client_cert) {
  14489. mg_free((void *)(conn->request_info.client_cert->subject));
  14490. mg_free((void *)(conn->request_info.client_cert->issuer));
  14491. mg_free((void *)(conn->request_info.client_cert->serial));
  14492. mg_free((void *)(conn->request_info.client_cert->finger));
  14493. /* Free certificate memory */
  14494. X509_free(
  14495. (X509 *)conn->request_info.client_cert->peer_cert);
  14496. conn->request_info.client_cert->peer_cert = 0;
  14497. conn->request_info.client_cert->subject = 0;
  14498. conn->request_info.client_cert->issuer = 0;
  14499. conn->request_info.client_cert->serial = 0;
  14500. conn->request_info.client_cert->finger = 0;
  14501. mg_free(conn->request_info.client_cert);
  14502. conn->request_info.client_cert = 0;
  14503. }
  14504. }
  14505. #endif
  14506. } else {
  14507. /* process HTTP connection */
  14508. process_new_connection(conn);
  14509. }
  14510. DEBUG_TRACE("%s", "Connection closed");
  14511. }
  14512. pthread_setspecific(sTlsKey, NULL);
  14513. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14514. CloseHandle(tls.pthread_cond_helper_mutex);
  14515. #endif
  14516. pthread_mutex_destroy(&conn->mutex);
  14517. /* Free the request buffer. */
  14518. conn->buf_size = 0;
  14519. mg_free(conn->buf);
  14520. conn->buf = NULL;
  14521. #if defined(USE_SERVER_STATS)
  14522. conn->conn_state = 9; /* done */
  14523. #endif
  14524. DEBUG_TRACE("%s", "exiting");
  14525. return NULL;
  14526. }
  14527. /* Threads have different return types on Windows and Unix. */
  14528. #ifdef _WIN32
  14529. static unsigned __stdcall worker_thread(void *thread_func_param)
  14530. {
  14531. struct worker_thread_args *pwta =
  14532. (struct worker_thread_args *)thread_func_param;
  14533. worker_thread_run(pwta);
  14534. mg_free(thread_func_param);
  14535. return 0;
  14536. }
  14537. #else
  14538. static void *
  14539. worker_thread(void *thread_func_param)
  14540. {
  14541. struct worker_thread_args *pwta =
  14542. (struct worker_thread_args *)thread_func_param;
  14543. struct sigaction sa;
  14544. /* Ignore SIGPIPE */
  14545. memset(&sa, 0, sizeof(sa));
  14546. sa.sa_handler = SIG_IGN;
  14547. sigaction(SIGPIPE, &sa, NULL);
  14548. worker_thread_run(pwta);
  14549. mg_free(thread_func_param);
  14550. return NULL;
  14551. }
  14552. #endif /* _WIN32 */
  14553. static void
  14554. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  14555. {
  14556. struct socket so;
  14557. char src_addr[IP_ADDR_STR_LEN];
  14558. socklen_t len = sizeof(so.rsa);
  14559. int on = 1;
  14560. if (!listener) {
  14561. return;
  14562. }
  14563. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  14564. == INVALID_SOCKET) {
  14565. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  14566. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  14567. mg_cry_internal(fc(ctx),
  14568. "%s: %s is not allowed to connect",
  14569. __func__,
  14570. src_addr);
  14571. closesocket(so.sock);
  14572. } else {
  14573. /* Put so socket structure into the queue */
  14574. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  14575. set_close_on_exec(so.sock, fc(ctx));
  14576. so.is_ssl = listener->is_ssl;
  14577. so.ssl_redir = listener->ssl_redir;
  14578. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  14579. mg_cry_internal(fc(ctx),
  14580. "%s: getsockname() failed: %s",
  14581. __func__,
  14582. strerror(ERRNO));
  14583. }
  14584. /* Set TCP keep-alive. This is needed because if HTTP-level
  14585. * keep-alive
  14586. * is enabled, and client resets the connection, server won't get
  14587. * TCP FIN or RST and will keep the connection open forever. With
  14588. * TCP keep-alive, next keep-alive handshake will figure out that
  14589. * the client is down and will close the server end.
  14590. * Thanks to Igor Klopov who suggested the patch. */
  14591. if (setsockopt(so.sock,
  14592. SOL_SOCKET,
  14593. SO_KEEPALIVE,
  14594. (SOCK_OPT_TYPE)&on,
  14595. sizeof(on)) != 0) {
  14596. mg_cry_internal(
  14597. fc(ctx),
  14598. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  14599. __func__,
  14600. strerror(ERRNO));
  14601. }
  14602. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  14603. * to effectively fill up the underlying IP packet payload and
  14604. * reduce the overhead of sending lots of small buffers. However
  14605. * this hurts the server's throughput (ie. operations per second)
  14606. * when HTTP 1.1 persistent connections are used and the responses
  14607. * are relatively small (eg. less than 1400 bytes).
  14608. */
  14609. if ((ctx != NULL) && (ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  14610. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  14611. if (set_tcp_nodelay(so.sock, 1) != 0) {
  14612. mg_cry_internal(
  14613. fc(ctx),
  14614. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  14615. __func__,
  14616. strerror(ERRNO));
  14617. }
  14618. }
  14619. /* We are using non-blocking sockets. Thus, the
  14620. * set_sock_timeout(so.sock, timeout);
  14621. * call is no longer required. */
  14622. /* The "non blocking" property should already be
  14623. * inherited from the parent socket. Set it for
  14624. * non-compliant socket implementations. */
  14625. set_non_blocking_mode(so.sock);
  14626. so.in_use = 0;
  14627. produce_socket(ctx, &so);
  14628. }
  14629. }
  14630. static void
  14631. master_thread_run(void *thread_func_param)
  14632. {
  14633. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  14634. struct mg_workerTLS tls;
  14635. struct pollfd *pfd;
  14636. unsigned int i;
  14637. unsigned int workerthreadcount;
  14638. if (!ctx) {
  14639. return;
  14640. }
  14641. mg_set_thread_name("master");
  14642. /* Increase priority of the master thread */
  14643. #if defined(_WIN32)
  14644. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  14645. #elif defined(USE_MASTER_THREAD_PRIORITY)
  14646. int min_prio = sched_get_priority_min(SCHED_RR);
  14647. int max_prio = sched_get_priority_max(SCHED_RR);
  14648. if ((min_prio >= 0) && (max_prio >= 0)
  14649. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  14650. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  14651. struct sched_param sched_param = {0};
  14652. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  14653. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  14654. }
  14655. #endif
  14656. /* Initialize thread local storage */
  14657. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14658. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14659. #endif
  14660. tls.is_master = 1;
  14661. pthread_setspecific(sTlsKey, &tls);
  14662. if (ctx->callbacks.init_thread) {
  14663. /* Callback for the master thread (type 0) */
  14664. ctx->callbacks.init_thread(ctx, 0);
  14665. }
  14666. /* Server starts *now* */
  14667. ctx->start_time = time(NULL);
  14668. /* Start the server */
  14669. pfd = ctx->listening_socket_fds;
  14670. while (ctx->stop_flag == 0) {
  14671. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14672. pfd[i].fd = ctx->listening_sockets[i].sock;
  14673. pfd[i].events = POLLIN;
  14674. }
  14675. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  14676. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14677. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  14678. * successful poll, and POLLIN is defined as
  14679. * (POLLRDNORM | POLLRDBAND)
  14680. * Therefore, we're checking pfd[i].revents & POLLIN, not
  14681. * pfd[i].revents == POLLIN. */
  14682. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  14683. accept_new_connection(&ctx->listening_sockets[i], ctx);
  14684. }
  14685. }
  14686. }
  14687. }
  14688. /* Here stop_flag is 1 - Initiate shutdown. */
  14689. DEBUG_TRACE("%s", "stopping workers");
  14690. /* Stop signal received: somebody called mg_stop. Quit. */
  14691. close_all_listening_sockets(ctx);
  14692. /* Wakeup workers that are waiting for connections to handle. */
  14693. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14694. #if defined(ALTERNATIVE_QUEUE)
  14695. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14696. event_signal(ctx->client_wait_events[i]);
  14697. /* Since we know all sockets, we can shutdown the connections. */
  14698. if (ctx->client_socks[i].in_use) {
  14699. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  14700. }
  14701. }
  14702. #else
  14703. pthread_cond_broadcast(&ctx->sq_full);
  14704. #endif
  14705. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14706. /* Join all worker threads to avoid leaking threads. */
  14707. workerthreadcount = ctx->cfg_worker_threads;
  14708. for (i = 0; i < workerthreadcount; i++) {
  14709. if (ctx->worker_threadids[i] != 0) {
  14710. mg_join_thread(ctx->worker_threadids[i]);
  14711. }
  14712. }
  14713. #if defined(USE_LUA)
  14714. /* Free Lua state of lua background task */
  14715. if (ctx->lua_background_state) {
  14716. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14717. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  14718. if (lua_istable(lstate, -1)) {
  14719. reg_boolean(lstate, "shutdown", 1);
  14720. lua_pop(lstate, 1);
  14721. mg_sleep(2);
  14722. }
  14723. lua_close(lstate);
  14724. ctx->lua_background_state = 0;
  14725. }
  14726. #endif
  14727. DEBUG_TRACE("%s", "exiting");
  14728. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14729. CloseHandle(tls.pthread_cond_helper_mutex);
  14730. #endif
  14731. pthread_setspecific(sTlsKey, NULL);
  14732. /* Signal mg_stop() that we're done.
  14733. * WARNING: This must be the very last thing this
  14734. * thread does, as ctx becomes invalid after this line. */
  14735. ctx->stop_flag = 2;
  14736. }
  14737. /* Threads have different return types on Windows and Unix. */
  14738. #ifdef _WIN32
  14739. static unsigned __stdcall master_thread(void *thread_func_param)
  14740. {
  14741. master_thread_run(thread_func_param);
  14742. return 0;
  14743. }
  14744. #else
  14745. static void *
  14746. master_thread(void *thread_func_param)
  14747. {
  14748. struct sigaction sa;
  14749. /* Ignore SIGPIPE */
  14750. memset(&sa, 0, sizeof(sa));
  14751. sa.sa_handler = SIG_IGN;
  14752. sigaction(SIGPIPE, &sa, NULL);
  14753. master_thread_run(thread_func_param);
  14754. return NULL;
  14755. }
  14756. #endif /* _WIN32 */
  14757. static void
  14758. free_context(struct mg_context *ctx)
  14759. {
  14760. int i;
  14761. struct mg_handler_info *tmp_rh;
  14762. if (ctx == NULL) {
  14763. return;
  14764. }
  14765. if (ctx->callbacks.exit_context) {
  14766. ctx->callbacks.exit_context(ctx);
  14767. }
  14768. /* All threads exited, no sync is needed. Destroy thread mutex and
  14769. * condvars
  14770. */
  14771. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  14772. #if defined(ALTERNATIVE_QUEUE)
  14773. mg_free(ctx->client_socks);
  14774. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14775. event_destroy(ctx->client_wait_events[i]);
  14776. }
  14777. mg_free(ctx->client_wait_events);
  14778. #else
  14779. (void)pthread_cond_destroy(&ctx->sq_empty);
  14780. (void)pthread_cond_destroy(&ctx->sq_full);
  14781. #endif
  14782. /* Destroy other context global data structures mutex */
  14783. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  14784. #if defined(USE_TIMERS)
  14785. timers_exit(ctx);
  14786. #endif
  14787. /* Deallocate config parameters */
  14788. for (i = 0; i < NUM_OPTIONS; i++) {
  14789. if (ctx->dd.config[i] != NULL) {
  14790. #if defined(_MSC_VER)
  14791. #pragma warning(suppress : 6001)
  14792. #endif
  14793. mg_free(ctx->dd.config[i]);
  14794. }
  14795. }
  14796. /* Deallocate request handlers */
  14797. while (ctx->dd.handlers) {
  14798. tmp_rh = ctx->dd.handlers;
  14799. ctx->dd.handlers = tmp_rh->next;
  14800. mg_free(tmp_rh->uri);
  14801. mg_free(tmp_rh);
  14802. }
  14803. #ifndef NO_SSL
  14804. /* Deallocate SSL context */
  14805. if (ctx->dd.ssl_ctx != NULL) {
  14806. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  14807. int callback_ret =
  14808. (ctx->callbacks.external_ssl_ctx == NULL)
  14809. ? 0
  14810. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  14811. if (callback_ret == 0) {
  14812. SSL_CTX_free(ctx->dd.ssl_ctx);
  14813. }
  14814. /* else: ignore error and ommit SSL_CTX_free in case
  14815. * callback_ret is 1 */
  14816. }
  14817. #endif /* !NO_SSL */
  14818. /* Deallocate worker thread ID array */
  14819. if (ctx->worker_threadids != NULL) {
  14820. mg_free(ctx->worker_threadids);
  14821. }
  14822. /* Deallocate worker thread ID array */
  14823. if (ctx->worker_connections != NULL) {
  14824. mg_free(ctx->worker_connections);
  14825. }
  14826. /* deallocate system name string */
  14827. mg_free(ctx->systemName);
  14828. /* Deallocate context itself */
  14829. mg_free(ctx);
  14830. }
  14831. void
  14832. mg_stop(struct mg_context *ctx)
  14833. {
  14834. pthread_t mt;
  14835. if (!ctx) {
  14836. return;
  14837. }
  14838. /* We don't use a lock here. Calling mg_stop with the same ctx from
  14839. * two threads is not allowed. */
  14840. mt = ctx->masterthreadid;
  14841. if (mt == 0) {
  14842. return;
  14843. }
  14844. ctx->masterthreadid = 0;
  14845. /* Set stop flag, so all threads know they have to exit. */
  14846. ctx->stop_flag = 1;
  14847. /* Wait until everything has stopped. */
  14848. while (ctx->stop_flag != 2) {
  14849. (void)mg_sleep(10);
  14850. }
  14851. mg_join_thread(mt);
  14852. free_context(ctx);
  14853. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14854. (void)WSACleanup();
  14855. #endif /* _WIN32 && !__SYMBIAN32__ */
  14856. }
  14857. static void
  14858. get_system_name(char **sysName)
  14859. {
  14860. #if defined(_WIN32)
  14861. #if !defined(__SYMBIAN32__)
  14862. #if defined(_WIN32_WCE)
  14863. *sysName = mg_strdup("WinCE");
  14864. #else
  14865. char name[128];
  14866. DWORD dwVersion = 0;
  14867. DWORD dwMajorVersion = 0;
  14868. DWORD dwMinorVersion = 0;
  14869. DWORD dwBuild = 0;
  14870. BOOL wowRet, isWoW = FALSE;
  14871. #ifdef _MSC_VER
  14872. #pragma warning(push)
  14873. /* GetVersion was declared deprecated */
  14874. #pragma warning(disable : 4996)
  14875. #endif
  14876. dwVersion = GetVersion();
  14877. #ifdef _MSC_VER
  14878. #pragma warning(pop)
  14879. #endif
  14880. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14881. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14882. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  14883. (void)dwBuild;
  14884. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  14885. sprintf(name,
  14886. "Windows %u.%u%s",
  14887. (unsigned)dwMajorVersion,
  14888. (unsigned)dwMinorVersion,
  14889. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  14890. *sysName = mg_strdup(name);
  14891. #endif
  14892. #else
  14893. *sysName = mg_strdup("Symbian");
  14894. #endif
  14895. #else
  14896. struct utsname name;
  14897. memset(&name, 0, sizeof(name));
  14898. uname(&name);
  14899. *sysName = mg_strdup(name.sysname);
  14900. #endif
  14901. }
  14902. struct mg_context *
  14903. mg_start(const struct mg_callbacks *callbacks,
  14904. void *user_data,
  14905. const char **options)
  14906. {
  14907. struct mg_context *ctx;
  14908. const char *name, *value, *default_value;
  14909. int idx, ok, workerthreadcount;
  14910. unsigned int i;
  14911. int itmp;
  14912. void (*exit_callback)(const struct mg_context *ctx) = 0;
  14913. struct mg_workerTLS tls;
  14914. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14915. WSADATA data;
  14916. WSAStartup(MAKEWORD(2, 2), &data);
  14917. #endif /* _WIN32 && !__SYMBIAN32__ */
  14918. /* Allocate context and initialize reasonable general case defaults. */
  14919. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  14920. return NULL;
  14921. }
  14922. /* Random number generator will initialize at the first call */
  14923. ctx->dd.auth_nonce_mask =
  14924. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  14925. if (mg_init_library_called == 0) {
  14926. /* Legacy INIT, if mg_start is called without mg_init_library.
  14927. * Note: This may cause a memory leak */
  14928. const char *ports_option =
  14929. config_options[LISTENING_PORTS].default_value;
  14930. if (options) {
  14931. const char **run_options = options;
  14932. const char *optname = config_options[LISTENING_PORTS].name;
  14933. /* Try to find the "listening_ports" option */
  14934. while (*run_options) {
  14935. if (!strcmp(*run_options, optname)) {
  14936. ports_option = run_options[1];
  14937. }
  14938. run_options += 2;
  14939. }
  14940. }
  14941. if (is_ssl_port_used(ports_option)) {
  14942. /* Initialize with SSL support */
  14943. mg_init_library(MG_FEATURES_TLS);
  14944. } else {
  14945. /* Initialize without SSL support */
  14946. mg_init_library(MG_FEATURES_DEFAULT);
  14947. }
  14948. }
  14949. tls.is_master = -1;
  14950. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14951. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14952. tls.pthread_cond_helper_mutex = NULL;
  14953. #endif
  14954. pthread_setspecific(sTlsKey, &tls);
  14955. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  14956. #if !defined(ALTERNATIVE_QUEUE)
  14957. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  14958. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  14959. #endif
  14960. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  14961. if (!ok) {
  14962. /* Fatal error - abort start. However, this situation should never
  14963. * occur in practice. */
  14964. mg_cry_internal(fc(ctx),
  14965. "%s",
  14966. "Cannot initialize thread synchronization objects");
  14967. mg_free(ctx);
  14968. pthread_setspecific(sTlsKey, NULL);
  14969. return NULL;
  14970. }
  14971. if (callbacks) {
  14972. ctx->callbacks = *callbacks;
  14973. exit_callback = callbacks->exit_context;
  14974. ctx->callbacks.exit_context = 0;
  14975. }
  14976. ctx->user_data = user_data;
  14977. ctx->dd.handlers = NULL;
  14978. ctx->dd.next = NULL;
  14979. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14980. ctx->dd.shared_lua_websockets = NULL;
  14981. #endif
  14982. /* Store options */
  14983. while (options && (name = *options++) != NULL) {
  14984. if ((idx = get_option_index(name)) == -1) {
  14985. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  14986. free_context(ctx);
  14987. pthread_setspecific(sTlsKey, NULL);
  14988. return NULL;
  14989. } else if ((value = *options++) == NULL) {
  14990. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  14991. free_context(ctx);
  14992. pthread_setspecific(sTlsKey, NULL);
  14993. return NULL;
  14994. }
  14995. if (ctx->dd.config[idx] != NULL) {
  14996. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  14997. mg_free(ctx->dd.config[idx]);
  14998. }
  14999. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15000. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15001. }
  15002. /* Set default value if needed */
  15003. for (i = 0; config_options[i].name != NULL; i++) {
  15004. default_value = config_options[i].default_value;
  15005. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15006. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15007. }
  15008. }
  15009. /* Request size option */
  15010. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15011. if (itmp < 1024) {
  15012. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15013. free_context(ctx);
  15014. pthread_setspecific(sTlsKey, NULL);
  15015. return NULL;
  15016. }
  15017. ctx->max_request_size = (unsigned)itmp;
  15018. /* Worker thread count option */
  15019. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15020. if (workerthreadcount > MAX_WORKER_THREADS) {
  15021. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15022. free_context(ctx);
  15023. pthread_setspecific(sTlsKey, NULL);
  15024. return NULL;
  15025. }
  15026. if (workerthreadcount <= 0) {
  15027. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15028. free_context(ctx);
  15029. pthread_setspecific(sTlsKey, NULL);
  15030. return NULL;
  15031. }
  15032. /* Document root */
  15033. #if defined(NO_FILES)
  15034. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15035. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15036. free_context(ctx);
  15037. pthread_setspecific(sTlsKey, NULL);
  15038. return NULL;
  15039. }
  15040. #endif
  15041. get_system_name(&ctx->systemName);
  15042. #if defined(USE_LUA)
  15043. /* If a Lua background script has been configured, start it. */
  15044. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15045. char ebuf[256];
  15046. struct vec opt_vec;
  15047. struct vec eq_vec;
  15048. const char *sparams;
  15049. lua_State *state = (void *)mg_prepare_lua_context_script(
  15050. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15051. if (!state) {
  15052. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15053. free_context(ctx);
  15054. pthread_setspecific(sTlsKey, NULL);
  15055. return NULL;
  15056. }
  15057. ctx->lua_background_state = (void *)state;
  15058. lua_newtable(state);
  15059. reg_boolean(state, "shutdown", 0);
  15060. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15061. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15062. reg_llstring(
  15063. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15064. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15065. break;
  15066. }
  15067. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15068. } else {
  15069. ctx->lua_background_state = 0;
  15070. }
  15071. #endif
  15072. /* NOTE(lsm): order is important here. SSL certificates must
  15073. * be initialized before listening ports. UID must be set last. */
  15074. if (!set_gpass_option(ctx, NULL) ||
  15075. #if !defined(NO_SSL)
  15076. !init_ssl_ctx(ctx, NULL) ||
  15077. #endif
  15078. !set_ports_option(ctx) ||
  15079. #if !defined(_WIN32)
  15080. !set_uid_option(ctx) ||
  15081. #endif
  15082. !set_acl_option(ctx)) {
  15083. free_context(ctx);
  15084. pthread_setspecific(sTlsKey, NULL);
  15085. return NULL;
  15086. }
  15087. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  15088. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15089. sizeof(pthread_t),
  15090. ctx);
  15091. if (ctx->worker_threadids == NULL) {
  15092. mg_cry_internal(fc(ctx),
  15093. "%s",
  15094. "Not enough memory for worker thread ID array");
  15095. free_context(ctx);
  15096. pthread_setspecific(sTlsKey, NULL);
  15097. return NULL;
  15098. }
  15099. ctx->worker_connections =
  15100. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15101. sizeof(struct mg_connection),
  15102. ctx);
  15103. if (ctx->worker_connections == NULL) {
  15104. mg_cry_internal(fc(ctx),
  15105. "%s",
  15106. "Not enough memory for worker thread connection array");
  15107. free_context(ctx);
  15108. pthread_setspecific(sTlsKey, NULL);
  15109. return NULL;
  15110. }
  15111. #if defined(ALTERNATIVE_QUEUE)
  15112. ctx->client_wait_events =
  15113. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  15114. ctx->cfg_worker_threads,
  15115. ctx);
  15116. if (ctx->client_wait_events == NULL) {
  15117. mg_cry_internal(fc(ctx),
  15118. "%s",
  15119. "Not enough memory for worker event array");
  15120. mg_free(ctx->worker_threadids);
  15121. free_context(ctx);
  15122. pthread_setspecific(sTlsKey, NULL);
  15123. return NULL;
  15124. }
  15125. ctx->client_socks =
  15126. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  15127. ctx->cfg_worker_threads,
  15128. ctx);
  15129. if (ctx->client_wait_events == NULL) {
  15130. mg_cry_internal(fc(ctx),
  15131. "%s",
  15132. "Not enough memory for worker socket array");
  15133. mg_free(ctx->client_socks);
  15134. mg_free(ctx->worker_threadids);
  15135. free_context(ctx);
  15136. pthread_setspecific(sTlsKey, NULL);
  15137. return NULL;
  15138. }
  15139. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15140. ctx->client_wait_events[i] = event_create();
  15141. if (ctx->client_wait_events[i] == 0) {
  15142. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  15143. while (i > 0) {
  15144. i--;
  15145. event_destroy(ctx->client_wait_events[i]);
  15146. }
  15147. mg_free(ctx->client_socks);
  15148. mg_free(ctx->worker_threadids);
  15149. free_context(ctx);
  15150. pthread_setspecific(sTlsKey, NULL);
  15151. return NULL;
  15152. }
  15153. }
  15154. #endif
  15155. #if defined(USE_TIMERS)
  15156. if (timers_init(ctx) != 0) {
  15157. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  15158. free_context(ctx);
  15159. pthread_setspecific(sTlsKey, NULL);
  15160. return NULL;
  15161. }
  15162. #endif
  15163. /* Context has been created - init user libraries */
  15164. if (ctx->callbacks.init_context) {
  15165. ctx->callbacks.init_context(ctx);
  15166. }
  15167. ctx->callbacks.exit_context = exit_callback;
  15168. ctx->context_type = CONTEXT_SERVER; /* server context */
  15169. /* Start master (listening) thread */
  15170. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  15171. /* Start worker threads */
  15172. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15173. struct worker_thread_args *wta = (struct worker_thread_args *)
  15174. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  15175. if (wta) {
  15176. wta->ctx = ctx;
  15177. wta->index = (int)i;
  15178. }
  15179. if ((wta == NULL)
  15180. || (mg_start_thread_with_id(worker_thread,
  15181. wta,
  15182. &ctx->worker_threadids[i]) != 0)) {
  15183. /* thread was not created */
  15184. if (wta != NULL) {
  15185. mg_free(wta);
  15186. }
  15187. if (i > 0) {
  15188. mg_cry_internal(fc(ctx),
  15189. "Cannot start worker thread %i: error %ld",
  15190. i + 1,
  15191. (long)ERRNO);
  15192. } else {
  15193. mg_cry_internal(fc(ctx),
  15194. "Cannot create threads: error %ld",
  15195. (long)ERRNO);
  15196. free_context(ctx);
  15197. pthread_setspecific(sTlsKey, NULL);
  15198. return NULL;
  15199. }
  15200. break;
  15201. }
  15202. }
  15203. pthread_setspecific(sTlsKey, NULL);
  15204. return ctx;
  15205. }
  15206. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15207. /* Add an additional domain to an already running web server. */
  15208. int
  15209. mg_start_domain(struct mg_context *ctx, const char **options)
  15210. {
  15211. const char *name;
  15212. const char *value;
  15213. const char *default_value;
  15214. struct mg_domain_context *new_dom;
  15215. struct mg_domain_context *dom;
  15216. int idx, i;
  15217. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  15218. return -1;
  15219. }
  15220. new_dom = (struct mg_domain_context *)
  15221. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  15222. if (!new_dom) {
  15223. /* Out of memory */
  15224. return -6;
  15225. }
  15226. /* Store options - TODO: unite duplicate code */
  15227. while (options && (name = *options++) != NULL) {
  15228. if ((idx = get_option_index(name)) == -1) {
  15229. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15230. mg_free(new_dom);
  15231. return -2;
  15232. } else if ((value = *options++) == NULL) {
  15233. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15234. mg_free(new_dom);
  15235. return -2;
  15236. }
  15237. if (new_dom->config[idx] != NULL) {
  15238. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15239. mg_free(new_dom->config[idx]);
  15240. }
  15241. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  15242. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15243. }
  15244. /* Authentication domain is mandatory */
  15245. /* TODO: Maybe use a new option hostname? */
  15246. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  15247. return -4;
  15248. }
  15249. /* Set default value if needed. Take the config value from
  15250. * ctx as a default value. */
  15251. for (i = 0; config_options[i].name != NULL; i++) {
  15252. default_value = ctx->dd.config[i];
  15253. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  15254. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  15255. }
  15256. }
  15257. new_dom->handlers = NULL;
  15258. new_dom->next = NULL;
  15259. new_dom->nonce_count = 0;
  15260. new_dom->auth_nonce_mask =
  15261. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  15262. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15263. new_dom->shared_lua_websockets = NULL;
  15264. #endif
  15265. if (!init_ssl_ctx(ctx, new_dom)) {
  15266. /* Init SSL failed */
  15267. mg_free(new_dom);
  15268. return -3;
  15269. }
  15270. /* Add element to linked list. */
  15271. mg_lock_context(ctx);
  15272. idx = 0;
  15273. dom = &(ctx->dd);
  15274. for (;;) {
  15275. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  15276. dom->config[AUTHENTICATION_DOMAIN])) {
  15277. /* Domain collision */
  15278. mg_cry_internal(fc(ctx),
  15279. "domain %s already in use",
  15280. new_dom->config[AUTHENTICATION_DOMAIN]);
  15281. mg_free(new_dom);
  15282. return -5;
  15283. }
  15284. /* Count number of domains */
  15285. idx++;
  15286. if (dom->next == NULL) {
  15287. dom->next = new_dom;
  15288. break;
  15289. }
  15290. dom = dom->next;
  15291. }
  15292. mg_unlock_context(ctx);
  15293. /* Return domain number */
  15294. return idx;
  15295. }
  15296. #endif
  15297. /* Feature check API function */
  15298. unsigned
  15299. mg_check_feature(unsigned feature)
  15300. {
  15301. static const unsigned feature_set = 0
  15302. /* Set bits for available features according to API documentation.
  15303. * This bit mask is created at compile time, according to the active
  15304. * preprocessor defines. It is a single const value at runtime. */
  15305. #if !defined(NO_FILES)
  15306. | MG_FEATURES_FILES
  15307. #endif
  15308. #if !defined(NO_SSL)
  15309. | MG_FEATURES_SSL
  15310. #endif
  15311. #if !defined(NO_CGI)
  15312. | MG_FEATURES_CGI
  15313. #endif
  15314. #if defined(USE_IPV6)
  15315. | MG_FEATURES_IPV6
  15316. #endif
  15317. #if defined(USE_WEBSOCKET)
  15318. | MG_FEATURES_WEBSOCKET
  15319. #endif
  15320. #if defined(USE_LUA)
  15321. | MG_FEATURES_LUA
  15322. #endif
  15323. #if defined(USE_DUKTAPE)
  15324. | MG_FEATURES_SSJS
  15325. #endif
  15326. #if !defined(NO_CACHING)
  15327. | MG_FEATURES_CACHE
  15328. #endif
  15329. #if defined(USE_SERVER_STATS)
  15330. | MG_FEATURES_STATS
  15331. #endif
  15332. /* Set some extra bits not defined in the API documentation.
  15333. * These bits may change without further notice. */
  15334. #if defined(MG_LEGACY_INTERFACE)
  15335. | 0x8000u
  15336. #endif
  15337. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15338. | 0x4000u
  15339. #endif
  15340. #if defined(MEMORY_DEBUGGING)
  15341. | 0x1000u
  15342. #endif
  15343. #if defined(USE_TIMERS)
  15344. | 0x0200u
  15345. #endif
  15346. #if !defined(NO_NONCE_CHECK)
  15347. | 0x0400u
  15348. #endif
  15349. #if !defined(NO_POPEN)
  15350. | 0x0800u
  15351. #endif
  15352. ;
  15353. return (feature & feature_set);
  15354. }
  15355. /* strcat with additional NULL check to avoid clang scan-build warning. */
  15356. #define strcat0(a, b) \
  15357. { \
  15358. if ((a != NULL) && (b != NULL)) { \
  15359. strcat(a, b); \
  15360. } \
  15361. }
  15362. /* Get system information. It can be printed or stored by the caller.
  15363. * Return the size of available information. */
  15364. static int
  15365. mg_get_system_info_impl(char *buffer, int buflen)
  15366. {
  15367. char block[256];
  15368. int system_info_length = 0;
  15369. #if defined(_WIN32)
  15370. const char *eol = "\r\n";
  15371. #else
  15372. const char *eol = "\n";
  15373. #endif
  15374. const char *eoobj = "}";
  15375. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15376. if ((buffer == NULL) || (buflen < 1)) {
  15377. buflen = 0;
  15378. } else {
  15379. *buffer = 0;
  15380. }
  15381. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15382. system_info_length += (int)strlen(block);
  15383. if (system_info_length < buflen) {
  15384. strcat0(buffer, block);
  15385. }
  15386. /* Server version */
  15387. {
  15388. const char *version = mg_version();
  15389. mg_snprintf(NULL,
  15390. NULL,
  15391. block,
  15392. sizeof(block),
  15393. "\"version\" : \"%s\",%s",
  15394. version,
  15395. eol);
  15396. system_info_length += (int)strlen(block);
  15397. if (system_info_length < buflen) {
  15398. strcat0(buffer, block);
  15399. }
  15400. }
  15401. /* System info */
  15402. {
  15403. #if defined(_WIN32)
  15404. #if !defined(__SYMBIAN32__)
  15405. DWORD dwVersion = 0;
  15406. DWORD dwMajorVersion = 0;
  15407. DWORD dwMinorVersion = 0;
  15408. SYSTEM_INFO si;
  15409. GetSystemInfo(&si);
  15410. #ifdef _MSC_VER
  15411. #pragma warning(push)
  15412. /* GetVersion was declared deprecated */
  15413. #pragma warning(disable : 4996)
  15414. #endif
  15415. dwVersion = GetVersion();
  15416. #ifdef _MSC_VER
  15417. #pragma warning(pop)
  15418. #endif
  15419. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15420. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15421. mg_snprintf(NULL,
  15422. NULL,
  15423. block,
  15424. sizeof(block),
  15425. "\"os\" : \"Windows %u.%u\",%s",
  15426. (unsigned)dwMajorVersion,
  15427. (unsigned)dwMinorVersion,
  15428. eol);
  15429. system_info_length += (int)strlen(block);
  15430. if (system_info_length < buflen) {
  15431. strcat0(buffer, block);
  15432. }
  15433. mg_snprintf(NULL,
  15434. NULL,
  15435. block,
  15436. sizeof(block),
  15437. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  15438. (unsigned)si.wProcessorArchitecture,
  15439. (unsigned)si.dwNumberOfProcessors,
  15440. (unsigned)si.dwActiveProcessorMask,
  15441. eol);
  15442. system_info_length += (int)strlen(block);
  15443. if (system_info_length < buflen) {
  15444. strcat0(buffer, block);
  15445. }
  15446. #else
  15447. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  15448. system_info_length += (int)strlen(block);
  15449. if (system_info_length < buflen) {
  15450. strcat0(buffer, block);
  15451. }
  15452. #endif
  15453. #else
  15454. struct utsname name;
  15455. memset(&name, 0, sizeof(name));
  15456. uname(&name);
  15457. mg_snprintf(NULL,
  15458. NULL,
  15459. block,
  15460. sizeof(block),
  15461. "\"os\" : \"%s %s (%s) - %s\",%s",
  15462. name.sysname,
  15463. name.version,
  15464. name.release,
  15465. name.machine,
  15466. eol);
  15467. system_info_length += (int)strlen(block);
  15468. if (system_info_length < buflen) {
  15469. strcat0(buffer, block);
  15470. }
  15471. #endif
  15472. }
  15473. /* Features */
  15474. {
  15475. mg_snprintf(NULL,
  15476. NULL,
  15477. block,
  15478. sizeof(block),
  15479. "\"features\" : %lu,%s"
  15480. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  15481. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  15482. eol,
  15483. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  15484. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  15485. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  15486. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  15487. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  15488. : "",
  15489. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  15490. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  15491. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  15492. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  15493. eol);
  15494. system_info_length += (int)strlen(block);
  15495. if (system_info_length < buflen) {
  15496. strcat0(buffer, block);
  15497. }
  15498. #ifdef USE_LUA
  15499. mg_snprintf(NULL,
  15500. NULL,
  15501. block,
  15502. sizeof(block),
  15503. "\"lua_version\" : \"%u (%s)\",%s",
  15504. (unsigned)LUA_VERSION_NUM,
  15505. LUA_RELEASE,
  15506. eol);
  15507. system_info_length += (int)strlen(block);
  15508. if (system_info_length < buflen) {
  15509. strcat0(buffer, block);
  15510. }
  15511. #endif
  15512. #if defined(USE_DUKTAPE)
  15513. mg_snprintf(NULL,
  15514. NULL,
  15515. block,
  15516. sizeof(block),
  15517. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  15518. (unsigned)DUK_VERSION / 10000,
  15519. ((unsigned)DUK_VERSION / 100) % 100,
  15520. (unsigned)DUK_VERSION % 100,
  15521. eol);
  15522. system_info_length += (int)strlen(block);
  15523. if (system_info_length < buflen) {
  15524. strcat0(buffer, block);
  15525. }
  15526. #endif
  15527. }
  15528. /* Build date */
  15529. {
  15530. #if defined(__GNUC__)
  15531. #pragma GCC diagnostic push
  15532. /* Disable bogus compiler warning -Wdate-time */
  15533. /* TODO: The obvious flags do not know:
  15534. * #pragma GCC diagnostic ignored "-Wdate-time"
  15535. * If someone knows other flags, please tell me. See also #561.
  15536. */
  15537. #endif
  15538. mg_snprintf(NULL,
  15539. NULL,
  15540. block,
  15541. sizeof(block),
  15542. "\"build\" : \"%s\",%s",
  15543. __DATE__,
  15544. eol);
  15545. #if defined(__GNUC__)
  15546. #pragma GCC diagnostic pop
  15547. #endif
  15548. system_info_length += (int)strlen(block);
  15549. if (system_info_length < buflen) {
  15550. strcat0(buffer, block);
  15551. }
  15552. }
  15553. /* Compiler information */
  15554. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  15555. {
  15556. #if defined(_MSC_VER)
  15557. mg_snprintf(NULL,
  15558. NULL,
  15559. block,
  15560. sizeof(block),
  15561. "\"compiler\" : \"MSC: %u (%u)\",%s",
  15562. (unsigned)_MSC_VER,
  15563. (unsigned)_MSC_FULL_VER,
  15564. eol);
  15565. system_info_length += (int)strlen(block);
  15566. if (system_info_length < buflen) {
  15567. strcat0(buffer, block);
  15568. }
  15569. #elif defined(__MINGW64__)
  15570. mg_snprintf(NULL,
  15571. NULL,
  15572. block,
  15573. sizeof(block),
  15574. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  15575. (unsigned)__MINGW64_VERSION_MAJOR,
  15576. (unsigned)__MINGW64_VERSION_MINOR,
  15577. eol);
  15578. system_info_length += (int)strlen(block);
  15579. if (system_info_length < buflen) {
  15580. strcat0(buffer, block);
  15581. }
  15582. mg_snprintf(NULL,
  15583. NULL,
  15584. block,
  15585. sizeof(block),
  15586. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15587. (unsigned)__MINGW32_MAJOR_VERSION,
  15588. (unsigned)__MINGW32_MINOR_VERSION,
  15589. eol);
  15590. system_info_length += (int)strlen(block);
  15591. if (system_info_length < buflen) {
  15592. strcat0(buffer, block);
  15593. }
  15594. #elif defined(__MINGW32__)
  15595. mg_snprintf(NULL,
  15596. NULL,
  15597. block,
  15598. sizeof(block),
  15599. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15600. (unsigned)__MINGW32_MAJOR_VERSION,
  15601. (unsigned)__MINGW32_MINOR_VERSION,
  15602. eol);
  15603. system_info_length += (int)strlen(block);
  15604. if (system_info_length < buflen) {
  15605. strcat0(buffer, block);
  15606. }
  15607. #elif defined(__clang__)
  15608. mg_snprintf(NULL,
  15609. NULL,
  15610. block,
  15611. sizeof(block),
  15612. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  15613. __clang_major__,
  15614. __clang_minor__,
  15615. __clang_patchlevel__,
  15616. __clang_version__,
  15617. eol);
  15618. system_info_length += (int)strlen(block);
  15619. if (system_info_length < buflen) {
  15620. strcat0(buffer, block);
  15621. }
  15622. #elif defined(__GNUC__)
  15623. mg_snprintf(NULL,
  15624. NULL,
  15625. block,
  15626. sizeof(block),
  15627. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  15628. (unsigned)__GNUC__,
  15629. (unsigned)__GNUC_MINOR__,
  15630. (unsigned)__GNUC_PATCHLEVEL__,
  15631. eol);
  15632. system_info_length += (int)strlen(block);
  15633. if (system_info_length < buflen) {
  15634. strcat0(buffer, block);
  15635. }
  15636. #elif defined(__INTEL_COMPILER)
  15637. mg_snprintf(NULL,
  15638. NULL,
  15639. block,
  15640. sizeof(block),
  15641. "\"compiler\" : \"Intel C/C++: %u\",%s",
  15642. (unsigned)__INTEL_COMPILER,
  15643. eol);
  15644. system_info_length += (int)strlen(block);
  15645. if (system_info_length < buflen) {
  15646. strcat0(buffer, block);
  15647. }
  15648. #elif defined(__BORLANDC__)
  15649. mg_snprintf(NULL,
  15650. NULL,
  15651. block,
  15652. sizeof(block),
  15653. "\"compiler\" : \"Borland C: 0x%x\",%s",
  15654. (unsigned)__BORLANDC__,
  15655. eol);
  15656. system_info_length += (int)strlen(block);
  15657. if (system_info_length < buflen) {
  15658. strcat0(buffer, block);
  15659. }
  15660. #elif defined(__SUNPRO_C)
  15661. mg_snprintf(NULL,
  15662. NULL,
  15663. block,
  15664. sizeof(block),
  15665. "\"compiler\" : \"Solaris: 0x%x\",%s",
  15666. (unsigned)__SUNPRO_C,
  15667. eol);
  15668. system_info_length += (int)strlen(block);
  15669. if (system_info_length < buflen) {
  15670. strcat0(buffer, block);
  15671. }
  15672. #else
  15673. mg_snprintf(NULL,
  15674. NULL,
  15675. block,
  15676. sizeof(block),
  15677. "\"compiler\" : \"other\",%s",
  15678. eol);
  15679. system_info_length += (int)strlen(block);
  15680. if (system_info_length < buflen) {
  15681. strcat0(buffer, block);
  15682. }
  15683. #endif
  15684. }
  15685. /* Determine 32/64 bit data mode.
  15686. * see https://en.wikipedia.org/wiki/64-bit_computing */
  15687. {
  15688. mg_snprintf(NULL,
  15689. NULL,
  15690. block,
  15691. sizeof(block),
  15692. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  15693. "char:%u/%u, "
  15694. "ptr:%u, size:%u, time:%u\"%s",
  15695. (unsigned)sizeof(short),
  15696. (unsigned)sizeof(int),
  15697. (unsigned)sizeof(long),
  15698. (unsigned)sizeof(long long),
  15699. (unsigned)sizeof(float),
  15700. (unsigned)sizeof(double),
  15701. (unsigned)sizeof(long double),
  15702. (unsigned)sizeof(char),
  15703. (unsigned)sizeof(wchar_t),
  15704. (unsigned)sizeof(void *),
  15705. (unsigned)sizeof(size_t),
  15706. (unsigned)sizeof(time_t),
  15707. eol);
  15708. system_info_length += (int)strlen(block);
  15709. if (system_info_length < buflen) {
  15710. strcat0(buffer, block);
  15711. }
  15712. }
  15713. /* Terminate string */
  15714. if ((buflen > 0) && buffer && buffer[0]) {
  15715. if (system_info_length < buflen) {
  15716. strcat0(buffer, eoobj);
  15717. strcat0(buffer, eol);
  15718. }
  15719. }
  15720. system_info_length += reserved_len;
  15721. return system_info_length;
  15722. }
  15723. #if defined(USE_SERVER_STATS)
  15724. /* Get context information. It can be printed or stored by the caller.
  15725. * Return the size of available information. */
  15726. static int
  15727. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  15728. {
  15729. char block[256];
  15730. int context_info_length = 0;
  15731. #if defined(_WIN32)
  15732. const char *eol = "\r\n";
  15733. #else
  15734. const char *eol = "\n";
  15735. #endif
  15736. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  15737. const char *eoobj = "}";
  15738. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15739. if ((buffer == NULL) || (buflen < 1)) {
  15740. buflen = 0;
  15741. } else {
  15742. *buffer = 0;
  15743. }
  15744. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15745. context_info_length += (int)strlen(block);
  15746. if (context_info_length < buflen) {
  15747. strcat0(buffer, block);
  15748. }
  15749. /* Memory information */
  15750. if (ms) {
  15751. mg_snprintf(NULL,
  15752. NULL,
  15753. block,
  15754. sizeof(block),
  15755. "\"memory\" : {%s"
  15756. "\"blocks\" : %i,%s"
  15757. "\"used\" : %" INT64_FMT ",%s"
  15758. "\"maxUsed\" : %" INT64_FMT "%s"
  15759. "}%s%s",
  15760. eol,
  15761. ms->blockCount,
  15762. eol,
  15763. ms->totalMemUsed,
  15764. eol,
  15765. ms->maxMemUsed,
  15766. eol,
  15767. (ctx ? "," : ""),
  15768. eol);
  15769. context_info_length += (int)strlen(block);
  15770. if (context_info_length + reserved_len < buflen) {
  15771. strcat0(buffer, block);
  15772. }
  15773. }
  15774. /* Connections information */
  15775. if (ctx) {
  15776. mg_snprintf(NULL,
  15777. NULL,
  15778. block,
  15779. sizeof(block),
  15780. "\"connections\" : {%s"
  15781. "\"active\" : %i,%s"
  15782. "\"maxActive\" : %i,%s"
  15783. "\"total\" : %" INT64_FMT "%s"
  15784. "},%s",
  15785. eol,
  15786. ctx->active_connections,
  15787. eol,
  15788. ctx->max_connections,
  15789. eol,
  15790. ctx->total_connections,
  15791. eol,
  15792. eol);
  15793. context_info_length += (int)strlen(block);
  15794. if (context_info_length + reserved_len < buflen) {
  15795. strcat0(buffer, block);
  15796. }
  15797. }
  15798. /* Requests information */
  15799. if (ctx) {
  15800. mg_snprintf(NULL,
  15801. NULL,
  15802. block,
  15803. sizeof(block),
  15804. "\"requests\" : {%s"
  15805. "\"total\" : %" INT64_FMT "%s"
  15806. "},%s",
  15807. eol,
  15808. ctx->total_requests,
  15809. eol,
  15810. eol);
  15811. context_info_length += (int)strlen(block);
  15812. if (context_info_length + reserved_len < buflen) {
  15813. strcat0(buffer, block);
  15814. }
  15815. }
  15816. /* Data information */
  15817. if (ctx) {
  15818. mg_snprintf(NULL,
  15819. NULL,
  15820. block,
  15821. sizeof(block),
  15822. "\"data\" : {%s"
  15823. "\"read\" : %" INT64_FMT "%s,"
  15824. "\"written\" : %" INT64_FMT "%s"
  15825. "},%s",
  15826. eol,
  15827. ctx->total_data_read,
  15828. eol,
  15829. ctx->total_data_written,
  15830. eol,
  15831. eol);
  15832. context_info_length += (int)strlen(block);
  15833. if (context_info_length + reserved_len < buflen) {
  15834. strcat0(buffer, block);
  15835. }
  15836. }
  15837. /* Execution time information */
  15838. if (ctx) {
  15839. char start_time_str[64] = {0};
  15840. char now_str[64] = {0};
  15841. time_t start_time = ctx->start_time;
  15842. time_t now = time(NULL);
  15843. gmt_time_string(start_time_str,
  15844. sizeof(start_time_str) - 1,
  15845. &start_time);
  15846. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15847. mg_snprintf(NULL,
  15848. NULL,
  15849. block,
  15850. sizeof(block),
  15851. "\"time\" : {%s"
  15852. "\"uptime\" : %.0f,%s"
  15853. "\"start\" : \"%s\",%s"
  15854. "\"now\" : \"%s\"%s"
  15855. "}%s",
  15856. eol,
  15857. difftime(now, start_time),
  15858. eol,
  15859. start_time_str,
  15860. eol,
  15861. now_str,
  15862. eol,
  15863. eol);
  15864. context_info_length += (int)strlen(block);
  15865. if (context_info_length + reserved_len < buflen) {
  15866. strcat0(buffer, block);
  15867. }
  15868. }
  15869. /* Terminate string */
  15870. if ((buflen > 0) && buffer && buffer[0]) {
  15871. if (context_info_length < buflen) {
  15872. strcat0(buffer, eoobj);
  15873. strcat0(buffer, eol);
  15874. }
  15875. }
  15876. context_info_length += reserved_len;
  15877. return context_info_length;
  15878. }
  15879. #endif
  15880. #ifdef MG_EXPERIMENTAL_INTERFACES
  15881. /* Get connection information. It can be printed or stored by the caller.
  15882. * Return the size of available information. */
  15883. static int
  15884. mg_get_connection_info_impl(const struct mg_context *ctx,
  15885. int idx,
  15886. char *buffer,
  15887. int buflen)
  15888. {
  15889. const struct mg_connection *conn;
  15890. const struct mg_request_info *ri;
  15891. char block[256];
  15892. int connection_info_length = 0;
  15893. int state = 0;
  15894. const char *state_str = "unknown";
  15895. #if defined(_WIN32)
  15896. const char *eol = "\r\n";
  15897. #else
  15898. const char *eol = "\n";
  15899. #endif
  15900. const char *eoobj = "}";
  15901. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15902. if ((buffer == NULL) || (buflen < 1)) {
  15903. buflen = 0;
  15904. } else {
  15905. *buffer = 0;
  15906. }
  15907. if ((ctx == NULL) || (idx < 0)) {
  15908. /* Parameter error */
  15909. return 0;
  15910. }
  15911. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  15912. /* Out of range */
  15913. return 0;
  15914. }
  15915. /* Take connection [idx]. This connection is not locked in
  15916. * any way, so some other thread might use it. */
  15917. conn = (ctx->worker_connections) + idx;
  15918. /* Initialize output string */
  15919. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15920. connection_info_length += (int)strlen(block);
  15921. if (connection_info_length < buflen) {
  15922. strcat0(buffer, block);
  15923. }
  15924. /* Init variables */
  15925. ri = &(conn->request_info);
  15926. #if defined(USE_SERVER_STATS)
  15927. state = conn->conn_state;
  15928. /* State as string */
  15929. switch (state) {
  15930. case 0:
  15931. state_str = "undefined";
  15932. break;
  15933. case 1:
  15934. state_str = "not used";
  15935. break;
  15936. case 2:
  15937. state_str = "init";
  15938. break;
  15939. case 3:
  15940. state_str = "ready";
  15941. break;
  15942. case 4:
  15943. state_str = "processing";
  15944. break;
  15945. case 5:
  15946. state_str = "processed";
  15947. break;
  15948. case 6:
  15949. state_str = "to close";
  15950. break;
  15951. case 7:
  15952. state_str = "closing";
  15953. break;
  15954. case 8:
  15955. state_str = "closed";
  15956. break;
  15957. case 9:
  15958. state_str = "done";
  15959. break;
  15960. }
  15961. #endif
  15962. /* Connection info */
  15963. if ((state >= 3) && (state < 9)) {
  15964. mg_snprintf(NULL,
  15965. NULL,
  15966. block,
  15967. sizeof(block),
  15968. "\"connection\" : {%s"
  15969. "\"remote\" : {%s"
  15970. "\"protocol\" : \"%s\",%s"
  15971. "\"addr\" : \"%s\",%s"
  15972. "\"port\" : %u%s"
  15973. "},%s"
  15974. "\"handled_requests\" : %u%s"
  15975. "},%s",
  15976. eol,
  15977. eol,
  15978. get_proto_name(conn),
  15979. eol,
  15980. ri->remote_addr,
  15981. eol,
  15982. ri->remote_port,
  15983. eol,
  15984. eol,
  15985. conn->handled_requests,
  15986. eol,
  15987. eol);
  15988. connection_info_length += (int)strlen(block);
  15989. if (connection_info_length + reserved_len < buflen) {
  15990. strcat0(buffer, block);
  15991. }
  15992. }
  15993. /* Request info */
  15994. if ((state >= 4) && (state < 6)) {
  15995. mg_snprintf(NULL,
  15996. NULL,
  15997. block,
  15998. sizeof(block),
  15999. "\"request_info\" : {%s"
  16000. "\"method\" : \"%s\",%s"
  16001. "\"uri\" : \"%s\",%s"
  16002. "\"query\" : %s%s%s%s"
  16003. "},%s",
  16004. eol,
  16005. ri->request_method,
  16006. eol,
  16007. ri->request_uri,
  16008. eol,
  16009. ri->query_string ? "\"" : "",
  16010. ri->query_string ? ri->query_string : "null",
  16011. ri->query_string ? "\"" : "",
  16012. eol,
  16013. eol);
  16014. connection_info_length += (int)strlen(block);
  16015. if (connection_info_length + reserved_len < buflen) {
  16016. strcat0(buffer, block);
  16017. }
  16018. }
  16019. /* Execution time information */
  16020. if ((state >= 2) && (state < 9)) {
  16021. char start_time_str[64] = {0};
  16022. char now_str[64] = {0};
  16023. time_t start_time = conn->conn_birth_time;
  16024. time_t now = time(NULL);
  16025. gmt_time_string(start_time_str,
  16026. sizeof(start_time_str) - 1,
  16027. &start_time);
  16028. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16029. mg_snprintf(NULL,
  16030. NULL,
  16031. block,
  16032. sizeof(block),
  16033. "\"time\" : {%s"
  16034. "\"uptime\" : %.0f,%s"
  16035. "\"start\" : \"%s\",%s"
  16036. "\"now\" : \"%s\"%s"
  16037. "},%s",
  16038. eol,
  16039. difftime(now, start_time),
  16040. eol,
  16041. start_time_str,
  16042. eol,
  16043. now_str,
  16044. eol,
  16045. eol);
  16046. connection_info_length += (int)strlen(block);
  16047. if (connection_info_length + reserved_len < buflen) {
  16048. strcat0(buffer, block);
  16049. }
  16050. }
  16051. /* Remote user name */
  16052. if ((ri->remote_user) && (state < 9)) {
  16053. mg_snprintf(NULL,
  16054. NULL,
  16055. block,
  16056. sizeof(block),
  16057. "\"user\" : {%s"
  16058. "\"name\" : \"%s\",%s"
  16059. "},%s",
  16060. eol,
  16061. ri->remote_user,
  16062. eol,
  16063. eol);
  16064. connection_info_length += (int)strlen(block);
  16065. if (connection_info_length + reserved_len < buflen) {
  16066. strcat0(buffer, block);
  16067. }
  16068. }
  16069. /* Data block */
  16070. if (state >= 3) {
  16071. mg_snprintf(NULL,
  16072. NULL,
  16073. block,
  16074. sizeof(block),
  16075. "\"data\" : {%s"
  16076. "\"read\" : %" INT64_FMT ",%s"
  16077. "\"written\" : %" INT64_FMT "%s"
  16078. "},%s",
  16079. eol,
  16080. conn->consumed_content,
  16081. eol,
  16082. conn->num_bytes_sent,
  16083. eol,
  16084. eol);
  16085. connection_info_length += (int)strlen(block);
  16086. if (connection_info_length + reserved_len < buflen) {
  16087. strcat0(buffer, block);
  16088. }
  16089. }
  16090. /* State */
  16091. mg_snprintf(NULL,
  16092. NULL,
  16093. block,
  16094. sizeof(block),
  16095. "\"state\" : \"%s\"%s",
  16096. state_str,
  16097. eol);
  16098. connection_info_length += (int)strlen(block);
  16099. if (connection_info_length + reserved_len < buflen) {
  16100. strcat0(buffer, block);
  16101. }
  16102. /* Terminate string */
  16103. if ((buflen > 0) && buffer && buffer[0]) {
  16104. if (connection_info_length < buflen) {
  16105. strcat0(buffer, eoobj);
  16106. strcat0(buffer, eol);
  16107. }
  16108. }
  16109. connection_info_length += reserved_len;
  16110. return connection_info_length;
  16111. }
  16112. #endif
  16113. /* Get system information. It can be printed or stored by the caller.
  16114. * Return the size of available information. */
  16115. int
  16116. mg_get_system_info(char *buffer, int buflen)
  16117. {
  16118. if ((buffer == NULL) || (buflen < 1)) {
  16119. return mg_get_system_info_impl(NULL, 0);
  16120. } else {
  16121. /* Reset buffer, so we can always use strcat. */
  16122. buffer[0] = 0;
  16123. return mg_get_system_info_impl(buffer, buflen);
  16124. }
  16125. }
  16126. /* Get context information. It can be printed or stored by the caller.
  16127. * Return the size of available information. */
  16128. int
  16129. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16130. {
  16131. #if defined(USE_SERVER_STATS)
  16132. if ((buffer == NULL) || (buflen < 1)) {
  16133. return mg_get_context_info_impl(ctx, NULL, 0);
  16134. } else {
  16135. /* Reset buffer, so we can always use strcat. */
  16136. buffer[0] = 0;
  16137. return mg_get_context_info_impl(ctx, buffer, buflen);
  16138. }
  16139. #else
  16140. (void)ctx;
  16141. if ((buffer != NULL) && (buflen > 0)) {
  16142. buffer[0] = 0;
  16143. }
  16144. return 0;
  16145. #endif
  16146. }
  16147. #ifdef MG_EXPERIMENTAL_INTERFACES
  16148. int
  16149. mg_get_connection_info(const struct mg_context *ctx,
  16150. int idx,
  16151. char *buffer,
  16152. int buflen)
  16153. {
  16154. if ((buffer == NULL) || (buflen < 1)) {
  16155. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  16156. } else {
  16157. /* Reset buffer, so we can always use strcat. */
  16158. buffer[0] = 0;
  16159. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  16160. }
  16161. }
  16162. #endif
  16163. /* Initialize this library. This function does not need to be thread safe.
  16164. */
  16165. unsigned
  16166. mg_init_library(unsigned features)
  16167. {
  16168. #if !defined(NO_SSL)
  16169. char ebuf[128];
  16170. #endif
  16171. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  16172. unsigned features_inited = features_to_init;
  16173. if (mg_init_library_called <= 0) {
  16174. /* Not initialized yet */
  16175. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  16176. return 0;
  16177. }
  16178. }
  16179. mg_global_lock();
  16180. if (mg_init_library_called <= 0) {
  16181. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  16182. /* Fatal error - abort start. However, this situation should
  16183. * never occur in practice. */
  16184. mg_global_unlock();
  16185. return 0;
  16186. }
  16187. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16188. InitializeCriticalSection(&global_log_file_lock);
  16189. #endif /* _WIN32 && !__SYMBIAN32__ */
  16190. #if !defined(_WIN32)
  16191. pthread_mutexattr_init(&pthread_mutex_attr);
  16192. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  16193. #endif
  16194. #if defined(USE_LUA)
  16195. lua_init_optional_libraries();
  16196. #endif
  16197. }
  16198. mg_global_unlock();
  16199. #if !defined(NO_SSL)
  16200. if (features_to_init & MG_FEATURES_SSL) {
  16201. if (!mg_ssl_initialized) {
  16202. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  16203. mg_ssl_initialized = 1;
  16204. } else {
  16205. (void)ebuf;
  16206. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  16207. features_inited &= ~(2u);
  16208. }
  16209. } else {
  16210. /* ssl already initialized */
  16211. }
  16212. }
  16213. #endif
  16214. /* Start WinSock for Windows */
  16215. mg_global_lock();
  16216. if (mg_init_library_called <= 0) {
  16217. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16218. WSADATA data;
  16219. WSAStartup(MAKEWORD(2, 2), &data);
  16220. #endif /* _WIN32 && !__SYMBIAN32__ */
  16221. mg_init_library_called = 1;
  16222. } else {
  16223. mg_init_library_called++;
  16224. }
  16225. mg_global_unlock();
  16226. return features_inited;
  16227. }
  16228. /* Un-initialize this library. */
  16229. unsigned
  16230. mg_exit_library(void)
  16231. {
  16232. if (mg_init_library_called <= 0) {
  16233. return 0;
  16234. }
  16235. mg_global_lock();
  16236. mg_init_library_called--;
  16237. if (mg_init_library_called == 0) {
  16238. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16239. (void)WSACleanup();
  16240. #endif /* _WIN32 && !__SYMBIAN32__ */
  16241. #if !defined(NO_SSL)
  16242. if (mg_ssl_initialized) {
  16243. uninitialize_ssl();
  16244. mg_ssl_initialized = 0;
  16245. }
  16246. #endif
  16247. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16248. (void)DeleteCriticalSection(&global_log_file_lock);
  16249. #endif /* _WIN32 && !__SYMBIAN32__ */
  16250. #if !defined(_WIN32)
  16251. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  16252. #endif
  16253. (void)pthread_key_delete(sTlsKey);
  16254. #if defined(USE_LUA)
  16255. lua_exit_optional_libraries();
  16256. #endif
  16257. mg_global_unlock();
  16258. (void)pthread_mutex_destroy(&global_lock_mutex);
  16259. return 1;
  16260. }
  16261. mg_global_unlock();
  16262. return 1;
  16263. }
  16264. /* End of civetweb.c */