civetweb.c 501 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855
  1. /* Copyright (c) 2013-2018 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. struct mg_file;
  511. static const char *
  512. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  513. /* POSIX dirent interface */
  514. struct dirent {
  515. char d_name[PATH_MAX];
  516. };
  517. typedef struct DIR {
  518. HANDLE handle;
  519. WIN32_FIND_DATAW info;
  520. struct dirent result;
  521. } DIR;
  522. #if defined(_WIN32) && !defined(POLLIN)
  523. #ifndef HAVE_POLL
  524. struct pollfd {
  525. SOCKET fd;
  526. short events;
  527. short revents;
  528. };
  529. #define POLLIN (0x0300)
  530. #endif
  531. #endif
  532. /* Mark required libraries */
  533. #if defined(_MSC_VER)
  534. #pragma comment(lib, "Ws2_32.lib")
  535. #endif
  536. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  537. WINDOWS / UNIX include block */
  538. #include <sys/wait.h>
  539. #include <sys/socket.h>
  540. #include <sys/poll.h>
  541. #include <netinet/in.h>
  542. #include <arpa/inet.h>
  543. #include <sys/time.h>
  544. #include <sys/utsname.h>
  545. #include <stdint.h>
  546. #include <inttypes.h>
  547. #include <netdb.h>
  548. #include <netinet/tcp.h>
  549. typedef const void *SOCK_OPT_TYPE;
  550. #if defined(ANDROID)
  551. typedef unsigned short int in_port_t;
  552. #endif
  553. #include <pwd.h>
  554. #include <unistd.h>
  555. #include <grp.h>
  556. #include <dirent.h>
  557. #define vsnprintf_impl vsnprintf
  558. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  559. #include <dlfcn.h>
  560. #endif
  561. #include <pthread.h>
  562. #if defined(__MACH__)
  563. #define SSL_LIB "libssl.dylib"
  564. #define CRYPTO_LIB "libcrypto.dylib"
  565. #else
  566. #if !defined(SSL_LIB)
  567. #define SSL_LIB "libssl.so"
  568. #endif
  569. #if !defined(CRYPTO_LIB)
  570. #define CRYPTO_LIB "libcrypto.so"
  571. #endif
  572. #endif
  573. #ifndef O_BINARY
  574. #define O_BINARY (0)
  575. #endif /* O_BINARY */
  576. #define closesocket(a) (close(a))
  577. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  578. #define mg_remove(conn, x) (remove(x))
  579. #define mg_sleep(x) (usleep((x)*1000))
  580. #define mg_opendir(conn, x) (opendir(x))
  581. #define mg_closedir(x) (closedir(x))
  582. #define mg_readdir(x) (readdir(x))
  583. #define ERRNO (errno)
  584. #define INVALID_SOCKET (-1)
  585. #define INT64_FMT PRId64
  586. #define UINT64_FMT PRIu64
  587. typedef int SOCKET;
  588. #define WINCDECL
  589. #if defined(__hpux)
  590. /* HPUX 11 does not have monotonic, fall back to realtime */
  591. #ifndef CLOCK_MONOTONIC
  592. #define CLOCK_MONOTONIC CLOCK_REALTIME
  593. #endif
  594. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  595. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  596. * the prototypes use int* rather than socklen_t* which matches the
  597. * actual library expectation. When called with the wrong size arg
  598. * accept() returns a zero client inet addr and check_acl() always
  599. * fails. Since socklen_t is widely used below, just force replace
  600. * their typedef with int. - DTL
  601. */
  602. #define socklen_t int
  603. #endif /* hpux */
  604. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  605. WINDOWS / UNIX include block */
  606. /* va_copy should always be a macro, C99 and C++11 - DTL */
  607. #ifndef va_copy
  608. #define va_copy(x, y) ((x) = (y))
  609. #endif
  610. #ifdef _WIN32
  611. /* Create substitutes for POSIX functions in Win32. */
  612. #if defined(__MINGW32__)
  613. /* Show no warning in case system functions are not used. */
  614. #pragma GCC diagnostic push
  615. #pragma GCC diagnostic ignored "-Wunused-function"
  616. #endif
  617. static CRITICAL_SECTION global_log_file_lock;
  618. FUNCTION_MAY_BE_UNUSED
  619. static DWORD
  620. pthread_self(void)
  621. {
  622. return GetCurrentThreadId();
  623. }
  624. FUNCTION_MAY_BE_UNUSED
  625. static int
  626. pthread_key_create(
  627. pthread_key_t *key,
  628. void (*_ignored)(void *) /* destructor not supported for Windows */
  629. )
  630. {
  631. (void)_ignored;
  632. if ((key != 0)) {
  633. *key = TlsAlloc();
  634. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  635. }
  636. return -2;
  637. }
  638. FUNCTION_MAY_BE_UNUSED
  639. static int
  640. pthread_key_delete(pthread_key_t key)
  641. {
  642. return TlsFree(key) ? 0 : 1;
  643. }
  644. FUNCTION_MAY_BE_UNUSED
  645. static int
  646. pthread_setspecific(pthread_key_t key, void *value)
  647. {
  648. return TlsSetValue(key, value) ? 0 : 1;
  649. }
  650. FUNCTION_MAY_BE_UNUSED
  651. static void *
  652. pthread_getspecific(pthread_key_t key)
  653. {
  654. return TlsGetValue(key);
  655. }
  656. #if defined(__MINGW32__)
  657. /* Enable unused function warning again */
  658. #pragma GCC diagnostic pop
  659. #endif
  660. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  661. #else
  662. static pthread_mutexattr_t pthread_mutex_attr;
  663. #endif /* _WIN32 */
  664. #define PASSWORDS_FILE_NAME ".htpasswd"
  665. #define CGI_ENVIRONMENT_SIZE (4096)
  666. #define MAX_CGI_ENVIR_VARS (256)
  667. #define MG_BUF_LEN (8192)
  668. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  669. #if defined(_WIN32_WCE)
  670. /* Create substitutes for POSIX functions in Win32. */
  671. #if defined(__MINGW32__)
  672. /* Show no warning in case system functions are not used. */
  673. #pragma GCC diagnostic push
  674. #pragma GCC diagnostic ignored "-Wunused-function"
  675. #endif
  676. FUNCTION_MAY_BE_UNUSED
  677. static time_t
  678. time(time_t *ptime)
  679. {
  680. time_t t;
  681. SYSTEMTIME st;
  682. FILETIME ft;
  683. GetSystemTime(&st);
  684. SystemTimeToFileTime(&st, &ft);
  685. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  686. if (ptime != NULL) {
  687. *ptime = t;
  688. }
  689. return t;
  690. }
  691. FUNCTION_MAY_BE_UNUSED
  692. static struct tm *
  693. localtime_s(const time_t *ptime, struct tm *ptm)
  694. {
  695. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  696. FILETIME ft, lft;
  697. SYSTEMTIME st;
  698. TIME_ZONE_INFORMATION tzinfo;
  699. if (ptm == NULL) {
  700. return NULL;
  701. }
  702. *(int64_t *)&ft = t;
  703. FileTimeToLocalFileTime(&ft, &lft);
  704. FileTimeToSystemTime(&lft, &st);
  705. ptm->tm_year = st.wYear - 1900;
  706. ptm->tm_mon = st.wMonth - 1;
  707. ptm->tm_wday = st.wDayOfWeek;
  708. ptm->tm_mday = st.wDay;
  709. ptm->tm_hour = st.wHour;
  710. ptm->tm_min = st.wMinute;
  711. ptm->tm_sec = st.wSecond;
  712. ptm->tm_yday = 0; /* hope nobody uses this */
  713. ptm->tm_isdst =
  714. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  715. return ptm;
  716. }
  717. FUNCTION_MAY_BE_UNUSED
  718. static struct tm *
  719. gmtime_s(const time_t *ptime, struct tm *ptm)
  720. {
  721. /* FIXME(lsm): fix this. */
  722. return localtime_s(ptime, ptm);
  723. }
  724. static int mg_atomic_inc(volatile int *addr);
  725. static struct tm tm_array[MAX_WORKER_THREADS];
  726. static int tm_index = 0;
  727. FUNCTION_MAY_BE_UNUSED
  728. static struct tm *
  729. localtime(const time_t *ptime)
  730. {
  731. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  732. return localtime_s(ptime, tm_array + i);
  733. }
  734. FUNCTION_MAY_BE_UNUSED
  735. static struct tm *
  736. gmtime(const time_t *ptime)
  737. {
  738. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  739. return gmtime_s(ptime, tm_array + i);
  740. }
  741. FUNCTION_MAY_BE_UNUSED
  742. static size_t
  743. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  744. {
  745. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  746. * for WinCE"); */
  747. return 0;
  748. }
  749. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  750. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  751. #define remove(f) mg_remove(NULL, f)
  752. FUNCTION_MAY_BE_UNUSED
  753. static int
  754. rename(const char *a, const char *b)
  755. {
  756. wchar_t wa[W_PATH_MAX];
  757. wchar_t wb[W_PATH_MAX];
  758. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  759. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  760. return MoveFileW(wa, wb) ? 0 : -1;
  761. }
  762. struct stat {
  763. int64_t st_size;
  764. time_t st_mtime;
  765. };
  766. FUNCTION_MAY_BE_UNUSED
  767. static int
  768. stat(const char *name, struct stat *st)
  769. {
  770. wchar_t wbuf[W_PATH_MAX];
  771. WIN32_FILE_ATTRIBUTE_DATA attr;
  772. time_t creation_time, write_time;
  773. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  774. memset(&attr, 0, sizeof(attr));
  775. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  776. st->st_size =
  777. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  778. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  779. attr.ftLastWriteTime.dwHighDateTime);
  780. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  781. attr.ftCreationTime.dwHighDateTime);
  782. if (creation_time > write_time) {
  783. st->st_mtime = creation_time;
  784. } else {
  785. st->st_mtime = write_time;
  786. }
  787. return 0;
  788. }
  789. #define access(x, a) 1 /* not required anyway */
  790. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  791. /* Values from errno.h in Windows SDK (Visual Studio). */
  792. #define EEXIST 17
  793. #define EACCES 13
  794. #define ENOENT 2
  795. #if defined(__MINGW32__)
  796. /* Enable unused function warning again */
  797. #pragma GCC diagnostic pop
  798. #endif
  799. #endif /* defined(_WIN32_WCE) */
  800. #if defined(__GNUC__) || defined(__MINGW32__)
  801. /* Show no warning in case system functions are not used. */
  802. #define GCC_VERSION \
  803. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  804. #if GCC_VERSION >= 40500
  805. #pragma GCC diagnostic push
  806. #pragma GCC diagnostic ignored "-Wunused-function"
  807. #endif /* GCC_VERSION >= 40500 */
  808. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  809. #if defined(__clang__)
  810. /* Show no warning in case system functions are not used. */
  811. #pragma clang diagnostic push
  812. #pragma clang diagnostic ignored "-Wunused-function"
  813. #endif
  814. static pthread_mutex_t global_lock_mutex;
  815. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  816. /* Forward declaration for Windows */
  817. FUNCTION_MAY_BE_UNUSED
  818. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  819. FUNCTION_MAY_BE_UNUSED
  820. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  821. #endif
  822. FUNCTION_MAY_BE_UNUSED
  823. static void
  824. mg_global_lock(void)
  825. {
  826. (void)pthread_mutex_lock(&global_lock_mutex);
  827. }
  828. FUNCTION_MAY_BE_UNUSED
  829. static void
  830. mg_global_unlock(void)
  831. {
  832. (void)pthread_mutex_unlock(&global_lock_mutex);
  833. }
  834. FUNCTION_MAY_BE_UNUSED
  835. static int
  836. mg_atomic_inc(volatile int *addr)
  837. {
  838. int ret;
  839. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  840. /* Depending on the SDK, this function uses either
  841. * (volatile unsigned int *) or (volatile LONG *),
  842. * so whatever you use, the other SDK is likely to raise a warning. */
  843. ret = InterlockedIncrement((volatile long *)addr);
  844. #elif defined(__GNUC__) \
  845. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  846. && !defined(NO_ATOMICS)
  847. ret = __sync_add_and_fetch(addr, 1);
  848. #else
  849. mg_global_lock();
  850. ret = (++(*addr));
  851. mg_global_unlock();
  852. #endif
  853. return ret;
  854. }
  855. FUNCTION_MAY_BE_UNUSED
  856. static int
  857. mg_atomic_dec(volatile int *addr)
  858. {
  859. int ret;
  860. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  861. /* Depending on the SDK, this function uses either
  862. * (volatile unsigned int *) or (volatile LONG *),
  863. * so whatever you use, the other SDK is likely to raise a warning. */
  864. ret = InterlockedDecrement((volatile long *)addr);
  865. #elif defined(__GNUC__) \
  866. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  867. && !defined(NO_ATOMICS)
  868. ret = __sync_sub_and_fetch(addr, 1);
  869. #else
  870. mg_global_lock();
  871. ret = (--(*addr));
  872. mg_global_unlock();
  873. #endif
  874. return ret;
  875. }
  876. #if defined(USE_SERVER_STATS)
  877. static int64_t
  878. mg_atomic_add(volatile int64_t *addr, int64_t value)
  879. {
  880. int64_t ret;
  881. #if defined(_WIN64) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  882. ret = InterlockedAdd64(addr, value);
  883. #elif defined(__GNUC__) \
  884. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  885. && !defined(NO_ATOMICS)
  886. ret = __sync_add_and_fetch(addr, value);
  887. #else
  888. mg_global_lock();
  889. *addr += value;
  890. ret = (*addr);
  891. mg_global_unlock();
  892. #endif
  893. return ret;
  894. }
  895. #endif
  896. #if defined(__GNUC__)
  897. /* Show no warning in case system functions are not used. */
  898. #if GCC_VERSION >= 40500
  899. #pragma GCC diagnostic pop
  900. #endif /* GCC_VERSION >= 40500 */
  901. #endif /* defined(__GNUC__) */
  902. #if defined(__clang__)
  903. /* Show no warning in case system functions are not used. */
  904. #pragma clang diagnostic pop
  905. #endif
  906. #if defined(USE_SERVER_STATS)
  907. struct mg_memory_stat {
  908. volatile int64_t totalMemUsed;
  909. volatile int64_t maxMemUsed;
  910. volatile int blockCount;
  911. };
  912. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  913. static void *
  914. mg_malloc_ex(size_t size,
  915. struct mg_context *ctx,
  916. const char *file,
  917. unsigned line)
  918. {
  919. void *data = malloc(size + 2 * sizeof(uintptr_t));
  920. void *memory = 0;
  921. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  922. #if defined(MEMORY_DEBUGGING)
  923. char mallocStr[256];
  924. #else
  925. (void)file;
  926. (void)line;
  927. #endif
  928. if (data) {
  929. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  930. if (mmem > mstat->maxMemUsed) {
  931. /* could use atomic compare exchange, but this
  932. * seems overkill for statistics data */
  933. mstat->maxMemUsed = mmem;
  934. }
  935. mg_atomic_inc(&mstat->blockCount);
  936. ((uintptr_t *)data)[0] = size;
  937. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  938. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  939. }
  940. #if defined(MEMORY_DEBUGGING)
  941. sprintf(mallocStr,
  942. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  943. memory,
  944. (unsigned long)size,
  945. (unsigned long)mstat->totalMemUsed,
  946. (unsigned long)mstat->blockCount,
  947. file,
  948. line);
  949. #if defined(_WIN32)
  950. OutputDebugStringA(mallocStr);
  951. #else
  952. DEBUG_TRACE("%s", mallocStr);
  953. #endif
  954. #endif
  955. return memory;
  956. }
  957. static void *
  958. mg_calloc_ex(size_t count,
  959. size_t size,
  960. struct mg_context *ctx,
  961. const char *file,
  962. unsigned line)
  963. {
  964. void *data = mg_malloc_ex(size * count, ctx, file, line);
  965. if (data) {
  966. memset(data, 0, size * count);
  967. }
  968. return data;
  969. }
  970. static void
  971. mg_free_ex(void *memory, const char *file, unsigned line)
  972. {
  973. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  974. #if defined(MEMORY_DEBUGGING)
  975. char mallocStr[256];
  976. #else
  977. (void)file;
  978. (void)line;
  979. #endif
  980. if (memory) {
  981. uintptr_t size = ((uintptr_t *)data)[0];
  982. struct mg_memory_stat *mstat =
  983. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  984. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  985. mg_atomic_dec(&mstat->blockCount);
  986. #if defined(MEMORY_DEBUGGING)
  987. sprintf(mallocStr,
  988. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  989. memory,
  990. (unsigned long)size,
  991. (unsigned long)mstat->totalMemUsed,
  992. (unsigned long)mstat->blockCount,
  993. file,
  994. line);
  995. #if defined(_WIN32)
  996. OutputDebugStringA(mallocStr);
  997. #else
  998. DEBUG_TRACE("%s", mallocStr);
  999. #endif
  1000. #endif
  1001. free(data);
  1002. }
  1003. }
  1004. static void *
  1005. mg_realloc_ex(void *memory,
  1006. size_t newsize,
  1007. struct mg_context *ctx,
  1008. const char *file,
  1009. unsigned line)
  1010. {
  1011. void *data;
  1012. void *_realloc;
  1013. uintptr_t oldsize;
  1014. #if defined(MEMORY_DEBUGGING)
  1015. char mallocStr[256];
  1016. #else
  1017. (void)file;
  1018. (void)line;
  1019. #endif
  1020. if (newsize) {
  1021. if (memory) {
  1022. /* Reallocate existing block */
  1023. struct mg_memory_stat *mstat;
  1024. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1025. oldsize = ((uintptr_t *)data)[0];
  1026. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1027. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1028. if (_realloc) {
  1029. data = _realloc;
  1030. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1031. #if defined(MEMORY_DEBUGGING)
  1032. sprintf(mallocStr,
  1033. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1034. memory,
  1035. (unsigned long)oldsize,
  1036. (unsigned long)mstat->totalMemUsed,
  1037. (unsigned long)mstat->blockCount,
  1038. file,
  1039. line);
  1040. #if defined(_WIN32)
  1041. OutputDebugStringA(mallocStr);
  1042. #else
  1043. DEBUG_TRACE("%s", mallocStr);
  1044. #endif
  1045. #endif
  1046. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1047. #if defined(MEMORY_DEBUGGING)
  1048. sprintf(mallocStr,
  1049. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1050. memory,
  1051. (unsigned long)newsize,
  1052. (unsigned long)mstat->totalMemUsed,
  1053. (unsigned long)mstat->blockCount,
  1054. file,
  1055. line);
  1056. #if defined(_WIN32)
  1057. OutputDebugStringA(mallocStr);
  1058. #else
  1059. DEBUG_TRACE("%s", mallocStr);
  1060. #endif
  1061. #endif
  1062. *(uintptr_t *)data = newsize;
  1063. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1064. } else {
  1065. #if defined(MEMORY_DEBUGGING)
  1066. #if defined(_WIN32)
  1067. OutputDebugStringA("MEM: realloc failed\n");
  1068. #else
  1069. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1070. #endif
  1071. #endif
  1072. return _realloc;
  1073. }
  1074. } else {
  1075. /* Allocate new block */
  1076. data = mg_malloc_ex(newsize, ctx, file, line);
  1077. }
  1078. } else {
  1079. /* Free existing block */
  1080. data = 0;
  1081. mg_free_ex(memory, file, line);
  1082. }
  1083. return data;
  1084. }
  1085. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1086. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1087. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1088. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1089. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1090. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1091. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1092. #else /* USE_SERVER_STATS */
  1093. static __inline void *
  1094. mg_malloc(size_t a)
  1095. {
  1096. return malloc(a);
  1097. }
  1098. static __inline void *
  1099. mg_calloc(size_t a, size_t b)
  1100. {
  1101. return calloc(a, b);
  1102. }
  1103. static __inline void *
  1104. mg_realloc(void *a, size_t b)
  1105. {
  1106. return realloc(a, b);
  1107. }
  1108. static __inline void
  1109. mg_free(void *a)
  1110. {
  1111. free(a);
  1112. }
  1113. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1114. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1115. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1116. #define mg_free_ctx(a, c) mg_free(a)
  1117. #endif /* USE_SERVER_STATS */
  1118. static void mg_vsnprintf(const struct mg_connection *conn,
  1119. int *truncated,
  1120. char *buf,
  1121. size_t buflen,
  1122. const char *fmt,
  1123. va_list ap);
  1124. static void mg_snprintf(const struct mg_connection *conn,
  1125. int *truncated,
  1126. char *buf,
  1127. size_t buflen,
  1128. PRINTF_FORMAT_STRING(const char *fmt),
  1129. ...) PRINTF_ARGS(5, 6);
  1130. /* This following lines are just meant as a reminder to use the mg-functions
  1131. * for memory management */
  1132. #ifdef malloc
  1133. #undef malloc
  1134. #endif
  1135. #ifdef calloc
  1136. #undef calloc
  1137. #endif
  1138. #ifdef realloc
  1139. #undef realloc
  1140. #endif
  1141. #ifdef free
  1142. #undef free
  1143. #endif
  1144. #ifdef snprintf
  1145. #undef snprintf
  1146. #endif
  1147. #ifdef vsnprintf
  1148. #undef vsnprintf
  1149. #endif
  1150. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1151. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1152. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1153. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1154. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1155. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  1156. * but this define only works well for Windows. */
  1157. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1158. #endif
  1159. /* mg_init_library counter */
  1160. static int mg_init_library_called = 0;
  1161. #if !defined(NO_SSL)
  1162. static int mg_ssl_initialized = 0;
  1163. #endif
  1164. static pthread_key_t sTlsKey; /* Thread local storage index */
  1165. static int thread_idx_max = 0;
  1166. struct mg_workerTLS {
  1167. int is_master;
  1168. unsigned long thread_idx;
  1169. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1170. HANDLE pthread_cond_helper_mutex;
  1171. struct mg_workerTLS *next_waiting_thread;
  1172. #endif
  1173. };
  1174. #if defined(__GNUC__) || defined(__MINGW32__)
  1175. /* Show no warning in case system functions are not used. */
  1176. #if GCC_VERSION >= 40500
  1177. #pragma GCC diagnostic push
  1178. #pragma GCC diagnostic ignored "-Wunused-function"
  1179. #endif /* GCC_VERSION >= 40500 */
  1180. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1181. #if defined(__clang__)
  1182. /* Show no warning in case system functions are not used. */
  1183. #pragma clang diagnostic push
  1184. #pragma clang diagnostic ignored "-Wunused-function"
  1185. #endif
  1186. /* Get a unique thread ID as unsigned long, independent from the data type
  1187. * of thread IDs defined by the operating system API.
  1188. * If two calls to mg_current_thread_id return the same value, they calls
  1189. * are done from the same thread. If they return different values, they are
  1190. * done from different threads. (Provided this function is used in the same
  1191. * process context and threads are not repeatedly created and deleted, but
  1192. * CivetWeb does not do that).
  1193. * This function must match the signature required for SSL id callbacks:
  1194. * CRYPTO_set_id_callback
  1195. */
  1196. FUNCTION_MAY_BE_UNUSED
  1197. static unsigned long
  1198. mg_current_thread_id(void)
  1199. {
  1200. #ifdef _WIN32
  1201. return GetCurrentThreadId();
  1202. #else
  1203. #ifdef __clang__
  1204. #pragma clang diagnostic push
  1205. #pragma clang diagnostic ignored "-Wunreachable-code"
  1206. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1207. * or not, so one of the two conditions will be unreachable by construction.
  1208. * Unfortunately the C standard does not define a way to check this at
  1209. * compile time, since the #if preprocessor conditions can not use the sizeof
  1210. * operator as an argument. */
  1211. #endif
  1212. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1213. /* This is the problematic case for CRYPTO_set_id_callback:
  1214. * The OS pthread_t can not be cast to unsigned long. */
  1215. struct mg_workerTLS *tls =
  1216. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1217. if (tls == NULL) {
  1218. /* SSL called from an unknown thread: Create some thread index.
  1219. */
  1220. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1221. tls->is_master = -2; /* -2 means "3rd party thread" */
  1222. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1223. pthread_setspecific(sTlsKey, tls);
  1224. }
  1225. return tls->thread_idx;
  1226. } else {
  1227. /* pthread_t may be any data type, so a simple cast to unsigned long
  1228. * can rise a warning/error, depending on the platform.
  1229. * Here memcpy is used as an anything-to-anything cast. */
  1230. unsigned long ret = 0;
  1231. pthread_t t = pthread_self();
  1232. memcpy(&ret, &t, sizeof(pthread_t));
  1233. return ret;
  1234. }
  1235. #ifdef __clang__
  1236. #pragma clang diagnostic pop
  1237. #endif
  1238. #endif
  1239. }
  1240. FUNCTION_MAY_BE_UNUSED
  1241. static uint64_t
  1242. mg_get_current_time_ns(void)
  1243. {
  1244. struct timespec tsnow;
  1245. clock_gettime(CLOCK_REALTIME, &tsnow);
  1246. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1247. }
  1248. #if defined(__GNUC__)
  1249. /* Show no warning in case system functions are not used. */
  1250. #if GCC_VERSION >= 40500
  1251. #pragma GCC diagnostic pop
  1252. #endif /* GCC_VERSION >= 40500 */
  1253. #endif /* defined(__GNUC__) */
  1254. #if defined(__clang__)
  1255. /* Show no warning in case system functions are not used. */
  1256. #pragma clang diagnostic pop
  1257. #endif
  1258. #if defined(NEED_DEBUG_TRACE_FUNC)
  1259. static void
  1260. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1261. {
  1262. va_list args;
  1263. uint64_t nsnow;
  1264. static uint64_t nslast;
  1265. struct timespec tsnow;
  1266. /* Get some operating system independent thread id */
  1267. unsigned long thread_id = mg_current_thread_id();
  1268. clock_gettime(CLOCK_REALTIME, &tsnow);
  1269. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1270. + ((uint64_t)tsnow.tv_nsec);
  1271. if (!nslast) {
  1272. nslast = nsnow;
  1273. }
  1274. flockfile(stdout);
  1275. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1276. (unsigned long)tsnow.tv_sec,
  1277. (unsigned long)tsnow.tv_nsec,
  1278. nsnow - nslast,
  1279. thread_id,
  1280. func,
  1281. line);
  1282. va_start(args, fmt);
  1283. vprintf(fmt, args);
  1284. va_end(args);
  1285. putchar('\n');
  1286. fflush(stdout);
  1287. funlockfile(stdout);
  1288. nslast = nsnow;
  1289. }
  1290. #endif /* NEED_DEBUG_TRACE_FUNC */
  1291. #define MD5_STATIC static
  1292. #include "md5.inl"
  1293. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1294. #ifdef NO_SOCKLEN_T
  1295. typedef int socklen_t;
  1296. #endif /* NO_SOCKLEN_T */
  1297. #define _DARWIN_UNLIMITED_SELECT
  1298. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1299. #if !defined(MSG_NOSIGNAL)
  1300. #define MSG_NOSIGNAL (0)
  1301. #endif
  1302. #if !defined(SOMAXCONN)
  1303. #define SOMAXCONN (100)
  1304. #endif
  1305. /* Size of the accepted socket queue */
  1306. #if !defined(MGSQLEN)
  1307. #define MGSQLEN (20)
  1308. #endif
  1309. #if defined(NO_SSL)
  1310. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1311. typedef struct SSL_CTX SSL_CTX;
  1312. #else
  1313. #if defined(NO_SSL_DL)
  1314. #include <openssl/ssl.h>
  1315. #include <openssl/err.h>
  1316. #include <openssl/crypto.h>
  1317. #include <openssl/x509.h>
  1318. #include <openssl/pem.h>
  1319. #include <openssl/engine.h>
  1320. #include <openssl/conf.h>
  1321. #include <openssl/dh.h>
  1322. #include <openssl/bn.h>
  1323. #include <openssl/opensslv.h>
  1324. #else
  1325. /* SSL loaded dynamically from DLL.
  1326. * I put the prototypes here to be independent from OpenSSL source
  1327. * installation. */
  1328. typedef struct ssl_st SSL;
  1329. typedef struct ssl_method_st SSL_METHOD;
  1330. typedef struct ssl_ctx_st SSL_CTX;
  1331. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1332. typedef struct x509_name X509_NAME;
  1333. typedef struct asn1_integer ASN1_INTEGER;
  1334. typedef struct bignum BIGNUM;
  1335. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1336. typedef struct evp_md EVP_MD;
  1337. typedef struct x509 X509;
  1338. #define SSL_CTRL_OPTIONS (32)
  1339. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1340. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1341. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1342. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1343. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1344. #define SSL_VERIFY_NONE (0)
  1345. #define SSL_VERIFY_PEER (1)
  1346. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1347. #define SSL_VERIFY_CLIENT_ONCE (4)
  1348. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1349. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1350. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1351. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1352. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1353. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1354. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1355. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1356. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1357. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1358. #define SSL_CB_HANDSHAKE_START (0x10)
  1359. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1360. #define SSL_ERROR_NONE (0)
  1361. #define SSL_ERROR_SSL (1)
  1362. #define SSL_ERROR_WANT_READ (2)
  1363. #define SSL_ERROR_WANT_WRITE (3)
  1364. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1365. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1366. #define SSL_ERROR_ZERO_RETURN (6)
  1367. #define SSL_ERROR_WANT_CONNECT (7)
  1368. #define SSL_ERROR_WANT_ACCEPT (8)
  1369. #define TLSEXT_TYPE_server_name (0)
  1370. #define TLSEXT_NAMETYPE_host_name (0)
  1371. #define SSL_TLSEXT_ERR_OK (0)
  1372. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1373. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1374. #define SSL_TLSEXT_ERR_NOACK (3)
  1375. struct ssl_func {
  1376. const char *name; /* SSL function name */
  1377. void (*ptr)(void); /* Function pointer */
  1378. };
  1379. #ifdef OPENSSL_API_1_1
  1380. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1381. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1382. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1383. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1384. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1385. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1386. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1387. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1388. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1389. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1390. #define OPENSSL_init_ssl \
  1391. (*(int (*)(uint64_t opts, \
  1392. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1393. #define SSL_CTX_use_PrivateKey_file \
  1394. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1395. #define SSL_CTX_use_certificate_file \
  1396. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1397. #define SSL_CTX_set_default_passwd_cb \
  1398. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1399. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1400. #define SSL_CTX_use_certificate_chain_file \
  1401. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1402. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1403. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1404. #define SSL_CTX_set_verify \
  1405. (*(void (*)(SSL_CTX *, \
  1406. int, \
  1407. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1408. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1409. #define SSL_CTX_load_verify_locations \
  1410. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1411. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1412. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1413. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1414. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1415. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1416. #define SSL_CIPHER_get_name \
  1417. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1418. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1419. #define SSL_CTX_set_session_id_context \
  1420. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1421. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1422. #define SSL_CTX_set_cipher_list \
  1423. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1424. #define SSL_CTX_set_options \
  1425. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1426. #define SSL_CTX_set_info_callback \
  1427. (*(void (*)(SSL_CTX * ctx, \
  1428. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1429. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1430. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1431. #define SSL_CTX_callback_ctrl \
  1432. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1433. #define SSL_get_servername \
  1434. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1435. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1436. #define SSL_CTX_clear_options(ctx, op) \
  1437. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1438. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1439. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1440. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1441. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1442. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1443. SSL_CTX_callback_ctrl(ctx, \
  1444. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1445. (void (*)(void))cb)
  1446. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1447. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1448. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1449. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1450. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1451. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1452. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1453. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1454. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1455. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1456. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1457. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1458. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1459. #define X509_NAME_oneline \
  1460. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1461. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1462. #define EVP_get_digestbyname \
  1463. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1464. #define EVP_Digest \
  1465. (*(int (*)( \
  1466. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1467. crypto_sw[10].ptr)
  1468. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1469. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1470. #define ASN1_INTEGER_to_BN \
  1471. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1472. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1473. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1474. #define OPENSSL_free(a) CRYPTO_free(a)
  1475. /* init_ssl_ctx() function updates this array.
  1476. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1477. * of respective functions. The macros above (like SSL_connect()) are really
  1478. * just calling these functions indirectly via the pointer. */
  1479. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1480. {"SSL_accept", NULL},
  1481. {"SSL_connect", NULL},
  1482. {"SSL_read", NULL},
  1483. {"SSL_write", NULL},
  1484. {"SSL_get_error", NULL},
  1485. {"SSL_set_fd", NULL},
  1486. {"SSL_new", NULL},
  1487. {"SSL_CTX_new", NULL},
  1488. {"TLS_server_method", NULL},
  1489. {"OPENSSL_init_ssl", NULL},
  1490. {"SSL_CTX_use_PrivateKey_file", NULL},
  1491. {"SSL_CTX_use_certificate_file", NULL},
  1492. {"SSL_CTX_set_default_passwd_cb", NULL},
  1493. {"SSL_CTX_free", NULL},
  1494. {"SSL_CTX_use_certificate_chain_file", NULL},
  1495. {"TLS_client_method", NULL},
  1496. {"SSL_pending", NULL},
  1497. {"SSL_CTX_set_verify", NULL},
  1498. {"SSL_shutdown", NULL},
  1499. {"SSL_CTX_load_verify_locations", NULL},
  1500. {"SSL_CTX_set_default_verify_paths", NULL},
  1501. {"SSL_CTX_set_verify_depth", NULL},
  1502. {"SSL_get_peer_certificate", NULL},
  1503. {"SSL_get_version", NULL},
  1504. {"SSL_get_current_cipher", NULL},
  1505. {"SSL_CIPHER_get_name", NULL},
  1506. {"SSL_CTX_check_private_key", NULL},
  1507. {"SSL_CTX_set_session_id_context", NULL},
  1508. {"SSL_CTX_ctrl", NULL},
  1509. {"SSL_CTX_set_cipher_list", NULL},
  1510. {"SSL_CTX_set_options", NULL},
  1511. {"SSL_CTX_set_info_callback", NULL},
  1512. {"SSL_get_ex_data", NULL},
  1513. {"SSL_set_ex_data", NULL},
  1514. {"SSL_CTX_callback_ctrl", NULL},
  1515. {"SSL_get_servername", NULL},
  1516. {"SSL_set_SSL_CTX", NULL},
  1517. {NULL, NULL}};
  1518. /* Similar array as ssl_sw. These functions could be located in different
  1519. * lib. */
  1520. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1521. {"ERR_error_string", NULL},
  1522. {"ERR_remove_state", NULL},
  1523. {"CONF_modules_unload", NULL},
  1524. {"X509_free", NULL},
  1525. {"X509_get_subject_name", NULL},
  1526. {"X509_get_issuer_name", NULL},
  1527. {"X509_NAME_oneline", NULL},
  1528. {"X509_get_serialNumber", NULL},
  1529. {"EVP_get_digestbyname", NULL},
  1530. {"EVP_Digest", NULL},
  1531. {"i2d_X509", NULL},
  1532. {"BN_bn2hex", NULL},
  1533. {"ASN1_INTEGER_to_BN", NULL},
  1534. {"BN_free", NULL},
  1535. {"CRYPTO_free", NULL},
  1536. {NULL, NULL}};
  1537. #else
  1538. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1539. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1540. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1541. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1542. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1543. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1544. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1545. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1546. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1547. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1548. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1549. #define SSL_CTX_use_PrivateKey_file \
  1550. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1551. #define SSL_CTX_use_certificate_file \
  1552. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1553. #define SSL_CTX_set_default_passwd_cb \
  1554. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1555. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1556. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1557. #define SSL_CTX_use_certificate_chain_file \
  1558. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1559. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1560. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1561. #define SSL_CTX_set_verify \
  1562. (*(void (*)(SSL_CTX *, \
  1563. int, \
  1564. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1565. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1566. #define SSL_CTX_load_verify_locations \
  1567. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1568. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1569. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1570. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1571. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1572. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1573. #define SSL_CIPHER_get_name \
  1574. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1575. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1576. #define SSL_CTX_set_session_id_context \
  1577. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1578. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1579. #define SSL_CTX_set_cipher_list \
  1580. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1581. #define SSL_CTX_set_info_callback \
  1582. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1583. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1584. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1585. #define SSL_CTX_callback_ctrl \
  1586. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1587. #define SSL_get_servername \
  1588. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1589. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1590. #define SSL_CTX_set_options(ctx, op) \
  1591. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1592. #define SSL_CTX_clear_options(ctx, op) \
  1593. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1594. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1595. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1596. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1597. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1598. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1599. SSL_CTX_callback_ctrl(ctx, \
  1600. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1601. (void (*)(void))cb)
  1602. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1603. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1604. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1605. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1606. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1607. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1608. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1609. #define CRYPTO_set_locking_callback \
  1610. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1611. #define CRYPTO_set_id_callback \
  1612. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1613. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1614. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1615. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1616. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1617. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1618. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1619. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1620. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1621. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1622. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1623. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1624. #define X509_NAME_oneline \
  1625. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1626. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1627. #define i2c_ASN1_INTEGER \
  1628. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1629. #define EVP_get_digestbyname \
  1630. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1631. #define EVP_Digest \
  1632. (*(int (*)( \
  1633. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1634. crypto_sw[18].ptr)
  1635. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1636. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1637. #define ASN1_INTEGER_to_BN \
  1638. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1639. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1640. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1641. #define OPENSSL_free(a) CRYPTO_free(a)
  1642. /* init_ssl_ctx() function updates this array.
  1643. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1644. * of respective functions. The macros above (like SSL_connect()) are really
  1645. * just calling these functions indirectly via the pointer. */
  1646. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1647. {"SSL_accept", NULL},
  1648. {"SSL_connect", NULL},
  1649. {"SSL_read", NULL},
  1650. {"SSL_write", NULL},
  1651. {"SSL_get_error", NULL},
  1652. {"SSL_set_fd", NULL},
  1653. {"SSL_new", NULL},
  1654. {"SSL_CTX_new", NULL},
  1655. {"SSLv23_server_method", NULL},
  1656. {"SSL_library_init", NULL},
  1657. {"SSL_CTX_use_PrivateKey_file", NULL},
  1658. {"SSL_CTX_use_certificate_file", NULL},
  1659. {"SSL_CTX_set_default_passwd_cb", NULL},
  1660. {"SSL_CTX_free", NULL},
  1661. {"SSL_load_error_strings", NULL},
  1662. {"SSL_CTX_use_certificate_chain_file", NULL},
  1663. {"SSLv23_client_method", NULL},
  1664. {"SSL_pending", NULL},
  1665. {"SSL_CTX_set_verify", NULL},
  1666. {"SSL_shutdown", NULL},
  1667. {"SSL_CTX_load_verify_locations", NULL},
  1668. {"SSL_CTX_set_default_verify_paths", NULL},
  1669. {"SSL_CTX_set_verify_depth", NULL},
  1670. {"SSL_get_peer_certificate", NULL},
  1671. {"SSL_get_version", NULL},
  1672. {"SSL_get_current_cipher", NULL},
  1673. {"SSL_CIPHER_get_name", NULL},
  1674. {"SSL_CTX_check_private_key", NULL},
  1675. {"SSL_CTX_set_session_id_context", NULL},
  1676. {"SSL_CTX_ctrl", NULL},
  1677. {"SSL_CTX_set_cipher_list", NULL},
  1678. {"SSL_CTX_set_info_callback", NULL},
  1679. {"SSL_get_ex_data", NULL},
  1680. {"SSL_set_ex_data", NULL},
  1681. {"SSL_CTX_callback_ctrl", NULL},
  1682. {"SSL_get_servername", NULL},
  1683. {"SSL_set_SSL_CTX", NULL},
  1684. {NULL, NULL}};
  1685. /* Similar array as ssl_sw. These functions could be located in different
  1686. * lib. */
  1687. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1688. {"CRYPTO_set_locking_callback", NULL},
  1689. {"CRYPTO_set_id_callback", NULL},
  1690. {"ERR_get_error", NULL},
  1691. {"ERR_error_string", NULL},
  1692. {"ERR_remove_state", NULL},
  1693. {"ERR_free_strings", NULL},
  1694. {"ENGINE_cleanup", NULL},
  1695. {"CONF_modules_unload", NULL},
  1696. {"CRYPTO_cleanup_all_ex_data", NULL},
  1697. {"EVP_cleanup", NULL},
  1698. {"X509_free", NULL},
  1699. {"X509_get_subject_name", NULL},
  1700. {"X509_get_issuer_name", NULL},
  1701. {"X509_NAME_oneline", NULL},
  1702. {"X509_get_serialNumber", NULL},
  1703. {"i2c_ASN1_INTEGER", NULL},
  1704. {"EVP_get_digestbyname", NULL},
  1705. {"EVP_Digest", NULL},
  1706. {"i2d_X509", NULL},
  1707. {"BN_bn2hex", NULL},
  1708. {"ASN1_INTEGER_to_BN", NULL},
  1709. {"BN_free", NULL},
  1710. {"CRYPTO_free", NULL},
  1711. {NULL, NULL}};
  1712. #endif /* OPENSSL_API_1_1 */
  1713. #endif /* NO_SSL_DL */
  1714. #endif /* NO_SSL */
  1715. #if !defined(NO_CACHING)
  1716. static const char *month_names[] = {"Jan",
  1717. "Feb",
  1718. "Mar",
  1719. "Apr",
  1720. "May",
  1721. "Jun",
  1722. "Jul",
  1723. "Aug",
  1724. "Sep",
  1725. "Oct",
  1726. "Nov",
  1727. "Dec"};
  1728. #endif /* !NO_CACHING */
  1729. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1730. * the
  1731. * union u. */
  1732. union usa {
  1733. struct sockaddr sa;
  1734. struct sockaddr_in sin;
  1735. #if defined(USE_IPV6)
  1736. struct sockaddr_in6 sin6;
  1737. #endif
  1738. };
  1739. /* Describes a string (chunk of memory). */
  1740. struct vec {
  1741. const char *ptr;
  1742. size_t len;
  1743. };
  1744. struct mg_file_stat {
  1745. /* File properties filled by mg_stat: */
  1746. uint64_t size;
  1747. time_t last_modified;
  1748. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1749. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1750. * case we need a "Content-Eencoding: gzip" header */
  1751. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1752. };
  1753. struct mg_file_in_memory {
  1754. char *p;
  1755. uint32_t pos;
  1756. char mode;
  1757. };
  1758. struct mg_file_access {
  1759. /* File properties filled by mg_fopen: */
  1760. FILE *fp;
  1761. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1762. * support library. Use some struct mg_file_in_memory *mf; instead of
  1763. * membuf char pointer. */
  1764. const char *membuf;
  1765. };
  1766. struct mg_file {
  1767. struct mg_file_stat stat;
  1768. struct mg_file_access access;
  1769. };
  1770. #define STRUCT_FILE_INITIALIZER \
  1771. { \
  1772. { \
  1773. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1774. } \
  1775. , \
  1776. { \
  1777. (FILE *) NULL, (const char *)NULL \
  1778. } \
  1779. }
  1780. /* Describes listening socket, or socket which was accept()-ed by the master
  1781. * thread and queued for future handling by the worker thread. */
  1782. struct socket {
  1783. SOCKET sock; /* Listening socket */
  1784. union usa lsa; /* Local socket address */
  1785. union usa rsa; /* Remote socket address */
  1786. unsigned char is_ssl; /* Is port SSL-ed */
  1787. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1788. * port */
  1789. unsigned char in_use; /* Is valid */
  1790. };
  1791. /* Enum const for all options must be in sync with
  1792. * static struct mg_option config_options[]
  1793. * This is tested in the unit test (test/private.c)
  1794. * "Private Config Options"
  1795. */
  1796. enum {
  1797. LISTENING_PORTS,
  1798. NUM_THREADS,
  1799. RUN_AS_USER,
  1800. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1801. * socket option typedef TCP_NODELAY. */
  1802. MAX_REQUEST_SIZE,
  1803. LINGER_TIMEOUT,
  1804. #if defined(__linux__)
  1805. ALLOW_SENDFILE_CALL,
  1806. #endif
  1807. #if defined(_WIN32)
  1808. CASE_SENSITIVE_FILES,
  1809. #endif
  1810. THROTTLE,
  1811. ACCESS_LOG_FILE,
  1812. ERROR_LOG_FILE,
  1813. ENABLE_KEEP_ALIVE,
  1814. REQUEST_TIMEOUT,
  1815. KEEP_ALIVE_TIMEOUT,
  1816. #if defined(USE_WEBSOCKET)
  1817. WEBSOCKET_TIMEOUT,
  1818. ENABLE_WEBSOCKET_PING_PONG,
  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, NULL},
  1904. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1905. #endif
  1906. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1907. #if defined(USE_LUA)
  1908. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1909. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1910. #endif
  1911. /* Once for each domain */
  1912. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1913. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1914. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1915. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1916. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1917. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1918. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1919. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1920. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1921. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1922. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1923. {"index_files",
  1924. MG_CONFIG_TYPE_STRING_LIST,
  1925. #ifdef USE_LUA
  1926. "index.xhtml,index.html,index.htm,"
  1927. "index.lp,index.lsp,index.lua,index.cgi,"
  1928. "index.shtml,index.php"},
  1929. #else
  1930. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1931. #endif
  1932. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1933. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1934. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1935. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1936. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1937. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1938. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1939. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1940. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1941. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1942. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1943. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1944. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  1945. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1946. #if defined(USE_LUA)
  1947. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1948. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1949. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1950. #endif
  1951. #if defined(USE_DUKTAPE)
  1952. /* The support for duktape is still in alpha version state.
  1953. * The name of this config option might change. */
  1954. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1955. #endif
  1956. #if defined(USE_WEBSOCKET)
  1957. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1958. #endif
  1959. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1960. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1961. #endif
  1962. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1963. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1964. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1965. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1966. #if !defined(NO_CACHING)
  1967. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1968. #endif
  1969. #if !defined(NO_SSL)
  1970. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1971. #endif
  1972. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1973. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1974. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1975. /* Check if the config_options and the corresponding enum have compatible
  1976. * sizes. */
  1977. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1978. == (NUM_OPTIONS + 1),
  1979. "config_options and enum not sync");
  1980. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1981. struct mg_handler_info {
  1982. /* Name/Pattern of the URI. */
  1983. char *uri;
  1984. size_t uri_len;
  1985. /* handler type */
  1986. int handler_type;
  1987. /* Handler for http/https or authorization requests. */
  1988. mg_request_handler handler;
  1989. /* Handler for ws/wss (websocket) requests. */
  1990. mg_websocket_connect_handler connect_handler;
  1991. mg_websocket_ready_handler ready_handler;
  1992. mg_websocket_data_handler data_handler;
  1993. mg_websocket_close_handler close_handler;
  1994. /* accepted subprotocols for ws/wss requests. */
  1995. struct mg_websocket_subprotocols *subprotocols;
  1996. /* Handler for authorization requests */
  1997. mg_authorization_handler auth_handler;
  1998. /* User supplied argument for the handler function. */
  1999. void *cbdata;
  2000. /* next handler in a linked list */
  2001. struct mg_handler_info *next;
  2002. };
  2003. enum {
  2004. CONTEXT_INVALID,
  2005. CONTEXT_SERVER,
  2006. CONTEXT_HTTP_CLIENT,
  2007. CONTEXT_WS_CLIENT
  2008. };
  2009. struct mg_domain_context {
  2010. SSL_CTX *ssl_ctx; /* SSL context */
  2011. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2012. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2013. /* Server nonce */
  2014. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2015. unsigned long nonce_count; /* Used nonces, used for authentication */
  2016. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2017. /* linked list of shared lua websockets */
  2018. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2019. #endif
  2020. /* Linked list of domains */
  2021. struct mg_domain_context *next;
  2022. };
  2023. struct mg_context {
  2024. /* Part 1 - Physical context:
  2025. * This holds threads, ports, timeouts, ...
  2026. * set for the entire server, independent from the
  2027. * addressed hostname.
  2028. */
  2029. /* Connection related */
  2030. int context_type; /* See CONTEXT_* above */
  2031. struct socket *listening_sockets;
  2032. struct pollfd *listening_socket_fds;
  2033. unsigned int num_listening_sockets;
  2034. struct mg_connection *worker_connections; /* The connection struct, pre-
  2035. * allocated for each worker */
  2036. #if defined(USE_SERVER_STATS)
  2037. int active_connections;
  2038. int max_connections;
  2039. int64_t total_connections;
  2040. int64_t total_requests;
  2041. int64_t total_data_read;
  2042. int64_t total_data_written;
  2043. #endif
  2044. /* Thread related */
  2045. volatile int stop_flag; /* Should we stop event loop */
  2046. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2047. pthread_t masterthreadid; /* The master thread ID */
  2048. unsigned int
  2049. cfg_worker_threads; /* The number of configured worker threads. */
  2050. pthread_t *worker_threadids; /* The worker thread IDs */
  2051. /* Connection to thread dispatching */
  2052. #ifdef ALTERNATIVE_QUEUE
  2053. struct socket *client_socks;
  2054. void **client_wait_events;
  2055. #else
  2056. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2057. volatile int sq_head; /* Head of the socket queue */
  2058. volatile int sq_tail; /* Tail of the socket queue */
  2059. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2060. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2061. #endif
  2062. /* Memory related */
  2063. unsigned int max_request_size; /* The max request size */
  2064. #if defined(USE_SERVER_STATS)
  2065. struct mg_memory_stat ctx_memory;
  2066. #endif
  2067. /* Operating system related */
  2068. char *systemName; /* What operating system is running */
  2069. time_t start_time; /* Server start time, used for authentication
  2070. * and for diagnstics. */
  2071. #if defined(USE_TIMERS)
  2072. struct ttimers *timers;
  2073. #endif
  2074. /* Lua specific: Background operations and shared websockets */
  2075. #if defined(USE_LUA)
  2076. void *lua_background_state;
  2077. #endif
  2078. /* Server nonce */
  2079. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2080. /* Server callbacks */
  2081. struct mg_callbacks callbacks; /* User-defined callback function */
  2082. void *user_data; /* User-defined data */
  2083. /* Part 2 - Logical domain:
  2084. * This holds hostname, TLS certificate, document root, ...
  2085. * set for a domain hosted at the server.
  2086. * There may be multiple domains hosted at one physical server.
  2087. * The default domain "dd" is the first element of a list of
  2088. * domains.
  2089. */
  2090. struct mg_domain_context dd; /* default domain */
  2091. };
  2092. #if defined(USE_SERVER_STATS)
  2093. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2094. static struct mg_memory_stat *
  2095. get_memory_stat(struct mg_context *ctx)
  2096. {
  2097. if (ctx) {
  2098. return &(ctx->ctx_memory);
  2099. }
  2100. return &mg_common_memory;
  2101. }
  2102. #endif
  2103. enum {
  2104. CONNECTION_TYPE_INVALID,
  2105. CONNECTION_TYPE_REQUEST,
  2106. CONNECTION_TYPE_RESPONSE
  2107. };
  2108. struct mg_connection {
  2109. int connection_type; /* see CONNECTION_TYPE_* above */
  2110. struct mg_request_info request_info;
  2111. struct mg_response_info response_info;
  2112. struct mg_context *phys_ctx;
  2113. struct mg_domain_context *dom_ctx;
  2114. #if defined(USE_SERVER_STATS)
  2115. int conn_state; /* 0 = undef, numerical value may change in different
  2116. * versions. For the current definition, see
  2117. * mg_get_connection_info_impl */
  2118. #endif
  2119. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2120. SSL *ssl; /* SSL descriptor */
  2121. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2122. struct socket client; /* Connected client */
  2123. time_t conn_birth_time; /* Time (wall clock) when connection was
  2124. * established */
  2125. struct timespec req_time; /* Time (since system start) when the request
  2126. * was received */
  2127. int64_t num_bytes_sent; /* Total bytes sent to client */
  2128. int64_t content_len; /* Content-Length header value */
  2129. int64_t consumed_content; /* How many bytes of content have been read */
  2130. int is_chunked; /* Transfer-Encoding is chunked:
  2131. * 0 = not chunked,
  2132. * 1 = chunked, do data read yet,
  2133. * 2 = chunked, some data read,
  2134. * 3 = chunked, all data read
  2135. */
  2136. size_t chunk_remainder; /* Unread data from the last chunk */
  2137. char *buf; /* Buffer for received data */
  2138. char *path_info; /* PATH_INFO part of the URL */
  2139. int must_close; /* 1 if connection must be closed */
  2140. int accept_gzip; /* 1 if gzip encoding is accepted */
  2141. int in_error_handler; /* 1 if in handler for user defined error
  2142. * pages */
  2143. #if defined(USE_WEBSOCKET)
  2144. int in_websocket_handling; /* 1 if in read_websocket */
  2145. #endif
  2146. int handled_requests; /* Number of requests handled by this connection
  2147. */
  2148. int buf_size; /* Buffer size */
  2149. int request_len; /* Size of the request + headers in a buffer */
  2150. int data_len; /* Total size of data in a buffer */
  2151. int status_code; /* HTTP reply status code, e.g. 200 */
  2152. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2153. * throttle */
  2154. time_t last_throttle_time; /* Last time throttled data was sent */
  2155. int64_t last_throttle_bytes; /* Bytes sent this second */
  2156. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2157. * atomic transmissions for websockets */
  2158. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2159. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2160. #endif
  2161. int thread_index; /* Thread index within ctx */
  2162. };
  2163. /* Directory entry */
  2164. struct de {
  2165. struct mg_connection *conn;
  2166. char *file_name;
  2167. struct mg_file_stat file;
  2168. };
  2169. #if defined(USE_WEBSOCKET)
  2170. static int is_websocket_protocol(const struct mg_connection *conn);
  2171. #else
  2172. #define is_websocket_protocol(conn) (0)
  2173. #endif
  2174. #define mg_cry_internal(conn, fmt, ...) \
  2175. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2176. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2177. const char *func,
  2178. unsigned line,
  2179. const char *fmt,
  2180. ...) PRINTF_ARGS(4, 5);
  2181. #if !defined(NO_THREAD_NAME)
  2182. #if defined(_WIN32) && defined(_MSC_VER)
  2183. /* Set the thread name for debugging purposes in Visual Studio
  2184. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2185. */
  2186. #pragma pack(push, 8)
  2187. typedef struct tagTHREADNAME_INFO {
  2188. DWORD dwType; /* Must be 0x1000. */
  2189. LPCSTR szName; /* Pointer to name (in user addr space). */
  2190. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2191. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2192. } THREADNAME_INFO;
  2193. #pragma pack(pop)
  2194. #elif defined(__linux__)
  2195. #include <sys/prctl.h>
  2196. #include <sys/sendfile.h>
  2197. #ifdef ALTERNATIVE_QUEUE
  2198. #include <sys/eventfd.h>
  2199. #endif /* ALTERNATIVE_QUEUE */
  2200. #if defined(ALTERNATIVE_QUEUE)
  2201. static void *
  2202. event_create(void)
  2203. {
  2204. int evhdl = eventfd(0, EFD_CLOEXEC);
  2205. int *ret;
  2206. if (evhdl == -1) {
  2207. /* Linux uses -1 on error, Windows NULL. */
  2208. /* However, Linux does not return 0 on success either. */
  2209. return 0;
  2210. }
  2211. ret = (int *)mg_malloc(sizeof(int));
  2212. if (ret) {
  2213. *ret = evhdl;
  2214. } else {
  2215. (void)close(evhdl);
  2216. }
  2217. return (void *)ret;
  2218. }
  2219. static int
  2220. event_wait(void *eventhdl)
  2221. {
  2222. uint64_t u;
  2223. int evhdl, s;
  2224. if (!eventhdl) {
  2225. /* error */
  2226. return 0;
  2227. }
  2228. evhdl = *(int *)eventhdl;
  2229. s = (int)read(evhdl, &u, sizeof(u));
  2230. if (s != sizeof(u)) {
  2231. /* error */
  2232. return 0;
  2233. }
  2234. (void)u; /* the value is not required */
  2235. return 1;
  2236. }
  2237. static int
  2238. event_signal(void *eventhdl)
  2239. {
  2240. uint64_t u = 1;
  2241. int evhdl, s;
  2242. if (!eventhdl) {
  2243. /* error */
  2244. return 0;
  2245. }
  2246. evhdl = *(int *)eventhdl;
  2247. s = (int)write(evhdl, &u, sizeof(u));
  2248. if (s != sizeof(u)) {
  2249. /* error */
  2250. return 0;
  2251. }
  2252. return 1;
  2253. }
  2254. static void
  2255. event_destroy(void *eventhdl)
  2256. {
  2257. int evhdl;
  2258. if (!eventhdl) {
  2259. /* error */
  2260. return;
  2261. }
  2262. evhdl = *(int *)eventhdl;
  2263. close(evhdl);
  2264. mg_free(eventhdl);
  2265. }
  2266. #endif
  2267. #endif
  2268. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2269. struct posix_event {
  2270. pthread_mutex_t mutex;
  2271. pthread_cond_t cond;
  2272. };
  2273. static void *
  2274. event_create(void)
  2275. {
  2276. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2277. if (ret == 0) {
  2278. /* out of memory */
  2279. return 0;
  2280. }
  2281. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2282. /* pthread mutex not available */
  2283. mg_free(ret);
  2284. return 0;
  2285. }
  2286. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2287. /* pthread cond not available */
  2288. pthread_mutex_destroy(&(ret->mutex));
  2289. mg_free(ret);
  2290. return 0;
  2291. }
  2292. return (void *)ret;
  2293. }
  2294. static int
  2295. event_wait(void *eventhdl)
  2296. {
  2297. struct posix_event *ev = (struct posix_event *)eventhdl;
  2298. pthread_mutex_lock(&(ev->mutex));
  2299. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2300. pthread_mutex_unlock(&(ev->mutex));
  2301. return 1;
  2302. }
  2303. static int
  2304. event_signal(void *eventhdl)
  2305. {
  2306. struct posix_event *ev = (struct posix_event *)eventhdl;
  2307. pthread_mutex_lock(&(ev->mutex));
  2308. pthread_cond_signal(&(ev->cond));
  2309. pthread_mutex_unlock(&(ev->mutex));
  2310. return 1;
  2311. }
  2312. static void
  2313. event_destroy(void *eventhdl)
  2314. {
  2315. struct posix_event *ev = (struct posix_event *)eventhdl;
  2316. pthread_cond_destroy(&(ev->cond));
  2317. pthread_mutex_destroy(&(ev->mutex));
  2318. mg_free(ev);
  2319. }
  2320. #endif
  2321. static void
  2322. mg_set_thread_name(const char *name)
  2323. {
  2324. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2325. mg_snprintf(
  2326. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2327. #if defined(_WIN32)
  2328. #if defined(_MSC_VER)
  2329. /* Windows and Visual Studio Compiler */
  2330. __try
  2331. {
  2332. THREADNAME_INFO info;
  2333. info.dwType = 0x1000;
  2334. info.szName = threadName;
  2335. info.dwThreadID = ~0U;
  2336. info.dwFlags = 0;
  2337. RaiseException(0x406D1388,
  2338. 0,
  2339. sizeof(info) / sizeof(ULONG_PTR),
  2340. (ULONG_PTR *)&info);
  2341. }
  2342. __except(EXCEPTION_EXECUTE_HANDLER)
  2343. {
  2344. }
  2345. #elif defined(__MINGW32__)
  2346. /* No option known to set thread name for MinGW */
  2347. #endif
  2348. #elif defined(__GLIBC__) \
  2349. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2350. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2351. (void)pthread_setname_np(pthread_self(), threadName);
  2352. #elif defined(__linux__)
  2353. /* on linux we can use the old prctl function */
  2354. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2355. #endif
  2356. }
  2357. #else /* !defined(NO_THREAD_NAME) */
  2358. void
  2359. mg_set_thread_name(const char *threadName)
  2360. {
  2361. }
  2362. #endif
  2363. #if defined(MG_LEGACY_INTERFACE)
  2364. const char **
  2365. mg_get_valid_option_names(void)
  2366. {
  2367. /* This function is deprecated. Use mg_get_valid_options instead. */
  2368. static const char *
  2369. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2370. int i;
  2371. for (i = 0; config_options[i].name != NULL; i++) {
  2372. data[i * 2] = config_options[i].name;
  2373. data[i * 2 + 1] = config_options[i].default_value;
  2374. }
  2375. return data;
  2376. }
  2377. #endif
  2378. const struct mg_option *
  2379. mg_get_valid_options(void)
  2380. {
  2381. return config_options;
  2382. }
  2383. /* Do not open file (used in is_file_in_memory) */
  2384. #define MG_FOPEN_MODE_NONE (0)
  2385. /* Open file for read only access */
  2386. #define MG_FOPEN_MODE_READ (1)
  2387. /* Open file for writing, create and overwrite */
  2388. #define MG_FOPEN_MODE_WRITE (2)
  2389. /* Open file for writing, create and append */
  2390. #define MG_FOPEN_MODE_APPEND (4)
  2391. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2392. * output filep and return 1, otherwise return 0 and don't modify anything.
  2393. */
  2394. static int
  2395. open_file_in_memory(const struct mg_connection *conn,
  2396. const char *path,
  2397. struct mg_file *filep,
  2398. int mode)
  2399. {
  2400. #if defined(MG_USE_OPEN_FILE)
  2401. size_t size = 0;
  2402. const char *buf = NULL;
  2403. if (!conn) {
  2404. return 0;
  2405. }
  2406. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2407. return 0;
  2408. }
  2409. if (conn->phys_ctx->callbacks.open_file) {
  2410. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2411. if (buf != NULL) {
  2412. if (filep == NULL) {
  2413. /* This is a file in memory, but we cannot store the
  2414. * properties
  2415. * now.
  2416. * Called from "is_file_in_memory" function. */
  2417. return 1;
  2418. }
  2419. /* NOTE: override filep->size only on success. Otherwise, it
  2420. * might
  2421. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2422. filep->access.membuf = buf;
  2423. filep->access.fp = NULL;
  2424. /* Size was set by the callback */
  2425. filep->stat.size = size;
  2426. /* Assume the data may change during runtime by setting
  2427. * last_modified = now */
  2428. filep->stat.last_modified = time(NULL);
  2429. filep->stat.is_directory = 0;
  2430. filep->stat.is_gzipped = 0;
  2431. }
  2432. }
  2433. return (buf != NULL);
  2434. #else
  2435. (void)conn;
  2436. (void)path;
  2437. (void)filep;
  2438. (void)mode;
  2439. return 0;
  2440. #endif
  2441. }
  2442. static int
  2443. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2444. {
  2445. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2446. }
  2447. static int
  2448. is_file_opened(const struct mg_file_access *fileacc)
  2449. {
  2450. if (!fileacc) {
  2451. return 0;
  2452. }
  2453. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2454. }
  2455. static int mg_stat(const struct mg_connection *conn,
  2456. const char *path,
  2457. struct mg_file_stat *filep);
  2458. /* mg_fopen will open a file either in memory or on the disk.
  2459. * The input parameter path is a string in UTF-8 encoding.
  2460. * The input parameter mode is MG_FOPEN_MODE_*
  2461. * On success, either fp or membuf will be set in the output
  2462. * struct file. All status members will also be set.
  2463. * The function returns 1 on success, 0 on error. */
  2464. static int
  2465. mg_fopen(const struct mg_connection *conn,
  2466. const char *path,
  2467. int mode,
  2468. struct mg_file *filep)
  2469. {
  2470. int found;
  2471. if (!filep) {
  2472. return 0;
  2473. }
  2474. filep->access.fp = NULL;
  2475. filep->access.membuf = NULL;
  2476. if (!is_file_in_memory(conn, path)) {
  2477. /* filep is initialized in mg_stat: all fields with memset to,
  2478. * some fields like size and modification date with values */
  2479. found = mg_stat(conn, path, &(filep->stat));
  2480. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2481. /* file does not exist and will not be created */
  2482. return 0;
  2483. }
  2484. #ifdef _WIN32
  2485. {
  2486. wchar_t wbuf[W_PATH_MAX];
  2487. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2488. switch (mode) {
  2489. case MG_FOPEN_MODE_READ:
  2490. filep->access.fp = _wfopen(wbuf, L"rb");
  2491. break;
  2492. case MG_FOPEN_MODE_WRITE:
  2493. filep->access.fp = _wfopen(wbuf, L"wb");
  2494. break;
  2495. case MG_FOPEN_MODE_APPEND:
  2496. filep->access.fp = _wfopen(wbuf, L"ab");
  2497. break;
  2498. }
  2499. }
  2500. #else
  2501. /* Linux et al already use unicode. No need to convert. */
  2502. switch (mode) {
  2503. case MG_FOPEN_MODE_READ:
  2504. filep->access.fp = fopen(path, "r");
  2505. break;
  2506. case MG_FOPEN_MODE_WRITE:
  2507. filep->access.fp = fopen(path, "w");
  2508. break;
  2509. case MG_FOPEN_MODE_APPEND:
  2510. filep->access.fp = fopen(path, "a");
  2511. break;
  2512. }
  2513. #endif
  2514. if (!found) {
  2515. /* File did not exist before fopen was called.
  2516. * Maybe it has been created now. Get stat info
  2517. * like creation time now. */
  2518. found = mg_stat(conn, path, &(filep->stat));
  2519. (void)found;
  2520. }
  2521. /* file is on disk */
  2522. return (filep->access.fp != NULL);
  2523. } else {
  2524. /* is_file_in_memory returned true */
  2525. if (open_file_in_memory(conn, path, filep, mode)) {
  2526. /* file is in memory */
  2527. return (filep->access.membuf != NULL);
  2528. }
  2529. }
  2530. /* Open failed */
  2531. return 0;
  2532. }
  2533. /* return 0 on success, just like fclose */
  2534. static int
  2535. mg_fclose(struct mg_file_access *fileacc)
  2536. {
  2537. int ret = -1;
  2538. if (fileacc != NULL) {
  2539. if (fileacc->fp != NULL) {
  2540. ret = fclose(fileacc->fp);
  2541. } else if (fileacc->membuf != NULL) {
  2542. ret = 0;
  2543. }
  2544. /* reset all members of fileacc */
  2545. memset(fileacc, 0, sizeof(*fileacc));
  2546. }
  2547. return ret;
  2548. }
  2549. static void
  2550. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2551. {
  2552. for (; *src != '\0' && n > 1; n--) {
  2553. *dst++ = *src++;
  2554. }
  2555. *dst = '\0';
  2556. }
  2557. static int
  2558. lowercase(const char *s)
  2559. {
  2560. return tolower(*(const unsigned char *)s);
  2561. }
  2562. int
  2563. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2564. {
  2565. int diff = 0;
  2566. if (len > 0) {
  2567. do {
  2568. diff = lowercase(s1++) - lowercase(s2++);
  2569. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2570. }
  2571. return diff;
  2572. }
  2573. int
  2574. mg_strcasecmp(const char *s1, const char *s2)
  2575. {
  2576. int diff;
  2577. do {
  2578. diff = lowercase(s1++) - lowercase(s2++);
  2579. } while (diff == 0 && s1[-1] != '\0');
  2580. return diff;
  2581. }
  2582. static char *
  2583. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2584. {
  2585. char *p;
  2586. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2587. * defined */
  2588. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2589. mg_strlcpy(p, ptr, len + 1);
  2590. }
  2591. return p;
  2592. }
  2593. static char *
  2594. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2595. {
  2596. return mg_strndup_ctx(str, strlen(str), ctx);
  2597. }
  2598. static char *
  2599. mg_strdup(const char *str)
  2600. {
  2601. return mg_strndup_ctx(str, strlen(str), NULL);
  2602. }
  2603. static const char *
  2604. mg_strcasestr(const char *big_str, const char *small_str)
  2605. {
  2606. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2607. if (big_len >= small_len) {
  2608. for (i = 0; i <= (big_len - small_len); i++) {
  2609. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2610. return big_str + i;
  2611. }
  2612. }
  2613. }
  2614. return NULL;
  2615. }
  2616. /* Return null terminated string of given maximum length.
  2617. * Report errors if length is exceeded. */
  2618. static void
  2619. mg_vsnprintf(const struct mg_connection *conn,
  2620. int *truncated,
  2621. char *buf,
  2622. size_t buflen,
  2623. const char *fmt,
  2624. va_list ap)
  2625. {
  2626. int n, ok;
  2627. if (buflen == 0) {
  2628. if (truncated) {
  2629. *truncated = 1;
  2630. }
  2631. return;
  2632. }
  2633. #ifdef __clang__
  2634. #pragma clang diagnostic push
  2635. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2636. /* Using fmt as a non-literal is intended here, since it is mostly called
  2637. * indirectly by mg_snprintf */
  2638. #endif
  2639. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2640. ok = (n >= 0) && ((size_t)n < buflen);
  2641. #ifdef __clang__
  2642. #pragma clang diagnostic pop
  2643. #endif
  2644. if (ok) {
  2645. if (truncated) {
  2646. *truncated = 0;
  2647. }
  2648. } else {
  2649. if (truncated) {
  2650. *truncated = 1;
  2651. }
  2652. mg_cry_internal(conn,
  2653. "truncating vsnprintf buffer: [%.*s]",
  2654. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2655. buf);
  2656. n = (int)buflen - 1;
  2657. }
  2658. buf[n] = '\0';
  2659. }
  2660. static void
  2661. mg_snprintf(const struct mg_connection *conn,
  2662. int *truncated,
  2663. char *buf,
  2664. size_t buflen,
  2665. const char *fmt,
  2666. ...)
  2667. {
  2668. va_list ap;
  2669. va_start(ap, fmt);
  2670. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2671. va_end(ap);
  2672. }
  2673. static int
  2674. get_option_index(const char *name)
  2675. {
  2676. int i;
  2677. for (i = 0; config_options[i].name != NULL; i++) {
  2678. if (strcmp(config_options[i].name, name) == 0) {
  2679. return i;
  2680. }
  2681. }
  2682. return -1;
  2683. }
  2684. const char *
  2685. mg_get_option(const struct mg_context *ctx, const char *name)
  2686. {
  2687. int i;
  2688. if ((i = get_option_index(name)) == -1) {
  2689. return NULL;
  2690. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2691. return "";
  2692. } else {
  2693. return ctx->dd.config[i];
  2694. }
  2695. }
  2696. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2697. struct mg_context *
  2698. mg_get_context(const struct mg_connection *conn)
  2699. {
  2700. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2701. }
  2702. void *
  2703. mg_get_user_data(const struct mg_context *ctx)
  2704. {
  2705. return (ctx == NULL) ? NULL : ctx->user_data;
  2706. }
  2707. void
  2708. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2709. {
  2710. if (conn != NULL) {
  2711. conn->request_info.conn_data = data;
  2712. }
  2713. }
  2714. void *
  2715. mg_get_user_connection_data(const struct mg_connection *conn)
  2716. {
  2717. if (conn != NULL) {
  2718. return conn->request_info.conn_data;
  2719. }
  2720. return NULL;
  2721. }
  2722. #if defined(MG_LEGACY_INTERFACE)
  2723. /* Deprecated: Use mg_get_server_ports instead. */
  2724. size_t
  2725. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2726. {
  2727. size_t i;
  2728. if (!ctx) {
  2729. return 0;
  2730. }
  2731. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2732. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2733. ports[i] =
  2734. #if defined(USE_IPV6)
  2735. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2736. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2737. :
  2738. #endif
  2739. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2740. }
  2741. return i;
  2742. }
  2743. #endif
  2744. int
  2745. mg_get_server_ports(const struct mg_context *ctx,
  2746. int size,
  2747. struct mg_server_ports *ports)
  2748. {
  2749. int i, cnt = 0;
  2750. if (size <= 0) {
  2751. return -1;
  2752. }
  2753. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2754. if (!ctx) {
  2755. return -1;
  2756. }
  2757. if (!ctx->listening_sockets) {
  2758. return -1;
  2759. }
  2760. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2761. ports[cnt].port =
  2762. #if defined(USE_IPV6)
  2763. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2764. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2765. :
  2766. #endif
  2767. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2768. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2769. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2770. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2771. /* IPv4 */
  2772. ports[cnt].protocol = 1;
  2773. cnt++;
  2774. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2775. /* IPv6 */
  2776. ports[cnt].protocol = 3;
  2777. cnt++;
  2778. }
  2779. }
  2780. return cnt;
  2781. }
  2782. static void
  2783. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2784. {
  2785. buf[0] = '\0';
  2786. if (!usa) {
  2787. return;
  2788. }
  2789. if (usa->sa.sa_family == AF_INET) {
  2790. getnameinfo(&usa->sa,
  2791. sizeof(usa->sin),
  2792. buf,
  2793. (unsigned)len,
  2794. NULL,
  2795. 0,
  2796. NI_NUMERICHOST);
  2797. }
  2798. #if defined(USE_IPV6)
  2799. else if (usa->sa.sa_family == AF_INET6) {
  2800. getnameinfo(&usa->sa,
  2801. sizeof(usa->sin6),
  2802. buf,
  2803. (unsigned)len,
  2804. NULL,
  2805. 0,
  2806. NI_NUMERICHOST);
  2807. }
  2808. #endif
  2809. }
  2810. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2811. * included in all responses other than 100, 101, 5xx. */
  2812. static void
  2813. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2814. {
  2815. #ifndef REENTRANT_TIME
  2816. struct tm *tm;
  2817. tm = ((t != NULL) ? gmtime(t) : NULL);
  2818. if (tm != NULL) {
  2819. #else
  2820. struct tm _tm;
  2821. struct tm *tm = &_tm;
  2822. if (t != NULL) {
  2823. gmtime_r(t, tm);
  2824. #endif
  2825. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2826. } else {
  2827. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2828. buf[buf_len - 1] = '\0';
  2829. }
  2830. }
  2831. /* difftime for struct timespec. Return value is in seconds. */
  2832. static double
  2833. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2834. {
  2835. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2836. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2837. }
  2838. /* Print error message to the opened error log stream. */
  2839. static void
  2840. mg_cry_internal_impl(const struct mg_connection *conn,
  2841. const char *func,
  2842. unsigned line,
  2843. const char *fmt,
  2844. va_list ap)
  2845. {
  2846. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2847. struct mg_file fi;
  2848. time_t timestamp;
  2849. /* Unused, in the RELEASE build */
  2850. (void)func;
  2851. (void)line;
  2852. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2853. buf[sizeof(buf) - 1] = 0;
  2854. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2855. if (!conn) {
  2856. puts(buf);
  2857. return;
  2858. }
  2859. /* Do not lock when getting the callback value, here and below.
  2860. * I suppose this is fine, since function cannot disappear in the
  2861. * same way string option can. */
  2862. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2863. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2864. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2865. if (mg_fopen(conn,
  2866. conn->dom_ctx->config[ERROR_LOG_FILE],
  2867. MG_FOPEN_MODE_APPEND,
  2868. &fi) == 0) {
  2869. fi.access.fp = NULL;
  2870. }
  2871. } else {
  2872. fi.access.fp = NULL;
  2873. }
  2874. if (fi.access.fp != NULL) {
  2875. flockfile(fi.access.fp);
  2876. timestamp = time(NULL);
  2877. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2878. fprintf(fi.access.fp,
  2879. "[%010lu] [error] [client %s] ",
  2880. (unsigned long)timestamp,
  2881. src_addr);
  2882. if (conn->request_info.request_method != NULL) {
  2883. fprintf(fi.access.fp,
  2884. "%s %s: ",
  2885. conn->request_info.request_method,
  2886. conn->request_info.request_uri
  2887. ? conn->request_info.request_uri
  2888. : "");
  2889. }
  2890. fprintf(fi.access.fp, "%s", buf);
  2891. fputc('\n', fi.access.fp);
  2892. fflush(fi.access.fp);
  2893. funlockfile(fi.access.fp);
  2894. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2895. * mg_cry here anyway ;-) */
  2896. }
  2897. }
  2898. }
  2899. static void
  2900. mg_cry_internal_wrap(const struct mg_connection *conn,
  2901. const char *func,
  2902. unsigned line,
  2903. const char *fmt,
  2904. ...)
  2905. {
  2906. va_list ap;
  2907. va_start(ap, fmt);
  2908. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2909. va_end(ap);
  2910. }
  2911. void
  2912. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2913. {
  2914. va_list ap;
  2915. va_start(ap, fmt);
  2916. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2917. va_end(ap);
  2918. }
  2919. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2920. /* Return fake connection structure. Used for logging, if connection
  2921. * is not applicable at the moment of logging. */
  2922. static struct mg_connection *
  2923. fc(struct mg_context *ctx)
  2924. {
  2925. static struct mg_connection fake_connection;
  2926. fake_connection.phys_ctx = ctx;
  2927. fake_connection.dom_ctx = &(ctx->dd);
  2928. return &fake_connection;
  2929. }
  2930. const char *
  2931. mg_version(void)
  2932. {
  2933. return CIVETWEB_VERSION;
  2934. }
  2935. const struct mg_request_info *
  2936. mg_get_request_info(const struct mg_connection *conn)
  2937. {
  2938. if (!conn) {
  2939. return NULL;
  2940. }
  2941. #if 1 /* TODO: deal with legacy */
  2942. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2943. static char txt[16];
  2944. sprintf(txt, "%03i", conn->response_info.status_code);
  2945. ((struct mg_connection *)conn)->request_info.local_uri =
  2946. ((struct mg_connection *)conn)->request_info.request_uri =
  2947. txt; /* TODO: not thread safe */
  2948. ((struct mg_connection *)conn)->request_info.num_headers =
  2949. conn->response_info.num_headers;
  2950. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2951. conn->response_info.http_headers,
  2952. sizeof(conn->response_info.http_headers));
  2953. } else
  2954. #endif
  2955. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2956. return NULL;
  2957. }
  2958. return &conn->request_info;
  2959. }
  2960. const struct mg_response_info *
  2961. mg_get_response_info(const struct mg_connection *conn)
  2962. {
  2963. if (!conn) {
  2964. return NULL;
  2965. }
  2966. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2967. return NULL;
  2968. }
  2969. return &conn->response_info;
  2970. }
  2971. static const char *
  2972. get_proto_name(const struct mg_connection *conn)
  2973. {
  2974. #ifdef __clang__
  2975. #pragma clang diagnostic push
  2976. #pragma clang diagnostic ignored "-Wunreachable-code"
  2977. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2978. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2979. * unreachable, but splitting into four different #ifdef clauses here is more
  2980. * complicated.
  2981. */
  2982. #endif
  2983. const struct mg_request_info *ri = &conn->request_info;
  2984. const char *proto =
  2985. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2986. : (ri->is_ssl ? "https" : "http"));
  2987. return proto;
  2988. #ifdef __clang__
  2989. #pragma clang diagnostic pop
  2990. #endif
  2991. }
  2992. int
  2993. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2994. {
  2995. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2996. return -1;
  2997. } else {
  2998. int truncated = 0;
  2999. const struct mg_request_info *ri = &conn->request_info;
  3000. const char *proto = get_proto_name(conn);
  3001. if (ri->local_uri == NULL) {
  3002. return -1;
  3003. }
  3004. if ((ri->request_uri != NULL)
  3005. && strcmp(ri->local_uri, ri->request_uri)) {
  3006. mg_snprintf(conn,
  3007. &truncated,
  3008. buf,
  3009. buflen,
  3010. "%s://%s",
  3011. proto,
  3012. ri->request_uri);
  3013. if (truncated) {
  3014. return -1;
  3015. }
  3016. return 0;
  3017. } else {
  3018. #if defined(USE_IPV6)
  3019. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3020. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3021. : htons(conn->client.lsa.sin.sin_port);
  3022. #else
  3023. int port = htons(conn->client.lsa.sin.sin_port);
  3024. #endif
  3025. int def_port = ri->is_ssl ? 443 : 80;
  3026. int auth_domain_check_enabled =
  3027. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3028. && (!mg_strcasecmp(
  3029. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  3030. "yes"));
  3031. const char *server_domain =
  3032. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3033. char portstr[16];
  3034. char server_ip[48];
  3035. if (port != def_port) {
  3036. sprintf(portstr, ":%u", (unsigned)port);
  3037. } else {
  3038. portstr[0] = 0;
  3039. }
  3040. if (!auth_domain_check_enabled || !server_domain) {
  3041. sockaddr_to_string(server_ip,
  3042. sizeof(server_ip),
  3043. &conn->client.lsa);
  3044. server_domain = server_ip;
  3045. }
  3046. mg_snprintf(conn,
  3047. &truncated,
  3048. buf,
  3049. buflen,
  3050. "%s://%s%s%s",
  3051. proto,
  3052. server_domain,
  3053. portstr,
  3054. ri->local_uri);
  3055. if (truncated) {
  3056. return -1;
  3057. }
  3058. return 0;
  3059. }
  3060. }
  3061. }
  3062. /* Skip the characters until one of the delimiters characters found.
  3063. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3064. * Advance pointer to buffer to the next word. Return found 0-terminated
  3065. * word.
  3066. * Delimiters can be quoted with quotechar. */
  3067. static char *
  3068. skip_quoted(char **buf,
  3069. const char *delimiters,
  3070. const char *whitespace,
  3071. char quotechar)
  3072. {
  3073. char *p, *begin_word, *end_word, *end_whitespace;
  3074. begin_word = *buf;
  3075. end_word = begin_word + strcspn(begin_word, delimiters);
  3076. /* Check for quotechar */
  3077. if (end_word > begin_word) {
  3078. p = end_word - 1;
  3079. while (*p == quotechar) {
  3080. /* While the delimiter is quoted, look for the next delimiter.
  3081. */
  3082. /* This happens, e.g., in calls from parse_auth_header,
  3083. * if the user name contains a " character. */
  3084. /* If there is anything beyond end_word, copy it. */
  3085. if (*end_word != '\0') {
  3086. size_t end_off = strcspn(end_word + 1, delimiters);
  3087. memmove(p, end_word, end_off + 1);
  3088. p += end_off; /* p must correspond to end_word - 1 */
  3089. end_word += end_off + 1;
  3090. } else {
  3091. *p = '\0';
  3092. break;
  3093. }
  3094. }
  3095. for (p++; p < end_word; p++) {
  3096. *p = '\0';
  3097. }
  3098. }
  3099. if (*end_word == '\0') {
  3100. *buf = end_word;
  3101. } else {
  3102. #if defined(__GNUC__) || defined(__MINGW32__)
  3103. /* Disable spurious conversion warning for GCC */
  3104. #if GCC_VERSION >= 40500
  3105. #pragma GCC diagnostic push
  3106. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3107. #endif /* GCC_VERSION >= 40500 */
  3108. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3109. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3110. #if defined(__GNUC__) || defined(__MINGW32__)
  3111. #if GCC_VERSION >= 40500
  3112. #pragma GCC diagnostic pop
  3113. #endif /* GCC_VERSION >= 40500 */
  3114. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3115. for (p = end_word; p < end_whitespace; p++) {
  3116. *p = '\0';
  3117. }
  3118. *buf = end_whitespace;
  3119. }
  3120. return begin_word;
  3121. }
  3122. /* Return HTTP header value, or NULL if not found. */
  3123. static const char *
  3124. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3125. {
  3126. int i;
  3127. for (i = 0; i < num_hdr; i++) {
  3128. if (!mg_strcasecmp(name, hdr[i].name)) {
  3129. return hdr[i].value;
  3130. }
  3131. }
  3132. return NULL;
  3133. }
  3134. #if defined(USE_WEBSOCKET)
  3135. /* Retrieve requested HTTP header multiple values, and return the number of
  3136. * found occurrences */
  3137. static int
  3138. get_req_headers(const struct mg_request_info *ri,
  3139. const char *name,
  3140. const char **output,
  3141. int output_max_size)
  3142. {
  3143. int i;
  3144. int cnt = 0;
  3145. if (ri) {
  3146. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3147. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3148. output[cnt++] = ri->http_headers[i].value;
  3149. }
  3150. }
  3151. }
  3152. return cnt;
  3153. }
  3154. #endif
  3155. const char *
  3156. mg_get_header(const struct mg_connection *conn, const char *name)
  3157. {
  3158. if (!conn) {
  3159. return NULL;
  3160. }
  3161. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3162. return get_header(conn->request_info.http_headers,
  3163. conn->request_info.num_headers,
  3164. name);
  3165. }
  3166. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3167. return get_header(conn->response_info.http_headers,
  3168. conn->response_info.num_headers,
  3169. name);
  3170. }
  3171. return NULL;
  3172. }
  3173. static const char *
  3174. get_http_version(const struct mg_connection *conn)
  3175. {
  3176. if (!conn) {
  3177. return NULL;
  3178. }
  3179. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3180. return conn->request_info.http_version;
  3181. }
  3182. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3183. return conn->response_info.http_version;
  3184. }
  3185. return NULL;
  3186. }
  3187. /* A helper function for traversing a comma separated list of values.
  3188. * It returns a list pointer shifted to the next value, or NULL if the end
  3189. * of the list found.
  3190. * Value is stored in val vector. If value has form "x=y", then eq_val
  3191. * vector is initialized to point to the "y" part, and val vector length
  3192. * is adjusted to point only to "x". */
  3193. static const char *
  3194. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3195. {
  3196. int end;
  3197. reparse:
  3198. if (val == NULL || list == NULL || *list == '\0') {
  3199. /* End of the list */
  3200. return NULL;
  3201. }
  3202. /* Skip over leading LWS */
  3203. while (*list == ' ' || *list == '\t')
  3204. list++;
  3205. val->ptr = list;
  3206. if ((list = strchr(val->ptr, ',')) != NULL) {
  3207. /* Comma found. Store length and shift the list ptr */
  3208. val->len = ((size_t)(list - val->ptr));
  3209. list++;
  3210. } else {
  3211. /* This value is the last one */
  3212. list = val->ptr + strlen(val->ptr);
  3213. val->len = ((size_t)(list - val->ptr));
  3214. }
  3215. /* Adjust length for trailing LWS */
  3216. end = (int)val->len - 1;
  3217. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3218. end--;
  3219. val->len = (size_t)(end + 1);
  3220. if (val->len == 0) {
  3221. /* Ignore any empty entries. */
  3222. goto reparse;
  3223. }
  3224. if (eq_val != NULL) {
  3225. /* Value has form "x=y", adjust pointers and lengths
  3226. * so that val points to "x", and eq_val points to "y". */
  3227. eq_val->len = 0;
  3228. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3229. if (eq_val->ptr != NULL) {
  3230. eq_val->ptr++; /* Skip over '=' character */
  3231. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3232. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3233. }
  3234. }
  3235. return list;
  3236. }
  3237. /* A helper function for checking if a comma separated list of values
  3238. * contains
  3239. * the given option (case insensitvely).
  3240. * 'header' can be NULL, in which case false is returned. */
  3241. static int
  3242. header_has_option(const char *header, const char *option)
  3243. {
  3244. struct vec opt_vec;
  3245. struct vec eq_vec;
  3246. DEBUG_ASSERT(option != NULL);
  3247. DEBUG_ASSERT(option[0] != '\0');
  3248. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3249. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3250. return 1;
  3251. }
  3252. return 0;
  3253. }
  3254. /* Perform case-insensitive match of string against pattern */
  3255. static int
  3256. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3257. {
  3258. const char *or_str;
  3259. size_t i;
  3260. int j, len, res;
  3261. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3262. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3263. return (res > 0) ? res : match_prefix(or_str + 1,
  3264. (size_t)((pattern + pattern_len)
  3265. - (or_str + 1)),
  3266. str);
  3267. }
  3268. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  3269. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3270. continue;
  3271. } else if (pattern[i] == '$') {
  3272. return (str[j] == '\0') ? j : -1;
  3273. } else if (pattern[i] == '*') {
  3274. i++;
  3275. if (pattern[i] == '*') {
  3276. i++;
  3277. len = (int)strlen(str + j);
  3278. } else {
  3279. len = (int)strcspn(str + j, "/");
  3280. }
  3281. if (i == pattern_len) {
  3282. return j + len;
  3283. }
  3284. do {
  3285. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3286. } while (res == -1 && len-- > 0);
  3287. return (res == -1) ? -1 : j + res + len;
  3288. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3289. return -1;
  3290. }
  3291. }
  3292. return j;
  3293. }
  3294. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3295. * This function must tolerate situations when connection info is not
  3296. * set up, for example if request parsing failed. */
  3297. static int
  3298. should_keep_alive(const struct mg_connection *conn)
  3299. {
  3300. const char *http_version;
  3301. const char *header;
  3302. /* First satisfy needs of the server */
  3303. if ((conn == NULL) || conn->must_close) {
  3304. /* Close, if civetweb framework needs to close */
  3305. return 0;
  3306. }
  3307. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3308. /* Close, if keep alive is not enabled */
  3309. return 0;
  3310. }
  3311. /* Check explicit wish of the client */
  3312. header = mg_get_header(conn, "Connection");
  3313. if (header) {
  3314. /* If there is a connection header from the client, obey */
  3315. if (header_has_option(header, "keep-alive")) {
  3316. return 1;
  3317. }
  3318. return 0;
  3319. }
  3320. /* Use default of the standard */
  3321. http_version = get_http_version(conn);
  3322. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3323. /* HTTP 1.1 default is keep alive */
  3324. return 1;
  3325. }
  3326. /* HTTP 1.0 (and earlier) default is to close the connection */
  3327. return 0;
  3328. }
  3329. static int
  3330. should_decode_url(const struct mg_connection *conn)
  3331. {
  3332. if (!conn || !conn->dom_ctx) {
  3333. return 0;
  3334. }
  3335. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3336. }
  3337. static const char *
  3338. suggest_connection_header(const struct mg_connection *conn)
  3339. {
  3340. return should_keep_alive(conn) ? "keep-alive" : "close";
  3341. }
  3342. static int
  3343. send_no_cache_header(struct mg_connection *conn)
  3344. {
  3345. /* Send all current and obsolete cache opt-out directives. */
  3346. return mg_printf(conn,
  3347. "Cache-Control: no-cache, no-store, "
  3348. "must-revalidate, private, max-age=0\r\n"
  3349. "Pragma: no-cache\r\n"
  3350. "Expires: 0\r\n");
  3351. }
  3352. static int
  3353. send_static_cache_header(struct mg_connection *conn)
  3354. {
  3355. #if !defined(NO_CACHING)
  3356. /* Read the server config to check how long a file may be cached.
  3357. * The configuration is in seconds. */
  3358. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3359. if (max_age <= 0) {
  3360. /* 0 means "do not cache". All values <0 are reserved
  3361. * and may be used differently in the future. */
  3362. /* If a file should not be cached, do not only send
  3363. * max-age=0, but also pragmas and Expires headers. */
  3364. return send_no_cache_header(conn);
  3365. }
  3366. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3367. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3368. /* See also https://www.mnot.net/cache_docs/ */
  3369. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3370. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3371. * leap
  3372. * year to 31622400 seconds. For the moment, we just send whatever has
  3373. * been configured, still the behavior for >1 year should be considered
  3374. * as undefined. */
  3375. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3376. #else /* NO_CACHING */
  3377. return send_no_cache_header(conn);
  3378. #endif /* !NO_CACHING */
  3379. }
  3380. static int
  3381. send_additional_header(struct mg_connection *conn)
  3382. {
  3383. int i = 0;
  3384. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3385. #if !defined(NO_SSL)
  3386. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3387. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3388. if (max_age >= 0) {
  3389. i += mg_printf(conn,
  3390. "Strict-Transport-Security: max-age=%u\r\n",
  3391. (unsigned)max_age);
  3392. }
  3393. }
  3394. #endif
  3395. if (header && header[0]) {
  3396. i += mg_printf(conn, "%s\r\n", header);
  3397. }
  3398. return i;
  3399. }
  3400. static void handle_file_based_request(struct mg_connection *conn,
  3401. const char *path,
  3402. struct mg_file *filep);
  3403. const char *
  3404. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3405. {
  3406. /* See IANA HTTP status code assignment:
  3407. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3408. */
  3409. switch (response_code) {
  3410. /* RFC2616 Section 10.1 - Informational 1xx */
  3411. case 100:
  3412. return "Continue"; /* RFC2616 Section 10.1.1 */
  3413. case 101:
  3414. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3415. case 102:
  3416. return "Processing"; /* RFC2518 Section 10.1 */
  3417. /* RFC2616 Section 10.2 - Successful 2xx */
  3418. case 200:
  3419. return "OK"; /* RFC2616 Section 10.2.1 */
  3420. case 201:
  3421. return "Created"; /* RFC2616 Section 10.2.2 */
  3422. case 202:
  3423. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3424. case 203:
  3425. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3426. case 204:
  3427. return "No Content"; /* RFC2616 Section 10.2.5 */
  3428. case 205:
  3429. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3430. case 206:
  3431. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3432. case 207:
  3433. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3434. */
  3435. case 208:
  3436. return "Already Reported"; /* RFC5842 Section 7.1 */
  3437. case 226:
  3438. return "IM used"; /* RFC3229 Section 10.4.1 */
  3439. /* RFC2616 Section 10.3 - Redirection 3xx */
  3440. case 300:
  3441. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3442. case 301:
  3443. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3444. case 302:
  3445. return "Found"; /* RFC2616 Section 10.3.3 */
  3446. case 303:
  3447. return "See Other"; /* RFC2616 Section 10.3.4 */
  3448. case 304:
  3449. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3450. case 305:
  3451. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3452. case 307:
  3453. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3454. case 308:
  3455. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3456. /* RFC2616 Section 10.4 - Client Error 4xx */
  3457. case 400:
  3458. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3459. case 401:
  3460. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3461. case 402:
  3462. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3463. case 403:
  3464. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3465. case 404:
  3466. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3467. case 405:
  3468. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3469. case 406:
  3470. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3471. case 407:
  3472. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3473. case 408:
  3474. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3475. case 409:
  3476. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3477. case 410:
  3478. return "Gone"; /* RFC2616 Section 10.4.11 */
  3479. case 411:
  3480. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3481. case 412:
  3482. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3483. case 413:
  3484. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3485. case 414:
  3486. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3487. case 415:
  3488. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3489. case 416:
  3490. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3491. */
  3492. case 417:
  3493. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3494. case 421:
  3495. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3496. case 422:
  3497. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3498. * Section 11.2 */
  3499. case 423:
  3500. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3501. case 424:
  3502. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3503. * Section 11.4 */
  3504. case 426:
  3505. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3506. case 428:
  3507. return "Precondition Required"; /* RFC 6585, Section 3 */
  3508. case 429:
  3509. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3510. case 431:
  3511. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3512. case 451:
  3513. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3514. * Section 3 */
  3515. /* RFC2616 Section 10.5 - Server Error 5xx */
  3516. case 500:
  3517. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3518. case 501:
  3519. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3520. case 502:
  3521. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3522. case 503:
  3523. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3524. case 504:
  3525. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3526. case 505:
  3527. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3528. case 506:
  3529. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3530. case 507:
  3531. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3532. * Section 11.5 */
  3533. case 508:
  3534. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3535. case 510:
  3536. return "Not Extended"; /* RFC 2774, Section 7 */
  3537. case 511:
  3538. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3539. /* Other status codes, not shown in the IANA HTTP status code
  3540. * assignment.
  3541. * E.g., "de facto" standards due to common use, ... */
  3542. case 418:
  3543. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3544. case 419:
  3545. return "Authentication Timeout"; /* common use */
  3546. case 420:
  3547. return "Enhance Your Calm"; /* common use */
  3548. case 440:
  3549. return "Login Timeout"; /* common use */
  3550. case 509:
  3551. return "Bandwidth Limit Exceeded"; /* common use */
  3552. default:
  3553. /* This error code is unknown. This should not happen. */
  3554. if (conn) {
  3555. mg_cry_internal(conn,
  3556. "Unknown HTTP response code: %u",
  3557. response_code);
  3558. }
  3559. /* Return at least a category according to RFC 2616 Section 10. */
  3560. if (response_code >= 100 && response_code < 200) {
  3561. /* Unknown informational status code */
  3562. return "Information";
  3563. }
  3564. if (response_code >= 200 && response_code < 300) {
  3565. /* Unknown success code */
  3566. return "Success";
  3567. }
  3568. if (response_code >= 300 && response_code < 400) {
  3569. /* Unknown redirection code */
  3570. return "Redirection";
  3571. }
  3572. if (response_code >= 400 && response_code < 500) {
  3573. /* Unknown request error code */
  3574. return "Client Error";
  3575. }
  3576. if (response_code >= 500 && response_code < 600) {
  3577. /* Unknown server error code */
  3578. return "Server Error";
  3579. }
  3580. /* Response code not even within reasonable range */
  3581. return "";
  3582. }
  3583. }
  3584. static void
  3585. mg_send_http_error_impl(struct mg_connection *conn,
  3586. int status,
  3587. const char *fmt,
  3588. va_list args)
  3589. {
  3590. char errmsg_buf[MG_BUF_LEN];
  3591. char path_buf[PATH_MAX];
  3592. va_list ap;
  3593. int len, i, page_handler_found, scope, truncated, has_body;
  3594. char date[64];
  3595. time_t curtime = time(NULL);
  3596. const char *error_handler = NULL;
  3597. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3598. const char *error_page_file_ext, *tstr;
  3599. int handled_by_callback = 0;
  3600. const char *status_text = mg_get_response_code_text(conn, status);
  3601. if ((conn == NULL) || (fmt == NULL)) {
  3602. return;
  3603. }
  3604. /* Set status (for log) */
  3605. conn->status_code = status;
  3606. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3607. has_body = ((status > 199) && (status != 204) && (status != 304));
  3608. /* Prepare message in buf, if required */
  3609. if (has_body || (!conn->in_error_handler
  3610. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3611. /* Store error message in errmsg_buf */
  3612. va_copy(ap, args);
  3613. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3614. va_end(ap);
  3615. /* In a debug build, print all html errors */
  3616. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3617. }
  3618. /* If there is a http_error callback, call it.
  3619. * But don't do it recursively, if callback calls mg_send_http_error again.
  3620. */
  3621. if (!conn->in_error_handler
  3622. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3623. /* Mark in_error_handler to avoid recursion and call user callback. */
  3624. conn->in_error_handler = 1;
  3625. handled_by_callback =
  3626. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3627. == 0);
  3628. conn->in_error_handler = 0;
  3629. }
  3630. if (!handled_by_callback) {
  3631. /* Check for recursion */
  3632. if (conn->in_error_handler) {
  3633. DEBUG_TRACE(
  3634. "Recursion when handling error %u - fall back to default",
  3635. status);
  3636. } else {
  3637. /* Send user defined error pages, if defined */
  3638. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3639. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3640. page_handler_found = 0;
  3641. if (error_handler != NULL) {
  3642. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3643. switch (scope) {
  3644. case 1: /* Handler for specific error, e.g. 404 error */
  3645. mg_snprintf(conn,
  3646. &truncated,
  3647. path_buf,
  3648. sizeof(path_buf) - 32,
  3649. "%serror%03u.",
  3650. error_handler,
  3651. status);
  3652. break;
  3653. case 2: /* Handler for error group, e.g., 5xx error
  3654. * handler
  3655. * for all server errors (500-599) */
  3656. mg_snprintf(conn,
  3657. &truncated,
  3658. path_buf,
  3659. sizeof(path_buf) - 32,
  3660. "%serror%01uxx.",
  3661. error_handler,
  3662. status / 100);
  3663. break;
  3664. default: /* Handler for all errors */
  3665. mg_snprintf(conn,
  3666. &truncated,
  3667. path_buf,
  3668. sizeof(path_buf) - 32,
  3669. "%serror.",
  3670. error_handler);
  3671. break;
  3672. }
  3673. /* String truncation in buf may only occur if
  3674. * error_handler is too long. This string is
  3675. * from the config, not from a client. */
  3676. (void)truncated;
  3677. len = (int)strlen(path_buf);
  3678. tstr = strchr(error_page_file_ext, '.');
  3679. while (tstr) {
  3680. for (i = 1;
  3681. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3682. i++)
  3683. path_buf[len + i - 1] = tstr[i];
  3684. path_buf[len + i - 1] = 0;
  3685. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3686. DEBUG_TRACE("Check error page %s - found",
  3687. path_buf);
  3688. page_handler_found = 1;
  3689. break;
  3690. }
  3691. DEBUG_TRACE("Check error page %s - not found",
  3692. path_buf);
  3693. tstr = strchr(tstr + i, '.');
  3694. }
  3695. }
  3696. }
  3697. if (page_handler_found) {
  3698. conn->in_error_handler = 1;
  3699. handle_file_based_request(conn, path_buf, &error_page_file);
  3700. conn->in_error_handler = 0;
  3701. return;
  3702. }
  3703. }
  3704. /* No custom error page. Send default error page. */
  3705. gmt_time_string(date, sizeof(date), &curtime);
  3706. conn->must_close = 1;
  3707. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3708. send_no_cache_header(conn);
  3709. send_additional_header(conn);
  3710. if (has_body) {
  3711. mg_printf(conn,
  3712. "%s",
  3713. "Content-Type: text/plain; charset=utf-8\r\n");
  3714. }
  3715. mg_printf(conn,
  3716. "Date: %s\r\n"
  3717. "Connection: close\r\n\r\n",
  3718. date);
  3719. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3720. if (has_body) {
  3721. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3722. if (fmt != NULL) {
  3723. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3724. }
  3725. } else {
  3726. /* No body allowed. Close the connection. */
  3727. DEBUG_TRACE("Error %i", status);
  3728. }
  3729. }
  3730. }
  3731. void
  3732. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3733. {
  3734. va_list ap;
  3735. va_start(ap, fmt);
  3736. mg_send_http_error_impl(conn, status, fmt, ap);
  3737. va_end(ap);
  3738. }
  3739. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3740. /* Create substitutes for POSIX functions in Win32. */
  3741. #if defined(__MINGW32__)
  3742. /* Show no warning in case system functions are not used. */
  3743. #pragma GCC diagnostic push
  3744. #pragma GCC diagnostic ignored "-Wunused-function"
  3745. #endif
  3746. FUNCTION_MAY_BE_UNUSED
  3747. static int
  3748. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3749. {
  3750. (void)unused;
  3751. *mutex = CreateMutex(NULL, FALSE, NULL);
  3752. return (*mutex == NULL) ? -1 : 0;
  3753. }
  3754. FUNCTION_MAY_BE_UNUSED
  3755. static int
  3756. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3757. {
  3758. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3759. }
  3760. FUNCTION_MAY_BE_UNUSED
  3761. static int
  3762. pthread_mutex_lock(pthread_mutex_t *mutex)
  3763. {
  3764. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  3765. : -1;
  3766. }
  3767. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3768. FUNCTION_MAY_BE_UNUSED
  3769. static int
  3770. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3771. {
  3772. switch (WaitForSingleObject(*mutex, 0)) {
  3773. case WAIT_OBJECT_0:
  3774. return 0;
  3775. case WAIT_TIMEOUT:
  3776. return -2; /* EBUSY */
  3777. }
  3778. return -1;
  3779. }
  3780. #endif
  3781. FUNCTION_MAY_BE_UNUSED
  3782. static int
  3783. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3784. {
  3785. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3786. }
  3787. FUNCTION_MAY_BE_UNUSED
  3788. static int
  3789. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3790. {
  3791. (void)unused;
  3792. InitializeCriticalSection(&cv->threadIdSec);
  3793. cv->waiting_thread = NULL;
  3794. return 0;
  3795. }
  3796. FUNCTION_MAY_BE_UNUSED
  3797. static int
  3798. pthread_cond_timedwait(pthread_cond_t *cv,
  3799. pthread_mutex_t *mutex,
  3800. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  3801. {
  3802. struct mg_workerTLS **ptls,
  3803. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3804. int ok;
  3805. int64_t nsnow, nswaitabs, nswaitrel;
  3806. DWORD mswaitrel;
  3807. EnterCriticalSection(&cv->threadIdSec);
  3808. /* Add this thread to cv's waiting list */
  3809. ptls = &cv->waiting_thread;
  3810. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3811. ;
  3812. tls->next_waiting_thread = NULL;
  3813. *ptls = tls;
  3814. LeaveCriticalSection(&cv->threadIdSec);
  3815. if (abstime) {
  3816. nsnow = mg_get_current_time_ns();
  3817. nswaitabs =
  3818. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3819. nswaitrel = nswaitabs - nsnow;
  3820. if (nswaitrel < 0) {
  3821. nswaitrel = 0;
  3822. }
  3823. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3824. } else {
  3825. mswaitrel = (DWORD)INFINITE;
  3826. }
  3827. pthread_mutex_unlock(mutex);
  3828. ok = (WAIT_OBJECT_0
  3829. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3830. if (!ok) {
  3831. ok = 1;
  3832. EnterCriticalSection(&cv->threadIdSec);
  3833. ptls = &cv->waiting_thread;
  3834. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3835. if (*ptls == tls) {
  3836. *ptls = tls->next_waiting_thread;
  3837. ok = 0;
  3838. break;
  3839. }
  3840. }
  3841. LeaveCriticalSection(&cv->threadIdSec);
  3842. if (ok) {
  3843. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  3844. (DWORD)INFINITE);
  3845. }
  3846. }
  3847. /* This thread has been removed from cv's waiting list */
  3848. pthread_mutex_lock(mutex);
  3849. return ok ? 0 : -1;
  3850. }
  3851. FUNCTION_MAY_BE_UNUSED
  3852. static int
  3853. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3854. {
  3855. return pthread_cond_timedwait(cv, mutex, NULL);
  3856. }
  3857. FUNCTION_MAY_BE_UNUSED
  3858. static int
  3859. pthread_cond_signal(pthread_cond_t *cv)
  3860. {
  3861. HANDLE wkup = NULL;
  3862. BOOL ok = FALSE;
  3863. EnterCriticalSection(&cv->threadIdSec);
  3864. if (cv->waiting_thread) {
  3865. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3866. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3867. ok = SetEvent(wkup);
  3868. DEBUG_ASSERT(ok);
  3869. }
  3870. LeaveCriticalSection(&cv->threadIdSec);
  3871. return ok ? 0 : 1;
  3872. }
  3873. FUNCTION_MAY_BE_UNUSED
  3874. static int
  3875. pthread_cond_broadcast(pthread_cond_t *cv)
  3876. {
  3877. EnterCriticalSection(&cv->threadIdSec);
  3878. while (cv->waiting_thread) {
  3879. pthread_cond_signal(cv);
  3880. }
  3881. LeaveCriticalSection(&cv->threadIdSec);
  3882. return 0;
  3883. }
  3884. FUNCTION_MAY_BE_UNUSED
  3885. static int
  3886. pthread_cond_destroy(pthread_cond_t *cv)
  3887. {
  3888. EnterCriticalSection(&cv->threadIdSec);
  3889. DEBUG_ASSERT(cv->waiting_thread == NULL);
  3890. LeaveCriticalSection(&cv->threadIdSec);
  3891. DeleteCriticalSection(&cv->threadIdSec);
  3892. return 0;
  3893. }
  3894. #ifdef ALTERNATIVE_QUEUE
  3895. FUNCTION_MAY_BE_UNUSED
  3896. static void *
  3897. event_create(void)
  3898. {
  3899. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3900. }
  3901. FUNCTION_MAY_BE_UNUSED
  3902. static int
  3903. event_wait(void *eventhdl)
  3904. {
  3905. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  3906. return (res == WAIT_OBJECT_0);
  3907. }
  3908. FUNCTION_MAY_BE_UNUSED
  3909. static int
  3910. event_signal(void *eventhdl)
  3911. {
  3912. return (int)SetEvent((HANDLE)eventhdl);
  3913. }
  3914. FUNCTION_MAY_BE_UNUSED
  3915. static void
  3916. event_destroy(void *eventhdl)
  3917. {
  3918. CloseHandle((HANDLE)eventhdl);
  3919. }
  3920. #endif
  3921. #if defined(__MINGW32__)
  3922. /* Enable unused function warning again */
  3923. #pragma GCC diagnostic pop
  3924. #endif
  3925. /* For Windows, change all slashes to backslashes in path names. */
  3926. static void
  3927. change_slashes_to_backslashes(char *path)
  3928. {
  3929. int i;
  3930. for (i = 0; path[i] != '\0'; i++) {
  3931. if (path[i] == '/') {
  3932. path[i] = '\\';
  3933. }
  3934. /* remove double backslash (check i > 0 to preserve UNC paths,
  3935. * like \\server\file.txt) */
  3936. if ((path[i] == '\\') && (i > 0)) {
  3937. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3938. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3939. }
  3940. }
  3941. }
  3942. }
  3943. static int
  3944. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3945. {
  3946. int diff;
  3947. do {
  3948. diff = tolower(*s1) - tolower(*s2);
  3949. s1++;
  3950. s2++;
  3951. } while ((diff == 0) && (s1[-1] != '\0'));
  3952. return diff;
  3953. }
  3954. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3955. * wbuf and wbuf_len is a target buffer and its length. */
  3956. static void
  3957. path_to_unicode(const struct mg_connection *conn,
  3958. const char *path,
  3959. wchar_t *wbuf,
  3960. size_t wbuf_len)
  3961. {
  3962. char buf[PATH_MAX], buf2[PATH_MAX];
  3963. wchar_t wbuf2[W_PATH_MAX + 1];
  3964. DWORD long_len, err;
  3965. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3966. mg_strlcpy(buf, path, sizeof(buf));
  3967. change_slashes_to_backslashes(buf);
  3968. /* Convert to Unicode and back. If doubly-converted string does not
  3969. * match the original, something is fishy, reject. */
  3970. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3971. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3972. WideCharToMultiByte(
  3973. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3974. if (strcmp(buf, buf2) != 0) {
  3975. wbuf[0] = L'\0';
  3976. }
  3977. /* Windows file systems are not case sensitive, but you can still use
  3978. * uppercase and lowercase letters (on all modern file systems).
  3979. * The server can check if the URI uses the same upper/lowercase
  3980. * letters an the file system, effectively making Windows servers
  3981. * case sensitive (like Linux servers are). It is still not possible
  3982. * to use two files with the same name in different cases on Windows
  3983. * (like /a and /A) - this would be possible in Linux.
  3984. * As a default, Windows is not case sensitive, but the case sensitive
  3985. * file name check can be activated by an additional configuration. */
  3986. if (conn) {
  3987. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  3988. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  3989. "yes")) {
  3990. /* Use case sensitive compare function */
  3991. fcompare = wcscmp;
  3992. }
  3993. }
  3994. (void)conn; /* conn is currently unused */
  3995. #if !defined(_WIN32_WCE)
  3996. /* Only accept a full file path, not a Windows short (8.3) path. */
  3997. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3998. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3999. if (long_len == 0) {
  4000. err = GetLastError();
  4001. if (err == ERROR_FILE_NOT_FOUND) {
  4002. /* File does not exist. This is not always a problem here. */
  4003. return;
  4004. }
  4005. }
  4006. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4007. /* Short name is used. */
  4008. wbuf[0] = L'\0';
  4009. }
  4010. #else
  4011. (void)long_len;
  4012. (void)wbuf2;
  4013. (void)err;
  4014. if (strchr(path, '~')) {
  4015. wbuf[0] = L'\0';
  4016. }
  4017. #endif
  4018. }
  4019. /* Windows happily opens files with some garbage at the end of file name.
  4020. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4021. * "a.cgi", despite one would expect an error back.
  4022. * This function returns non-0 if path ends with some garbage. */
  4023. static int
  4024. path_cannot_disclose_cgi(const char *path)
  4025. {
  4026. static const char *allowed_last_characters = "_-";
  4027. int last = path[strlen(path) - 1];
  4028. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  4029. }
  4030. static int
  4031. mg_stat(const struct mg_connection *conn,
  4032. const char *path,
  4033. struct mg_file_stat *filep)
  4034. {
  4035. wchar_t wbuf[W_PATH_MAX];
  4036. WIN32_FILE_ATTRIBUTE_DATA info;
  4037. time_t creation_time;
  4038. if (!filep) {
  4039. return 0;
  4040. }
  4041. memset(filep, 0, sizeof(*filep));
  4042. if (conn && is_file_in_memory(conn, path)) {
  4043. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4044. * memset */
  4045. /* Quick fix (for 1.9.x): */
  4046. /* mg_stat must fill all fields, also for files in memory */
  4047. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4048. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4049. filep->size = tmp_file.stat.size;
  4050. filep->location = 2;
  4051. /* TODO: for 1.10: restructure how files in memory are handled */
  4052. /* The "file in memory" feature is a candidate for deletion.
  4053. * Please join the discussion at
  4054. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4055. */
  4056. filep->last_modified = time(NULL); /* TODO */
  4057. /* last_modified = now ... assumes the file may change during
  4058. * runtime,
  4059. * so every mg_fopen call may return different data */
  4060. /* last_modified = conn->phys_ctx.start_time;
  4061. * May be used it the data does not change during runtime. This
  4062. * allows
  4063. * browser caching. Since we do not know, we have to assume the file
  4064. * in memory may change. */
  4065. return 1;
  4066. }
  4067. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4068. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4069. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4070. filep->last_modified =
  4071. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4072. info.ftLastWriteTime.dwHighDateTime);
  4073. /* On Windows, the file creation time can be higher than the
  4074. * modification time, e.g. when a file is copied.
  4075. * Since the Last-Modified timestamp is used for caching
  4076. * it should be based on the most recent timestamp. */
  4077. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4078. info.ftCreationTime.dwHighDateTime);
  4079. if (creation_time > filep->last_modified) {
  4080. filep->last_modified = creation_time;
  4081. }
  4082. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4083. /* If file name is fishy, reset the file structure and return
  4084. * error.
  4085. * Note it is important to reset, not just return the error, cause
  4086. * functions like is_file_opened() check the struct. */
  4087. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4088. memset(filep, 0, sizeof(*filep));
  4089. return 0;
  4090. }
  4091. return 1;
  4092. }
  4093. return 0;
  4094. }
  4095. static int
  4096. mg_remove(const struct mg_connection *conn, const char *path)
  4097. {
  4098. wchar_t wbuf[W_PATH_MAX];
  4099. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4100. return DeleteFileW(wbuf) ? 0 : -1;
  4101. }
  4102. static int
  4103. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4104. {
  4105. wchar_t wbuf[W_PATH_MAX];
  4106. (void)mode;
  4107. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4108. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4109. }
  4110. /* Create substitutes for POSIX functions in Win32. */
  4111. #if defined(__MINGW32__)
  4112. /* Show no warning in case system functions are not used. */
  4113. #pragma GCC diagnostic push
  4114. #pragma GCC diagnostic ignored "-Wunused-function"
  4115. #endif
  4116. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4117. FUNCTION_MAY_BE_UNUSED
  4118. static DIR *
  4119. mg_opendir(const struct mg_connection *conn, const char *name)
  4120. {
  4121. DIR *dir = NULL;
  4122. wchar_t wpath[W_PATH_MAX];
  4123. DWORD attrs;
  4124. if (name == NULL) {
  4125. SetLastError(ERROR_BAD_ARGUMENTS);
  4126. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4127. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4128. } else {
  4129. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4130. attrs = GetFileAttributesW(wpath);
  4131. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4132. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4133. (void)wcscat(wpath, L"\\*");
  4134. dir->handle = FindFirstFileW(wpath, &dir->info);
  4135. dir->result.d_name[0] = '\0';
  4136. } else {
  4137. mg_free(dir);
  4138. dir = NULL;
  4139. }
  4140. }
  4141. return dir;
  4142. }
  4143. FUNCTION_MAY_BE_UNUSED
  4144. static int
  4145. mg_closedir(DIR *dir)
  4146. {
  4147. int result = 0;
  4148. if (dir != NULL) {
  4149. if (dir->handle != INVALID_HANDLE_VALUE)
  4150. result = FindClose(dir->handle) ? 0 : -1;
  4151. mg_free(dir);
  4152. } else {
  4153. result = -1;
  4154. SetLastError(ERROR_BAD_ARGUMENTS);
  4155. }
  4156. return result;
  4157. }
  4158. FUNCTION_MAY_BE_UNUSED
  4159. static struct dirent *
  4160. mg_readdir(DIR *dir)
  4161. {
  4162. struct dirent *result = 0;
  4163. if (dir) {
  4164. if (dir->handle != INVALID_HANDLE_VALUE) {
  4165. result = &dir->result;
  4166. (void)WideCharToMultiByte(CP_UTF8,
  4167. 0,
  4168. dir->info.cFileName,
  4169. -1,
  4170. result->d_name,
  4171. sizeof(result->d_name),
  4172. NULL,
  4173. NULL);
  4174. if (!FindNextFileW(dir->handle, &dir->info)) {
  4175. (void)FindClose(dir->handle);
  4176. dir->handle = INVALID_HANDLE_VALUE;
  4177. }
  4178. } else {
  4179. SetLastError(ERROR_FILE_NOT_FOUND);
  4180. }
  4181. } else {
  4182. SetLastError(ERROR_BAD_ARGUMENTS);
  4183. }
  4184. return result;
  4185. }
  4186. #ifndef HAVE_POLL
  4187. FUNCTION_MAY_BE_UNUSED
  4188. static int
  4189. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4190. {
  4191. struct timeval tv;
  4192. fd_set set;
  4193. unsigned int i;
  4194. int result;
  4195. SOCKET maxfd = 0;
  4196. memset(&tv, 0, sizeof(tv));
  4197. tv.tv_sec = milliseconds / 1000;
  4198. tv.tv_usec = (milliseconds % 1000) * 1000;
  4199. FD_ZERO(&set);
  4200. for (i = 0; i < n; i++) {
  4201. FD_SET((SOCKET)pfd[i].fd, &set);
  4202. pfd[i].revents = 0;
  4203. if (pfd[i].fd > maxfd) {
  4204. maxfd = pfd[i].fd;
  4205. }
  4206. }
  4207. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4208. for (i = 0; i < n; i++) {
  4209. if (FD_ISSET(pfd[i].fd, &set)) {
  4210. pfd[i].revents = POLLIN;
  4211. }
  4212. }
  4213. }
  4214. /* We should subtract the time used in select from remaining
  4215. * "milliseconds", in particular if called from mg_poll with a
  4216. * timeout quantum.
  4217. * Unfortunately, the remaining time is not stored in "tv" in all
  4218. * implementations, so the result in "tv" must be considered undefined.
  4219. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4220. return result;
  4221. }
  4222. #endif /* HAVE_POLL */
  4223. #if defined(__MINGW32__)
  4224. /* Enable unused function warning again */
  4225. #pragma GCC diagnostic pop
  4226. #endif
  4227. static void
  4228. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4229. {
  4230. (void)conn; /* Unused. */
  4231. #if defined(_WIN32_WCE)
  4232. (void)sock;
  4233. #else
  4234. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4235. #endif
  4236. }
  4237. int
  4238. mg_start_thread(mg_thread_func_t f, void *p)
  4239. {
  4240. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4241. /* Compile-time option to control stack size, e.g.
  4242. * -DUSE_STACK_SIZE=16384
  4243. */
  4244. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4245. == ((uintptr_t)(-1L)))
  4246. ? -1
  4247. : 0);
  4248. #else
  4249. return (
  4250. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4251. ? -1
  4252. : 0);
  4253. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4254. }
  4255. /* Start a thread storing the thread context. */
  4256. static int
  4257. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4258. void *p,
  4259. pthread_t *threadidptr)
  4260. {
  4261. uintptr_t uip;
  4262. HANDLE threadhandle;
  4263. int result = -1;
  4264. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4265. threadhandle = (HANDLE)uip;
  4266. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4267. *threadidptr = threadhandle;
  4268. result = 0;
  4269. }
  4270. return result;
  4271. }
  4272. /* Wait for a thread to finish. */
  4273. static int
  4274. mg_join_thread(pthread_t threadid)
  4275. {
  4276. int result;
  4277. DWORD dwevent;
  4278. result = -1;
  4279. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4280. if (dwevent == WAIT_FAILED) {
  4281. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4282. } else {
  4283. if (dwevent == WAIT_OBJECT_0) {
  4284. CloseHandle(threadid);
  4285. result = 0;
  4286. }
  4287. }
  4288. return result;
  4289. }
  4290. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4291. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4292. /* Create substitutes for POSIX functions in Win32. */
  4293. #if defined(__MINGW32__)
  4294. /* Show no warning in case system functions are not used. */
  4295. #pragma GCC diagnostic push
  4296. #pragma GCC diagnostic ignored "-Wunused-function"
  4297. #endif
  4298. FUNCTION_MAY_BE_UNUSED
  4299. static HANDLE
  4300. dlopen(const char *dll_name, int flags)
  4301. {
  4302. wchar_t wbuf[W_PATH_MAX];
  4303. (void)flags;
  4304. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4305. return LoadLibraryW(wbuf);
  4306. }
  4307. FUNCTION_MAY_BE_UNUSED
  4308. static int
  4309. dlclose(void *handle)
  4310. {
  4311. int result;
  4312. if (FreeLibrary((HMODULE)handle) != 0) {
  4313. result = 0;
  4314. } else {
  4315. result = -1;
  4316. }
  4317. return result;
  4318. }
  4319. #if defined(__MINGW32__)
  4320. /* Enable unused function warning again */
  4321. #pragma GCC diagnostic pop
  4322. #endif
  4323. #endif
  4324. #if !defined(NO_CGI)
  4325. #define SIGKILL (0)
  4326. static int
  4327. kill(pid_t pid, int sig_num)
  4328. {
  4329. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4330. (void)CloseHandle((HANDLE)pid);
  4331. return 0;
  4332. }
  4333. static void
  4334. trim_trailing_whitespaces(char *s)
  4335. {
  4336. char *e = s + strlen(s) - 1;
  4337. while ((e > s) && isspace(*(unsigned char *)e)) {
  4338. *e-- = '\0';
  4339. }
  4340. }
  4341. static pid_t
  4342. spawn_process(struct mg_connection *conn,
  4343. const char *prog,
  4344. char *envblk,
  4345. char *envp[],
  4346. int fdin[2],
  4347. int fdout[2],
  4348. int fderr[2],
  4349. const char *dir)
  4350. {
  4351. HANDLE me;
  4352. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4353. cmdline[PATH_MAX], buf[PATH_MAX];
  4354. int truncated;
  4355. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4356. STARTUPINFOA si;
  4357. PROCESS_INFORMATION pi = {0};
  4358. (void)envp;
  4359. memset(&si, 0, sizeof(si));
  4360. si.cb = sizeof(si);
  4361. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4362. si.wShowWindow = SW_HIDE;
  4363. me = GetCurrentProcess();
  4364. DuplicateHandle(me,
  4365. (HANDLE)_get_osfhandle(fdin[0]),
  4366. me,
  4367. &si.hStdInput,
  4368. 0,
  4369. TRUE,
  4370. DUPLICATE_SAME_ACCESS);
  4371. DuplicateHandle(me,
  4372. (HANDLE)_get_osfhandle(fdout[1]),
  4373. me,
  4374. &si.hStdOutput,
  4375. 0,
  4376. TRUE,
  4377. DUPLICATE_SAME_ACCESS);
  4378. DuplicateHandle(me,
  4379. (HANDLE)_get_osfhandle(fderr[1]),
  4380. me,
  4381. &si.hStdError,
  4382. 0,
  4383. TRUE,
  4384. DUPLICATE_SAME_ACCESS);
  4385. /* Mark handles that should not be inherited. See
  4386. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4387. */
  4388. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4389. HANDLE_FLAG_INHERIT,
  4390. 0);
  4391. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4392. HANDLE_FLAG_INHERIT,
  4393. 0);
  4394. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4395. HANDLE_FLAG_INHERIT,
  4396. 0);
  4397. /* If CGI file is a script, try to read the interpreter line */
  4398. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4399. if (interp == NULL) {
  4400. buf[0] = buf[1] = '\0';
  4401. /* Read the first line of the script into the buffer */
  4402. mg_snprintf(
  4403. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4404. if (truncated) {
  4405. pi.hProcess = (pid_t)-1;
  4406. goto spawn_cleanup;
  4407. }
  4408. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4409. p = (char *)file.access.membuf;
  4410. mg_fgets(buf, sizeof(buf), &file, &p);
  4411. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4412. buf[sizeof(buf) - 1] = '\0';
  4413. }
  4414. if ((buf[0] == '#') && (buf[1] == '!')) {
  4415. trim_trailing_whitespaces(buf + 2);
  4416. } else {
  4417. buf[2] = '\0';
  4418. }
  4419. interp = buf + 2;
  4420. }
  4421. if (interp[0] != '\0') {
  4422. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4423. interp = full_interp;
  4424. }
  4425. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4426. if (interp[0] != '\0') {
  4427. mg_snprintf(conn,
  4428. &truncated,
  4429. cmdline,
  4430. sizeof(cmdline),
  4431. "\"%s\" \"%s\\%s\"",
  4432. interp,
  4433. full_dir,
  4434. prog);
  4435. } else {
  4436. mg_snprintf(conn,
  4437. &truncated,
  4438. cmdline,
  4439. sizeof(cmdline),
  4440. "\"%s\\%s\"",
  4441. full_dir,
  4442. prog);
  4443. }
  4444. if (truncated) {
  4445. pi.hProcess = (pid_t)-1;
  4446. goto spawn_cleanup;
  4447. }
  4448. DEBUG_TRACE("Running [%s]", cmdline);
  4449. if (CreateProcessA(NULL,
  4450. cmdline,
  4451. NULL,
  4452. NULL,
  4453. TRUE,
  4454. CREATE_NEW_PROCESS_GROUP,
  4455. envblk,
  4456. NULL,
  4457. &si,
  4458. &pi) == 0) {
  4459. mg_cry_internal(
  4460. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4461. pi.hProcess = (pid_t)-1;
  4462. /* goto spawn_cleanup; */
  4463. }
  4464. spawn_cleanup:
  4465. (void)CloseHandle(si.hStdOutput);
  4466. (void)CloseHandle(si.hStdError);
  4467. (void)CloseHandle(si.hStdInput);
  4468. if (pi.hThread != NULL) {
  4469. (void)CloseHandle(pi.hThread);
  4470. }
  4471. return (pid_t)pi.hProcess;
  4472. }
  4473. #endif /* !NO_CGI */
  4474. static int
  4475. set_blocking_mode(SOCKET sock)
  4476. {
  4477. unsigned long non_blocking = 0;
  4478. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4479. }
  4480. static int
  4481. set_non_blocking_mode(SOCKET sock)
  4482. {
  4483. unsigned long non_blocking = 1;
  4484. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4485. }
  4486. #else
  4487. static int
  4488. mg_stat(const struct mg_connection *conn,
  4489. const char *path,
  4490. struct mg_file_stat *filep)
  4491. {
  4492. struct stat st;
  4493. if (!filep) {
  4494. return 0;
  4495. }
  4496. memset(filep, 0, sizeof(*filep));
  4497. if (conn && is_file_in_memory(conn, path)) {
  4498. /* Quick fix (for 1.9.x): */
  4499. /* mg_stat must fill all fields, also for files in memory */
  4500. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4501. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4502. filep->size = tmp_file.stat.size;
  4503. filep->last_modified = time(NULL);
  4504. filep->location = 2;
  4505. /* TODO: for 1.10: restructure how files in memory are handled */
  4506. return 1;
  4507. }
  4508. if (0 == stat(path, &st)) {
  4509. filep->size = (uint64_t)(st.st_size);
  4510. filep->last_modified = st.st_mtime;
  4511. filep->is_directory = S_ISDIR(st.st_mode);
  4512. return 1;
  4513. }
  4514. return 0;
  4515. }
  4516. static void
  4517. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4518. {
  4519. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4520. if (conn) {
  4521. mg_cry_internal(conn,
  4522. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4523. __func__,
  4524. strerror(ERRNO));
  4525. }
  4526. }
  4527. }
  4528. int
  4529. mg_start_thread(mg_thread_func_t func, void *param)
  4530. {
  4531. pthread_t thread_id;
  4532. pthread_attr_t attr;
  4533. int result;
  4534. (void)pthread_attr_init(&attr);
  4535. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4536. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4537. /* Compile-time option to control stack size,
  4538. * e.g. -DUSE_STACK_SIZE=16384 */
  4539. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4540. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4541. result = pthread_create(&thread_id, &attr, func, param);
  4542. pthread_attr_destroy(&attr);
  4543. return result;
  4544. }
  4545. /* Start a thread storing the thread context. */
  4546. static int
  4547. mg_start_thread_with_id(mg_thread_func_t func,
  4548. void *param,
  4549. pthread_t *threadidptr)
  4550. {
  4551. pthread_t thread_id;
  4552. pthread_attr_t attr;
  4553. int result;
  4554. (void)pthread_attr_init(&attr);
  4555. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4556. /* Compile-time option to control stack size,
  4557. * e.g. -DUSE_STACK_SIZE=16384 */
  4558. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4559. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4560. result = pthread_create(&thread_id, &attr, func, param);
  4561. pthread_attr_destroy(&attr);
  4562. if ((result == 0) && (threadidptr != NULL)) {
  4563. *threadidptr = thread_id;
  4564. }
  4565. return result;
  4566. }
  4567. /* Wait for a thread to finish. */
  4568. static int
  4569. mg_join_thread(pthread_t threadid)
  4570. {
  4571. int result;
  4572. result = pthread_join(threadid, NULL);
  4573. return result;
  4574. }
  4575. #ifndef NO_CGI
  4576. static pid_t
  4577. spawn_process(struct mg_connection *conn,
  4578. const char *prog,
  4579. char *envblk,
  4580. char *envp[],
  4581. int fdin[2],
  4582. int fdout[2],
  4583. int fderr[2],
  4584. const char *dir)
  4585. {
  4586. pid_t pid;
  4587. const char *interp;
  4588. (void)envblk;
  4589. if (conn == NULL) {
  4590. return 0;
  4591. }
  4592. if ((pid = fork()) == -1) {
  4593. /* Parent */
  4594. mg_send_http_error(conn,
  4595. 500,
  4596. "Error: Creating CGI process\nfork(): %s",
  4597. strerror(ERRNO));
  4598. } else if (pid == 0) {
  4599. /* Child */
  4600. if (chdir(dir) != 0) {
  4601. mg_cry_internal(
  4602. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4603. } else if (dup2(fdin[0], 0) == -1) {
  4604. mg_cry_internal(conn,
  4605. "%s: dup2(%d, 0): %s",
  4606. __func__,
  4607. fdin[0],
  4608. strerror(ERRNO));
  4609. } else if (dup2(fdout[1], 1) == -1) {
  4610. mg_cry_internal(conn,
  4611. "%s: dup2(%d, 1): %s",
  4612. __func__,
  4613. fdout[1],
  4614. strerror(ERRNO));
  4615. } else if (dup2(fderr[1], 2) == -1) {
  4616. mg_cry_internal(conn,
  4617. "%s: dup2(%d, 2): %s",
  4618. __func__,
  4619. fderr[1],
  4620. strerror(ERRNO));
  4621. } else {
  4622. /* Keep stderr and stdout in two different pipes.
  4623. * Stdout will be sent back to the client,
  4624. * stderr should go into a server error log. */
  4625. (void)close(fdin[0]);
  4626. (void)close(fdout[1]);
  4627. (void)close(fderr[1]);
  4628. /* Close write end fdin and read end fdout and fderr */
  4629. (void)close(fdin[1]);
  4630. (void)close(fdout[0]);
  4631. (void)close(fderr[0]);
  4632. /* After exec, all signal handlers are restored to their default
  4633. * values, with one exception of SIGCHLD. According to
  4634. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4635. * will leave unchanged after exec if it was set to be ignored.
  4636. * Restore it to default action. */
  4637. signal(SIGCHLD, SIG_DFL);
  4638. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4639. if (interp == NULL) {
  4640. (void)execle(prog, prog, NULL, envp);
  4641. mg_cry_internal(conn,
  4642. "%s: execle(%s): %s",
  4643. __func__,
  4644. prog,
  4645. strerror(ERRNO));
  4646. } else {
  4647. (void)execle(interp, interp, prog, NULL, envp);
  4648. mg_cry_internal(conn,
  4649. "%s: execle(%s %s): %s",
  4650. __func__,
  4651. interp,
  4652. prog,
  4653. strerror(ERRNO));
  4654. }
  4655. }
  4656. exit(EXIT_FAILURE);
  4657. }
  4658. return pid;
  4659. }
  4660. #endif /* !NO_CGI */
  4661. static int
  4662. set_non_blocking_mode(SOCKET sock)
  4663. {
  4664. int flags = fcntl(sock, F_GETFL, 0);
  4665. if (flags < 0) {
  4666. return -1;
  4667. }
  4668. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4669. return -1;
  4670. }
  4671. return 0;
  4672. }
  4673. static int
  4674. set_blocking_mode(SOCKET sock)
  4675. {
  4676. int flags = fcntl(sock, F_GETFL, 0);
  4677. if (flags < 0) {
  4678. return -1;
  4679. }
  4680. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4681. return -1;
  4682. }
  4683. return 0;
  4684. }
  4685. #endif /* _WIN32 / else */
  4686. /* End of initial operating system specific define block. */
  4687. /* Get a random number (independent of C rand function) */
  4688. static uint64_t
  4689. get_random(void)
  4690. {
  4691. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4692. static uint64_t lcg = 0; /* Linear congruential generator */
  4693. uint64_t now = mg_get_current_time_ns();
  4694. if (lfsr == 0) {
  4695. /* lfsr will be only 0 if has not been initialized,
  4696. * so this code is called only once. */
  4697. lfsr = mg_get_current_time_ns();
  4698. lcg = mg_get_current_time_ns();
  4699. } else {
  4700. /* Get the next step of both random number generators. */
  4701. lfsr = (lfsr >> 1)
  4702. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4703. << 63);
  4704. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4705. }
  4706. /* Combining two pseudo-random number generators and a high resolution
  4707. * part
  4708. * of the current server time will make it hard (impossible?) to guess
  4709. * the
  4710. * next number. */
  4711. return (lfsr ^ lcg ^ now);
  4712. }
  4713. static int
  4714. mg_poll(struct pollfd *pfd,
  4715. unsigned int n,
  4716. int milliseconds,
  4717. volatile int *stop_server)
  4718. {
  4719. /* Call poll, but only for a maximum time of a few seconds.
  4720. * This will allow to stop the server after some seconds, instead
  4721. * of having to wait for a long socket timeout. */
  4722. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4723. do {
  4724. int result;
  4725. if (*stop_server) {
  4726. /* Shut down signal */
  4727. return -2;
  4728. }
  4729. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4730. ms_now = milliseconds;
  4731. }
  4732. result = poll(pfd, n, ms_now);
  4733. if (result != 0) {
  4734. /* Poll returned either success (1) or error (-1).
  4735. * Forward both to the caller. */
  4736. return result;
  4737. }
  4738. /* Poll returned timeout (0). */
  4739. if (milliseconds > 0) {
  4740. milliseconds -= ms_now;
  4741. }
  4742. } while (milliseconds != 0);
  4743. /* timeout: return 0 */
  4744. return 0;
  4745. }
  4746. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4747. * descriptor.
  4748. * Return value:
  4749. * >=0 .. number of bytes successfully written
  4750. * -1 .. timeout
  4751. * -2 .. error
  4752. */
  4753. static int
  4754. push_inner(struct mg_context *ctx,
  4755. FILE *fp,
  4756. SOCKET sock,
  4757. SSL *ssl,
  4758. const char *buf,
  4759. int len,
  4760. double timeout)
  4761. {
  4762. uint64_t start = 0, now = 0, timeout_ns = 0;
  4763. int n, err;
  4764. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4765. #ifdef _WIN32
  4766. typedef int len_t;
  4767. #else
  4768. typedef size_t len_t;
  4769. #endif
  4770. if (timeout > 0) {
  4771. now = mg_get_current_time_ns();
  4772. start = now;
  4773. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4774. }
  4775. if (ctx == NULL) {
  4776. return -2;
  4777. }
  4778. #ifdef NO_SSL
  4779. if (ssl) {
  4780. return -2;
  4781. }
  4782. #endif
  4783. /* Try to read until it succeeds, fails, times out, or the server
  4784. * shuts down. */
  4785. for (;;) {
  4786. #ifndef NO_SSL
  4787. if (ssl != NULL) {
  4788. n = SSL_write(ssl, buf, len);
  4789. if (n <= 0) {
  4790. err = SSL_get_error(ssl, n);
  4791. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4792. err = ERRNO;
  4793. } else if ((err == SSL_ERROR_WANT_READ)
  4794. || (err == SSL_ERROR_WANT_WRITE)) {
  4795. n = 0;
  4796. } else {
  4797. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4798. return -2;
  4799. }
  4800. } else {
  4801. err = 0;
  4802. }
  4803. } else
  4804. #endif
  4805. if (fp != NULL) {
  4806. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4807. if (ferror(fp)) {
  4808. n = -1;
  4809. err = ERRNO;
  4810. } else {
  4811. err = 0;
  4812. }
  4813. } else {
  4814. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4815. err = (n < 0) ? ERRNO : 0;
  4816. #ifdef _WIN32
  4817. if (err == WSAEWOULDBLOCK) {
  4818. err = 0;
  4819. n = 0;
  4820. }
  4821. #else
  4822. if (err == EWOULDBLOCK) {
  4823. err = 0;
  4824. n = 0;
  4825. }
  4826. #endif
  4827. if (n < 0) {
  4828. /* shutdown of the socket at client side */
  4829. return -2;
  4830. }
  4831. }
  4832. if (ctx->stop_flag) {
  4833. return -2;
  4834. }
  4835. if ((n > 0) || ((n == 0) && (len == 0))) {
  4836. /* some data has been read, or no data was requested */
  4837. return n;
  4838. }
  4839. if (n < 0) {
  4840. /* socket error - check errno */
  4841. DEBUG_TRACE("send() failed, error %d", err);
  4842. /* TODO (mid): error handling depending on the error code.
  4843. * These codes are different between Windows and Linux.
  4844. * Currently there is no problem with failing send calls,
  4845. * if there is a reproducible situation, it should be
  4846. * investigated in detail.
  4847. */
  4848. return -2;
  4849. }
  4850. /* Only in case n=0 (timeout), repeat calling the write function */
  4851. /* If send failed, wait before retry */
  4852. if (fp != NULL) {
  4853. /* For files, just wait a fixed time,
  4854. * maybe an average disk seek time. */
  4855. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4856. } else {
  4857. /* For sockets, wait for the socket using select */
  4858. fd_set wfds;
  4859. struct timeval tv;
  4860. int sret;
  4861. #if defined(__GNUC__) || defined(__MINGW32__)
  4862. /* GCC seems to have a flaw with it's own socket macros:
  4863. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4864. */
  4865. #pragma GCC diagnostic push
  4866. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4867. #endif
  4868. FD_ZERO(&wfds);
  4869. FD_SET(sock, &wfds);
  4870. tv.tv_sec = (time_t)(ms_wait / 1000);
  4871. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4872. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4873. #if defined(__GNUC__) || defined(__MINGW32__)
  4874. #pragma GCC diagnostic pop
  4875. #endif
  4876. if (sret > 0) {
  4877. /* We got ready to write. Don't check the timeout
  4878. * but directly go back to write again. */
  4879. continue;
  4880. }
  4881. }
  4882. if (timeout > 0) {
  4883. now = mg_get_current_time_ns();
  4884. if ((now - start) > timeout_ns) {
  4885. /* Timeout */
  4886. break;
  4887. }
  4888. }
  4889. }
  4890. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4891. used */
  4892. return -1;
  4893. }
  4894. static int64_t
  4895. push_all(struct mg_context *ctx,
  4896. FILE *fp,
  4897. SOCKET sock,
  4898. SSL *ssl,
  4899. const char *buf,
  4900. int64_t len)
  4901. {
  4902. double timeout = -1.0;
  4903. int64_t n, nwritten = 0;
  4904. if (ctx == NULL) {
  4905. return -1;
  4906. }
  4907. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  4908. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  4909. }
  4910. while ((len > 0) && (ctx->stop_flag == 0)) {
  4911. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4912. if (n < 0) {
  4913. if (nwritten == 0) {
  4914. nwritten = n; /* Propagate the error */
  4915. }
  4916. break;
  4917. } else if (n == 0) {
  4918. break; /* No more data to write */
  4919. } else {
  4920. nwritten += n;
  4921. len -= n;
  4922. }
  4923. }
  4924. return nwritten;
  4925. }
  4926. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4927. * Return value:
  4928. * >=0 .. number of bytes successfully read
  4929. * -1 .. timeout
  4930. * -2 .. error
  4931. */
  4932. static int
  4933. pull_inner(FILE *fp,
  4934. struct mg_connection *conn,
  4935. char *buf,
  4936. int len,
  4937. double timeout)
  4938. {
  4939. int nread, err = 0;
  4940. #ifdef _WIN32
  4941. typedef int len_t;
  4942. #else
  4943. typedef size_t len_t;
  4944. #endif
  4945. #ifndef NO_SSL
  4946. int ssl_pending;
  4947. #endif
  4948. /* We need an additional wait loop around this, because in some cases
  4949. * with TLSwe may get data from the socket but not from SSL_read.
  4950. * In this case we need to repeat at least once.
  4951. */
  4952. if (fp != NULL) {
  4953. #if !defined(_WIN32_WCE)
  4954. /* Use read() instead of fread(), because if we're reading from the
  4955. * CGI pipe, fread() may block until IO buffer is filled up. We
  4956. * cannot afford to block and must pass all read bytes immediately
  4957. * to the client. */
  4958. nread = (int)read(fileno(fp), buf, (size_t)len);
  4959. #else
  4960. /* WinCE does not support CGI pipes */
  4961. nread = (int)fread(buf, 1, (size_t)len, fp);
  4962. #endif
  4963. err = (nread < 0) ? ERRNO : 0;
  4964. if ((nread == 0) && (len > 0)) {
  4965. /* Should get data, but got EOL */
  4966. return -2;
  4967. }
  4968. #ifndef NO_SSL
  4969. } else if ((conn->ssl != NULL)
  4970. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4971. /* We already know there is no more data buffered in conn->buf
  4972. * but there is more available in the SSL layer. So don't poll
  4973. * conn->client.sock yet. */
  4974. if (ssl_pending > len) {
  4975. ssl_pending = len;
  4976. }
  4977. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4978. if (nread <= 0) {
  4979. err = SSL_get_error(conn->ssl, nread);
  4980. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4981. err = ERRNO;
  4982. } else if ((err == SSL_ERROR_WANT_READ)
  4983. || (err == SSL_ERROR_WANT_WRITE)) {
  4984. nread = 0;
  4985. } else {
  4986. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4987. return -1;
  4988. }
  4989. } else {
  4990. err = 0;
  4991. }
  4992. } else if (conn->ssl != NULL) {
  4993. struct pollfd pfd[1];
  4994. int pollres;
  4995. pfd[0].fd = conn->client.sock;
  4996. pfd[0].events = POLLIN;
  4997. pollres = mg_poll(pfd,
  4998. 1,
  4999. (int)(timeout * 1000.0),
  5000. &(conn->phys_ctx->stop_flag));
  5001. if (conn->phys_ctx->stop_flag) {
  5002. return -2;
  5003. }
  5004. if (pollres > 0) {
  5005. nread = SSL_read(conn->ssl, buf, len);
  5006. if (nread <= 0) {
  5007. err = SSL_get_error(conn->ssl, nread);
  5008. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5009. err = ERRNO;
  5010. } else if ((err == SSL_ERROR_WANT_READ)
  5011. || (err == SSL_ERROR_WANT_WRITE)) {
  5012. nread = 0;
  5013. } else {
  5014. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5015. return -2;
  5016. }
  5017. } else {
  5018. err = 0;
  5019. }
  5020. } else if (pollres < 0) {
  5021. /* Error */
  5022. return -2;
  5023. } else {
  5024. /* pollres = 0 means timeout */
  5025. nread = 0;
  5026. }
  5027. #endif
  5028. } else {
  5029. struct pollfd pfd[1];
  5030. int pollres;
  5031. pfd[0].fd = conn->client.sock;
  5032. pfd[0].events = POLLIN;
  5033. pollres = mg_poll(pfd,
  5034. 1,
  5035. (int)(timeout * 1000.0),
  5036. &(conn->phys_ctx->stop_flag));
  5037. if (conn->phys_ctx->stop_flag) {
  5038. return -2;
  5039. }
  5040. if (pollres > 0) {
  5041. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5042. err = (nread < 0) ? ERRNO : 0;
  5043. if (nread <= 0) {
  5044. /* shutdown of the socket at client side */
  5045. return -2;
  5046. }
  5047. } else if (pollres < 0) {
  5048. /* error callint poll */
  5049. return -2;
  5050. } else {
  5051. /* pollres = 0 means timeout */
  5052. nread = 0;
  5053. }
  5054. }
  5055. if (conn->phys_ctx->stop_flag) {
  5056. return -2;
  5057. }
  5058. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5059. /* some data has been read, or no data was requested */
  5060. return nread;
  5061. }
  5062. if (nread < 0) {
  5063. /* socket error - check errno */
  5064. #ifdef _WIN32
  5065. if (err == WSAEWOULDBLOCK) {
  5066. /* TODO (low): check if this is still required */
  5067. /* standard case if called from close_socket_gracefully */
  5068. return -2;
  5069. } else if (err == WSAETIMEDOUT) {
  5070. /* TODO (low): check if this is still required */
  5071. /* timeout is handled by the while loop */
  5072. return 0;
  5073. } else if (err == WSAECONNABORTED) {
  5074. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5075. return -2;
  5076. } else {
  5077. DEBUG_TRACE("recv() failed, error %d", err);
  5078. return -2;
  5079. }
  5080. #else
  5081. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5082. * if the timeout is reached and if the socket was set to non-
  5083. * blocking in close_socket_gracefully, so we can not distinguish
  5084. * here. We have to wait for the timeout in both cases for now.
  5085. */
  5086. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5087. /* TODO (low): check if this is still required */
  5088. /* EAGAIN/EWOULDBLOCK:
  5089. * standard case if called from close_socket_gracefully
  5090. * => should return -1 */
  5091. /* or timeout occurred
  5092. * => the code must stay in the while loop */
  5093. /* EINTR can be generated on a socket with a timeout set even
  5094. * when SA_RESTART is effective for all relevant signals
  5095. * (see signal(7)).
  5096. * => stay in the while loop */
  5097. } else {
  5098. DEBUG_TRACE("recv() failed, error %d", err);
  5099. return -2;
  5100. }
  5101. #endif
  5102. }
  5103. /* Timeout occurred, but no data available. */
  5104. return -1;
  5105. }
  5106. static int
  5107. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5108. {
  5109. int n, nread = 0;
  5110. double timeout = -1.0;
  5111. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5112. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5113. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5114. }
  5115. if (timeout >= 0.0) {
  5116. start_time = mg_get_current_time_ns();
  5117. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5118. }
  5119. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5120. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5121. if (n == -2) {
  5122. if (nread == 0) {
  5123. nread = -1; /* Propagate the error */
  5124. }
  5125. break;
  5126. } else if (n == -1) {
  5127. /* timeout */
  5128. if (timeout >= 0.0) {
  5129. now = mg_get_current_time_ns();
  5130. if ((now - start_time) <= timeout_ns) {
  5131. continue;
  5132. }
  5133. }
  5134. break;
  5135. } else if (n == 0) {
  5136. break; /* No more data to read */
  5137. } else {
  5138. conn->consumed_content += n;
  5139. nread += n;
  5140. len -= n;
  5141. }
  5142. }
  5143. return nread;
  5144. }
  5145. static void
  5146. discard_unread_request_data(struct mg_connection *conn)
  5147. {
  5148. char buf[MG_BUF_LEN];
  5149. size_t to_read;
  5150. int nread;
  5151. if (conn == NULL) {
  5152. return;
  5153. }
  5154. to_read = sizeof(buf);
  5155. if (conn->is_chunked) {
  5156. /* Chunked encoding: 3=chunk read completely
  5157. * completely */
  5158. while (conn->is_chunked != 3) {
  5159. nread = mg_read(conn, buf, to_read);
  5160. if (nread <= 0) {
  5161. break;
  5162. }
  5163. }
  5164. } else {
  5165. /* Not chunked: content length is known */
  5166. while (conn->consumed_content < conn->content_len) {
  5167. if (to_read
  5168. > (size_t)(conn->content_len - conn->consumed_content)) {
  5169. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5170. }
  5171. nread = mg_read(conn, buf, to_read);
  5172. if (nread <= 0) {
  5173. break;
  5174. }
  5175. }
  5176. }
  5177. }
  5178. static int
  5179. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5180. {
  5181. int64_t n, buffered_len, nread;
  5182. int64_t len64 =
  5183. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5184. * int, we may not read more
  5185. * bytes */
  5186. const char *body;
  5187. if (conn == NULL) {
  5188. return 0;
  5189. }
  5190. /* If Content-Length is not set for a request with body data
  5191. * (e.g., a PUT or POST request), we do not know in advance
  5192. * how much data should be read. */
  5193. if (conn->consumed_content == 0) {
  5194. if (conn->is_chunked == 1) {
  5195. conn->content_len = len64;
  5196. conn->is_chunked = 2;
  5197. } else if (conn->content_len == -1) {
  5198. /* The body data is completed when the connection
  5199. * is closed. */
  5200. conn->content_len = INT64_MAX;
  5201. conn->must_close = 1;
  5202. }
  5203. }
  5204. nread = 0;
  5205. if (conn->consumed_content < conn->content_len) {
  5206. /* Adjust number of bytes to read. */
  5207. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5208. if (left_to_read < len64) {
  5209. /* Do not read more than the total content length of the
  5210. * request.
  5211. */
  5212. len64 = left_to_read;
  5213. }
  5214. /* Return buffered data */
  5215. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5216. - conn->consumed_content;
  5217. if (buffered_len > 0) {
  5218. if (len64 < buffered_len) {
  5219. buffered_len = len64;
  5220. }
  5221. body = conn->buf + conn->request_len + conn->consumed_content;
  5222. memcpy(buf, body, (size_t)buffered_len);
  5223. len64 -= buffered_len;
  5224. conn->consumed_content += buffered_len;
  5225. nread += buffered_len;
  5226. buf = (char *)buf + buffered_len;
  5227. }
  5228. /* We have returned all buffered data. Read new data from the remote
  5229. * socket.
  5230. */
  5231. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5232. nread += n;
  5233. } else {
  5234. nread = ((nread > 0) ? nread : n);
  5235. }
  5236. }
  5237. return (int)nread;
  5238. }
  5239. static char
  5240. mg_getc(struct mg_connection *conn)
  5241. {
  5242. char c;
  5243. if (conn == NULL) {
  5244. return 0;
  5245. }
  5246. if (mg_read_inner(conn, &c, 1) <= 0) {
  5247. return (char)0;
  5248. }
  5249. return c;
  5250. }
  5251. int
  5252. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5253. {
  5254. if (len > INT_MAX) {
  5255. len = INT_MAX;
  5256. }
  5257. if (conn == NULL) {
  5258. return 0;
  5259. }
  5260. if (conn->is_chunked) {
  5261. size_t all_read = 0;
  5262. while (len > 0) {
  5263. if (conn->is_chunked == 3) {
  5264. /* No more data left to read */
  5265. return 0;
  5266. }
  5267. if (conn->chunk_remainder) {
  5268. /* copy from the remainder of the last received chunk */
  5269. long read_ret;
  5270. size_t read_now =
  5271. ((conn->chunk_remainder > len) ? (len)
  5272. : (conn->chunk_remainder));
  5273. conn->content_len += (int)read_now;
  5274. read_ret =
  5275. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5276. if (read_ret < 1) {
  5277. /* read error */
  5278. return -1;
  5279. }
  5280. all_read += (size_t)read_ret;
  5281. conn->chunk_remainder -= (size_t)read_ret;
  5282. len -= (size_t)read_ret;
  5283. if (conn->chunk_remainder == 0) {
  5284. /* Add data bytes in the current chunk have been read,
  5285. * so we are expecting \r\n now. */
  5286. char x1, x2;
  5287. conn->content_len += 2;
  5288. x1 = mg_getc(conn);
  5289. x2 = mg_getc(conn);
  5290. if ((x1 != '\r') || (x2 != '\n')) {
  5291. /* Protocol violation */
  5292. return -1;
  5293. }
  5294. }
  5295. } else {
  5296. /* fetch a new chunk */
  5297. int i = 0;
  5298. char lenbuf[64];
  5299. char *end = 0;
  5300. unsigned long chunkSize = 0;
  5301. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5302. conn->content_len++;
  5303. lenbuf[i] = mg_getc(conn);
  5304. if ((i > 0) && (lenbuf[i] == '\r')
  5305. && (lenbuf[i - 1] != '\r')) {
  5306. continue;
  5307. }
  5308. if ((i > 1) && (lenbuf[i] == '\n')
  5309. && (lenbuf[i - 1] == '\r')) {
  5310. lenbuf[i + 1] = 0;
  5311. chunkSize = strtoul(lenbuf, &end, 16);
  5312. if (chunkSize == 0) {
  5313. /* regular end of content */
  5314. conn->is_chunked = 3;
  5315. }
  5316. break;
  5317. }
  5318. if (!isxdigit(lenbuf[i])) {
  5319. /* illegal character for chunk length */
  5320. return -1;
  5321. }
  5322. }
  5323. if ((end == NULL) || (*end != '\r')) {
  5324. /* chunksize not set correctly */
  5325. return -1;
  5326. }
  5327. if (chunkSize == 0) {
  5328. break;
  5329. }
  5330. conn->chunk_remainder = chunkSize;
  5331. }
  5332. }
  5333. return (int)all_read;
  5334. }
  5335. return mg_read_inner(conn, buf, len);
  5336. }
  5337. int
  5338. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5339. {
  5340. time_t now;
  5341. int64_t n, total, allowed;
  5342. if (conn == NULL) {
  5343. return 0;
  5344. }
  5345. if (conn->throttle > 0) {
  5346. if ((now = time(NULL)) != conn->last_throttle_time) {
  5347. conn->last_throttle_time = now;
  5348. conn->last_throttle_bytes = 0;
  5349. }
  5350. allowed = conn->throttle - conn->last_throttle_bytes;
  5351. if (allowed > (int64_t)len) {
  5352. allowed = (int64_t)len;
  5353. }
  5354. if ((total = push_all(conn->phys_ctx,
  5355. NULL,
  5356. conn->client.sock,
  5357. conn->ssl,
  5358. (const char *)buf,
  5359. (int64_t)allowed)) == allowed) {
  5360. buf = (const char *)buf + total;
  5361. conn->last_throttle_bytes += total;
  5362. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5363. allowed = (conn->throttle > ((int64_t)len - total))
  5364. ? (int64_t)len - total
  5365. : conn->throttle;
  5366. if ((n = push_all(conn->phys_ctx,
  5367. NULL,
  5368. conn->client.sock,
  5369. conn->ssl,
  5370. (const char *)buf,
  5371. (int64_t)allowed)) != allowed) {
  5372. break;
  5373. }
  5374. sleep(1);
  5375. conn->last_throttle_bytes = allowed;
  5376. conn->last_throttle_time = time(NULL);
  5377. buf = (const char *)buf + n;
  5378. total += n;
  5379. }
  5380. }
  5381. } else {
  5382. total = push_all(conn->phys_ctx,
  5383. NULL,
  5384. conn->client.sock,
  5385. conn->ssl,
  5386. (const char *)buf,
  5387. (int64_t)len);
  5388. }
  5389. if (total > 0) {
  5390. conn->num_bytes_sent += total;
  5391. }
  5392. return (int)total;
  5393. }
  5394. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5395. int
  5396. mg_send_chunk(struct mg_connection *conn,
  5397. const char *chunk,
  5398. unsigned int chunk_len)
  5399. {
  5400. char lenbuf[16];
  5401. size_t lenbuf_len;
  5402. int ret;
  5403. int t;
  5404. /* First store the length information in a text buffer. */
  5405. sprintf(lenbuf, "%x\r\n", chunk_len);
  5406. lenbuf_len = strlen(lenbuf);
  5407. /* Then send length information, chunk and terminating \r\n. */
  5408. ret = mg_write(conn, lenbuf, lenbuf_len);
  5409. if (ret != (int)lenbuf_len) {
  5410. return -1;
  5411. }
  5412. t = ret;
  5413. ret = mg_write(conn, chunk, chunk_len);
  5414. if (ret != (int)chunk_len) {
  5415. return -1;
  5416. }
  5417. t += ret;
  5418. ret = mg_write(conn, "\r\n", 2);
  5419. if (ret != 2) {
  5420. return -1;
  5421. }
  5422. t += ret;
  5423. return t;
  5424. }
  5425. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5426. static int
  5427. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5428. {
  5429. va_list ap_copy;
  5430. size_t size = MG_BUF_LEN / 4;
  5431. int len = -1;
  5432. *buf = NULL;
  5433. while (len < 0) {
  5434. if (*buf) {
  5435. mg_free(*buf);
  5436. }
  5437. size *= 4;
  5438. *buf = (char *)mg_malloc(size);
  5439. if (!*buf) {
  5440. break;
  5441. }
  5442. va_copy(ap_copy, ap);
  5443. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5444. va_end(ap_copy);
  5445. (*buf)[size - 1] = 0;
  5446. }
  5447. return len;
  5448. }
  5449. /* Print message to buffer. If buffer is large enough to hold the message,
  5450. * return buffer. If buffer is to small, allocate large enough buffer on
  5451. * heap,
  5452. * and return allocated buffer. */
  5453. static int
  5454. alloc_vprintf(char **out_buf,
  5455. char *prealloc_buf,
  5456. size_t prealloc_size,
  5457. const char *fmt,
  5458. va_list ap)
  5459. {
  5460. va_list ap_copy;
  5461. int len;
  5462. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5463. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5464. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5465. * Therefore, we make two passes: on first pass, get required message
  5466. * length.
  5467. * On second pass, actually print the message. */
  5468. va_copy(ap_copy, ap);
  5469. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5470. va_end(ap_copy);
  5471. if (len < 0) {
  5472. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5473. * Switch to alternative code path that uses incremental
  5474. * allocations.
  5475. */
  5476. va_copy(ap_copy, ap);
  5477. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5478. va_end(ap_copy);
  5479. } else if ((size_t)(len) >= prealloc_size) {
  5480. /* The pre-allocated buffer not large enough. */
  5481. /* Allocate a new buffer. */
  5482. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5483. if (!*out_buf) {
  5484. /* Allocation failed. Return -1 as "out of memory" error. */
  5485. return -1;
  5486. }
  5487. /* Buffer allocation successful. Store the string there. */
  5488. va_copy(ap_copy, ap);
  5489. IGNORE_UNUSED_RESULT(
  5490. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5491. va_end(ap_copy);
  5492. } else {
  5493. /* The pre-allocated buffer is large enough.
  5494. * Use it to store the string and return the address. */
  5495. va_copy(ap_copy, ap);
  5496. IGNORE_UNUSED_RESULT(
  5497. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5498. va_end(ap_copy);
  5499. *out_buf = prealloc_buf;
  5500. }
  5501. return len;
  5502. }
  5503. static int
  5504. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5505. {
  5506. char mem[MG_BUF_LEN];
  5507. char *buf = NULL;
  5508. int len;
  5509. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5510. len = mg_write(conn, buf, (size_t)len);
  5511. }
  5512. if ((buf != mem) && (buf != NULL)) {
  5513. mg_free(buf);
  5514. }
  5515. return len;
  5516. }
  5517. int
  5518. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5519. {
  5520. va_list ap;
  5521. int result;
  5522. va_start(ap, fmt);
  5523. result = mg_vprintf(conn, fmt, ap);
  5524. va_end(ap);
  5525. return result;
  5526. }
  5527. int
  5528. mg_url_decode(const char *src,
  5529. int src_len,
  5530. char *dst,
  5531. int dst_len,
  5532. int is_form_url_encoded)
  5533. {
  5534. int i, j, a, b;
  5535. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5536. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5537. if ((i < src_len - 2) && (src[i] == '%')
  5538. && isxdigit(*(const unsigned char *)(src + i + 1))
  5539. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5540. a = tolower(*(const unsigned char *)(src + i + 1));
  5541. b = tolower(*(const unsigned char *)(src + i + 2));
  5542. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5543. i += 2;
  5544. } else if (is_form_url_encoded && (src[i] == '+')) {
  5545. dst[j] = ' ';
  5546. } else {
  5547. dst[j] = src[i];
  5548. }
  5549. }
  5550. dst[j] = '\0'; /* Null-terminate the destination */
  5551. return (i >= src_len) ? j : -1;
  5552. }
  5553. int
  5554. mg_get_var(const char *data,
  5555. size_t data_len,
  5556. const char *name,
  5557. char *dst,
  5558. size_t dst_len)
  5559. {
  5560. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5561. }
  5562. int
  5563. mg_get_var2(const char *data,
  5564. size_t data_len,
  5565. const char *name,
  5566. char *dst,
  5567. size_t dst_len,
  5568. size_t occurrence)
  5569. {
  5570. const char *p, *e, *s;
  5571. size_t name_len;
  5572. int len;
  5573. if ((dst == NULL) || (dst_len == 0)) {
  5574. len = -2;
  5575. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5576. len = -1;
  5577. dst[0] = '\0';
  5578. } else {
  5579. name_len = strlen(name);
  5580. e = data + data_len;
  5581. len = -1;
  5582. dst[0] = '\0';
  5583. /* data is "var1=val1&var2=val2...". Find variable first */
  5584. for (p = data; p + name_len < e; p++) {
  5585. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5586. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5587. /* Point p to variable value */
  5588. p += name_len + 1;
  5589. /* Point s to the end of the value */
  5590. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5591. if (s == NULL) {
  5592. s = e;
  5593. }
  5594. DEBUG_ASSERT(s >= p);
  5595. if (s < p) {
  5596. return -3;
  5597. }
  5598. /* Decode variable into destination buffer */
  5599. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5600. /* Redirect error code from -1 to -2 (destination buffer too
  5601. * small). */
  5602. if (len == -1) {
  5603. len = -2;
  5604. }
  5605. break;
  5606. }
  5607. }
  5608. }
  5609. return len;
  5610. }
  5611. /* HCP24: some changes to compare hole var_name */
  5612. int
  5613. mg_get_cookie(const char *cookie_header,
  5614. const char *var_name,
  5615. char *dst,
  5616. size_t dst_size)
  5617. {
  5618. const char *s, *p, *end;
  5619. int name_len, len = -1;
  5620. if ((dst == NULL) || (dst_size == 0)) {
  5621. return -2;
  5622. }
  5623. dst[0] = '\0';
  5624. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5625. return -1;
  5626. }
  5627. name_len = (int)strlen(var_name);
  5628. end = s + strlen(s);
  5629. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5630. if (s[name_len] == '=') {
  5631. /* HCP24: now check is it a substring or a full cookie name */
  5632. if ((s == cookie_header) || (s[-1] == ' ')) {
  5633. s += name_len + 1;
  5634. if ((p = strchr(s, ' ')) == NULL) {
  5635. p = end;
  5636. }
  5637. if (p[-1] == ';') {
  5638. p--;
  5639. }
  5640. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5641. s++;
  5642. p--;
  5643. }
  5644. if ((size_t)(p - s) < dst_size) {
  5645. len = (int)(p - s);
  5646. mg_strlcpy(dst, s, (size_t)len + 1);
  5647. } else {
  5648. len = -3;
  5649. }
  5650. break;
  5651. }
  5652. }
  5653. }
  5654. return len;
  5655. }
  5656. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5657. static void
  5658. base64_encode(const unsigned char *src, int src_len, char *dst)
  5659. {
  5660. static const char *b64 =
  5661. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5662. int i, j, a, b, c;
  5663. for (i = j = 0; i < src_len; i += 3) {
  5664. a = src[i];
  5665. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5666. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5667. dst[j++] = b64[a >> 2];
  5668. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5669. if (i + 1 < src_len) {
  5670. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5671. }
  5672. if (i + 2 < src_len) {
  5673. dst[j++] = b64[c & 63];
  5674. }
  5675. }
  5676. while (j % 4 != 0) {
  5677. dst[j++] = '=';
  5678. }
  5679. dst[j++] = '\0';
  5680. }
  5681. #endif
  5682. #if defined(USE_LUA)
  5683. static unsigned char
  5684. b64reverse(char letter)
  5685. {
  5686. if ((letter >= 'A') && (letter <= 'Z')) {
  5687. return letter - 'A';
  5688. }
  5689. if ((letter >= 'a') && (letter <= 'z')) {
  5690. return letter - 'a' + 26;
  5691. }
  5692. if ((letter >= '0') && (letter <= '9')) {
  5693. return letter - '0' + 52;
  5694. }
  5695. if (letter == '+') {
  5696. return 62;
  5697. }
  5698. if (letter == '/') {
  5699. return 63;
  5700. }
  5701. if (letter == '=') {
  5702. return 255; /* normal end */
  5703. }
  5704. return 254; /* error */
  5705. }
  5706. static int
  5707. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5708. {
  5709. int i;
  5710. unsigned char a, b, c, d;
  5711. *dst_len = 0;
  5712. for (i = 0; i < src_len; i += 4) {
  5713. a = b64reverse(src[i]);
  5714. if (a >= 254) {
  5715. return i;
  5716. }
  5717. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5718. if (b >= 254) {
  5719. return i + 1;
  5720. }
  5721. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5722. if (c == 254) {
  5723. return i + 2;
  5724. }
  5725. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5726. if (d == 254) {
  5727. return i + 3;
  5728. }
  5729. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5730. if (c != 255) {
  5731. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5732. if (d != 255) {
  5733. dst[(*dst_len)++] = (c << 6) + d;
  5734. }
  5735. }
  5736. }
  5737. return -1;
  5738. }
  5739. #endif
  5740. static int
  5741. is_put_or_delete_method(const struct mg_connection *conn)
  5742. {
  5743. if (conn) {
  5744. const char *s = conn->request_info.request_method;
  5745. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5746. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5747. }
  5748. return 0;
  5749. }
  5750. #if !defined(NO_FILES)
  5751. static int
  5752. extention_matches_script(
  5753. struct mg_connection *conn, /* in: request (must be valid) */
  5754. const char *filename /* in: filename (must be valid) */
  5755. )
  5756. {
  5757. #if !defined(NO_CGI)
  5758. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  5759. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  5760. filename) > 0) {
  5761. return 1;
  5762. }
  5763. #endif
  5764. #if defined(USE_LUA)
  5765. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  5766. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5767. filename) > 0) {
  5768. return 1;
  5769. }
  5770. #endif
  5771. #if defined(USE_DUKTAPE)
  5772. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5773. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5774. filename) > 0) {
  5775. return 1;
  5776. }
  5777. #endif
  5778. /* filename and conn could be unused, if all preocessor conditions
  5779. * are false (no script language supported). */
  5780. (void)filename;
  5781. (void)conn;
  5782. return 0;
  5783. }
  5784. /* For given directory path, substitute it to valid index file.
  5785. * Return 1 if index file has been found, 0 if not found.
  5786. * If the file is found, it's stats is returned in stp. */
  5787. static int
  5788. substitute_index_file(struct mg_connection *conn,
  5789. char *path,
  5790. size_t path_len,
  5791. struct mg_file_stat *filestat)
  5792. {
  5793. const char *list = conn->dom_ctx->config[INDEX_FILES];
  5794. struct vec filename_vec;
  5795. size_t n = strlen(path);
  5796. int found = 0;
  5797. /* The 'path' given to us points to the directory. Remove all trailing
  5798. * directory separator characters from the end of the path, and
  5799. * then append single directory separator character. */
  5800. while ((n > 0) && (path[n - 1] == '/')) {
  5801. n--;
  5802. }
  5803. path[n] = '/';
  5804. /* Traverse index files list. For each entry, append it to the given
  5805. * path and see if the file exists. If it exists, break the loop */
  5806. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5807. /* Ignore too long entries that may overflow path buffer */
  5808. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  5809. continue;
  5810. }
  5811. /* Prepare full path to the index file */
  5812. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5813. /* Does it exist? */
  5814. if (mg_stat(conn, path, filestat)) {
  5815. /* Yes it does, break the loop */
  5816. found = 1;
  5817. break;
  5818. }
  5819. }
  5820. /* If no index file exists, restore directory path */
  5821. if (!found) {
  5822. path[n] = '\0';
  5823. }
  5824. return found;
  5825. }
  5826. #endif
  5827. static void
  5828. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  5829. char *filename, /* out: filename */
  5830. size_t filename_buf_len, /* in: size of filename buffer */
  5831. struct mg_file_stat *filestat, /* out: file status structure */
  5832. int *is_found, /* out: file found (directly) */
  5833. int *is_script_resource, /* out: handled by a script? */
  5834. int *is_websocket_request, /* out: websocket connetion? */
  5835. int *is_put_or_delete_request /* out: put/delete a file? */
  5836. )
  5837. {
  5838. char const *accept_encoding;
  5839. #if !defined(NO_FILES)
  5840. const char *uri = conn->request_info.local_uri;
  5841. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  5842. const char *rewrite;
  5843. struct vec a, b;
  5844. int match_len;
  5845. char gz_path[PATH_MAX];
  5846. int truncated;
  5847. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5848. char *tmp_str;
  5849. size_t tmp_str_len, sep_pos;
  5850. int allow_substitute_script_subresources;
  5851. #endif
  5852. #else
  5853. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5854. #endif
  5855. /* Step 1: Set all initially unknown outputs to zero */
  5856. memset(filestat, 0, sizeof(*filestat));
  5857. *filename = 0;
  5858. *is_found = 0;
  5859. *is_script_resource = 0;
  5860. /* Step 2: Check if the request attempts to modify the file system */
  5861. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5862. /* Step 3: Check if it is a websocket request, and modify the document
  5863. * root if required */
  5864. #if defined(USE_WEBSOCKET)
  5865. *is_websocket_request = is_websocket_protocol(conn);
  5866. #if !defined(NO_FILES)
  5867. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  5868. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  5869. }
  5870. #endif /* !NO_FILES */
  5871. #else /* USE_WEBSOCKET */
  5872. *is_websocket_request = 0;
  5873. #endif /* USE_WEBSOCKET */
  5874. /* Step 4: Check if gzip encoded response is allowed */
  5875. conn->accept_gzip = 0;
  5876. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5877. if (strstr(accept_encoding, "gzip") != NULL) {
  5878. conn->accept_gzip = 1;
  5879. }
  5880. }
  5881. #if !defined(NO_FILES)
  5882. /* Step 5: If there is no root directory, don't look for files. */
  5883. /* Note that root == NULL is a regular use case here. This occurs,
  5884. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5885. * config is not required. */
  5886. if (root == NULL) {
  5887. /* all file related outputs have already been set to 0, just return
  5888. */
  5889. return;
  5890. }
  5891. /* Step 6: Determine the local file path from the root path and the
  5892. * request uri. */
  5893. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5894. * part of the path one byte on the right. */
  5895. mg_snprintf(
  5896. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5897. if (truncated) {
  5898. goto interpret_cleanup;
  5899. }
  5900. /* Step 7: URI rewriting */
  5901. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  5902. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5903. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5904. mg_snprintf(conn,
  5905. &truncated,
  5906. filename,
  5907. filename_buf_len - 1,
  5908. "%.*s%s",
  5909. (int)b.len,
  5910. b.ptr,
  5911. uri + match_len);
  5912. break;
  5913. }
  5914. }
  5915. if (truncated) {
  5916. goto interpret_cleanup;
  5917. }
  5918. /* Step 8: Check if the file exists at the server */
  5919. /* Local file path and name, corresponding to requested URI
  5920. * is now stored in "filename" variable. */
  5921. if (mg_stat(conn, filename, filestat)) {
  5922. int uri_len = (int)strlen(uri);
  5923. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  5924. /* 8.1: File exists. */
  5925. *is_found = 1;
  5926. /* 8.2: Check if it is a script type. */
  5927. if (extention_matches_script(conn, filename)) {
  5928. /* The request addresses a CGI resource, Lua script or
  5929. * server-side javascript.
  5930. * The URI corresponds to the script itself (like
  5931. * /path/script.cgi), and there is no additional resource
  5932. * path (like /path/script.cgi/something).
  5933. * Requests that modify (replace or delete) a resource, like
  5934. * PUT and DELETE requests, should replace/delete the script
  5935. * file.
  5936. * Requests that read or write from/to a resource, like GET and
  5937. * POST requests, should call the script and return the
  5938. * generated response. */
  5939. *is_script_resource = (!*is_put_or_delete_request);
  5940. }
  5941. /* 8.3: If the request target is a directory, there could be
  5942. * a substitute file (index.html, index.cgi, ...). */
  5943. if (filestat->is_directory && is_uri_end_slash) {
  5944. /* Use a local copy here, since substitute_index_file will
  5945. * change the content of the file status */
  5946. struct mg_file_stat tmp_filestat;
  5947. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5948. if (substitute_index_file(
  5949. conn, filename, filename_buf_len, &tmp_filestat)) {
  5950. /* Substitute file found. Copy stat to the output, then
  5951. * check if the file is a script file */
  5952. *filestat = tmp_filestat;
  5953. if (extention_matches_script(conn, filename)) {
  5954. /* Substitute file is a script file */
  5955. *is_script_resource = 1;
  5956. } else {
  5957. /* Substitute file is a regular file */
  5958. *is_script_resource = 0;
  5959. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5960. }
  5961. }
  5962. /* If there is no substitute file, the server could return
  5963. * a directory listing in a later step */
  5964. }
  5965. return;
  5966. }
  5967. /* Step 9: Check for zipped files: */
  5968. /* If we can't find the actual file, look for the file
  5969. * with the same name but a .gz extension. If we find it,
  5970. * use that and set the gzipped flag in the file struct
  5971. * to indicate that the response need to have the content-
  5972. * encoding: gzip header.
  5973. * We can only do this if the browser declares support. */
  5974. if (conn->accept_gzip) {
  5975. mg_snprintf(
  5976. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5977. if (truncated) {
  5978. goto interpret_cleanup;
  5979. }
  5980. if (mg_stat(conn, gz_path, filestat)) {
  5981. if (filestat) {
  5982. filestat->is_gzipped = 1;
  5983. *is_found = 1;
  5984. }
  5985. /* Currently gz files can not be scripts. */
  5986. return;
  5987. }
  5988. }
  5989. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5990. /* Step 10: Script resources may handle sub-resources */
  5991. /* Support PATH_INFO for CGI scripts. */
  5992. tmp_str_len = strlen(filename);
  5993. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  5994. if (!tmp_str) {
  5995. /* Out of memory */
  5996. goto interpret_cleanup;
  5997. }
  5998. memcpy(tmp_str, filename, tmp_str_len + 1);
  5999. /* Check config, if index scripts may have sub-resources */
  6000. allow_substitute_script_subresources =
  6001. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6002. "yes");
  6003. sep_pos = tmp_str_len;
  6004. while (sep_pos > 0) {
  6005. sep_pos--;
  6006. if (tmp_str[sep_pos] == '/') {
  6007. int is_script = 0, does_exist = 0;
  6008. tmp_str[sep_pos] = 0;
  6009. if (tmp_str[0]) {
  6010. is_script = extention_matches_script(conn, tmp_str);
  6011. does_exist = mg_stat(conn, tmp_str, filestat);
  6012. }
  6013. if (does_exist && is_script) {
  6014. filename[sep_pos] = 0;
  6015. memmove(filename + sep_pos + 2,
  6016. filename + sep_pos + 1,
  6017. strlen(filename + sep_pos + 1) + 1);
  6018. conn->path_info = filename + sep_pos + 1;
  6019. filename[sep_pos + 1] = '/';
  6020. *is_script_resource = 1;
  6021. *is_found = 1;
  6022. break;
  6023. }
  6024. if (allow_substitute_script_subresources) {
  6025. if (substitute_index_file(
  6026. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6027. /* some intermediate directory has an index file */
  6028. if (extention_matches_script(conn, tmp_str)) {
  6029. char *tmp_str2;
  6030. DEBUG_TRACE("Substitute script %s serving path %s",
  6031. tmp_str,
  6032. filename);
  6033. /* this index file is a script */
  6034. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6035. conn->phys_ctx);
  6036. mg_snprintf(conn,
  6037. &truncated,
  6038. filename,
  6039. filename_buf_len,
  6040. "%s//%s",
  6041. tmp_str,
  6042. tmp_str2);
  6043. mg_free(tmp_str2);
  6044. if (truncated) {
  6045. mg_free(tmp_str);
  6046. goto interpret_cleanup;
  6047. }
  6048. sep_pos = strlen(tmp_str);
  6049. filename[sep_pos] = 0;
  6050. conn->path_info = filename + sep_pos + 1;
  6051. *is_script_resource = 1;
  6052. *is_found = 1;
  6053. break;
  6054. } else {
  6055. DEBUG_TRACE("Substitute file %s serving path %s",
  6056. tmp_str,
  6057. filename);
  6058. /* non-script files will not have sub-resources */
  6059. filename[sep_pos] = 0;
  6060. conn->path_info = 0;
  6061. *is_script_resource = 0;
  6062. *is_found = 0;
  6063. break;
  6064. }
  6065. }
  6066. }
  6067. tmp_str[sep_pos] = '/';
  6068. }
  6069. }
  6070. mg_free(tmp_str);
  6071. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6072. #endif /* !defined(NO_FILES) */
  6073. return;
  6074. #if !defined(NO_FILES)
  6075. /* Reset all outputs */
  6076. interpret_cleanup:
  6077. memset(filestat, 0, sizeof(*filestat));
  6078. *filename = 0;
  6079. *is_found = 0;
  6080. *is_script_resource = 0;
  6081. *is_websocket_request = 0;
  6082. *is_put_or_delete_request = 0;
  6083. #endif /* !defined(NO_FILES) */
  6084. }
  6085. /* Check whether full request is buffered. Return:
  6086. * -1 if request or response is malformed
  6087. * 0 if request or response is not yet fully buffered
  6088. * >0 actual request length, including last \r\n\r\n */
  6089. static int
  6090. get_http_header_len(const char *buf, int buflen)
  6091. {
  6092. int i;
  6093. for (i = 0; i < buflen; i++) {
  6094. /* Do an unsigned comparison in some conditions below */
  6095. const unsigned char c = ((const unsigned char *)buf)[i];
  6096. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6097. && !isprint(c)) {
  6098. /* abort scan as soon as one malformed character is found */
  6099. return -1;
  6100. }
  6101. if (i < buflen - 1) {
  6102. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6103. /* Two newline, no carriage return - not standard compliant,
  6104. * but
  6105. * it
  6106. * should be accepted */
  6107. return i + 2;
  6108. }
  6109. }
  6110. if (i < buflen - 3) {
  6111. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6112. && (buf[i + 3] == '\n')) {
  6113. /* Two \r\n - standard compliant */
  6114. return i + 4;
  6115. }
  6116. }
  6117. }
  6118. return 0;
  6119. }
  6120. #if !defined(NO_CACHING)
  6121. /* Convert month to the month number. Return -1 on error, or month number */
  6122. static int
  6123. get_month_index(const char *s)
  6124. {
  6125. size_t i;
  6126. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6127. if (!strcmp(s, month_names[i])) {
  6128. return (int)i;
  6129. }
  6130. }
  6131. return -1;
  6132. }
  6133. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6134. static time_t
  6135. parse_date_string(const char *datetime)
  6136. {
  6137. char month_str[32] = {0};
  6138. int second, minute, hour, day, month, year;
  6139. time_t result = (time_t)0;
  6140. struct tm tm;
  6141. if ((sscanf(datetime,
  6142. "%d/%3s/%d %d:%d:%d",
  6143. &day,
  6144. month_str,
  6145. &year,
  6146. &hour,
  6147. &minute,
  6148. &second) == 6) || (sscanf(datetime,
  6149. "%d %3s %d %d:%d:%d",
  6150. &day,
  6151. month_str,
  6152. &year,
  6153. &hour,
  6154. &minute,
  6155. &second) == 6)
  6156. || (sscanf(datetime,
  6157. "%*3s, %d %3s %d %d:%d:%d",
  6158. &day,
  6159. month_str,
  6160. &year,
  6161. &hour,
  6162. &minute,
  6163. &second) == 6) || (sscanf(datetime,
  6164. "%d-%3s-%d %d:%d:%d",
  6165. &day,
  6166. month_str,
  6167. &year,
  6168. &hour,
  6169. &minute,
  6170. &second) == 6)) {
  6171. month = get_month_index(month_str);
  6172. if ((month >= 0) && (year >= 1970)) {
  6173. memset(&tm, 0, sizeof(tm));
  6174. tm.tm_year = year - 1900;
  6175. tm.tm_mon = month;
  6176. tm.tm_mday = day;
  6177. tm.tm_hour = hour;
  6178. tm.tm_min = minute;
  6179. tm.tm_sec = second;
  6180. result = timegm(&tm);
  6181. }
  6182. }
  6183. return result;
  6184. }
  6185. #endif /* !NO_CACHING */
  6186. /* Protect against directory disclosure attack by removing '..',
  6187. * excessive '/' and '\' characters */
  6188. static void
  6189. remove_double_dots_and_double_slashes(char *s)
  6190. {
  6191. char *p = s;
  6192. while ((s[0] == '.') && (s[1] == '.')) {
  6193. s++;
  6194. }
  6195. while (*s != '\0') {
  6196. *p++ = *s++;
  6197. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6198. /* Skip all following slashes, backslashes and double-dots */
  6199. while (s[0] != '\0') {
  6200. if ((s[0] == '/') || (s[0] == '\\')) {
  6201. s++;
  6202. } else if ((s[0] == '.') && (s[1] == '.')) {
  6203. s += 2;
  6204. } else {
  6205. break;
  6206. }
  6207. }
  6208. }
  6209. }
  6210. *p = '\0';
  6211. }
  6212. static const struct {
  6213. const char *extension;
  6214. size_t ext_len;
  6215. const char *mime_type;
  6216. } builtin_mime_types[] = {
  6217. /* IANA registered MIME types
  6218. * (http://www.iana.org/assignments/media-types)
  6219. * application types */
  6220. {".doc", 4, "application/msword"},
  6221. {".eps", 4, "application/postscript"},
  6222. {".exe", 4, "application/octet-stream"},
  6223. {".js", 3, "application/javascript"},
  6224. {".json", 5, "application/json"},
  6225. {".pdf", 4, "application/pdf"},
  6226. {".ps", 3, "application/postscript"},
  6227. {".rtf", 4, "application/rtf"},
  6228. {".xhtml", 6, "application/xhtml+xml"},
  6229. {".xsl", 4, "application/xml"},
  6230. {".xslt", 5, "application/xml"},
  6231. /* fonts */
  6232. {".ttf", 4, "application/font-sfnt"},
  6233. {".cff", 4, "application/font-sfnt"},
  6234. {".otf", 4, "application/font-sfnt"},
  6235. {".aat", 4, "application/font-sfnt"},
  6236. {".sil", 4, "application/font-sfnt"},
  6237. {".pfr", 4, "application/font-tdpfr"},
  6238. {".woff", 5, "application/font-woff"},
  6239. /* audio */
  6240. {".mp3", 4, "audio/mpeg"},
  6241. {".oga", 4, "audio/ogg"},
  6242. {".ogg", 4, "audio/ogg"},
  6243. /* image */
  6244. {".gif", 4, "image/gif"},
  6245. {".ief", 4, "image/ief"},
  6246. {".jpeg", 5, "image/jpeg"},
  6247. {".jpg", 4, "image/jpeg"},
  6248. {".jpm", 4, "image/jpm"},
  6249. {".jpx", 4, "image/jpx"},
  6250. {".png", 4, "image/png"},
  6251. {".svg", 4, "image/svg+xml"},
  6252. {".tif", 4, "image/tiff"},
  6253. {".tiff", 5, "image/tiff"},
  6254. /* model */
  6255. {".wrl", 4, "model/vrml"},
  6256. /* text */
  6257. {".css", 4, "text/css"},
  6258. {".csv", 4, "text/csv"},
  6259. {".htm", 4, "text/html"},
  6260. {".html", 5, "text/html"},
  6261. {".sgm", 4, "text/sgml"},
  6262. {".shtm", 5, "text/html"},
  6263. {".shtml", 6, "text/html"},
  6264. {".txt", 4, "text/plain"},
  6265. {".xml", 4, "text/xml"},
  6266. /* video */
  6267. {".mov", 4, "video/quicktime"},
  6268. {".mp4", 4, "video/mp4"},
  6269. {".mpeg", 5, "video/mpeg"},
  6270. {".mpg", 4, "video/mpeg"},
  6271. {".ogv", 4, "video/ogg"},
  6272. {".qt", 3, "video/quicktime"},
  6273. /* not registered types
  6274. * (http://reference.sitepoint.com/html/mime-types-full,
  6275. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6276. {".arj", 4, "application/x-arj-compressed"},
  6277. {".gz", 3, "application/x-gunzip"},
  6278. {".rar", 4, "application/x-arj-compressed"},
  6279. {".swf", 4, "application/x-shockwave-flash"},
  6280. {".tar", 4, "application/x-tar"},
  6281. {".tgz", 4, "application/x-tar-gz"},
  6282. {".torrent", 8, "application/x-bittorrent"},
  6283. {".ppt", 4, "application/x-mspowerpoint"},
  6284. {".xls", 4, "application/x-msexcel"},
  6285. {".zip", 4, "application/x-zip-compressed"},
  6286. {".aac",
  6287. 4,
  6288. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6289. {".aif", 4, "audio/x-aif"},
  6290. {".m3u", 4, "audio/x-mpegurl"},
  6291. {".mid", 4, "audio/x-midi"},
  6292. {".ra", 3, "audio/x-pn-realaudio"},
  6293. {".ram", 4, "audio/x-pn-realaudio"},
  6294. {".wav", 4, "audio/x-wav"},
  6295. {".bmp", 4, "image/bmp"},
  6296. {".ico", 4, "image/x-icon"},
  6297. {".pct", 4, "image/x-pct"},
  6298. {".pict", 5, "image/pict"},
  6299. {".rgb", 4, "image/x-rgb"},
  6300. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6301. {".asf", 4, "video/x-ms-asf"},
  6302. {".avi", 4, "video/x-msvideo"},
  6303. {".m4v", 4, "video/x-m4v"},
  6304. {NULL, 0, NULL}};
  6305. const char *
  6306. mg_get_builtin_mime_type(const char *path)
  6307. {
  6308. const char *ext;
  6309. size_t i, path_len;
  6310. path_len = strlen(path);
  6311. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6312. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6313. if ((path_len > builtin_mime_types[i].ext_len)
  6314. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6315. return builtin_mime_types[i].mime_type;
  6316. }
  6317. }
  6318. return "text/plain";
  6319. }
  6320. /* Look at the "path" extension and figure what mime type it has.
  6321. * Store mime type in the vector. */
  6322. static void
  6323. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6324. {
  6325. struct vec ext_vec, mime_vec;
  6326. const char *list, *ext;
  6327. size_t path_len;
  6328. path_len = strlen(path);
  6329. if ((conn == NULL) || (vec == NULL)) {
  6330. if (vec != NULL) {
  6331. memset(vec, '\0', sizeof(struct vec));
  6332. }
  6333. return;
  6334. }
  6335. /* Scan user-defined mime types first, in case user wants to
  6336. * override default mime types. */
  6337. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6338. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6339. /* ext now points to the path suffix */
  6340. ext = path + path_len - ext_vec.len;
  6341. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6342. *vec = mime_vec;
  6343. return;
  6344. }
  6345. }
  6346. vec->ptr = mg_get_builtin_mime_type(path);
  6347. vec->len = strlen(vec->ptr);
  6348. }
  6349. /* Stringify binary data. Output buffer must be twice as big as input,
  6350. * because each byte takes 2 bytes in string representation */
  6351. static void
  6352. bin2str(char *to, const unsigned char *p, size_t len)
  6353. {
  6354. static const char *hex = "0123456789abcdef";
  6355. for (; len--; p++) {
  6356. *to++ = hex[p[0] >> 4];
  6357. *to++ = hex[p[0] & 0x0f];
  6358. }
  6359. *to = '\0';
  6360. }
  6361. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6362. */
  6363. char *
  6364. mg_md5(char buf[33], ...)
  6365. {
  6366. md5_byte_t hash[16];
  6367. const char *p;
  6368. va_list ap;
  6369. md5_state_t ctx;
  6370. md5_init(&ctx);
  6371. va_start(ap, buf);
  6372. while ((p = va_arg(ap, const char *)) != NULL) {
  6373. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6374. }
  6375. va_end(ap);
  6376. md5_finish(&ctx, hash);
  6377. bin2str(buf, hash, sizeof(hash));
  6378. return buf;
  6379. }
  6380. /* Check the user's password, return 1 if OK */
  6381. static int
  6382. check_password(const char *method,
  6383. const char *ha1,
  6384. const char *uri,
  6385. const char *nonce,
  6386. const char *nc,
  6387. const char *cnonce,
  6388. const char *qop,
  6389. const char *response)
  6390. {
  6391. char ha2[32 + 1], expected_response[32 + 1];
  6392. /* Some of the parameters may be NULL */
  6393. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6394. || (qop == NULL) || (response == NULL)) {
  6395. return 0;
  6396. }
  6397. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6398. if (strlen(response) != 32) {
  6399. return 0;
  6400. }
  6401. mg_md5(ha2, method, ":", uri, NULL);
  6402. mg_md5(expected_response,
  6403. ha1,
  6404. ":",
  6405. nonce,
  6406. ":",
  6407. nc,
  6408. ":",
  6409. cnonce,
  6410. ":",
  6411. qop,
  6412. ":",
  6413. ha2,
  6414. NULL);
  6415. return mg_strcasecmp(response, expected_response) == 0;
  6416. }
  6417. /* Use the global passwords file, if specified by auth_gpass option,
  6418. * or search for .htpasswd in the requested directory. */
  6419. static void
  6420. open_auth_file(struct mg_connection *conn,
  6421. const char *path,
  6422. struct mg_file *filep)
  6423. {
  6424. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6425. char name[PATH_MAX];
  6426. const char *p, *e,
  6427. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6428. int truncated;
  6429. if (gpass != NULL) {
  6430. /* Use global passwords file */
  6431. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6432. #ifdef DEBUG
  6433. /* Use mg_cry_internal here, since gpass has been configured. */
  6434. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6435. #endif
  6436. }
  6437. /* Important: using local struct mg_file to test path for
  6438. * is_directory flag. If filep is used, mg_stat() makes it
  6439. * appear as if auth file was opened.
  6440. * TODO(mid): Check if this is still required after rewriting
  6441. * mg_stat */
  6442. } else if (mg_stat(conn, path, &filep->stat)
  6443. && filep->stat.is_directory) {
  6444. mg_snprintf(conn,
  6445. &truncated,
  6446. name,
  6447. sizeof(name),
  6448. "%s/%s",
  6449. path,
  6450. PASSWORDS_FILE_NAME);
  6451. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6452. #ifdef DEBUG
  6453. /* Don't use mg_cry_internal here, but only a trace, since this
  6454. * is
  6455. * a typical case. It will occur for every directory
  6456. * without a password file. */
  6457. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6458. #endif
  6459. }
  6460. } else {
  6461. /* Try to find .htpasswd in requested directory. */
  6462. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6463. if (e[0] == '/') {
  6464. break;
  6465. }
  6466. }
  6467. mg_snprintf(conn,
  6468. &truncated,
  6469. name,
  6470. sizeof(name),
  6471. "%.*s/%s",
  6472. (int)(e - p),
  6473. p,
  6474. PASSWORDS_FILE_NAME);
  6475. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6476. #ifdef DEBUG
  6477. /* Don't use mg_cry_internal here, but only a trace, since this
  6478. * is
  6479. * a typical case. It will occur for every directory
  6480. * without a password file. */
  6481. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6482. #endif
  6483. }
  6484. }
  6485. }
  6486. }
  6487. /* Parsed Authorization header */
  6488. struct ah {
  6489. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6490. };
  6491. /* Return 1 on success. Always initializes the ah structure. */
  6492. static int
  6493. parse_auth_header(struct mg_connection *conn,
  6494. char *buf,
  6495. size_t buf_size,
  6496. struct ah *ah)
  6497. {
  6498. char *name, *value, *s;
  6499. const char *auth_header;
  6500. uint64_t nonce;
  6501. if (!ah || !conn) {
  6502. return 0;
  6503. }
  6504. (void)memset(ah, 0, sizeof(*ah));
  6505. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6506. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6507. return 0;
  6508. }
  6509. /* Make modifiable copy of the auth header */
  6510. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6511. s = buf;
  6512. /* Parse authorization header */
  6513. for (;;) {
  6514. /* Gobble initial spaces */
  6515. while (isspace(*(unsigned char *)s)) {
  6516. s++;
  6517. }
  6518. name = skip_quoted(&s, "=", " ", 0);
  6519. /* Value is either quote-delimited, or ends at first comma or space.
  6520. */
  6521. if (s[0] == '\"') {
  6522. s++;
  6523. value = skip_quoted(&s, "\"", " ", '\\');
  6524. if (s[0] == ',') {
  6525. s++;
  6526. }
  6527. } else {
  6528. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6529. * spaces */
  6530. }
  6531. if (*name == '\0') {
  6532. break;
  6533. }
  6534. if (!strcmp(name, "username")) {
  6535. ah->user = value;
  6536. } else if (!strcmp(name, "cnonce")) {
  6537. ah->cnonce = value;
  6538. } else if (!strcmp(name, "response")) {
  6539. ah->response = value;
  6540. } else if (!strcmp(name, "uri")) {
  6541. ah->uri = value;
  6542. } else if (!strcmp(name, "qop")) {
  6543. ah->qop = value;
  6544. } else if (!strcmp(name, "nc")) {
  6545. ah->nc = value;
  6546. } else if (!strcmp(name, "nonce")) {
  6547. ah->nonce = value;
  6548. }
  6549. }
  6550. #ifndef NO_NONCE_CHECK
  6551. /* Read the nonce from the response. */
  6552. if (ah->nonce == NULL) {
  6553. return 0;
  6554. }
  6555. s = NULL;
  6556. nonce = strtoull(ah->nonce, &s, 10);
  6557. if ((s == NULL) || (*s != 0)) {
  6558. return 0;
  6559. }
  6560. /* Convert the nonce from the client to a number. */
  6561. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6562. /* The converted number corresponds to the time the nounce has been
  6563. * created. This should not be earlier than the server start. */
  6564. /* Server side nonce check is valuable in all situations but one:
  6565. * if the server restarts frequently, but the client should not see
  6566. * that, so the server should accept nonces from previous starts. */
  6567. /* However, the reasonable default is to not accept a nonce from a
  6568. * previous start, so if anyone changed the access rights between
  6569. * two restarts, a new login is required. */
  6570. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6571. /* nonce is from a previous start of the server and no longer valid
  6572. * (replay attack?) */
  6573. return 0;
  6574. }
  6575. /* Check if the nonce is too high, so it has not (yet) been used by the
  6576. * server. */
  6577. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6578. + conn->dom_ctx->nonce_count)) {
  6579. return 0;
  6580. }
  6581. #else
  6582. (void)nonce;
  6583. #endif
  6584. /* CGI needs it as REMOTE_USER */
  6585. if (ah->user != NULL) {
  6586. conn->request_info.remote_user =
  6587. mg_strdup_ctx(ah->user, conn->phys_ctx);
  6588. } else {
  6589. return 0;
  6590. }
  6591. return 1;
  6592. }
  6593. static const char *
  6594. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6595. {
  6596. const char *eof;
  6597. size_t len;
  6598. const char *memend;
  6599. if (!filep) {
  6600. return NULL;
  6601. }
  6602. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6603. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6604. /* Search for \n from p till the end of stream */
  6605. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6606. if (eof != NULL) {
  6607. eof += 1; /* Include \n */
  6608. } else {
  6609. eof = memend; /* Copy remaining data */
  6610. }
  6611. len =
  6612. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6613. memcpy(buf, *p, len);
  6614. buf[len] = '\0';
  6615. *p += len;
  6616. return len ? eof : NULL;
  6617. } else if (filep->access.fp != NULL) {
  6618. return fgets(buf, (int)size, filep->access.fp);
  6619. } else {
  6620. return NULL;
  6621. }
  6622. }
  6623. /* Define the initial recursion depth for procesesing htpasswd files that
  6624. * include other htpasswd
  6625. * (or even the same) files. It is not difficult to provide a file or files
  6626. * s.t. they force civetweb
  6627. * to infinitely recurse and then crash.
  6628. */
  6629. #define INITIAL_DEPTH 9
  6630. #if INITIAL_DEPTH <= 0
  6631. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6632. #endif
  6633. struct read_auth_file_struct {
  6634. struct mg_connection *conn;
  6635. struct ah ah;
  6636. const char *domain;
  6637. char buf[256 + 256 + 40];
  6638. const char *f_user;
  6639. const char *f_domain;
  6640. const char *f_ha1;
  6641. };
  6642. static int
  6643. read_auth_file(struct mg_file *filep,
  6644. struct read_auth_file_struct *workdata,
  6645. int depth)
  6646. {
  6647. char *p;
  6648. int is_authorized = 0;
  6649. struct mg_file fp;
  6650. size_t l;
  6651. if (!filep || !workdata || (0 == depth)) {
  6652. return 0;
  6653. }
  6654. /* Loop over passwords file */
  6655. p = (char *)filep->access.membuf;
  6656. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6657. l = strlen(workdata->buf);
  6658. while (l > 0) {
  6659. if (isspace(workdata->buf[l - 1])
  6660. || iscntrl(workdata->buf[l - 1])) {
  6661. l--;
  6662. workdata->buf[l] = 0;
  6663. } else
  6664. break;
  6665. }
  6666. if (l < 1) {
  6667. continue;
  6668. }
  6669. workdata->f_user = workdata->buf;
  6670. if (workdata->f_user[0] == ':') {
  6671. /* user names may not contain a ':' and may not be empty,
  6672. * so lines starting with ':' may be used for a special purpose
  6673. */
  6674. if (workdata->f_user[1] == '#') {
  6675. /* :# is a comment */
  6676. continue;
  6677. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6678. if (mg_fopen(workdata->conn,
  6679. workdata->f_user + 9,
  6680. MG_FOPEN_MODE_READ,
  6681. &fp)) {
  6682. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6683. (void)mg_fclose(
  6684. &fp.access); /* ignore error on read only file */
  6685. /* No need to continue processing files once we have a
  6686. * match, since nothing will reset it back
  6687. * to 0.
  6688. */
  6689. if (is_authorized) {
  6690. return is_authorized;
  6691. }
  6692. } else {
  6693. mg_cry_internal(workdata->conn,
  6694. "%s: cannot open authorization file: %s",
  6695. __func__,
  6696. workdata->buf);
  6697. }
  6698. continue;
  6699. }
  6700. /* everything is invalid for the moment (might change in the
  6701. * future) */
  6702. mg_cry_internal(workdata->conn,
  6703. "%s: syntax error in authorization file: %s",
  6704. __func__,
  6705. workdata->buf);
  6706. continue;
  6707. }
  6708. workdata->f_domain = strchr(workdata->f_user, ':');
  6709. if (workdata->f_domain == NULL) {
  6710. mg_cry_internal(workdata->conn,
  6711. "%s: syntax error in authorization file: %s",
  6712. __func__,
  6713. workdata->buf);
  6714. continue;
  6715. }
  6716. *(char *)(workdata->f_domain) = 0;
  6717. (workdata->f_domain)++;
  6718. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6719. if (workdata->f_ha1 == NULL) {
  6720. mg_cry_internal(workdata->conn,
  6721. "%s: syntax error in authorization file: %s",
  6722. __func__,
  6723. workdata->buf);
  6724. continue;
  6725. }
  6726. *(char *)(workdata->f_ha1) = 0;
  6727. (workdata->f_ha1)++;
  6728. if (!strcmp(workdata->ah.user, workdata->f_user)
  6729. && !strcmp(workdata->domain, workdata->f_domain)) {
  6730. return check_password(workdata->conn->request_info.request_method,
  6731. workdata->f_ha1,
  6732. workdata->ah.uri,
  6733. workdata->ah.nonce,
  6734. workdata->ah.nc,
  6735. workdata->ah.cnonce,
  6736. workdata->ah.qop,
  6737. workdata->ah.response);
  6738. }
  6739. }
  6740. return is_authorized;
  6741. }
  6742. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6743. static int
  6744. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  6745. {
  6746. struct read_auth_file_struct workdata;
  6747. char buf[MG_BUF_LEN];
  6748. if (!conn || !conn->dom_ctx) {
  6749. return 0;
  6750. }
  6751. memset(&workdata, 0, sizeof(workdata));
  6752. workdata.conn = conn;
  6753. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6754. return 0;
  6755. }
  6756. if (realm) {
  6757. workdata.domain = realm;
  6758. } else {
  6759. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6760. }
  6761. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6762. }
  6763. /* Public function to check http digest authentication header */
  6764. int
  6765. mg_check_digest_access_authentication(struct mg_connection *conn,
  6766. const char *realm,
  6767. const char *filename)
  6768. {
  6769. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6770. int auth;
  6771. if (!conn || !filename) {
  6772. return -1;
  6773. }
  6774. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  6775. return -2;
  6776. }
  6777. auth = authorize(conn, &file, realm);
  6778. mg_fclose(&file.access);
  6779. return auth;
  6780. }
  6781. /* Return 1 if request is authorised, 0 otherwise. */
  6782. static int
  6783. check_authorization(struct mg_connection *conn, const char *path)
  6784. {
  6785. char fname[PATH_MAX];
  6786. struct vec uri_vec, filename_vec;
  6787. const char *list;
  6788. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6789. int authorized = 1, truncated;
  6790. if (!conn || !conn->dom_ctx) {
  6791. return 0;
  6792. }
  6793. list = conn->dom_ctx->config[PROTECT_URI];
  6794. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6795. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6796. mg_snprintf(conn,
  6797. &truncated,
  6798. fname,
  6799. sizeof(fname),
  6800. "%.*s",
  6801. (int)filename_vec.len,
  6802. filename_vec.ptr);
  6803. if (truncated
  6804. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6805. mg_cry_internal(conn,
  6806. "%s: cannot open %s: %s",
  6807. __func__,
  6808. fname,
  6809. strerror(errno));
  6810. }
  6811. break;
  6812. }
  6813. }
  6814. if (!is_file_opened(&file.access)) {
  6815. open_auth_file(conn, path, &file);
  6816. }
  6817. if (is_file_opened(&file.access)) {
  6818. authorized = authorize(conn, &file, NULL);
  6819. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6820. }
  6821. return authorized;
  6822. }
  6823. /* Internal function. Assumes conn is valid */
  6824. static void
  6825. send_authorization_request(struct mg_connection *conn, const char *realm)
  6826. {
  6827. char date[64];
  6828. time_t curtime = time(NULL);
  6829. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  6830. if (!realm) {
  6831. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6832. }
  6833. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  6834. nonce += conn->dom_ctx->nonce_count;
  6835. ++conn->dom_ctx->nonce_count;
  6836. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  6837. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6838. conn->status_code = 401;
  6839. conn->must_close = 1;
  6840. gmt_time_string(date, sizeof(date), &curtime);
  6841. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6842. send_no_cache_header(conn);
  6843. send_additional_header(conn);
  6844. mg_printf(conn,
  6845. "Date: %s\r\n"
  6846. "Connection: %s\r\n"
  6847. "Content-Length: 0\r\n"
  6848. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6849. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6850. date,
  6851. suggest_connection_header(conn),
  6852. realm,
  6853. nonce);
  6854. }
  6855. /* Interface function. Parameters are provided by the user, so do
  6856. * at least some basic checks.
  6857. */
  6858. int
  6859. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  6860. const char *realm)
  6861. {
  6862. if (conn && conn->dom_ctx) {
  6863. send_authorization_request(conn, realm);
  6864. return 0;
  6865. }
  6866. return -1;
  6867. }
  6868. #if !defined(NO_FILES)
  6869. static int
  6870. is_authorized_for_put(struct mg_connection *conn)
  6871. {
  6872. if (conn) {
  6873. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6874. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6875. int ret = 0;
  6876. if (passfile != NULL
  6877. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6878. ret = authorize(conn, &file, NULL);
  6879. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6880. }
  6881. return ret;
  6882. }
  6883. return 0;
  6884. }
  6885. #endif
  6886. int
  6887. mg_modify_passwords_file(const char *fname,
  6888. const char *domain,
  6889. const char *user,
  6890. const char *pass)
  6891. {
  6892. int found, i;
  6893. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6894. FILE *fp, *fp2;
  6895. found = 0;
  6896. fp = fp2 = NULL;
  6897. /* Regard empty password as no password - remove user record. */
  6898. if ((pass != NULL) && (pass[0] == '\0')) {
  6899. pass = NULL;
  6900. }
  6901. /* Other arguments must not be empty */
  6902. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6903. return 0;
  6904. }
  6905. /* Using the given file format, user name and domain must not contain
  6906. * ':'
  6907. */
  6908. if (strchr(user, ':') != NULL) {
  6909. return 0;
  6910. }
  6911. if (strchr(domain, ':') != NULL) {
  6912. return 0;
  6913. }
  6914. /* Do not allow control characters like newline in user name and domain.
  6915. * Do not allow excessively long names either. */
  6916. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6917. if (iscntrl(user[i])) {
  6918. return 0;
  6919. }
  6920. }
  6921. if (user[i]) {
  6922. return 0;
  6923. }
  6924. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6925. if (iscntrl(domain[i])) {
  6926. return 0;
  6927. }
  6928. }
  6929. if (domain[i]) {
  6930. return 0;
  6931. }
  6932. /* The maximum length of the path to the password file is limited */
  6933. if ((strlen(fname) + 4) >= PATH_MAX) {
  6934. return 0;
  6935. }
  6936. /* Create a temporary file name. Length has been checked before. */
  6937. strcpy(tmp, fname);
  6938. strcat(tmp, ".tmp");
  6939. /* Create the file if does not exist */
  6940. /* Use of fopen here is OK, since fname is only ASCII */
  6941. if ((fp = fopen(fname, "a+")) != NULL) {
  6942. (void)fclose(fp);
  6943. }
  6944. /* Open the given file and temporary file */
  6945. if ((fp = fopen(fname, "r")) == NULL) {
  6946. return 0;
  6947. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6948. fclose(fp);
  6949. return 0;
  6950. }
  6951. /* Copy the stuff to temporary file */
  6952. while (fgets(line, sizeof(line), fp) != NULL) {
  6953. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6954. continue;
  6955. }
  6956. u[255] = 0;
  6957. d[255] = 0;
  6958. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6959. found++;
  6960. if (pass != NULL) {
  6961. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6962. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6963. }
  6964. } else {
  6965. fprintf(fp2, "%s", line);
  6966. }
  6967. }
  6968. /* If new user, just add it */
  6969. if (!found && (pass != NULL)) {
  6970. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6971. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6972. }
  6973. /* Close files */
  6974. fclose(fp);
  6975. fclose(fp2);
  6976. /* Put the temp file in place of real file */
  6977. IGNORE_UNUSED_RESULT(remove(fname));
  6978. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6979. return 1;
  6980. }
  6981. static int
  6982. is_valid_port(unsigned long port)
  6983. {
  6984. return (port <= 0xffff);
  6985. }
  6986. static int
  6987. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6988. {
  6989. struct addrinfo hints, *res, *ressave;
  6990. int func_ret = 0;
  6991. int gai_ret;
  6992. memset(&hints, 0, sizeof(struct addrinfo));
  6993. hints.ai_family = af;
  6994. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6995. if (gai_ret != 0) {
  6996. /* gai_strerror could be used to convert gai_ret to a string */
  6997. /* POSIX return values: see
  6998. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6999. */
  7000. /* Windows return values: see
  7001. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7002. */
  7003. return 0;
  7004. }
  7005. ressave = res;
  7006. while (res) {
  7007. if (dstlen >= (size_t)res->ai_addrlen) {
  7008. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7009. func_ret = 1;
  7010. }
  7011. res = res->ai_next;
  7012. }
  7013. freeaddrinfo(ressave);
  7014. return func_ret;
  7015. }
  7016. static int
  7017. connect_socket(struct mg_context *ctx /* may be NULL */,
  7018. const char *host,
  7019. int port,
  7020. int use_ssl,
  7021. char *ebuf,
  7022. size_t ebuf_len,
  7023. SOCKET *sock /* output: socket, must not be NULL */,
  7024. union usa *sa /* output: socket address, must not be NULL */
  7025. )
  7026. {
  7027. int ip_ver = 0;
  7028. int conn_ret = -1;
  7029. *sock = INVALID_SOCKET;
  7030. memset(sa, 0, sizeof(*sa));
  7031. if (ebuf_len > 0) {
  7032. *ebuf = 0;
  7033. }
  7034. if (host == NULL) {
  7035. mg_snprintf(NULL,
  7036. NULL, /* No truncation check for ebuf */
  7037. ebuf,
  7038. ebuf_len,
  7039. "%s",
  7040. "NULL host");
  7041. return 0;
  7042. }
  7043. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7044. mg_snprintf(NULL,
  7045. NULL, /* No truncation check for ebuf */
  7046. ebuf,
  7047. ebuf_len,
  7048. "%s",
  7049. "invalid port");
  7050. return 0;
  7051. }
  7052. #if !defined(NO_SSL)
  7053. #if !defined(NO_SSL_DL)
  7054. #ifdef OPENSSL_API_1_1
  7055. if (use_ssl && (TLS_client_method == NULL)) {
  7056. mg_snprintf(NULL,
  7057. NULL, /* No truncation check for ebuf */
  7058. ebuf,
  7059. ebuf_len,
  7060. "%s",
  7061. "SSL is not initialized");
  7062. return 0;
  7063. }
  7064. #else
  7065. if (use_ssl && (SSLv23_client_method == NULL)) {
  7066. mg_snprintf(NULL,
  7067. NULL, /* No truncation check for ebuf */
  7068. ebuf,
  7069. ebuf_len,
  7070. "%s",
  7071. "SSL is not initialized");
  7072. return 0;
  7073. }
  7074. #endif /* OPENSSL_API_1_1 */
  7075. #else
  7076. (void)use_ssl;
  7077. #endif /* NO_SSL_DL */
  7078. #else
  7079. (void)use_ssl;
  7080. #endif /* !defined(NO_SSL) */
  7081. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7082. sa->sin.sin_family = AF_INET;
  7083. sa->sin.sin_port = htons((uint16_t)port);
  7084. ip_ver = 4;
  7085. #ifdef USE_IPV6
  7086. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7087. sa->sin6.sin6_family = AF_INET6;
  7088. sa->sin6.sin6_port = htons((uint16_t)port);
  7089. ip_ver = 6;
  7090. } else if (host[0] == '[') {
  7091. /* While getaddrinfo on Windows will work with [::1],
  7092. * getaddrinfo on Linux only works with ::1 (without []). */
  7093. size_t l = strlen(host + 1);
  7094. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7095. if (h) {
  7096. h[l - 1] = 0;
  7097. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7098. sa->sin6.sin6_family = AF_INET6;
  7099. sa->sin6.sin6_port = htons((uint16_t)port);
  7100. ip_ver = 6;
  7101. }
  7102. mg_free(h);
  7103. }
  7104. #endif
  7105. }
  7106. if (ip_ver == 0) {
  7107. mg_snprintf(NULL,
  7108. NULL, /* No truncation check for ebuf */
  7109. ebuf,
  7110. ebuf_len,
  7111. "%s",
  7112. "host not found");
  7113. return 0;
  7114. }
  7115. if (ip_ver == 4) {
  7116. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7117. }
  7118. #ifdef USE_IPV6
  7119. else if (ip_ver == 6) {
  7120. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7121. }
  7122. #endif
  7123. if (*sock == INVALID_SOCKET) {
  7124. mg_snprintf(NULL,
  7125. NULL, /* No truncation check for ebuf */
  7126. ebuf,
  7127. ebuf_len,
  7128. "socket(): %s",
  7129. strerror(ERRNO));
  7130. return 0;
  7131. }
  7132. if (0 != set_non_blocking_mode(*sock)) {
  7133. mg_snprintf(NULL,
  7134. NULL, /* No truncation check for ebuf */
  7135. ebuf,
  7136. ebuf_len,
  7137. "Cannot set socket to non-blocking: %s",
  7138. strerror(ERRNO));
  7139. closesocket(*sock);
  7140. *sock = INVALID_SOCKET;
  7141. return 0;
  7142. }
  7143. set_close_on_exec(*sock, fc(ctx));
  7144. if (ip_ver == 4) {
  7145. /* connected with IPv4 */
  7146. conn_ret = connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin));
  7147. }
  7148. #ifdef USE_IPV6
  7149. else if (ip_ver == 6) {
  7150. /* connected with IPv6 */
  7151. conn_ret =
  7152. connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6));
  7153. }
  7154. #endif
  7155. if (conn_ret != 0) {
  7156. fd_set fdset;
  7157. struct timeval timeout;
  7158. int sockerr = -1;
  7159. #if defined(_WIN32)
  7160. int len = (int)sizeof(sockerr);
  7161. #else
  7162. socklen_t len = (socklen_t)sizeof(sockerr);
  7163. #endif
  7164. FD_ZERO(&fdset);
  7165. FD_SET(*sock, &fdset);
  7166. timeout.tv_sec = 10; /* 10 second timeout */
  7167. timeout.tv_usec = 0;
  7168. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7169. /* Not connected */
  7170. mg_snprintf(NULL,
  7171. NULL, /* No truncation check for ebuf */
  7172. ebuf,
  7173. ebuf_len,
  7174. "connect(%s:%d): timeout",
  7175. host,
  7176. port);
  7177. closesocket(*sock);
  7178. *sock = INVALID_SOCKET;
  7179. return 0;
  7180. }
  7181. #if defined(_WIN32)
  7182. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)&sockerr, &len);
  7183. #else
  7184. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &len);
  7185. #endif
  7186. if (sockerr != 0) {
  7187. /* Not connected */
  7188. mg_snprintf(NULL,
  7189. NULL, /* No truncation check for ebuf */
  7190. ebuf,
  7191. ebuf_len,
  7192. "connect(%s:%d): error %s",
  7193. host,
  7194. port,
  7195. strerror(sockerr));
  7196. closesocket(*sock);
  7197. *sock = INVALID_SOCKET;
  7198. return 0;
  7199. }
  7200. }
  7201. return 1;
  7202. }
  7203. int
  7204. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7205. {
  7206. static const char *dont_escape = "._-$,;~()";
  7207. static const char *hex = "0123456789abcdef";
  7208. char *pos = dst;
  7209. const char *end = dst + dst_len - 1;
  7210. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7211. if (isalnum(*(const unsigned char *)src)
  7212. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7213. *pos = *src;
  7214. } else if (pos + 2 < end) {
  7215. pos[0] = '%';
  7216. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7217. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7218. pos += 2;
  7219. } else {
  7220. break;
  7221. }
  7222. }
  7223. *pos = '\0';
  7224. return (*src == '\0') ? (int)(pos - dst) : -1;
  7225. }
  7226. /* Return 0 on success, non-zero if an error occurs. */
  7227. static int
  7228. print_dir_entry(struct de *de)
  7229. {
  7230. size_t hrefsize;
  7231. char *href;
  7232. char size[64], mod[64];
  7233. #ifdef REENTRANT_TIME
  7234. struct tm _tm;
  7235. struct tm *tm = &_tm;
  7236. #else
  7237. struct tm *tm;
  7238. #endif
  7239. hrefsize = PATH_MAX * 3; /* worst case */
  7240. href = (char *)mg_malloc(hrefsize);
  7241. if (href == NULL) {
  7242. return -1;
  7243. }
  7244. if (de->file.is_directory) {
  7245. mg_snprintf(de->conn,
  7246. NULL, /* Buffer is big enough */
  7247. size,
  7248. sizeof(size),
  7249. "%s",
  7250. "[DIRECTORY]");
  7251. } else {
  7252. /* We use (signed) cast below because MSVC 6 compiler cannot
  7253. * convert unsigned __int64 to double. Sigh. */
  7254. if (de->file.size < 1024) {
  7255. mg_snprintf(de->conn,
  7256. NULL, /* Buffer is big enough */
  7257. size,
  7258. sizeof(size),
  7259. "%d",
  7260. (int)de->file.size);
  7261. } else if (de->file.size < 0x100000) {
  7262. mg_snprintf(de->conn,
  7263. NULL, /* Buffer is big enough */
  7264. size,
  7265. sizeof(size),
  7266. "%.1fk",
  7267. (double)de->file.size / 1024.0);
  7268. } else if (de->file.size < 0x40000000) {
  7269. mg_snprintf(de->conn,
  7270. NULL, /* Buffer is big enough */
  7271. size,
  7272. sizeof(size),
  7273. "%.1fM",
  7274. (double)de->file.size / 1048576);
  7275. } else {
  7276. mg_snprintf(de->conn,
  7277. NULL, /* Buffer is big enough */
  7278. size,
  7279. sizeof(size),
  7280. "%.1fG",
  7281. (double)de->file.size / 1073741824);
  7282. }
  7283. }
  7284. /* Note: mg_snprintf will not cause a buffer overflow above.
  7285. * So, string truncation checks are not required here. */
  7286. #ifdef REENTRANT_TIME
  7287. localtime_r(&de->file.last_modified, tm);
  7288. #else
  7289. tm = localtime(&de->file.last_modified);
  7290. #endif
  7291. if (tm != NULL) {
  7292. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7293. } else {
  7294. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7295. mod[sizeof(mod) - 1] = '\0';
  7296. }
  7297. mg_url_encode(de->file_name, href, hrefsize);
  7298. mg_printf(de->conn,
  7299. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7300. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7301. de->conn->request_info.local_uri,
  7302. href,
  7303. de->file.is_directory ? "/" : "",
  7304. de->file_name,
  7305. de->file.is_directory ? "/" : "",
  7306. mod,
  7307. size);
  7308. mg_free(href);
  7309. return 0;
  7310. }
  7311. /* This function is called from send_directory() and used for
  7312. * sorting directory entries by size, or name, or modification time.
  7313. * On windows, __cdecl specification is needed in case if project is built
  7314. * with __stdcall convention. qsort always requires __cdels callback. */
  7315. static int WINCDECL
  7316. compare_dir_entries(const void *p1, const void *p2)
  7317. {
  7318. if (p1 && p2) {
  7319. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7320. const char *query_string = a->conn->request_info.query_string;
  7321. int cmp_result = 0;
  7322. if (query_string == NULL) {
  7323. query_string = "na";
  7324. }
  7325. if (a->file.is_directory && !b->file.is_directory) {
  7326. return -1; /* Always put directories on top */
  7327. } else if (!a->file.is_directory && b->file.is_directory) {
  7328. return 1; /* Always put directories on top */
  7329. } else if (*query_string == 'n') {
  7330. cmp_result = strcmp(a->file_name, b->file_name);
  7331. } else if (*query_string == 's') {
  7332. cmp_result = (a->file.size == b->file.size)
  7333. ? 0
  7334. : ((a->file.size > b->file.size) ? 1 : -1);
  7335. } else if (*query_string == 'd') {
  7336. cmp_result =
  7337. (a->file.last_modified == b->file.last_modified)
  7338. ? 0
  7339. : ((a->file.last_modified > b->file.last_modified) ? 1
  7340. : -1);
  7341. }
  7342. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7343. }
  7344. return 0;
  7345. }
  7346. static int
  7347. must_hide_file(struct mg_connection *conn, const char *path)
  7348. {
  7349. if (conn && conn->dom_ctx) {
  7350. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7351. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7352. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7353. || ((pattern != NULL)
  7354. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7355. }
  7356. return 0;
  7357. }
  7358. static int
  7359. scan_directory(struct mg_connection *conn,
  7360. const char *dir,
  7361. void *data,
  7362. int (*cb)(struct de *, void *))
  7363. {
  7364. char path[PATH_MAX];
  7365. struct dirent *dp;
  7366. DIR *dirp;
  7367. struct de de;
  7368. int truncated;
  7369. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7370. return 0;
  7371. } else {
  7372. de.conn = conn;
  7373. while ((dp = mg_readdir(dirp)) != NULL) {
  7374. /* Do not show current dir and hidden files */
  7375. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7376. || must_hide_file(conn, dp->d_name)) {
  7377. continue;
  7378. }
  7379. mg_snprintf(
  7380. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7381. /* If we don't memset stat structure to zero, mtime will have
  7382. * garbage and strftime() will segfault later on in
  7383. * print_dir_entry(). memset is required only if mg_stat()
  7384. * fails. For more details, see
  7385. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7386. memset(&de.file, 0, sizeof(de.file));
  7387. if (truncated) {
  7388. /* If the path is not complete, skip processing. */
  7389. continue;
  7390. }
  7391. if (!mg_stat(conn, path, &de.file)) {
  7392. mg_cry_internal(conn,
  7393. "%s: mg_stat(%s) failed: %s",
  7394. __func__,
  7395. path,
  7396. strerror(ERRNO));
  7397. }
  7398. de.file_name = dp->d_name;
  7399. cb(&de, data);
  7400. }
  7401. (void)mg_closedir(dirp);
  7402. }
  7403. return 1;
  7404. }
  7405. #if !defined(NO_FILES)
  7406. static int
  7407. remove_directory(struct mg_connection *conn, const char *dir)
  7408. {
  7409. char path[PATH_MAX];
  7410. struct dirent *dp;
  7411. DIR *dirp;
  7412. struct de de;
  7413. int truncated;
  7414. int ok = 1;
  7415. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7416. return 0;
  7417. } else {
  7418. de.conn = conn;
  7419. while ((dp = mg_readdir(dirp)) != NULL) {
  7420. /* Do not show current dir (but show hidden files as they will
  7421. * also be removed) */
  7422. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7423. continue;
  7424. }
  7425. mg_snprintf(
  7426. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7427. /* If we don't memset stat structure to zero, mtime will have
  7428. * garbage and strftime() will segfault later on in
  7429. * print_dir_entry(). memset is required only if mg_stat()
  7430. * fails. For more details, see
  7431. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7432. memset(&de.file, 0, sizeof(de.file));
  7433. if (truncated) {
  7434. /* Do not delete anything shorter */
  7435. ok = 0;
  7436. continue;
  7437. }
  7438. if (!mg_stat(conn, path, &de.file)) {
  7439. mg_cry_internal(conn,
  7440. "%s: mg_stat(%s) failed: %s",
  7441. __func__,
  7442. path,
  7443. strerror(ERRNO));
  7444. ok = 0;
  7445. }
  7446. if (de.file.is_directory) {
  7447. if (remove_directory(conn, path) == 0) {
  7448. ok = 0;
  7449. }
  7450. } else {
  7451. /* This will fail file is the file is in memory */
  7452. if (mg_remove(conn, path) == 0) {
  7453. ok = 0;
  7454. }
  7455. }
  7456. }
  7457. (void)mg_closedir(dirp);
  7458. IGNORE_UNUSED_RESULT(rmdir(dir));
  7459. }
  7460. return ok;
  7461. }
  7462. #endif
  7463. struct dir_scan_data {
  7464. struct de *entries;
  7465. unsigned int num_entries;
  7466. unsigned int arr_size;
  7467. };
  7468. /* Behaves like realloc(), but frees original pointer on failure */
  7469. static void *
  7470. realloc2(void *ptr, size_t size)
  7471. {
  7472. void *new_ptr = mg_realloc(ptr, size);
  7473. if (new_ptr == NULL) {
  7474. mg_free(ptr);
  7475. }
  7476. return new_ptr;
  7477. }
  7478. static int
  7479. dir_scan_callback(struct de *de, void *data)
  7480. {
  7481. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7482. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7483. dsd->arr_size *= 2;
  7484. dsd->entries =
  7485. (struct de *)realloc2(dsd->entries,
  7486. dsd->arr_size * sizeof(dsd->entries[0]));
  7487. }
  7488. if (dsd->entries == NULL) {
  7489. /* TODO(lsm, low): propagate an error to the caller */
  7490. dsd->num_entries = 0;
  7491. } else {
  7492. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7493. dsd->entries[dsd->num_entries].file = de->file;
  7494. dsd->entries[dsd->num_entries].conn = de->conn;
  7495. dsd->num_entries++;
  7496. }
  7497. return 0;
  7498. }
  7499. static void
  7500. handle_directory_request(struct mg_connection *conn, const char *dir)
  7501. {
  7502. unsigned int i;
  7503. int sort_direction;
  7504. struct dir_scan_data data = {NULL, 0, 128};
  7505. char date[64];
  7506. time_t curtime = time(NULL);
  7507. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7508. mg_send_http_error(conn,
  7509. 500,
  7510. "Error: Cannot open directory\nopendir(%s): %s",
  7511. dir,
  7512. strerror(ERRNO));
  7513. return;
  7514. }
  7515. gmt_time_string(date, sizeof(date), &curtime);
  7516. if (!conn) {
  7517. return;
  7518. }
  7519. sort_direction = ((conn->request_info.query_string != NULL)
  7520. && (conn->request_info.query_string[1] == 'd'))
  7521. ? 'a'
  7522. : 'd';
  7523. conn->must_close = 1;
  7524. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7525. send_static_cache_header(conn);
  7526. send_additional_header(conn);
  7527. mg_printf(conn,
  7528. "Date: %s\r\n"
  7529. "Connection: close\r\n"
  7530. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7531. date);
  7532. mg_printf(conn,
  7533. "<html><head><title>Index of %s</title>"
  7534. "<style>th {text-align: left;}</style></head>"
  7535. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7536. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7537. "<th><a href=\"?d%c\">Modified</a></th>"
  7538. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7539. "<tr><td colspan=\"3\"><hr></td></tr>",
  7540. conn->request_info.local_uri,
  7541. conn->request_info.local_uri,
  7542. sort_direction,
  7543. sort_direction,
  7544. sort_direction);
  7545. /* Print first entry - link to a parent directory */
  7546. mg_printf(conn,
  7547. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7548. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7549. conn->request_info.local_uri,
  7550. "..",
  7551. "Parent directory",
  7552. "-",
  7553. "-");
  7554. /* Sort and print directory entries */
  7555. if (data.entries != NULL) {
  7556. qsort(data.entries,
  7557. (size_t)data.num_entries,
  7558. sizeof(data.entries[0]),
  7559. compare_dir_entries);
  7560. for (i = 0; i < data.num_entries; i++) {
  7561. print_dir_entry(&data.entries[i]);
  7562. mg_free(data.entries[i].file_name);
  7563. }
  7564. mg_free(data.entries);
  7565. }
  7566. mg_printf(conn, "%s", "</table></body></html>");
  7567. conn->status_code = 200;
  7568. }
  7569. /* Send len bytes from the opened file to the client. */
  7570. static void
  7571. send_file_data(struct mg_connection *conn,
  7572. struct mg_file *filep,
  7573. int64_t offset,
  7574. int64_t len)
  7575. {
  7576. char buf[MG_BUF_LEN];
  7577. int to_read, num_read, num_written;
  7578. int64_t size;
  7579. if (!filep || !conn) {
  7580. return;
  7581. }
  7582. /* Sanity check the offset */
  7583. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7584. : (int64_t)(filep->stat.size);
  7585. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7586. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7587. /* file stored in memory */
  7588. if (len > size - offset) {
  7589. len = size - offset;
  7590. }
  7591. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7592. } else if (len > 0 && filep->access.fp != NULL) {
  7593. /* file stored on disk */
  7594. #if defined(__linux__)
  7595. /* sendfile is only available for Linux */
  7596. if ((conn->ssl == 0) && (conn->throttle == 0)
  7597. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  7598. "yes"))) {
  7599. off_t sf_offs = (off_t)offset;
  7600. ssize_t sf_sent;
  7601. int sf_file = fileno(filep->access.fp);
  7602. int loop_cnt = 0;
  7603. do {
  7604. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7605. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7606. size_t sf_tosend =
  7607. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7608. sf_sent =
  7609. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7610. if (sf_sent > 0) {
  7611. len -= sf_sent;
  7612. offset += sf_sent;
  7613. } else if (loop_cnt == 0) {
  7614. /* This file can not be sent using sendfile.
  7615. * This might be the case for pseudo-files in the
  7616. * /sys/ and /proc/ file system.
  7617. * Use the regular user mode copy code instead. */
  7618. break;
  7619. } else if (sf_sent == 0) {
  7620. /* No error, but 0 bytes sent. May be EOF? */
  7621. return;
  7622. }
  7623. loop_cnt++;
  7624. } while ((len > 0) && (sf_sent >= 0));
  7625. if (sf_sent > 0) {
  7626. return; /* OK */
  7627. }
  7628. /* sf_sent<0 means error, thus fall back to the classic way */
  7629. /* This is always the case, if sf_file is not a "normal" file,
  7630. * e.g., for sending data from the output of a CGI process. */
  7631. offset = (int64_t)sf_offs;
  7632. }
  7633. #endif
  7634. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7635. mg_cry_internal(conn,
  7636. "%s: fseeko() failed: %s",
  7637. __func__,
  7638. strerror(ERRNO));
  7639. mg_send_http_error(
  7640. conn,
  7641. 500,
  7642. "%s",
  7643. "Error: Unable to access file at requested position.");
  7644. } else {
  7645. while (len > 0) {
  7646. /* Calculate how much to read from the file in the buffer */
  7647. to_read = sizeof(buf);
  7648. if ((int64_t)to_read > len) {
  7649. to_read = (int)len;
  7650. }
  7651. /* Read from file, exit the loop on error */
  7652. if ((num_read =
  7653. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7654. <= 0) {
  7655. break;
  7656. }
  7657. /* Send read bytes to the client, exit the loop on error */
  7658. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7659. != num_read) {
  7660. break;
  7661. }
  7662. /* Both read and were successful, adjust counters */
  7663. len -= num_written;
  7664. }
  7665. }
  7666. }
  7667. }
  7668. static int
  7669. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7670. {
  7671. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7672. }
  7673. static void
  7674. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7675. {
  7676. if ((filestat != NULL) && (buf != NULL)) {
  7677. mg_snprintf(NULL,
  7678. NULL, /* All calls to construct_etag use 64 byte buffer */
  7679. buf,
  7680. buf_len,
  7681. "\"%lx.%" INT64_FMT "\"",
  7682. (unsigned long)filestat->last_modified,
  7683. filestat->size);
  7684. }
  7685. }
  7686. static void
  7687. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7688. {
  7689. if (filep != NULL && filep->fp != NULL) {
  7690. #ifdef _WIN32
  7691. (void)conn; /* Unused. */
  7692. #else
  7693. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7694. mg_cry_internal(conn,
  7695. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7696. __func__,
  7697. strerror(ERRNO));
  7698. }
  7699. #endif
  7700. }
  7701. }
  7702. static void
  7703. handle_static_file_request(struct mg_connection *conn,
  7704. const char *path,
  7705. struct mg_file *filep,
  7706. const char *mime_type,
  7707. const char *additional_headers)
  7708. {
  7709. char date[64], lm[64], etag[64];
  7710. char range[128]; /* large enough, so there will be no overflow */
  7711. const char *msg = "OK", *hdr;
  7712. time_t curtime = time(NULL);
  7713. int64_t cl, r1, r2;
  7714. struct vec mime_vec;
  7715. int n, truncated;
  7716. char gz_path[PATH_MAX];
  7717. const char *encoding = "";
  7718. const char *cors1, *cors2, *cors3;
  7719. int allow_on_the_fly_compression;
  7720. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  7721. return;
  7722. }
  7723. if (mime_type == NULL) {
  7724. get_mime_type(conn, path, &mime_vec);
  7725. } else {
  7726. mime_vec.ptr = mime_type;
  7727. mime_vec.len = strlen(mime_type);
  7728. }
  7729. if (filep->stat.size > INT64_MAX) {
  7730. mg_send_http_error(conn,
  7731. 500,
  7732. "Error: File size is too large to send\n%" INT64_FMT,
  7733. filep->stat.size);
  7734. return;
  7735. }
  7736. cl = (int64_t)filep->stat.size;
  7737. conn->status_code = 200;
  7738. range[0] = '\0';
  7739. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7740. * it's important to rewrite the filename after resolving
  7741. * the mime type from it, to preserve the actual file's type */
  7742. allow_on_the_fly_compression = conn->accept_gzip;
  7743. if (filep->stat.is_gzipped) {
  7744. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7745. if (truncated) {
  7746. mg_send_http_error(conn,
  7747. 500,
  7748. "Error: Path of zipped file too long (%s)",
  7749. path);
  7750. return;
  7751. }
  7752. path = gz_path;
  7753. encoding = "Content-Encoding: gzip\r\n";
  7754. /* File is already compressed. No "on the fly" compression. */
  7755. allow_on_the_fly_compression = 0;
  7756. }
  7757. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7758. mg_send_http_error(conn,
  7759. 500,
  7760. "Error: Cannot open file\nfopen(%s): %s",
  7761. path,
  7762. strerror(ERRNO));
  7763. return;
  7764. }
  7765. fclose_on_exec(&filep->access, conn);
  7766. /* If Range: header specified, act accordingly */
  7767. r1 = r2 = 0;
  7768. hdr = mg_get_header(conn, "Range");
  7769. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7770. && (r1 >= 0) && (r2 >= 0)) {
  7771. /* actually, range requests don't play well with a pre-gzipped
  7772. * file (since the range is specified in the uncompressed space) */
  7773. if (filep->stat.is_gzipped) {
  7774. mg_send_http_error(
  7775. conn,
  7776. 416, /* 416 = Range Not Satisfiable */
  7777. "%s",
  7778. "Error: Range requests in gzipped files are not supported");
  7779. (void)mg_fclose(
  7780. &filep->access); /* ignore error on read only file */
  7781. return;
  7782. }
  7783. conn->status_code = 206;
  7784. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7785. mg_snprintf(conn,
  7786. NULL, /* range buffer is big enough */
  7787. range,
  7788. sizeof(range),
  7789. "Content-Range: bytes "
  7790. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7791. r1,
  7792. r1 + cl - 1,
  7793. filep->stat.size);
  7794. msg = "Partial Content";
  7795. /* Do not compress ranges. */
  7796. allow_on_the_fly_compression = 0;
  7797. }
  7798. hdr = mg_get_header(conn, "Origin");
  7799. if (hdr) {
  7800. /* Cross-origin resource sharing (CORS), see
  7801. * http://www.html5rocks.com/en/tutorials/cors/,
  7802. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7803. * -
  7804. * preflight is not supported for files. */
  7805. cors1 = "Access-Control-Allow-Origin: ";
  7806. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7807. cors3 = "\r\n";
  7808. } else {
  7809. cors1 = cors2 = cors3 = "";
  7810. }
  7811. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  7812. * according to
  7813. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7814. gmt_time_string(date, sizeof(date), &curtime);
  7815. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7816. construct_etag(etag, sizeof(etag), &filep->stat);
  7817. /* On the fly compression allowed */
  7818. if (allow_on_the_fly_compression) {
  7819. ;
  7820. /* TODO: add interface to compression module */
  7821. /* e.g., def from https://zlib.net/zlib_how.html */
  7822. /* Check license (zlib has a permissive license, but */
  7823. /* is still not MIT) and use dynamic binding like */
  7824. /* done with OpenSSL */
  7825. /* See #199 (https://github.com/civetweb/civetweb/issues/199) */
  7826. }
  7827. /* Send header */
  7828. (void)mg_printf(conn,
  7829. "HTTP/1.1 %d %s\r\n"
  7830. "%s%s%s"
  7831. "Date: %s\r\n",
  7832. conn->status_code,
  7833. msg,
  7834. cors1,
  7835. cors2,
  7836. cors3,
  7837. date);
  7838. send_static_cache_header(conn);
  7839. send_additional_header(conn);
  7840. (void)mg_printf(conn,
  7841. "Last-Modified: %s\r\n"
  7842. "Etag: %s\r\n"
  7843. "Content-Type: %.*s\r\n"
  7844. "Content-Length: %" INT64_FMT "\r\n"
  7845. "Connection: %s\r\n"
  7846. "Accept-Ranges: bytes\r\n"
  7847. "%s%s",
  7848. lm,
  7849. etag,
  7850. (int)mime_vec.len,
  7851. mime_vec.ptr,
  7852. cl,
  7853. suggest_connection_header(conn),
  7854. range,
  7855. encoding);
  7856. /* The previous code must not add any header starting with X- to make
  7857. * sure no one of the additional_headers is included twice */
  7858. if (additional_headers != NULL) {
  7859. (void)mg_printf(conn,
  7860. "%.*s\r\n\r\n",
  7861. (int)strlen(additional_headers),
  7862. additional_headers);
  7863. } else {
  7864. (void)mg_printf(conn, "\r\n");
  7865. }
  7866. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7867. send_file_data(conn, filep, r1, cl);
  7868. }
  7869. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7870. }
  7871. #if !defined(NO_CACHING)
  7872. /* Return True if we should reply 304 Not Modified. */
  7873. static int
  7874. is_not_modified(const struct mg_connection *conn,
  7875. const struct mg_file_stat *filestat)
  7876. {
  7877. char etag[64];
  7878. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7879. const char *inm = mg_get_header(conn, "If-None-Match");
  7880. construct_etag(etag, sizeof(etag), filestat);
  7881. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  7882. || ((ims != NULL)
  7883. && (filestat->last_modified <= parse_date_string(ims)));
  7884. }
  7885. static void
  7886. handle_not_modified_static_file_request(struct mg_connection *conn,
  7887. struct mg_file *filep)
  7888. {
  7889. char date[64], lm[64], etag[64];
  7890. time_t curtime = time(NULL);
  7891. if ((conn == NULL) || (filep == NULL)) {
  7892. return;
  7893. }
  7894. conn->status_code = 304;
  7895. gmt_time_string(date, sizeof(date), &curtime);
  7896. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7897. construct_etag(etag, sizeof(etag), &filep->stat);
  7898. (void)mg_printf(conn,
  7899. "HTTP/1.1 %d %s\r\n"
  7900. "Date: %s\r\n",
  7901. conn->status_code,
  7902. mg_get_response_code_text(conn, conn->status_code),
  7903. date);
  7904. send_static_cache_header(conn);
  7905. send_additional_header(conn);
  7906. (void)mg_printf(conn,
  7907. "Last-Modified: %s\r\n"
  7908. "Etag: %s\r\n"
  7909. "Connection: %s\r\n"
  7910. "\r\n",
  7911. lm,
  7912. etag,
  7913. suggest_connection_header(conn));
  7914. }
  7915. #endif
  7916. void
  7917. mg_send_file(struct mg_connection *conn, const char *path)
  7918. {
  7919. mg_send_mime_file(conn, path, NULL);
  7920. }
  7921. void
  7922. mg_send_mime_file(struct mg_connection *conn,
  7923. const char *path,
  7924. const char *mime_type)
  7925. {
  7926. mg_send_mime_file2(conn, path, mime_type, NULL);
  7927. }
  7928. void
  7929. mg_send_mime_file2(struct mg_connection *conn,
  7930. const char *path,
  7931. const char *mime_type,
  7932. const char *additional_headers)
  7933. {
  7934. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7935. if (!conn) {
  7936. /* No conn */
  7937. return;
  7938. }
  7939. if (mg_stat(conn, path, &file.stat)) {
  7940. #if !defined(NO_CACHING)
  7941. if (is_not_modified(conn, &file.stat)) {
  7942. /* Send 304 "Not Modified" - this must not send any body data */
  7943. handle_not_modified_static_file_request(conn, &file);
  7944. } else
  7945. #endif /* NO_CACHING */
  7946. if (file.stat.is_directory) {
  7947. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  7948. "yes")) {
  7949. handle_directory_request(conn, path);
  7950. } else {
  7951. mg_send_http_error(conn,
  7952. 403,
  7953. "%s",
  7954. "Error: Directory listing denied");
  7955. }
  7956. } else {
  7957. handle_static_file_request(
  7958. conn, path, &file, mime_type, additional_headers);
  7959. }
  7960. } else {
  7961. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7962. }
  7963. }
  7964. /* For a given PUT path, create all intermediate subdirectories.
  7965. * Return 0 if the path itself is a directory.
  7966. * Return 1 if the path leads to a file.
  7967. * Return -1 for if the path is too long.
  7968. * Return -2 if path can not be created.
  7969. */
  7970. static int
  7971. put_dir(struct mg_connection *conn, const char *path)
  7972. {
  7973. char buf[PATH_MAX];
  7974. const char *s, *p;
  7975. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7976. size_t len;
  7977. int res = 1;
  7978. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7979. len = (size_t)(p - path);
  7980. if (len >= sizeof(buf)) {
  7981. /* path too long */
  7982. res = -1;
  7983. break;
  7984. }
  7985. memcpy(buf, path, len);
  7986. buf[len] = '\0';
  7987. /* Try to create intermediate directory */
  7988. DEBUG_TRACE("mkdir(%s)", buf);
  7989. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7990. /* path does not exixt and can not be created */
  7991. res = -2;
  7992. break;
  7993. }
  7994. /* Is path itself a directory? */
  7995. if (p[1] == '\0') {
  7996. res = 0;
  7997. }
  7998. }
  7999. return res;
  8000. }
  8001. static void
  8002. remove_bad_file(const struct mg_connection *conn, const char *path)
  8003. {
  8004. int r = mg_remove(conn, path);
  8005. if (r != 0) {
  8006. mg_cry_internal(conn,
  8007. "%s: Cannot remove invalid file %s",
  8008. __func__,
  8009. path);
  8010. }
  8011. }
  8012. long long
  8013. mg_store_body(struct mg_connection *conn, const char *path)
  8014. {
  8015. char buf[MG_BUF_LEN];
  8016. long long len = 0;
  8017. int ret, n;
  8018. struct mg_file fi;
  8019. if (conn->consumed_content != 0) {
  8020. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8021. return -11;
  8022. }
  8023. ret = put_dir(conn, path);
  8024. if (ret < 0) {
  8025. /* -1 for path too long,
  8026. * -2 for path can not be created. */
  8027. return ret;
  8028. }
  8029. if (ret != 1) {
  8030. /* Return 0 means, path itself is a directory. */
  8031. return 0;
  8032. }
  8033. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8034. return -12;
  8035. }
  8036. ret = mg_read(conn, buf, sizeof(buf));
  8037. while (ret > 0) {
  8038. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8039. if (n != ret) {
  8040. (void)mg_fclose(
  8041. &fi.access); /* File is bad and will be removed anyway. */
  8042. remove_bad_file(conn, path);
  8043. return -13;
  8044. }
  8045. len += ret;
  8046. ret = mg_read(conn, buf, sizeof(buf));
  8047. }
  8048. /* File is open for writing. If fclose fails, there was probably an
  8049. * error flushing the buffer to disk, so the file on disk might be
  8050. * broken. Delete it and return an error to the caller. */
  8051. if (mg_fclose(&fi.access) != 0) {
  8052. remove_bad_file(conn, path);
  8053. return -14;
  8054. }
  8055. return len;
  8056. }
  8057. /* Parse a buffer:
  8058. * Forward the string pointer till the end of a word, then
  8059. * terminate it and forward till the begin of the next word.
  8060. */
  8061. static int
  8062. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8063. {
  8064. /* Forward until a space is found - use isgraph here */
  8065. /* See http://www.cplusplus.com/reference/cctype/ */
  8066. while (isgraph(**ppw)) {
  8067. (*ppw)++;
  8068. }
  8069. /* Check end of word */
  8070. if (eol) {
  8071. /* must be a end of line */
  8072. if ((**ppw != '\r') && (**ppw != '\n')) {
  8073. return -1;
  8074. }
  8075. } else {
  8076. /* must be a end of a word, but not a line */
  8077. if (**ppw != ' ') {
  8078. return -1;
  8079. }
  8080. }
  8081. /* Terminate and forward to the next word */
  8082. do {
  8083. **ppw = 0;
  8084. (*ppw)++;
  8085. } while ((**ppw) && isspace(**ppw));
  8086. /* Check after term */
  8087. if (!eol) {
  8088. /* if it's not the end of line, there must be a next word */
  8089. if (!isgraph(**ppw)) {
  8090. return -1;
  8091. }
  8092. }
  8093. /* ok */
  8094. return 1;
  8095. }
  8096. /* Parse HTTP headers from the given buffer, advance buf pointer
  8097. * to the point where parsing stopped.
  8098. * All parameters must be valid pointers (not NULL).
  8099. * Return <0 on error. */
  8100. static int
  8101. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8102. {
  8103. int i;
  8104. int num_headers = 0;
  8105. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8106. char *dp = *buf;
  8107. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8108. dp++;
  8109. }
  8110. if (dp == *buf) {
  8111. /* End of headers reached. */
  8112. break;
  8113. }
  8114. if (*dp != ':') {
  8115. /* This is not a valid field. */
  8116. return -1;
  8117. }
  8118. /* End of header key (*dp == ':') */
  8119. /* Truncate here and set the key name */
  8120. *dp = 0;
  8121. hdr[i].name = *buf;
  8122. do {
  8123. dp++;
  8124. } while (*dp == ' ');
  8125. /* The rest of the line is the value */
  8126. hdr[i].value = dp;
  8127. *buf = dp + strcspn(dp, "\r\n");
  8128. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8129. *buf = NULL;
  8130. }
  8131. num_headers = i + 1;
  8132. if (*buf) {
  8133. (*buf)[0] = 0;
  8134. (*buf)[1] = 0;
  8135. *buf += 2;
  8136. } else {
  8137. *buf = dp;
  8138. break;
  8139. }
  8140. if ((*buf)[0] == '\r') {
  8141. /* This is the end of the header */
  8142. break;
  8143. }
  8144. }
  8145. return num_headers;
  8146. }
  8147. struct mg_http_method_info {
  8148. const char *name;
  8149. int request_has_body;
  8150. int response_has_body;
  8151. int is_safe;
  8152. int is_idempotent;
  8153. int is_cacheable;
  8154. };
  8155. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8156. static struct mg_http_method_info http_methods[] = {
  8157. /* HTTP (RFC 2616) */
  8158. {"GET", 0, 1, 1, 1, 1},
  8159. {"POST", 1, 1, 0, 0, 0},
  8160. {"PUT", 1, 0, 0, 1, 0},
  8161. {"DELETE", 0, 0, 0, 1, 0},
  8162. {"HEAD", 0, 0, 1, 1, 1},
  8163. {"OPTIONS", 0, 0, 1, 1, 0},
  8164. {"CONNECT", 1, 1, 0, 0, 0},
  8165. /* TRACE method (RFC 2616) is not supported for security reasons */
  8166. /* PATCH method (RFC 5789) */
  8167. {"PATCH", 1, 0, 0, 0, 0},
  8168. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8169. /* WEBDAV (RFC 2518) */
  8170. {"PROPFIND", 0, 1, 1, 1, 0},
  8171. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8172. * Some PROPFIND results MAY be cached, with care,
  8173. * as there is no cache validation mechanism for
  8174. * most properties. This method is both safe and
  8175. * idempotent (see Section 9.1 of [RFC2616]). */
  8176. {"MKCOL", 0, 0, 0, 1, 0},
  8177. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8178. * When MKCOL is invoked without a request body,
  8179. * the newly created collection SHOULD have no
  8180. * members. A MKCOL request message may contain
  8181. * a message body. The precise behavior of a MKCOL
  8182. * request when the body is present is undefined,
  8183. * ... ==> We do not support MKCOL with body data.
  8184. * This method is idempotent, but not safe (see
  8185. * Section 9.1 of [RFC2616]). Responses to this
  8186. * method MUST NOT be cached. */
  8187. /* Unsupported WEBDAV Methods: */
  8188. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8189. /* + 11 methods from RFC 3253 */
  8190. /* ORDERPATCH (RFC 3648) */
  8191. /* ACL (RFC 3744) */
  8192. /* SEARCH (RFC 5323) */
  8193. /* + MicroSoft extensions
  8194. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8195. /* REPORT method (RFC 3253) */
  8196. {"REPORT", 1, 1, 1, 1, 1},
  8197. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8198. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8199. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8200. * to be useful for REST in case a "GET request with body" is
  8201. * required. */
  8202. {NULL, 0, 0, 0, 0, 0}
  8203. /* end of list */
  8204. };
  8205. static const struct mg_http_method_info *
  8206. get_http_method_info(const char *method)
  8207. {
  8208. /* Check if the method is known to the server. The list of all known
  8209. * HTTP methods can be found here at
  8210. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8211. */
  8212. const struct mg_http_method_info *m = http_methods;
  8213. while (m->name) {
  8214. if (!strcmp(m->name, method)) {
  8215. return m;
  8216. }
  8217. m++;
  8218. }
  8219. return NULL;
  8220. }
  8221. static int
  8222. is_valid_http_method(const char *method)
  8223. {
  8224. return (get_http_method_info(method) != NULL);
  8225. }
  8226. /* Parse HTTP request, fill in mg_request_info structure.
  8227. * This function modifies the buffer by NUL-terminating
  8228. * HTTP request components, header names and header values.
  8229. * Parameters:
  8230. * buf (in/out): pointer to the HTTP header to parse and split
  8231. * len (in): length of HTTP header buffer
  8232. * re (out): parsed header as mg_request_info
  8233. * buf and ri must be valid pointers (not NULL), len>0.
  8234. * Returns <0 on error. */
  8235. static int
  8236. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8237. {
  8238. int request_length;
  8239. int init_skip = 0;
  8240. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8241. * remote_port */
  8242. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8243. NULL;
  8244. ri->num_headers = 0;
  8245. /* RFC says that all initial whitespaces should be ingored */
  8246. /* This included all leading \r and \n (isspace) */
  8247. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8248. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8249. buf++;
  8250. len--;
  8251. init_skip++;
  8252. }
  8253. if (len == 0) {
  8254. /* Incomplete request */
  8255. return 0;
  8256. }
  8257. /* Control characters are not allowed, including zero */
  8258. if (iscntrl(*(unsigned char *)buf)) {
  8259. return -1;
  8260. }
  8261. /* Find end of HTTP header */
  8262. request_length = get_http_header_len(buf, len);
  8263. if (request_length <= 0) {
  8264. return request_length;
  8265. }
  8266. buf[request_length - 1] = '\0';
  8267. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8268. return -1;
  8269. }
  8270. /* The first word has to be the HTTP method */
  8271. ri->request_method = buf;
  8272. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8273. return -1;
  8274. }
  8275. /* Check for a valid http method */
  8276. if (!is_valid_http_method(ri->request_method)) {
  8277. return -1;
  8278. }
  8279. /* The second word is the URI */
  8280. ri->request_uri = buf;
  8281. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8282. return -1;
  8283. }
  8284. /* Next would be the HTTP version */
  8285. ri->http_version = buf;
  8286. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8287. return -1;
  8288. }
  8289. /* Check for a valid HTTP version key */
  8290. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8291. /* Invalid request */
  8292. return -1;
  8293. }
  8294. ri->http_version += 5;
  8295. /* Parse all HTTP headers */
  8296. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8297. if (ri->num_headers < 0) {
  8298. /* Error while parsing headers */
  8299. return -1;
  8300. }
  8301. return request_length + init_skip;
  8302. }
  8303. static int
  8304. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8305. {
  8306. int response_length;
  8307. int init_skip = 0;
  8308. char *tmp, *tmp2;
  8309. long l;
  8310. /* Initialize elements. */
  8311. ri->http_version = ri->status_text = NULL;
  8312. ri->num_headers = ri->status_code = 0;
  8313. /* RFC says that all initial whitespaces should be ingored */
  8314. /* This included all leading \r and \n (isspace) */
  8315. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8316. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8317. buf++;
  8318. len--;
  8319. init_skip++;
  8320. }
  8321. if (len == 0) {
  8322. /* Incomplete request */
  8323. return 0;
  8324. }
  8325. /* Control characters are not allowed, including zero */
  8326. if (iscntrl(*(unsigned char *)buf)) {
  8327. return -1;
  8328. }
  8329. /* Find end of HTTP header */
  8330. response_length = get_http_header_len(buf, len);
  8331. if (response_length <= 0) {
  8332. return response_length;
  8333. }
  8334. buf[response_length - 1] = '\0';
  8335. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8336. return -1;
  8337. }
  8338. /* The first word is the HTTP version */
  8339. /* Check for a valid HTTP version key */
  8340. if (strncmp(buf, "HTTP/", 5) != 0) {
  8341. /* Invalid request */
  8342. return -1;
  8343. }
  8344. buf += 5;
  8345. if (!isgraph(buf[0])) {
  8346. /* Invalid request */
  8347. return -1;
  8348. }
  8349. ri->http_version = buf;
  8350. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8351. return -1;
  8352. }
  8353. /* The second word is the status as a number */
  8354. tmp = buf;
  8355. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8356. return -1;
  8357. }
  8358. l = strtol(tmp, &tmp2, 10);
  8359. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8360. /* Everything else but a 3 digit code is invalid */
  8361. return -1;
  8362. }
  8363. ri->status_code = (int)l;
  8364. /* The rest of the line is the status text */
  8365. ri->status_text = buf;
  8366. /* Find end of status text */
  8367. /* isgraph or isspace = isprint */
  8368. while (isprint(*buf)) {
  8369. buf++;
  8370. }
  8371. if ((*buf != '\r') && (*buf != '\n')) {
  8372. return -1;
  8373. }
  8374. /* Terminate string and forward buf to next line */
  8375. do {
  8376. *buf = 0;
  8377. buf++;
  8378. } while ((*buf) && isspace(*buf));
  8379. /* Parse all HTTP headers */
  8380. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8381. if (ri->num_headers < 0) {
  8382. /* Error while parsing headers */
  8383. return -1;
  8384. }
  8385. return response_length + init_skip;
  8386. }
  8387. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8388. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8389. * buffer (which marks the end of HTTP request). Buffer buf may already
  8390. * have some data. The length of the data is stored in nread.
  8391. * Upon every read operation, increase nread by the number of bytes read. */
  8392. static int
  8393. read_message(FILE *fp,
  8394. struct mg_connection *conn,
  8395. char *buf,
  8396. int bufsiz,
  8397. int *nread)
  8398. {
  8399. int request_len, n = 0;
  8400. struct timespec last_action_time;
  8401. double request_timeout;
  8402. if (!conn) {
  8403. return 0;
  8404. }
  8405. memset(&last_action_time, 0, sizeof(last_action_time));
  8406. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8407. /* value of request_timeout is in seconds, config in milliseconds */
  8408. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8409. } else {
  8410. request_timeout = -1.0;
  8411. }
  8412. if (conn->handled_requests > 0) {
  8413. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8414. request_timeout =
  8415. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8416. }
  8417. }
  8418. request_len = get_http_header_len(buf, *nread);
  8419. /* first time reading from this connection */
  8420. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8421. while (request_len == 0) {
  8422. /* Full request not yet received */
  8423. if (conn->phys_ctx->stop_flag != 0) {
  8424. /* Server is to be stopped. */
  8425. return -1;
  8426. }
  8427. if (*nread >= bufsiz) {
  8428. /* Request too long */
  8429. return -2;
  8430. }
  8431. n = pull_inner(
  8432. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8433. if (n == -2) {
  8434. /* Receive error */
  8435. return -1;
  8436. }
  8437. if (n > 0) {
  8438. *nread += n;
  8439. request_len = get_http_header_len(buf, *nread);
  8440. } else {
  8441. request_len = 0;
  8442. }
  8443. if ((request_len == 0) && (request_timeout >= 0)) {
  8444. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8445. > request_timeout) {
  8446. /* Timeout */
  8447. return -1;
  8448. }
  8449. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8450. }
  8451. }
  8452. return request_len;
  8453. }
  8454. #if !defined(NO_CGI) || !defined(NO_FILES)
  8455. static int
  8456. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8457. {
  8458. const char *expect, *body;
  8459. char buf[MG_BUF_LEN];
  8460. int to_read, nread, success = 0;
  8461. int64_t buffered_len;
  8462. double timeout = -1.0;
  8463. if (!conn) {
  8464. return 0;
  8465. }
  8466. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8467. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8468. }
  8469. expect = mg_get_header(conn, "Expect");
  8470. DEBUG_ASSERT(fp != NULL);
  8471. if (!fp) {
  8472. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8473. return 0;
  8474. }
  8475. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8476. /* Content length is not specified by the client. */
  8477. mg_send_http_error(conn,
  8478. 411,
  8479. "%s",
  8480. "Error: Client did not specify content length");
  8481. } else if ((expect != NULL)
  8482. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8483. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8484. */
  8485. mg_send_http_error(conn,
  8486. 417,
  8487. "Error: Can not fulfill expectation %s",
  8488. expect);
  8489. } else {
  8490. if (expect != NULL) {
  8491. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8492. conn->status_code = 100;
  8493. } else {
  8494. conn->status_code = 200;
  8495. }
  8496. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8497. - conn->consumed_content;
  8498. DEBUG_ASSERT(buffered_len >= 0);
  8499. DEBUG_ASSERT(conn->consumed_content == 0);
  8500. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8501. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8502. return 0;
  8503. }
  8504. if (buffered_len > 0) {
  8505. if ((int64_t)buffered_len > conn->content_len) {
  8506. buffered_len = (int)conn->content_len;
  8507. }
  8508. body = conn->buf + conn->request_len + conn->consumed_content;
  8509. push_all(
  8510. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8511. conn->consumed_content += buffered_len;
  8512. }
  8513. nread = 0;
  8514. while (conn->consumed_content < conn->content_len) {
  8515. to_read = sizeof(buf);
  8516. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8517. to_read = (int)(conn->content_len - conn->consumed_content);
  8518. }
  8519. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8520. if (nread == -2) {
  8521. /* error */
  8522. break;
  8523. }
  8524. if (nread > 0) {
  8525. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  8526. != nread) {
  8527. break;
  8528. }
  8529. }
  8530. conn->consumed_content += nread;
  8531. }
  8532. if (conn->consumed_content == conn->content_len) {
  8533. success = (nread >= 0);
  8534. }
  8535. /* Each error code path in this function must send an error */
  8536. if (!success) {
  8537. /* NOTE: Maybe some data has already been sent. */
  8538. /* TODO (low): If some data has been sent, a correct error
  8539. * reply can no longer be sent, so just close the connection */
  8540. mg_send_http_error(conn, 500, "%s", "");
  8541. }
  8542. }
  8543. return success;
  8544. }
  8545. #endif
  8546. #if !defined(NO_CGI)
  8547. /* This structure helps to create an environment for the spawned CGI
  8548. * program.
  8549. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8550. * last element must be NULL.
  8551. * However, on Windows there is a requirement that all these
  8552. * VARIABLE=VALUE\0
  8553. * strings must reside in a contiguous buffer. The end of the buffer is
  8554. * marked by two '\0' characters.
  8555. * We satisfy both worlds: we create an envp array (which is vars), all
  8556. * entries are actually pointers inside buf. */
  8557. struct cgi_environment {
  8558. struct mg_connection *conn;
  8559. /* Data block */
  8560. char *buf; /* Environment buffer */
  8561. size_t buflen; /* Space available in buf */
  8562. size_t bufused; /* Space taken in buf */
  8563. /* Index block */
  8564. char **var; /* char **envp */
  8565. size_t varlen; /* Number of variables available in var */
  8566. size_t varused; /* Number of variables stored in var */
  8567. };
  8568. static void addenv(struct cgi_environment *env,
  8569. PRINTF_FORMAT_STRING(const char *fmt),
  8570. ...) PRINTF_ARGS(2, 3);
  8571. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8572. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8573. static void
  8574. addenv(struct cgi_environment *env, const char *fmt, ...)
  8575. {
  8576. size_t n, space;
  8577. int truncated = 0;
  8578. char *added;
  8579. va_list ap;
  8580. /* Calculate how much space is left in the buffer */
  8581. space = (env->buflen - env->bufused);
  8582. /* Calculate an estimate for the required space */
  8583. n = strlen(fmt) + 2 + 128;
  8584. do {
  8585. if (space <= n) {
  8586. /* Allocate new buffer */
  8587. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8588. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  8589. if (!added) {
  8590. /* Out of memory */
  8591. mg_cry_internal(
  8592. env->conn,
  8593. "%s: Cannot allocate memory for CGI variable [%s]",
  8594. __func__,
  8595. fmt);
  8596. return;
  8597. }
  8598. env->buf = added;
  8599. env->buflen = n;
  8600. space = (env->buflen - env->bufused);
  8601. }
  8602. /* Make a pointer to the free space int the buffer */
  8603. added = env->buf + env->bufused;
  8604. /* Copy VARIABLE=VALUE\0 string into the free space */
  8605. va_start(ap, fmt);
  8606. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8607. va_end(ap);
  8608. /* Do not add truncated strings to the environment */
  8609. if (truncated) {
  8610. /* Reallocate the buffer */
  8611. space = 0;
  8612. n = 1;
  8613. }
  8614. } while (truncated);
  8615. /* Calculate number of bytes added to the environment */
  8616. n = strlen(added) + 1;
  8617. env->bufused += n;
  8618. /* Now update the variable index */
  8619. space = (env->varlen - env->varused);
  8620. if (space < 2) {
  8621. mg_cry_internal(env->conn,
  8622. "%s: Cannot register CGI variable [%s]",
  8623. __func__,
  8624. fmt);
  8625. return;
  8626. }
  8627. /* Append a pointer to the added string into the envp array */
  8628. env->var[env->varused] = added;
  8629. env->varused++;
  8630. }
  8631. /* Return 0 on success, non-zero if an error occurs. */
  8632. static int
  8633. prepare_cgi_environment(struct mg_connection *conn,
  8634. const char *prog,
  8635. struct cgi_environment *env)
  8636. {
  8637. const char *s;
  8638. struct vec var_vec;
  8639. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8640. int i, truncated, uri_len;
  8641. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8642. return -1;
  8643. }
  8644. env->conn = conn;
  8645. env->buflen = CGI_ENVIRONMENT_SIZE;
  8646. env->bufused = 0;
  8647. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  8648. if (env->buf == NULL) {
  8649. mg_cry_internal(conn,
  8650. "%s: Not enough memory for environmental buffer",
  8651. __func__);
  8652. return -1;
  8653. }
  8654. env->varlen = MAX_CGI_ENVIR_VARS;
  8655. env->varused = 0;
  8656. env->var =
  8657. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  8658. if (env->var == NULL) {
  8659. mg_cry_internal(conn,
  8660. "%s: Not enough memory for environmental variables",
  8661. __func__);
  8662. mg_free(env->buf);
  8663. return -1;
  8664. }
  8665. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  8666. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8667. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8668. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8669. /* Prepare the environment block */
  8670. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8671. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8672. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8673. #if defined(USE_IPV6)
  8674. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8675. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8676. } else
  8677. #endif
  8678. {
  8679. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8680. }
  8681. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8682. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8683. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8684. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8685. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8686. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8687. /* SCRIPT_NAME */
  8688. uri_len = (int)strlen(conn->request_info.local_uri);
  8689. if (conn->path_info == NULL) {
  8690. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8691. /* URI: /path_to_script/script.cgi */
  8692. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8693. } else {
  8694. /* URI: /path_to_script/ ... using index.cgi */
  8695. const char *index_file = strrchr(prog, '/');
  8696. if (index_file) {
  8697. addenv(env,
  8698. "SCRIPT_NAME=%s%s",
  8699. conn->request_info.local_uri,
  8700. index_file + 1);
  8701. }
  8702. }
  8703. } else {
  8704. /* URI: /path_to_script/script.cgi/path_info */
  8705. addenv(env,
  8706. "SCRIPT_NAME=%.*s",
  8707. uri_len - (int)strlen(conn->path_info),
  8708. conn->request_info.local_uri);
  8709. }
  8710. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8711. if (conn->path_info == NULL) {
  8712. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8713. } else {
  8714. addenv(env,
  8715. "PATH_TRANSLATED=%s%s",
  8716. conn->dom_ctx->config[DOCUMENT_ROOT],
  8717. conn->path_info);
  8718. }
  8719. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8720. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8721. addenv(env, "CONTENT_TYPE=%s", s);
  8722. }
  8723. if (conn->request_info.query_string != NULL) {
  8724. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8725. }
  8726. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8727. addenv(env, "CONTENT_LENGTH=%s", s);
  8728. }
  8729. if ((s = getenv("PATH")) != NULL) {
  8730. addenv(env, "PATH=%s", s);
  8731. }
  8732. if (conn->path_info != NULL) {
  8733. addenv(env, "PATH_INFO=%s", conn->path_info);
  8734. }
  8735. if (conn->status_code > 0) {
  8736. /* CGI error handler should show the status code */
  8737. addenv(env, "STATUS=%d", conn->status_code);
  8738. }
  8739. #if defined(_WIN32)
  8740. if ((s = getenv("COMSPEC")) != NULL) {
  8741. addenv(env, "COMSPEC=%s", s);
  8742. }
  8743. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8744. addenv(env, "SYSTEMROOT=%s", s);
  8745. }
  8746. if ((s = getenv("SystemDrive")) != NULL) {
  8747. addenv(env, "SystemDrive=%s", s);
  8748. }
  8749. if ((s = getenv("ProgramFiles")) != NULL) {
  8750. addenv(env, "ProgramFiles=%s", s);
  8751. }
  8752. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8753. addenv(env, "ProgramFiles(x86)=%s", s);
  8754. }
  8755. #else
  8756. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8757. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8758. }
  8759. #endif /* _WIN32 */
  8760. if ((s = getenv("PERLLIB")) != NULL) {
  8761. addenv(env, "PERLLIB=%s", s);
  8762. }
  8763. if (conn->request_info.remote_user != NULL) {
  8764. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8765. addenv(env, "%s", "AUTH_TYPE=Digest");
  8766. }
  8767. /* Add all headers as HTTP_* variables */
  8768. for (i = 0; i < conn->request_info.num_headers; i++) {
  8769. (void)mg_snprintf(conn,
  8770. &truncated,
  8771. http_var_name,
  8772. sizeof(http_var_name),
  8773. "HTTP_%s",
  8774. conn->request_info.http_headers[i].name);
  8775. if (truncated) {
  8776. mg_cry_internal(conn,
  8777. "%s: HTTP header variable too long [%s]",
  8778. __func__,
  8779. conn->request_info.http_headers[i].name);
  8780. continue;
  8781. }
  8782. /* Convert variable name into uppercase, and change - to _ */
  8783. for (p = http_var_name; *p != '\0'; p++) {
  8784. if (*p == '-') {
  8785. *p = '_';
  8786. }
  8787. *p = (char)toupper(*(unsigned char *)p);
  8788. }
  8789. addenv(env,
  8790. "%s=%s",
  8791. http_var_name,
  8792. conn->request_info.http_headers[i].value);
  8793. }
  8794. /* Add user-specified variables */
  8795. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  8796. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8797. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8798. }
  8799. env->var[env->varused] = NULL;
  8800. env->buf[env->bufused] = '\0';
  8801. return 0;
  8802. }
  8803. static void
  8804. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8805. {
  8806. char *buf;
  8807. size_t buflen;
  8808. int headers_len, data_len, i, truncated;
  8809. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8810. const char *status, *status_text, *connection_state;
  8811. char *pbuf, dir[PATH_MAX], *p;
  8812. struct mg_request_info ri;
  8813. struct cgi_environment blk;
  8814. FILE *in = NULL, *out = NULL, *err = NULL;
  8815. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8816. pid_t pid = (pid_t)-1;
  8817. if (conn == NULL) {
  8818. return;
  8819. }
  8820. buf = NULL;
  8821. buflen = 16384;
  8822. i = prepare_cgi_environment(conn, prog, &blk);
  8823. if (i != 0) {
  8824. blk.buf = NULL;
  8825. blk.var = NULL;
  8826. goto done;
  8827. }
  8828. /* CGI must be executed in its own directory. 'dir' must point to the
  8829. * directory containing executable program, 'p' must point to the
  8830. * executable program name relative to 'dir'. */
  8831. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8832. if (truncated) {
  8833. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  8834. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8835. goto done;
  8836. }
  8837. if ((p = strrchr(dir, '/')) != NULL) {
  8838. *p++ = '\0';
  8839. } else {
  8840. dir[0] = '.';
  8841. dir[1] = '\0';
  8842. p = (char *)prog;
  8843. }
  8844. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8845. status = strerror(ERRNO);
  8846. mg_cry_internal(
  8847. conn,
  8848. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8849. prog,
  8850. status);
  8851. mg_send_http_error(conn,
  8852. 500,
  8853. "Error: Cannot create CGI pipe: %s",
  8854. status);
  8855. goto done;
  8856. }
  8857. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  8858. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8859. if (pid == (pid_t)-1) {
  8860. status = strerror(ERRNO);
  8861. mg_cry_internal(
  8862. conn,
  8863. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8864. prog,
  8865. status);
  8866. mg_send_http_error(conn,
  8867. 500,
  8868. "Error: Cannot spawn CGI process [%s]: %s",
  8869. prog,
  8870. status);
  8871. goto done;
  8872. }
  8873. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  8874. */
  8875. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8876. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8877. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8878. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8879. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8880. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8881. /* Parent closes only one side of the pipes.
  8882. * If we don't mark them as closed, close() attempt before
  8883. * return from this function throws an exception on Windows.
  8884. * Windows does not like when closed descriptor is closed again. */
  8885. (void)close(fdin[0]);
  8886. (void)close(fdout[1]);
  8887. (void)close(fderr[1]);
  8888. fdin[0] = fdout[1] = fderr[1] = -1;
  8889. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8890. status = strerror(ERRNO);
  8891. mg_cry_internal(conn,
  8892. "Error: CGI program \"%s\": Can not open stdin: %s",
  8893. prog,
  8894. status);
  8895. mg_send_http_error(conn,
  8896. 500,
  8897. "Error: CGI can not open fdin\nfopen: %s",
  8898. status);
  8899. goto done;
  8900. }
  8901. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8902. status = strerror(ERRNO);
  8903. mg_cry_internal(conn,
  8904. "Error: CGI program \"%s\": Can not open stdout: %s",
  8905. prog,
  8906. status);
  8907. mg_send_http_error(conn,
  8908. 500,
  8909. "Error: CGI can not open fdout\nfopen: %s",
  8910. status);
  8911. goto done;
  8912. }
  8913. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8914. status = strerror(ERRNO);
  8915. mg_cry_internal(conn,
  8916. "Error: CGI program \"%s\": Can not open stderr: %s",
  8917. prog,
  8918. status);
  8919. mg_send_http_error(conn,
  8920. 500,
  8921. "Error: CGI can not open fdout\nfopen: %s",
  8922. status);
  8923. goto done;
  8924. }
  8925. setbuf(in, NULL);
  8926. setbuf(out, NULL);
  8927. setbuf(err, NULL);
  8928. fout.access.fp = out;
  8929. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  8930. DEBUG_TRACE("CGI: send body data (%lli)\n",
  8931. (signed long long)conn->request_info.content_length);
  8932. /* This is a POST/PUT request, or another request with body data. */
  8933. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8934. /* Error sending the body data */
  8935. mg_cry_internal(
  8936. conn,
  8937. "Error: CGI program \"%s\": Forward body data failed",
  8938. prog);
  8939. goto done;
  8940. }
  8941. }
  8942. /* Close so child gets an EOF. */
  8943. fclose(in);
  8944. in = NULL;
  8945. fdin[1] = -1;
  8946. /* Now read CGI reply into a buffer. We need to set correct
  8947. * status code, thus we need to see all HTTP headers first.
  8948. * Do not send anything back to client, until we buffer in all
  8949. * HTTP headers. */
  8950. data_len = 0;
  8951. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  8952. if (buf == NULL) {
  8953. mg_send_http_error(conn,
  8954. 500,
  8955. "Error: Not enough memory for CGI buffer (%u bytes)",
  8956. (unsigned int)buflen);
  8957. mg_cry_internal(
  8958. conn,
  8959. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  8960. "bytes)",
  8961. prog,
  8962. (unsigned int)buflen);
  8963. goto done;
  8964. }
  8965. DEBUG_TRACE("CGI: %s", "wait for response");
  8966. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  8967. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  8968. if (headers_len <= 0) {
  8969. /* Could not parse the CGI response. Check if some error message on
  8970. * stderr. */
  8971. i = pull_all(err, conn, buf, (int)buflen);
  8972. if (i > 0) {
  8973. mg_cry_internal(conn,
  8974. "Error: CGI program \"%s\" sent error "
  8975. "message: [%.*s]",
  8976. prog,
  8977. i,
  8978. buf);
  8979. mg_send_http_error(conn,
  8980. 500,
  8981. "Error: CGI program \"%s\" sent error "
  8982. "message: [%.*s]",
  8983. prog,
  8984. i,
  8985. buf);
  8986. } else {
  8987. mg_cry_internal(conn,
  8988. "Error: CGI program sent malformed or too big "
  8989. "(>%u bytes) HTTP headers: [%.*s]",
  8990. (unsigned)buflen,
  8991. data_len,
  8992. buf);
  8993. mg_send_http_error(conn,
  8994. 500,
  8995. "Error: CGI program sent malformed or too big "
  8996. "(>%u bytes) HTTP headers: [%.*s]",
  8997. (unsigned)buflen,
  8998. data_len,
  8999. buf);
  9000. }
  9001. goto done;
  9002. }
  9003. pbuf = buf;
  9004. buf[headers_len - 1] = '\0';
  9005. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9006. /* Make up and send the status line */
  9007. status_text = "OK";
  9008. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9009. != NULL) {
  9010. conn->status_code = atoi(status);
  9011. status_text = status;
  9012. while (isdigit(*(const unsigned char *)status_text)
  9013. || *status_text == ' ') {
  9014. status_text++;
  9015. }
  9016. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9017. != NULL) {
  9018. conn->status_code = 302;
  9019. } else {
  9020. conn->status_code = 200;
  9021. }
  9022. connection_state =
  9023. get_header(ri.http_headers, ri.num_headers, "Connection");
  9024. if (!header_has_option(connection_state, "keep-alive")) {
  9025. conn->must_close = 1;
  9026. }
  9027. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9028. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9029. /* Send headers */
  9030. for (i = 0; i < ri.num_headers; i++) {
  9031. mg_printf(conn,
  9032. "%s: %s\r\n",
  9033. ri.http_headers[i].name,
  9034. ri.http_headers[i].value);
  9035. }
  9036. mg_write(conn, "\r\n", 2);
  9037. /* Send chunk of data that may have been read after the headers */
  9038. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9039. /* Read the rest of CGI output and send to the client */
  9040. send_file_data(conn, &fout, 0, INT64_MAX);
  9041. DEBUG_TRACE("CGI: %s", "all data sent");
  9042. done:
  9043. mg_free(blk.var);
  9044. mg_free(blk.buf);
  9045. if (pid != (pid_t)-1) {
  9046. kill(pid, SIGKILL);
  9047. #if !defined(_WIN32)
  9048. {
  9049. int st;
  9050. while (waitpid(pid, &st, 0) != -1)
  9051. ; /* clean zombies */
  9052. }
  9053. #endif
  9054. }
  9055. if (fdin[0] != -1) {
  9056. close(fdin[0]);
  9057. }
  9058. if (fdout[1] != -1) {
  9059. close(fdout[1]);
  9060. }
  9061. if (in != NULL) {
  9062. fclose(in);
  9063. } else if (fdin[1] != -1) {
  9064. close(fdin[1]);
  9065. }
  9066. if (out != NULL) {
  9067. fclose(out);
  9068. } else if (fdout[0] != -1) {
  9069. close(fdout[0]);
  9070. }
  9071. if (err != NULL) {
  9072. fclose(err);
  9073. } else if (fderr[0] != -1) {
  9074. close(fderr[0]);
  9075. }
  9076. if (buf != NULL) {
  9077. mg_free(buf);
  9078. }
  9079. }
  9080. #endif /* !NO_CGI */
  9081. #if !defined(NO_FILES)
  9082. static void
  9083. mkcol(struct mg_connection *conn, const char *path)
  9084. {
  9085. int rc, body_len;
  9086. struct de de;
  9087. char date[64];
  9088. time_t curtime = time(NULL);
  9089. if (conn == NULL) {
  9090. return;
  9091. }
  9092. /* TODO (mid): Check the mg_send_http_error situations in this function
  9093. */
  9094. memset(&de.file, 0, sizeof(de.file));
  9095. if (!mg_stat(conn, path, &de.file)) {
  9096. mg_cry_internal(conn,
  9097. "%s: mg_stat(%s) failed: %s",
  9098. __func__,
  9099. path,
  9100. strerror(ERRNO));
  9101. }
  9102. if (de.file.last_modified) {
  9103. /* TODO (mid): This check does not seem to make any sense ! */
  9104. /* TODO (mid): Add a webdav unit test first, before changing
  9105. * anything here. */
  9106. mg_send_http_error(
  9107. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9108. return;
  9109. }
  9110. body_len = conn->data_len - conn->request_len;
  9111. if (body_len > 0) {
  9112. mg_send_http_error(
  9113. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9114. return;
  9115. }
  9116. rc = mg_mkdir(conn, path, 0755);
  9117. if (rc == 0) {
  9118. conn->status_code = 201;
  9119. gmt_time_string(date, sizeof(date), &curtime);
  9120. mg_printf(conn,
  9121. "HTTP/1.1 %d Created\r\n"
  9122. "Date: %s\r\n",
  9123. conn->status_code,
  9124. date);
  9125. send_static_cache_header(conn);
  9126. send_additional_header(conn);
  9127. mg_printf(conn,
  9128. "Content-Length: 0\r\n"
  9129. "Connection: %s\r\n\r\n",
  9130. suggest_connection_header(conn));
  9131. } else if (rc == -1) {
  9132. if (errno == EEXIST) {
  9133. mg_send_http_error(
  9134. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9135. } else if (errno == EACCES) {
  9136. mg_send_http_error(
  9137. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9138. } else if (errno == ENOENT) {
  9139. mg_send_http_error(
  9140. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9141. } else {
  9142. mg_send_http_error(
  9143. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9144. }
  9145. }
  9146. }
  9147. static void
  9148. put_file(struct mg_connection *conn, const char *path)
  9149. {
  9150. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9151. const char *range;
  9152. int64_t r1, r2;
  9153. int rc;
  9154. char date[64];
  9155. time_t curtime = time(NULL);
  9156. if (conn == NULL) {
  9157. return;
  9158. }
  9159. if (mg_stat(conn, path, &file.stat)) {
  9160. /* File already exists */
  9161. conn->status_code = 200;
  9162. if (file.stat.is_directory) {
  9163. /* This is an already existing directory,
  9164. * so there is nothing to do for the server. */
  9165. rc = 0;
  9166. } else {
  9167. /* File exists and is not a directory. */
  9168. /* Can it be replaced? */
  9169. if (file.access.membuf != NULL) {
  9170. /* This is an "in-memory" file, that can not be replaced */
  9171. mg_send_http_error(conn,
  9172. 405,
  9173. "Error: Put not possible\nReplacing %s "
  9174. "is not supported",
  9175. path);
  9176. return;
  9177. }
  9178. /* Check if the server may write this file */
  9179. if (access(path, W_OK) == 0) {
  9180. /* Access granted */
  9181. conn->status_code = 200;
  9182. rc = 1;
  9183. } else {
  9184. mg_send_http_error(
  9185. conn,
  9186. 403,
  9187. "Error: Put not possible\nReplacing %s is not allowed",
  9188. path);
  9189. return;
  9190. }
  9191. }
  9192. } else {
  9193. /* File should be created */
  9194. conn->status_code = 201;
  9195. rc = put_dir(conn, path);
  9196. }
  9197. if (rc == 0) {
  9198. /* put_dir returns 0 if path is a directory */
  9199. gmt_time_string(date, sizeof(date), &curtime);
  9200. mg_printf(conn,
  9201. "HTTP/1.1 %d %s\r\n",
  9202. conn->status_code,
  9203. mg_get_response_code_text(NULL, conn->status_code));
  9204. send_no_cache_header(conn);
  9205. send_additional_header(conn);
  9206. mg_printf(conn,
  9207. "Date: %s\r\n"
  9208. "Content-Length: 0\r\n"
  9209. "Connection: %s\r\n\r\n",
  9210. date,
  9211. suggest_connection_header(conn));
  9212. /* Request to create a directory has been fulfilled successfully.
  9213. * No need to put a file. */
  9214. return;
  9215. }
  9216. if (rc == -1) {
  9217. /* put_dir returns -1 if the path is too long */
  9218. mg_send_http_error(conn,
  9219. 414,
  9220. "Error: Path too long\nput_dir(%s): %s",
  9221. path,
  9222. strerror(ERRNO));
  9223. return;
  9224. }
  9225. if (rc == -2) {
  9226. /* put_dir returns -2 if the directory can not be created */
  9227. mg_send_http_error(conn,
  9228. 500,
  9229. "Error: Can not create directory\nput_dir(%s): %s",
  9230. path,
  9231. strerror(ERRNO));
  9232. return;
  9233. }
  9234. /* A file should be created or overwritten. */
  9235. /* Currently CivetWeb does not nead read+write access. */
  9236. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9237. || file.access.fp == NULL) {
  9238. (void)mg_fclose(&file.access);
  9239. mg_send_http_error(conn,
  9240. 500,
  9241. "Error: Can not create file\nfopen(%s): %s",
  9242. path,
  9243. strerror(ERRNO));
  9244. return;
  9245. }
  9246. fclose_on_exec(&file.access, conn);
  9247. range = mg_get_header(conn, "Content-Range");
  9248. r1 = r2 = 0;
  9249. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9250. conn->status_code = 206; /* Partial content */
  9251. fseeko(file.access.fp, r1, SEEK_SET);
  9252. }
  9253. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9254. /* forward_body_data failed.
  9255. * The error code has already been sent to the client,
  9256. * and conn->status_code is already set. */
  9257. (void)mg_fclose(&file.access);
  9258. return;
  9259. }
  9260. if (mg_fclose(&file.access) != 0) {
  9261. /* fclose failed. This might have different reasons, but a likely
  9262. * one is "no space on disk", http 507. */
  9263. conn->status_code = 507;
  9264. }
  9265. gmt_time_string(date, sizeof(date), &curtime);
  9266. mg_printf(conn,
  9267. "HTTP/1.1 %d %s\r\n",
  9268. conn->status_code,
  9269. mg_get_response_code_text(NULL, conn->status_code));
  9270. send_no_cache_header(conn);
  9271. send_additional_header(conn);
  9272. mg_printf(conn,
  9273. "Date: %s\r\n"
  9274. "Content-Length: 0\r\n"
  9275. "Connection: %s\r\n\r\n",
  9276. date,
  9277. suggest_connection_header(conn));
  9278. }
  9279. static void
  9280. delete_file(struct mg_connection *conn, const char *path)
  9281. {
  9282. struct de de;
  9283. memset(&de.file, 0, sizeof(de.file));
  9284. if (!mg_stat(conn, path, &de.file)) {
  9285. /* mg_stat returns 0 if the file does not exist */
  9286. mg_send_http_error(conn,
  9287. 404,
  9288. "Error: Cannot delete file\nFile %s not found",
  9289. path);
  9290. return;
  9291. }
  9292. #if 0 /* Ignore if a file in memory is inside a folder */
  9293. if (de.access.membuf != NULL) {
  9294. /* the file is cached in memory */
  9295. mg_send_http_error(
  9296. conn,
  9297. 405,
  9298. "Error: Delete not possible\nDeleting %s is not supported",
  9299. path);
  9300. return;
  9301. }
  9302. #endif
  9303. if (de.file.is_directory) {
  9304. if (remove_directory(conn, path)) {
  9305. /* Delete is successful: Return 204 without content. */
  9306. mg_send_http_error(conn, 204, "%s", "");
  9307. } else {
  9308. /* Delete is not successful: Return 500 (Server error). */
  9309. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9310. }
  9311. return;
  9312. }
  9313. /* This is an existing file (not a directory).
  9314. * Check if write permission is granted. */
  9315. if (access(path, W_OK) != 0) {
  9316. /* File is read only */
  9317. mg_send_http_error(
  9318. conn,
  9319. 403,
  9320. "Error: Delete not possible\nDeleting %s is not allowed",
  9321. path);
  9322. return;
  9323. }
  9324. /* Try to delete it. */
  9325. if (mg_remove(conn, path) == 0) {
  9326. /* Delete was successful: Return 204 without content. */
  9327. mg_send_http_error(conn, 204, "%s", "");
  9328. } else {
  9329. /* Delete not successful (file locked). */
  9330. mg_send_http_error(conn,
  9331. 423,
  9332. "Error: Cannot delete file\nremove(%s): %s",
  9333. path,
  9334. strerror(ERRNO));
  9335. }
  9336. }
  9337. #endif /* !NO_FILES */
  9338. static void
  9339. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9340. static void
  9341. do_ssi_include(struct mg_connection *conn,
  9342. const char *ssi,
  9343. char *tag,
  9344. int include_level)
  9345. {
  9346. char file_name[MG_BUF_LEN], path[512], *p;
  9347. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9348. size_t len;
  9349. int truncated = 0;
  9350. if (conn == NULL) {
  9351. return;
  9352. }
  9353. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9354. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9355. * always < MG_BUF_LEN. */
  9356. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9357. /* File name is relative to the webserver root */
  9358. file_name[511] = 0;
  9359. (void)mg_snprintf(conn,
  9360. &truncated,
  9361. path,
  9362. sizeof(path),
  9363. "%s/%s",
  9364. conn->dom_ctx->config[DOCUMENT_ROOT],
  9365. file_name);
  9366. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9367. /* File name is relative to the webserver working directory
  9368. * or it is absolute system path */
  9369. file_name[511] = 0;
  9370. (void)
  9371. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9372. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9373. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9374. /* File name is relative to the currect document */
  9375. file_name[511] = 0;
  9376. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9377. if (!truncated) {
  9378. if ((p = strrchr(path, '/')) != NULL) {
  9379. p[1] = '\0';
  9380. }
  9381. len = strlen(path);
  9382. (void)mg_snprintf(conn,
  9383. &truncated,
  9384. path + len,
  9385. sizeof(path) - len,
  9386. "%s",
  9387. file_name);
  9388. }
  9389. } else {
  9390. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9391. return;
  9392. }
  9393. if (truncated) {
  9394. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9395. return;
  9396. }
  9397. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9398. mg_cry_internal(conn,
  9399. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9400. tag,
  9401. path,
  9402. strerror(ERRNO));
  9403. } else {
  9404. fclose_on_exec(&file.access, conn);
  9405. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9406. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9407. path) > 0) {
  9408. send_ssi_file(conn, path, &file, include_level + 1);
  9409. } else {
  9410. send_file_data(conn, &file, 0, INT64_MAX);
  9411. }
  9412. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9413. }
  9414. }
  9415. #if !defined(NO_POPEN)
  9416. static void
  9417. do_ssi_exec(struct mg_connection *conn, char *tag)
  9418. {
  9419. char cmd[1024] = "";
  9420. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9421. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9422. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9423. } else {
  9424. cmd[1023] = 0;
  9425. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9426. mg_cry_internal(conn,
  9427. "Cannot SSI #exec: [%s]: %s",
  9428. cmd,
  9429. strerror(ERRNO));
  9430. } else {
  9431. send_file_data(conn, &file, 0, INT64_MAX);
  9432. pclose(file.access.fp);
  9433. }
  9434. }
  9435. }
  9436. #endif /* !NO_POPEN */
  9437. static int
  9438. mg_fgetc(struct mg_file *filep, int offset)
  9439. {
  9440. if (filep == NULL) {
  9441. return EOF;
  9442. }
  9443. if ((filep->access.membuf != NULL) && (offset >= 0)
  9444. && (((unsigned int)(offset)) < filep->stat.size)) {
  9445. return ((const unsigned char *)filep->access.membuf)[offset];
  9446. } else if (filep->access.fp != NULL) {
  9447. return fgetc(filep->access.fp);
  9448. } else {
  9449. return EOF;
  9450. }
  9451. }
  9452. static void
  9453. send_ssi_file(struct mg_connection *conn,
  9454. const char *path,
  9455. struct mg_file *filep,
  9456. int include_level)
  9457. {
  9458. char buf[MG_BUF_LEN];
  9459. int ch, offset, len, in_tag, in_ssi_tag;
  9460. if (include_level > 10) {
  9461. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  9462. return;
  9463. }
  9464. in_tag = in_ssi_tag = len = offset = 0;
  9465. /* Read file, byte by byte, and look for SSI include tags */
  9466. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9467. if (in_tag) {
  9468. /* We are in a tag, either SSI tag or html tag */
  9469. if (ch == '>') {
  9470. /* Tag is closing */
  9471. buf[len++] = '>';
  9472. if (in_ssi_tag) {
  9473. /* Handle SSI tag */
  9474. buf[len] = 0;
  9475. if (!memcmp(buf + 5, "include", 7)) {
  9476. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9477. #if !defined(NO_POPEN)
  9478. } else if (!memcmp(buf + 5, "exec", 4)) {
  9479. do_ssi_exec(conn, buf + 9);
  9480. #endif /* !NO_POPEN */
  9481. } else {
  9482. mg_cry_internal(conn,
  9483. "%s: unknown SSI "
  9484. "command: \"%s\"",
  9485. path,
  9486. buf);
  9487. }
  9488. len = 0;
  9489. in_ssi_tag = in_tag = 0;
  9490. } else {
  9491. /* Not an SSI tag */
  9492. /* Flush buffer */
  9493. (void)mg_write(conn, buf, (size_t)len);
  9494. len = 0;
  9495. in_tag = 0;
  9496. }
  9497. } else {
  9498. /* Tag is still open */
  9499. buf[len++] = (char)(ch & 0xff);
  9500. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9501. /* All SSI tags start with <!--# */
  9502. in_ssi_tag = 1;
  9503. }
  9504. if ((len + 2) > (int)sizeof(buf)) {
  9505. /* Tag to long for buffer */
  9506. mg_cry_internal(conn, "%s: tag is too large", path);
  9507. return;
  9508. }
  9509. }
  9510. } else {
  9511. /* We are not in a tag yet. */
  9512. if (ch == '<') {
  9513. /* Tag is opening */
  9514. in_tag = 1;
  9515. /* Flush current buffer */
  9516. (void)mg_write(conn, buf, (size_t)len);
  9517. /* Store the < */
  9518. len = 1;
  9519. buf[0] = '<';
  9520. } else {
  9521. /* No Tag */
  9522. /* Add data to buffer */
  9523. buf[len++] = (char)(ch & 0xff);
  9524. /* Flush if buffer is full */
  9525. if (len == (int)sizeof(buf)) {
  9526. mg_write(conn, buf, (size_t)len);
  9527. len = 0;
  9528. }
  9529. }
  9530. }
  9531. }
  9532. /* Send the rest of buffered data */
  9533. if (len > 0) {
  9534. mg_write(conn, buf, (size_t)len);
  9535. }
  9536. }
  9537. static void
  9538. handle_ssi_file_request(struct mg_connection *conn,
  9539. const char *path,
  9540. struct mg_file *filep)
  9541. {
  9542. char date[64];
  9543. time_t curtime = time(NULL);
  9544. const char *cors1, *cors2, *cors3;
  9545. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9546. return;
  9547. }
  9548. if (mg_get_header(conn, "Origin")) {
  9549. /* Cross-origin resource sharing (CORS). */
  9550. cors1 = "Access-Control-Allow-Origin: ";
  9551. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9552. cors3 = "\r\n";
  9553. } else {
  9554. cors1 = cors2 = cors3 = "";
  9555. }
  9556. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9557. /* File exists (precondition for calling this function),
  9558. * but can not be opened by the server. */
  9559. mg_send_http_error(conn,
  9560. 500,
  9561. "Error: Cannot read file\nfopen(%s): %s",
  9562. path,
  9563. strerror(ERRNO));
  9564. } else {
  9565. conn->must_close = 1;
  9566. gmt_time_string(date, sizeof(date), &curtime);
  9567. fclose_on_exec(&filep->access, conn);
  9568. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9569. send_no_cache_header(conn);
  9570. send_additional_header(conn);
  9571. mg_printf(conn,
  9572. "%s%s%s"
  9573. "Date: %s\r\n"
  9574. "Content-Type: text/html\r\n"
  9575. "Connection: %s\r\n\r\n",
  9576. cors1,
  9577. cors2,
  9578. cors3,
  9579. date,
  9580. suggest_connection_header(conn));
  9581. send_ssi_file(conn, path, filep, 0);
  9582. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9583. }
  9584. }
  9585. #if !defined(NO_FILES)
  9586. static void
  9587. send_options(struct mg_connection *conn)
  9588. {
  9589. char date[64];
  9590. time_t curtime = time(NULL);
  9591. if (!conn) {
  9592. return;
  9593. }
  9594. conn->status_code = 200;
  9595. conn->must_close = 1;
  9596. gmt_time_string(date, sizeof(date), &curtime);
  9597. /* We do not set a "Cache-Control" header here, but leave the default.
  9598. * Since browsers do not send an OPTIONS request, we can not test the
  9599. * effect anyway. */
  9600. mg_printf(conn,
  9601. "HTTP/1.1 200 OK\r\n"
  9602. "Date: %s\r\n"
  9603. "Connection: %s\r\n"
  9604. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9605. "PROPFIND, MKCOL\r\n"
  9606. "DAV: 1\r\n",
  9607. date,
  9608. suggest_connection_header(conn));
  9609. send_additional_header(conn);
  9610. mg_printf(conn, "\r\n");
  9611. }
  9612. /* Writes PROPFIND properties for a collection element */
  9613. static void
  9614. print_props(struct mg_connection *conn,
  9615. const char *uri,
  9616. struct mg_file_stat *filep)
  9617. {
  9618. char mtime[64];
  9619. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9620. return;
  9621. }
  9622. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9623. mg_printf(conn,
  9624. "<d:response>"
  9625. "<d:href>%s</d:href>"
  9626. "<d:propstat>"
  9627. "<d:prop>"
  9628. "<d:resourcetype>%s</d:resourcetype>"
  9629. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9630. "<d:getlastmodified>%s</d:getlastmodified>"
  9631. "</d:prop>"
  9632. "<d:status>HTTP/1.1 200 OK</d:status>"
  9633. "</d:propstat>"
  9634. "</d:response>\n",
  9635. uri,
  9636. filep->is_directory ? "<d:collection/>" : "",
  9637. filep->size,
  9638. mtime);
  9639. }
  9640. static int
  9641. print_dav_dir_entry(struct de *de, void *data)
  9642. {
  9643. char href[PATH_MAX];
  9644. int truncated;
  9645. struct mg_connection *conn = (struct mg_connection *)data;
  9646. if (!de || !conn) {
  9647. return -1;
  9648. }
  9649. mg_snprintf(conn,
  9650. &truncated,
  9651. href,
  9652. sizeof(href),
  9653. "%s%s",
  9654. conn->request_info.local_uri,
  9655. de->file_name);
  9656. if (!truncated) {
  9657. size_t href_encoded_size;
  9658. char *href_encoded;
  9659. href_encoded_size = PATH_MAX * 3; /* worst case */
  9660. href_encoded = (char *)mg_malloc(href_encoded_size);
  9661. if (href_encoded == NULL) {
  9662. return -1;
  9663. }
  9664. mg_url_encode(href, href_encoded, href_encoded_size);
  9665. print_props(conn, href_encoded, &de->file);
  9666. mg_free(href_encoded);
  9667. }
  9668. return 0;
  9669. }
  9670. static void
  9671. handle_propfind(struct mg_connection *conn,
  9672. const char *path,
  9673. struct mg_file_stat *filep)
  9674. {
  9675. const char *depth = mg_get_header(conn, "Depth");
  9676. char date[64];
  9677. time_t curtime = time(NULL);
  9678. gmt_time_string(date, sizeof(date), &curtime);
  9679. if (!conn || !path || !filep || !conn->dom_ctx) {
  9680. return;
  9681. }
  9682. conn->must_close = 1;
  9683. conn->status_code = 207;
  9684. mg_printf(conn,
  9685. "HTTP/1.1 207 Multi-Status\r\n"
  9686. "Date: %s\r\n",
  9687. date);
  9688. send_static_cache_header(conn);
  9689. send_additional_header(conn);
  9690. mg_printf(conn,
  9691. "Connection: %s\r\n"
  9692. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9693. suggest_connection_header(conn));
  9694. mg_printf(conn,
  9695. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9696. "<d:multistatus xmlns:d='DAV:'>\n");
  9697. /* Print properties for the requested resource itself */
  9698. print_props(conn, conn->request_info.local_uri, filep);
  9699. /* If it is a directory, print directory entries too if Depth is not 0
  9700. */
  9701. if (filep && filep->is_directory
  9702. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9703. "yes")
  9704. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9705. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9706. }
  9707. mg_printf(conn, "%s\n", "</d:multistatus>");
  9708. }
  9709. #endif
  9710. void
  9711. mg_lock_connection(struct mg_connection *conn)
  9712. {
  9713. if (conn) {
  9714. (void)pthread_mutex_lock(&conn->mutex);
  9715. }
  9716. }
  9717. void
  9718. mg_unlock_connection(struct mg_connection *conn)
  9719. {
  9720. if (conn) {
  9721. (void)pthread_mutex_unlock(&conn->mutex);
  9722. }
  9723. }
  9724. void
  9725. mg_lock_context(struct mg_context *ctx)
  9726. {
  9727. if (ctx) {
  9728. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9729. }
  9730. }
  9731. void
  9732. mg_unlock_context(struct mg_context *ctx)
  9733. {
  9734. if (ctx) {
  9735. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9736. }
  9737. }
  9738. #if defined(USE_TIMERS)
  9739. #define TIMER_API static
  9740. #include "timer.inl"
  9741. #endif /* USE_TIMERS */
  9742. #ifdef USE_LUA
  9743. #include "mod_lua.inl"
  9744. #endif /* USE_LUA */
  9745. #ifdef USE_DUKTAPE
  9746. #include "mod_duktape.inl"
  9747. #endif /* USE_DUKTAPE */
  9748. #if defined(USE_WEBSOCKET)
  9749. #if !defined(NO_SSL_DL)
  9750. #define SHA_API static
  9751. #include "sha1.inl"
  9752. #endif
  9753. static int
  9754. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9755. {
  9756. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9757. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9758. SHA_CTX sha_ctx;
  9759. int truncated;
  9760. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9761. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9762. if (truncated) {
  9763. conn->must_close = 1;
  9764. return 0;
  9765. }
  9766. DEBUG_TRACE("%s", "Send websocket handshake");
  9767. SHA1_Init(&sha_ctx);
  9768. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9769. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9770. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9771. mg_printf(conn,
  9772. "HTTP/1.1 101 Switching Protocols\r\n"
  9773. "Upgrade: websocket\r\n"
  9774. "Connection: Upgrade\r\n"
  9775. "Sec-WebSocket-Accept: %s\r\n",
  9776. b64_sha);
  9777. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9778. mg_printf(conn,
  9779. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9780. conn->request_info.acceptedWebSocketSubprotocol);
  9781. } else {
  9782. mg_printf(conn, "%s", "\r\n");
  9783. }
  9784. return 1;
  9785. }
  9786. static void
  9787. read_websocket(struct mg_connection *conn,
  9788. mg_websocket_data_handler ws_data_handler,
  9789. void *callback_data)
  9790. {
  9791. /* Pointer to the beginning of the portion of the incoming websocket
  9792. * message queue.
  9793. * The original websocket upgrade request is never removed, so the queue
  9794. * begins after it. */
  9795. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9796. int n, error, exit_by_callback;
  9797. /* body_len is the length of the entire queue in bytes
  9798. * len is the length of the current message
  9799. * data_len is the length of the current message's data payload
  9800. * header_len is the length of the current message's header */
  9801. size_t i, len, mask_len = 0, header_len, body_len;
  9802. uint64_t data_len = 0;
  9803. /* "The masking key is a 32-bit value chosen at random by the client."
  9804. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9805. */
  9806. unsigned char mask[4];
  9807. /* data points to the place where the message is stored when passed to
  9808. * the websocket_data callback. This is either mem on the stack, or a
  9809. * dynamically allocated buffer if it is too large. */
  9810. unsigned char mem[4096];
  9811. unsigned char mop; /* mask flag and opcode */
  9812. double timeout = -1.0;
  9813. int enable_ping_pong = 0;
  9814. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  9815. enable_ping_pong =
  9816. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  9817. "yes");
  9818. }
  9819. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  9820. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9821. }
  9822. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  9823. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9824. }
  9825. conn->in_websocket_handling = 1;
  9826. mg_set_thread_name("wsock");
  9827. /* Loop continuously, reading messages from the socket, invoking the
  9828. * callback, and waiting repeatedly until an error occurs. */
  9829. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  9830. header_len = 0;
  9831. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  9832. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9833. len = buf[1] & 127;
  9834. mask_len = (buf[1] & 128) ? 4 : 0;
  9835. if ((len < 126) && (body_len >= mask_len)) {
  9836. /* inline 7-bit length field */
  9837. data_len = len;
  9838. header_len = 2 + mask_len;
  9839. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9840. /* 16-bit length field */
  9841. header_len = 4 + mask_len;
  9842. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9843. } else if (body_len >= (10 + mask_len)) {
  9844. /* 64-bit length field */
  9845. uint32_t l1, l2;
  9846. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9847. memcpy(&l2, &buf[6], 4);
  9848. header_len = 10 + mask_len;
  9849. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9850. if (data_len > (uint64_t)0x7FFF0000ul) {
  9851. /* no can do */
  9852. mg_cry_internal(
  9853. conn,
  9854. "%s",
  9855. "websocket out of memory; closing connection");
  9856. break;
  9857. }
  9858. }
  9859. }
  9860. if ((header_len > 0) && (body_len >= header_len)) {
  9861. /* Allocate space to hold websocket payload */
  9862. unsigned char *data = mem;
  9863. if ((size_t)data_len > (size_t)sizeof(mem)) {
  9864. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  9865. conn->phys_ctx);
  9866. if (data == NULL) {
  9867. /* Allocation failed, exit the loop and then close the
  9868. * connection */
  9869. mg_cry_internal(
  9870. conn,
  9871. "%s",
  9872. "websocket out of memory; closing connection");
  9873. break;
  9874. }
  9875. }
  9876. /* Copy the mask before we shift the queue and destroy it */
  9877. if (mask_len > 0) {
  9878. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9879. } else {
  9880. memset(mask, 0, sizeof(mask));
  9881. }
  9882. /* Read frame payload from the first message in the queue into
  9883. * data and advance the queue by moving the memory in place. */
  9884. DEBUG_ASSERT(body_len >= header_len);
  9885. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  9886. mop = buf[0]; /* current mask and opcode */
  9887. /* Overflow case */
  9888. len = body_len - header_len;
  9889. memcpy(data, buf + header_len, len);
  9890. error = 0;
  9891. while ((uint64_t)len < data_len) {
  9892. n = pull_inner(NULL,
  9893. conn,
  9894. (char *)(data + len),
  9895. (int)(data_len - len),
  9896. timeout);
  9897. if (n <= -2) {
  9898. error = 1;
  9899. break;
  9900. } else if (n > 0) {
  9901. len += (size_t)n;
  9902. } else {
  9903. /* Timeout: should retry */
  9904. /* TODO: retry condition */
  9905. }
  9906. }
  9907. if (error) {
  9908. mg_cry_internal(
  9909. conn,
  9910. "%s",
  9911. "Websocket pull failed; closing connection");
  9912. if (data != mem) {
  9913. mg_free(data);
  9914. }
  9915. break;
  9916. }
  9917. conn->data_len = conn->request_len;
  9918. } else {
  9919. mop = buf[0]; /* current mask and opcode, overwritten by
  9920. * memmove() */
  9921. /* Length of the message being read at the front of the
  9922. * queue. Cast to 31 bit is OK, since we limited
  9923. * data_len before. */
  9924. len = (size_t)data_len + header_len;
  9925. /* Copy the data payload into the data pointer for the
  9926. * callback. Cast to 31 bit is OK, since we
  9927. * limited data_len */
  9928. memcpy(data, buf + header_len, (size_t)data_len);
  9929. /* Move the queue forward len bytes */
  9930. memmove(buf, buf + len, body_len - len);
  9931. /* Mark the queue as advanced */
  9932. conn->data_len -= (int)len;
  9933. }
  9934. /* Apply mask if necessary */
  9935. if (mask_len > 0) {
  9936. for (i = 0; i < (size_t)data_len; i++) {
  9937. data[i] ^= mask[i & 3];
  9938. }
  9939. }
  9940. exit_by_callback = 0;
  9941. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  9942. /* filter PONG messages */
  9943. DEBUG_TRACE("PONG from %s:%u",
  9944. conn->request_info.remote_addr,
  9945. conn->request_info.remote_port);
  9946. } else {
  9947. /* Exit the loop if callback signals to exit (server side),
  9948. * or "connection close" opcode received (client side). */
  9949. if ((ws_data_handler != NULL)
  9950. && !ws_data_handler(conn,
  9951. mop,
  9952. (char *)data,
  9953. (size_t)data_len,
  9954. callback_data)) {
  9955. exit_by_callback = 1;
  9956. }
  9957. }
  9958. /* It a buffer has been allocated, free it again */
  9959. if (data != mem) {
  9960. mg_free(data);
  9961. }
  9962. if (exit_by_callback
  9963. || ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9964. /* Opcode == 8, connection close */
  9965. break;
  9966. }
  9967. /* Not breaking the loop, process next websocket frame. */
  9968. } else {
  9969. /* Read from the socket into the next available location in the
  9970. * message queue. */
  9971. n = pull_inner(NULL,
  9972. conn,
  9973. conn->buf + conn->data_len,
  9974. conn->buf_size - conn->data_len,
  9975. timeout);
  9976. if (n <= -2) {
  9977. /* Error, no bytes read */
  9978. break;
  9979. }
  9980. if (n > 0) {
  9981. conn->data_len += n;
  9982. } else {
  9983. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  9984. if (enable_ping_pong) {
  9985. int ret;
  9986. /* Send Websocket PING message */
  9987. DEBUG_TRACE("PING to %s:%u",
  9988. conn->request_info.remote_addr,
  9989. conn->request_info.remote_port);
  9990. ret = mg_websocket_write(conn,
  9991. MG_WEBSOCKET_OPCODE_PING,
  9992. NULL,
  9993. 0);
  9994. if (ret <= 0) {
  9995. /* Error: send failed */
  9996. break;
  9997. }
  9998. }
  9999. }
  10000. /* Timeout: should retry */
  10001. /* TODO: get timeout def */
  10002. }
  10003. }
  10004. }
  10005. mg_set_thread_name("worker");
  10006. conn->in_websocket_handling = 0;
  10007. }
  10008. static int
  10009. mg_websocket_write_exec(struct mg_connection *conn,
  10010. int opcode,
  10011. const char *data,
  10012. size_t dataLen,
  10013. uint32_t masking_key)
  10014. {
  10015. unsigned char header[14];
  10016. size_t headerLen;
  10017. int retval;
  10018. #if defined(__GNUC__) || defined(__MINGW32__)
  10019. /* Disable spurious conversion warning for GCC */
  10020. #pragma GCC diagnostic push
  10021. #pragma GCC diagnostic ignored "-Wconversion"
  10022. #endif
  10023. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10024. #if defined(__GNUC__) || defined(__MINGW32__)
  10025. #pragma GCC diagnostic pop
  10026. #endif
  10027. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10028. if (dataLen < 126) {
  10029. /* inline 7-bit length field */
  10030. header[1] = (unsigned char)dataLen;
  10031. headerLen = 2;
  10032. } else if (dataLen <= 0xFFFF) {
  10033. /* 16-bit length field */
  10034. uint16_t len = htons((uint16_t)dataLen);
  10035. header[1] = 126;
  10036. memcpy(header + 2, &len, 2);
  10037. headerLen = 4;
  10038. } else {
  10039. /* 64-bit length field */
  10040. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10041. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10042. header[1] = 127;
  10043. memcpy(header + 2, &len1, 4);
  10044. memcpy(header + 6, &len2, 4);
  10045. headerLen = 10;
  10046. }
  10047. if (masking_key) {
  10048. /* add mask */
  10049. header[1] |= 0x80;
  10050. memcpy(header + headerLen, &masking_key, 4);
  10051. headerLen += 4;
  10052. }
  10053. /* Note that POSIX/Winsock's send() is threadsafe
  10054. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10055. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10056. * push(), although that is only a problem if the packet is large or
  10057. * outgoing buffer is full). */
  10058. /* TODO: Check if this lock should be moved to user land.
  10059. * Currently the server sets this lock for websockets, but
  10060. * not for any other connection. It must be set for every
  10061. * conn read/written by more than one thread, no matter if
  10062. * it is a websocket or regular connection. */
  10063. (void)mg_lock_connection(conn);
  10064. retval = mg_write(conn, header, headerLen);
  10065. if (retval != (int)headerLen) {
  10066. /* Did not send complete header */
  10067. retval = -1;
  10068. } else {
  10069. if (dataLen > 0) {
  10070. retval = mg_write(conn, data, dataLen);
  10071. }
  10072. /* if dataLen == 0, the header length (2) is returned */
  10073. }
  10074. /* TODO: Remove this unlock as well, when lock is removed. */
  10075. mg_unlock_connection(conn);
  10076. return retval;
  10077. }
  10078. int
  10079. mg_websocket_write(struct mg_connection *conn,
  10080. int opcode,
  10081. const char *data,
  10082. size_t dataLen)
  10083. {
  10084. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10085. }
  10086. static void
  10087. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10088. {
  10089. size_t i = 0;
  10090. i = 0;
  10091. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10092. /* Convert in 32 bit words, if data is 4 byte aligned */
  10093. while (i < (in_len - 3)) {
  10094. *(uint32_t *)(void *)(out + i) =
  10095. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10096. i += 4;
  10097. }
  10098. }
  10099. if (i != in_len) {
  10100. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10101. while (i < in_len) {
  10102. *(uint8_t *)(void *)(out + i) =
  10103. *(uint8_t *)(void *)(in + i)
  10104. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10105. i++;
  10106. }
  10107. }
  10108. }
  10109. int
  10110. mg_websocket_client_write(struct mg_connection *conn,
  10111. int opcode,
  10112. const char *data,
  10113. size_t dataLen)
  10114. {
  10115. int retval = -1;
  10116. char *masked_data =
  10117. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10118. uint32_t masking_key = 0;
  10119. if (masked_data == NULL) {
  10120. /* Return -1 in an error case */
  10121. mg_cry_internal(conn,
  10122. "%s",
  10123. "Cannot allocate buffer for masked websocket response: "
  10124. "Out of memory");
  10125. return -1;
  10126. }
  10127. do {
  10128. /* Get a masking key - but not 0 */
  10129. masking_key = (uint32_t)get_random();
  10130. } while (masking_key == 0);
  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://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  12610. * https://linux.die.net/man/3/ssl_set_info_callback */
  12611. /* Note: There is no "const" for the first argument in the documentation,
  12612. * however some (maybe most, but not all) headers of OpenSSL versions /
  12613. * OpenSSL compatibility layers have it. Having a different definition
  12614. * will cause a warning in C and an error in C++. With inconsitent
  12615. * definitions of this function, having a warning in one version or
  12616. * another is unavoidable. */
  12617. static void
  12618. ssl_info_callback(SSL *ssl, int what, int ret)
  12619. {
  12620. (void)ret;
  12621. if (what & SSL_CB_HANDSHAKE_START) {
  12622. SSL_get_app_data(ssl);
  12623. }
  12624. if (what & SSL_CB_HANDSHAKE_DONE) {
  12625. /* TODO: check for openSSL 1.1 */
  12626. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  12627. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  12628. }
  12629. }
  12630. static int
  12631. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  12632. {
  12633. struct mg_context *ctx = (struct mg_context *)arg;
  12634. struct mg_domain_context *dom =
  12635. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  12636. #if defined(__GNUC__) || defined(__MINGW32__)
  12637. #pragma GCC diagnostic push
  12638. #pragma GCC diagnostic ignored "-Wcast-align"
  12639. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  12640. /* We used an aligned pointer in SSL_set_app_data */
  12641. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  12642. #if defined(__GNUC__) || defined(__MINGW32__)
  12643. #pragma GCC diagnostic pop
  12644. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  12645. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  12646. (void)ad;
  12647. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  12648. DEBUG_TRACE("%s", "internal error - assertion failed");
  12649. return SSL_TLSEXT_ERR_NOACK;
  12650. }
  12651. /* Old clients (Win XP) will not support SNI. Then, there
  12652. * is no server name available in the request - we can
  12653. * only work with the default certificate.
  12654. * Multiple HTTPS hosts on one IP+port are only possible
  12655. * with a certificate containing all alternative names.
  12656. */
  12657. if ((servername == NULL) || (*servername == 0)) {
  12658. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  12659. conn->dom_ctx = &(ctx->dd);
  12660. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  12661. return SSL_TLSEXT_ERR_NOACK;
  12662. }
  12663. DEBUG_TRACE("TLS connection to host %s", servername);
  12664. while (dom) {
  12665. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  12666. /* Found matching domain */
  12667. DEBUG_TRACE("TLS domain %s found",
  12668. dom->config[AUTHENTICATION_DOMAIN]);
  12669. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  12670. conn->dom_ctx = dom;
  12671. return SSL_TLSEXT_ERR_OK;
  12672. }
  12673. dom = dom->next;
  12674. }
  12675. /* Default domain */
  12676. DEBUG_TRACE("TLS default domain %s used",
  12677. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  12678. conn->dom_ctx = &(ctx->dd);
  12679. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  12680. return SSL_TLSEXT_ERR_OK;
  12681. }
  12682. /* Setup SSL CTX as required by CivetWeb */
  12683. static int
  12684. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  12685. struct mg_domain_context *dom_ctx,
  12686. const char *pem,
  12687. const char *chain)
  12688. {
  12689. int callback_ret;
  12690. int should_verify_peer;
  12691. int peer_certificate_optional;
  12692. const char *ca_path;
  12693. const char *ca_file;
  12694. int use_default_verify_paths;
  12695. int verify_depth;
  12696. time_t now_rt = time(NULL);
  12697. struct timespec now_mt;
  12698. md5_byte_t ssl_context_id[16];
  12699. md5_state_t md5state;
  12700. int protocol_ver;
  12701. #ifdef OPENSSL_API_1_1
  12702. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_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. #else
  12709. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  12710. mg_cry_internal(fc(phys_ctx),
  12711. "SSL_CTX_new (server) error: %s",
  12712. ssl_error());
  12713. return 0;
  12714. }
  12715. #endif /* OPENSSL_API_1_1 */
  12716. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  12717. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  12718. | SSL_OP_NO_TLSv1_1);
  12719. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  12720. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  12721. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  12722. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  12723. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  12724. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12725. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  12726. #if !defined(NO_SSL_DL)
  12727. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  12728. #endif /* NO_SSL_DL */
  12729. #ifdef __clang__
  12730. #pragma clang diagnostic push
  12731. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  12732. #endif
  12733. /* Depending on the OpenSSL version, the callback may be
  12734. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  12735. * yielding in an "incompatible-pointer-type" warning for the other
  12736. * version. It seems to be "unclear" what is correct:
  12737. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  12738. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  12739. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  12740. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  12741. * Disable this warning here.
  12742. * Alternative would be a version dependent ssl_info_callback and
  12743. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  12744. */
  12745. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  12746. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  12747. ssl_servername_callback);
  12748. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  12749. #ifdef __clang__
  12750. #pragma clang diagnostic pop
  12751. #endif
  12752. /* If a callback has been specified, call it. */
  12753. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  12754. ? 0
  12755. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  12756. phys_ctx->user_data));
  12757. /* If callback returns 0, civetweb sets up the SSL certificate.
  12758. * If it returns 1, civetweb assumes the calback already did this.
  12759. * If it returns -1, initializing ssl fails. */
  12760. if (callback_ret < 0) {
  12761. mg_cry_internal(fc(phys_ctx),
  12762. "SSL callback returned error: %i",
  12763. callback_ret);
  12764. return 0;
  12765. }
  12766. if (callback_ret > 0) {
  12767. /* Callback did everything. */
  12768. return 1;
  12769. }
  12770. /* Use some UID as session context ID. */
  12771. md5_init(&md5state);
  12772. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  12773. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  12774. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  12775. md5_append(&md5state,
  12776. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  12777. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  12778. md5_append(&md5state,
  12779. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  12780. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  12781. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  12782. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  12783. md5_finish(&md5state, ssl_context_id);
  12784. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  12785. (const unsigned char *)&ssl_context_id,
  12786. sizeof(ssl_context_id));
  12787. if (pem != NULL) {
  12788. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  12789. return 0;
  12790. }
  12791. }
  12792. /* Should we support client certificates? */
  12793. /* Default is "no". */
  12794. should_verify_peer = 0;
  12795. peer_certificate_optional = 0;
  12796. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12797. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  12798. /* Yes, they are mandatory */
  12799. should_verify_peer = 1;
  12800. peer_certificate_optional = 0;
  12801. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  12802. "optional") == 0) {
  12803. /* Yes, they are optional */
  12804. should_verify_peer = 1;
  12805. peer_certificate_optional = 1;
  12806. }
  12807. }
  12808. use_default_verify_paths =
  12809. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  12810. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  12811. == 0);
  12812. if (should_verify_peer) {
  12813. ca_path = dom_ctx->config[SSL_CA_PATH];
  12814. ca_file = dom_ctx->config[SSL_CA_FILE];
  12815. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  12816. != 1) {
  12817. mg_cry_internal(fc(phys_ctx),
  12818. "SSL_CTX_load_verify_locations error: %s "
  12819. "ssl_verify_peer requires setting "
  12820. "either ssl_ca_path or ssl_ca_file. "
  12821. "Is any of them present in the "
  12822. ".conf file?",
  12823. ssl_error());
  12824. return 0;
  12825. }
  12826. if (peer_certificate_optional) {
  12827. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  12828. } else {
  12829. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  12830. SSL_VERIFY_PEER
  12831. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  12832. NULL);
  12833. }
  12834. if (use_default_verify_paths
  12835. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  12836. mg_cry_internal(fc(phys_ctx),
  12837. "SSL_CTX_set_default_verify_paths error: %s",
  12838. ssl_error());
  12839. return 0;
  12840. }
  12841. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  12842. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  12843. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  12844. }
  12845. }
  12846. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  12847. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  12848. dom_ctx->config[SSL_CIPHER_LIST]) != 1) {
  12849. mg_cry_internal(fc(phys_ctx),
  12850. "SSL_CTX_set_cipher_list error: %s",
  12851. ssl_error());
  12852. }
  12853. }
  12854. return 1;
  12855. }
  12856. /* Check if SSL is required.
  12857. * If so, dynamically load SSL library
  12858. * and set up ctx->ssl_ctx pointer. */
  12859. static int
  12860. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  12861. {
  12862. void *ssl_ctx = 0;
  12863. int callback_ret;
  12864. const char *pem;
  12865. const char *chain;
  12866. char ebuf[128];
  12867. if (!phys_ctx) {
  12868. return 0;
  12869. }
  12870. if (!dom_ctx) {
  12871. dom_ctx = &(phys_ctx->dd);
  12872. }
  12873. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  12874. /* No SSL port is set. No need to setup SSL. */
  12875. return 1;
  12876. }
  12877. /* Check for external SSL_CTX */
  12878. callback_ret =
  12879. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  12880. ? 0
  12881. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  12882. phys_ctx->user_data));
  12883. if (callback_ret < 0) {
  12884. mg_cry_internal(fc(phys_ctx),
  12885. "external_ssl_ctx callback returned error: %i",
  12886. callback_ret);
  12887. return 0;
  12888. } else if (callback_ret > 0) {
  12889. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  12890. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12891. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  12892. return 0;
  12893. }
  12894. return 1;
  12895. }
  12896. /* else: external_ssl_ctx does not exist or returns 0,
  12897. * CivetWeb should continue initializing SSL */
  12898. /* If PEM file is not specified and the init_ssl callback
  12899. * is not specified, setup will fail. */
  12900. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  12901. && (phys_ctx->callbacks.init_ssl == NULL)) {
  12902. /* No certificate and no callback:
  12903. * Essential data to set up TLS is missing.
  12904. */
  12905. mg_cry_internal(fc(phys_ctx),
  12906. "Initializing SSL failed: -%s is not set",
  12907. config_options[SSL_CERTIFICATE].name);
  12908. return 0;
  12909. }
  12910. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12911. if (chain == NULL) {
  12912. chain = pem;
  12913. }
  12914. if ((chain != NULL) && (*chain == 0)) {
  12915. chain = NULL;
  12916. }
  12917. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12918. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  12919. return 0;
  12920. }
  12921. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  12922. }
  12923. static void
  12924. uninitialize_ssl(void)
  12925. {
  12926. #ifdef OPENSSL_API_1_1
  12927. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12928. /* Shutdown according to
  12929. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12930. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12931. */
  12932. CONF_modules_unload(1);
  12933. #else
  12934. int i;
  12935. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12936. /* Shutdown according to
  12937. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12938. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12939. */
  12940. CRYPTO_set_locking_callback(NULL);
  12941. CRYPTO_set_id_callback(NULL);
  12942. ENGINE_cleanup();
  12943. CONF_modules_unload(1);
  12944. ERR_free_strings();
  12945. EVP_cleanup();
  12946. CRYPTO_cleanup_all_ex_data();
  12947. ERR_remove_state(0);
  12948. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12949. pthread_mutex_destroy(&ssl_mutexes[i]);
  12950. }
  12951. mg_free(ssl_mutexes);
  12952. ssl_mutexes = NULL;
  12953. #endif /* OPENSSL_API_1_1 */
  12954. }
  12955. }
  12956. #endif /* !NO_SSL */
  12957. static int
  12958. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  12959. {
  12960. if (phys_ctx) {
  12961. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12962. const char *path;
  12963. if (!dom_ctx) {
  12964. dom_ctx = &(phys_ctx->dd);
  12965. }
  12966. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  12967. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  12968. mg_cry_internal(fc(phys_ctx),
  12969. "Cannot open %s: %s",
  12970. path,
  12971. strerror(ERRNO));
  12972. return 0;
  12973. }
  12974. return 1;
  12975. }
  12976. return 0;
  12977. }
  12978. static int
  12979. set_acl_option(struct mg_context *phys_ctx)
  12980. {
  12981. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  12982. }
  12983. static void
  12984. reset_per_request_attributes(struct mg_connection *conn)
  12985. {
  12986. if (!conn) {
  12987. return;
  12988. }
  12989. conn->connection_type =
  12990. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  12991. conn->num_bytes_sent = conn->consumed_content = 0;
  12992. conn->path_info = NULL;
  12993. conn->status_code = -1;
  12994. conn->content_len = -1;
  12995. conn->is_chunked = 0;
  12996. conn->must_close = 0;
  12997. conn->request_len = 0;
  12998. conn->throttle = 0;
  12999. conn->data_len = 0;
  13000. conn->chunk_remainder = 0;
  13001. conn->accept_gzip = 0;
  13002. conn->response_info.content_length = conn->request_info.content_length = -1;
  13003. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13004. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13005. conn->response_info.status_text = NULL;
  13006. conn->response_info.status_code = 0;
  13007. conn->request_info.remote_user = NULL;
  13008. conn->request_info.request_method = NULL;
  13009. conn->request_info.request_uri = NULL;
  13010. conn->request_info.local_uri = NULL;
  13011. #if defined(MG_LEGACY_INTERFACE)
  13012. /* Legacy before split into local_uri and request_uri */
  13013. conn->request_info.uri = NULL;
  13014. #endif
  13015. }
  13016. #if 0
  13017. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13018. * Leave this function here (commented out) for reference until
  13019. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13020. * no longer required.
  13021. */
  13022. static int
  13023. set_sock_timeout(SOCKET sock, int milliseconds)
  13024. {
  13025. int r0 = 0, r1, r2;
  13026. #ifdef _WIN32
  13027. /* Windows specific */
  13028. DWORD tv = (DWORD)milliseconds;
  13029. #else
  13030. /* Linux, ... (not Windows) */
  13031. struct timeval tv;
  13032. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13033. * max. time waiting for the acknowledged of TCP data before the connection
  13034. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13035. * If this option is not set, the default timeout of 20-30 minutes is used.
  13036. */
  13037. /* #define TCP_USER_TIMEOUT (18) */
  13038. #if defined(TCP_USER_TIMEOUT)
  13039. unsigned int uto = (unsigned int)milliseconds;
  13040. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13041. #endif
  13042. memset(&tv, 0, sizeof(tv));
  13043. tv.tv_sec = milliseconds / 1000;
  13044. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13045. #endif /* _WIN32 */
  13046. r1 = setsockopt(
  13047. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13048. r2 = setsockopt(
  13049. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13050. return r0 || r1 || r2;
  13051. }
  13052. #endif
  13053. static int
  13054. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13055. {
  13056. if (setsockopt(sock,
  13057. IPPROTO_TCP,
  13058. TCP_NODELAY,
  13059. (SOCK_OPT_TYPE)&nodelay_on,
  13060. sizeof(nodelay_on)) != 0) {
  13061. /* Error */
  13062. return 1;
  13063. }
  13064. /* OK */
  13065. return 0;
  13066. }
  13067. static void
  13068. close_socket_gracefully(struct mg_connection *conn)
  13069. {
  13070. #if defined(_WIN32)
  13071. char buf[MG_BUF_LEN];
  13072. int n;
  13073. #endif
  13074. struct linger linger;
  13075. int error_code = 0;
  13076. int linger_timeout = -2;
  13077. socklen_t opt_len = sizeof(error_code);
  13078. if (!conn) {
  13079. return;
  13080. }
  13081. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13082. * "Note that enabling a nonzero timeout on a nonblocking socket
  13083. * is not recommended.", so set it to blocking now */
  13084. set_blocking_mode(conn->client.sock);
  13085. /* Send FIN to the client */
  13086. shutdown(conn->client.sock, SHUTDOWN_WR);
  13087. #if defined(_WIN32)
  13088. /* Read and discard pending incoming data. If we do not do that and
  13089. * close
  13090. * the socket, the data in the send buffer may be discarded. This
  13091. * behaviour is seen on Windows, when client keeps sending data
  13092. * when server decides to close the connection; then when client
  13093. * does recv() it gets no data back. */
  13094. do {
  13095. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13096. } while (n > 0);
  13097. #endif
  13098. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13099. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13100. }
  13101. /* Set linger option according to configuration */
  13102. if (linger_timeout >= 0) {
  13103. /* Set linger option to avoid socket hanging out after close. This
  13104. * prevent ephemeral port exhaust problem under high QPS. */
  13105. linger.l_onoff = 1;
  13106. #if defined(_MSC_VER)
  13107. #pragma warning(push)
  13108. #pragma warning(disable : 4244)
  13109. #endif
  13110. #if defined(__GNUC__) || defined(__MINGW32__)
  13111. #pragma GCC diagnostic push
  13112. #pragma GCC diagnostic ignored "-Wconversion"
  13113. #endif
  13114. /* Data type of linger structure elements may differ,
  13115. * so we don't know what cast we need here.
  13116. * Disable type conversion warnings. */
  13117. linger.l_linger = (linger_timeout + 999) / 1000;
  13118. #if defined(__GNUC__) || defined(__MINGW32__)
  13119. #pragma GCC diagnostic pop
  13120. #endif
  13121. #if defined(_MSC_VER)
  13122. #pragma warning(pop)
  13123. #endif
  13124. } else {
  13125. linger.l_onoff = 0;
  13126. linger.l_linger = 0;
  13127. }
  13128. if (linger_timeout < -1) {
  13129. /* Default: don't configure any linger */
  13130. } else if (getsockopt(conn->client.sock,
  13131. SOL_SOCKET,
  13132. SO_ERROR,
  13133. (char *)&error_code,
  13134. &opt_len) != 0) {
  13135. /* Cannot determine if socket is already closed. This should
  13136. * not occur and never did in a test. Log an error message
  13137. * and continue. */
  13138. mg_cry_internal(conn,
  13139. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13140. __func__,
  13141. strerror(ERRNO));
  13142. } else if (error_code == ECONNRESET) {
  13143. /* Socket already closed by client/peer, close socket without linger
  13144. */
  13145. } else {
  13146. /* Set linger timeout */
  13147. if (setsockopt(conn->client.sock,
  13148. SOL_SOCKET,
  13149. SO_LINGER,
  13150. (char *)&linger,
  13151. sizeof(linger)) != 0) {
  13152. mg_cry_internal(
  13153. conn,
  13154. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  13155. __func__,
  13156. linger.l_onoff,
  13157. linger.l_linger,
  13158. strerror(ERRNO));
  13159. }
  13160. }
  13161. /* Now we know that our FIN is ACK-ed, safe to close */
  13162. closesocket(conn->client.sock);
  13163. conn->client.sock = INVALID_SOCKET;
  13164. }
  13165. static void
  13166. close_connection(struct mg_connection *conn)
  13167. {
  13168. #if defined(USE_SERVER_STATS)
  13169. conn->conn_state = 6; /* to close */
  13170. #endif
  13171. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13172. if (conn->lua_websocket_state) {
  13173. lua_websocket_close(conn, conn->lua_websocket_state);
  13174. conn->lua_websocket_state = NULL;
  13175. }
  13176. #endif
  13177. mg_lock_connection(conn);
  13178. /* Set close flag, so keep-alive loops will stop */
  13179. conn->must_close = 1;
  13180. /* call the connection_close callback if assigned */
  13181. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  13182. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13183. conn->phys_ctx->callbacks.connection_close(conn);
  13184. }
  13185. }
  13186. /* Reset user data, after close callback is called.
  13187. * Do not reuse it. If the user needs a destructor,
  13188. * it must be done in the connection_close callback. */
  13189. mg_set_user_connection_data(conn, NULL);
  13190. #if defined(USE_SERVER_STATS)
  13191. conn->conn_state = 7; /* closing */
  13192. #endif
  13193. #ifndef NO_SSL
  13194. if (conn->ssl != NULL) {
  13195. /* Run SSL_shutdown twice to ensure completely close SSL connection
  13196. */
  13197. SSL_shutdown(conn->ssl);
  13198. SSL_free(conn->ssl);
  13199. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  13200. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  13201. #ifndef OPENSSL_API_1_1
  13202. ERR_remove_state(0);
  13203. #endif
  13204. conn->ssl = NULL;
  13205. }
  13206. #endif
  13207. if (conn->client.sock != INVALID_SOCKET) {
  13208. close_socket_gracefully(conn);
  13209. conn->client.sock = INVALID_SOCKET;
  13210. }
  13211. if (conn->host) {
  13212. mg_free((void *)conn->host);
  13213. conn->host = NULL;
  13214. }
  13215. mg_unlock_connection(conn);
  13216. #if defined(USE_SERVER_STATS)
  13217. conn->conn_state = 8; /* closed */
  13218. #endif
  13219. }
  13220. void
  13221. mg_close_connection(struct mg_connection *conn)
  13222. {
  13223. #if defined(USE_WEBSOCKET)
  13224. struct mg_context *client_ctx = NULL;
  13225. #endif /* defined(USE_WEBSOCKET) */
  13226. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13227. return;
  13228. }
  13229. #if defined(USE_WEBSOCKET)
  13230. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13231. if (conn->in_websocket_handling) {
  13232. /* Set close flag, so the server thread can exit. */
  13233. conn->must_close = 1;
  13234. return;
  13235. }
  13236. }
  13237. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  13238. unsigned int i;
  13239. /* ws/wss client */
  13240. client_ctx = conn->phys_ctx;
  13241. /* client context: loops must end */
  13242. client_ctx->stop_flag = 1;
  13243. conn->must_close = 1;
  13244. /* We need to get the client thread out of the select/recv call
  13245. * here. */
  13246. /* Since we use a sleep quantum of some seconds to check for recv
  13247. * timeouts, we will just wait a few seconds in mg_join_thread. */
  13248. /* join worker thread */
  13249. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  13250. if (client_ctx->worker_threadids[i] != 0) {
  13251. mg_join_thread(client_ctx->worker_threadids[i]);
  13252. }
  13253. }
  13254. }
  13255. #endif /* defined(USE_WEBSOCKET) */
  13256. close_connection(conn);
  13257. #ifndef NO_SSL
  13258. if (conn->client_ssl_ctx != NULL) {
  13259. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  13260. }
  13261. #endif
  13262. #if defined(USE_WEBSOCKET)
  13263. if (client_ctx != NULL) {
  13264. /* free context */
  13265. mg_free(client_ctx->worker_threadids);
  13266. mg_free(client_ctx);
  13267. (void)pthread_mutex_destroy(&conn->mutex);
  13268. mg_free(conn);
  13269. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  13270. mg_free(conn);
  13271. }
  13272. #else
  13273. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  13274. mg_free(conn);
  13275. }
  13276. #endif /* defined(USE_WEBSOCKET) */
  13277. }
  13278. /* Only for memory statistics */
  13279. static struct mg_context common_client_context;
  13280. static struct mg_connection *
  13281. mg_connect_client_impl(const struct mg_client_options *client_options,
  13282. int use_ssl,
  13283. char *ebuf,
  13284. size_t ebuf_len)
  13285. {
  13286. struct mg_connection *conn = NULL;
  13287. SOCKET sock;
  13288. union usa sa;
  13289. struct sockaddr *psa;
  13290. socklen_t len;
  13291. unsigned max_req_size =
  13292. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  13293. /* Size of structures, aligned to 8 bytes */
  13294. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  13295. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  13296. conn = (struct mg_connection *)mg_calloc_ctx(1,
  13297. conn_size + ctx_size
  13298. + max_req_size,
  13299. &common_client_context);
  13300. if (conn == NULL) {
  13301. mg_snprintf(NULL,
  13302. NULL, /* No truncation check for ebuf */
  13303. ebuf,
  13304. ebuf_len,
  13305. "calloc(): %s",
  13306. strerror(ERRNO));
  13307. return NULL;
  13308. }
  13309. #if defined(__GNUC__) || defined(__MINGW32__)
  13310. #pragma GCC diagnostic push
  13311. #pragma GCC diagnostic ignored "-Wcast-align"
  13312. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13313. /* conn_size is aligned to 8 bytes */
  13314. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  13315. #if defined(__GNUC__) || defined(__MINGW32__)
  13316. #pragma GCC diagnostic pop
  13317. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13318. conn->buf = (((char *)conn) + conn_size + ctx_size);
  13319. conn->buf_size = (int)max_req_size;
  13320. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  13321. conn->dom_ctx = &(conn->phys_ctx->dd);
  13322. if (!connect_socket(&common_client_context,
  13323. client_options->host,
  13324. client_options->port,
  13325. use_ssl,
  13326. ebuf,
  13327. ebuf_len,
  13328. &sock,
  13329. &sa)) {
  13330. /* ebuf is set by connect_socket,
  13331. * free all memory and return NULL; */
  13332. mg_free(conn);
  13333. return NULL;
  13334. }
  13335. #ifndef NO_SSL
  13336. #ifdef OPENSSL_API_1_1
  13337. if (use_ssl
  13338. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  13339. mg_snprintf(NULL,
  13340. NULL, /* No truncation check for ebuf */
  13341. ebuf,
  13342. ebuf_len,
  13343. "SSL_CTX_new error");
  13344. closesocket(sock);
  13345. mg_free(conn);
  13346. return NULL;
  13347. }
  13348. #else
  13349. if (use_ssl
  13350. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  13351. == NULL) {
  13352. mg_snprintf(NULL,
  13353. NULL, /* No truncation check for ebuf */
  13354. ebuf,
  13355. ebuf_len,
  13356. "SSL_CTX_new error");
  13357. closesocket(sock);
  13358. mg_free(conn);
  13359. return NULL;
  13360. }
  13361. #endif /* OPENSSL_API_1_1 */
  13362. #endif /* NO_SSL */
  13363. #ifdef USE_IPV6
  13364. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  13365. : sizeof(conn->client.rsa.sin6);
  13366. psa = (sa.sa.sa_family == AF_INET)
  13367. ? (struct sockaddr *)&(conn->client.rsa.sin)
  13368. : (struct sockaddr *)&(conn->client.rsa.sin6);
  13369. #else
  13370. len = sizeof(conn->client.rsa.sin);
  13371. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  13372. #endif
  13373. conn->client.sock = sock;
  13374. conn->client.lsa = sa;
  13375. if (getsockname(sock, psa, &len) != 0) {
  13376. mg_cry_internal(conn,
  13377. "%s: getsockname() failed: %s",
  13378. __func__,
  13379. strerror(ERRNO));
  13380. }
  13381. conn->client.is_ssl = use_ssl ? 1 : 0;
  13382. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13383. #ifndef NO_SSL
  13384. if (use_ssl) {
  13385. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  13386. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  13387. * SSL_CTX_set_verify call is needed to switch off server
  13388. * certificate checking, which is off by default in OpenSSL and
  13389. * on in yaSSL. */
  13390. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  13391. * SSL_VERIFY_PEER, verify_ssl_server); */
  13392. if (client_options->client_cert) {
  13393. if (!ssl_use_pem_file(&common_client_context,
  13394. &(common_client_context.dd),
  13395. client_options->client_cert,
  13396. NULL)) {
  13397. mg_snprintf(NULL,
  13398. NULL, /* No truncation check for ebuf */
  13399. ebuf,
  13400. ebuf_len,
  13401. "Can not use SSL client certificate");
  13402. SSL_CTX_free(conn->client_ssl_ctx);
  13403. closesocket(sock);
  13404. mg_free(conn);
  13405. return NULL;
  13406. }
  13407. }
  13408. if (client_options->server_cert) {
  13409. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  13410. client_options->server_cert,
  13411. NULL);
  13412. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  13413. } else {
  13414. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  13415. }
  13416. if (!sslize(conn,
  13417. conn->client_ssl_ctx,
  13418. SSL_connect,
  13419. &(conn->phys_ctx->stop_flag))) {
  13420. mg_snprintf(NULL,
  13421. NULL, /* No truncation check for ebuf */
  13422. ebuf,
  13423. ebuf_len,
  13424. "SSL connection error");
  13425. SSL_CTX_free(conn->client_ssl_ctx);
  13426. closesocket(sock);
  13427. mg_free(conn);
  13428. return NULL;
  13429. }
  13430. }
  13431. #endif
  13432. if (0 != set_non_blocking_mode(sock)) {
  13433. /* TODO: handle error */
  13434. ;
  13435. }
  13436. return conn;
  13437. }
  13438. CIVETWEB_API struct mg_connection *
  13439. mg_connect_client_secure(const struct mg_client_options *client_options,
  13440. char *error_buffer,
  13441. size_t error_buffer_size)
  13442. {
  13443. return mg_connect_client_impl(client_options,
  13444. 1,
  13445. error_buffer,
  13446. error_buffer_size);
  13447. }
  13448. struct mg_connection *
  13449. mg_connect_client(const char *host,
  13450. int port,
  13451. int use_ssl,
  13452. char *error_buffer,
  13453. size_t error_buffer_size)
  13454. {
  13455. struct mg_client_options opts;
  13456. memset(&opts, 0, sizeof(opts));
  13457. opts.host = host;
  13458. opts.port = port;
  13459. return mg_connect_client_impl(&opts,
  13460. use_ssl,
  13461. error_buffer,
  13462. error_buffer_size);
  13463. }
  13464. static const struct {
  13465. const char *proto;
  13466. size_t proto_len;
  13467. unsigned default_port;
  13468. } abs_uri_protocols[] = {{"http://", 7, 80},
  13469. {"https://", 8, 443},
  13470. {"ws://", 5, 80},
  13471. {"wss://", 6, 443},
  13472. {NULL, 0, 0}};
  13473. /* Check if the uri is valid.
  13474. * return 0 for invalid uri,
  13475. * return 1 for *,
  13476. * return 2 for relative uri,
  13477. * return 3 for absolute uri without port,
  13478. * return 4 for absolute uri with port */
  13479. static int
  13480. get_uri_type(const char *uri)
  13481. {
  13482. int i;
  13483. const char *hostend, *portbegin;
  13484. char *portend;
  13485. unsigned long port;
  13486. /* According to the HTTP standard
  13487. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  13488. * URI can be an asterisk (*) or should start with slash (relative uri),
  13489. * or it should start with the protocol (absolute uri). */
  13490. if ((uri[0] == '*') && (uri[1] == '\0')) {
  13491. /* asterisk */
  13492. return 1;
  13493. }
  13494. /* Valid URIs according to RFC 3986
  13495. * (https://www.ietf.org/rfc/rfc3986.txt)
  13496. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  13497. * and unreserved characters A-Z a-z 0-9 and -._~
  13498. * and % encoded symbols.
  13499. */
  13500. for (i = 0; uri[i] != 0; i++) {
  13501. if (uri[i] < 33) {
  13502. /* control characters and spaces are invalid */
  13503. return 0;
  13504. }
  13505. if (uri[i] > 126) {
  13506. /* non-ascii characters must be % encoded */
  13507. return 0;
  13508. } else {
  13509. switch (uri[i]) {
  13510. case '"': /* 34 */
  13511. case '<': /* 60 */
  13512. case '>': /* 62 */
  13513. case '\\': /* 92 */
  13514. case '^': /* 94 */
  13515. case '`': /* 96 */
  13516. case '{': /* 123 */
  13517. case '|': /* 124 */
  13518. case '}': /* 125 */
  13519. return 0;
  13520. default:
  13521. /* character is ok */
  13522. break;
  13523. }
  13524. }
  13525. }
  13526. /* A relative uri starts with a / character */
  13527. if (uri[0] == '/') {
  13528. /* relative uri */
  13529. return 2;
  13530. }
  13531. /* It could be an absolute uri: */
  13532. /* This function only checks if the uri is valid, not if it is
  13533. * addressing the current server. So civetweb can also be used
  13534. * as a proxy server. */
  13535. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13536. if (mg_strncasecmp(uri,
  13537. abs_uri_protocols[i].proto,
  13538. abs_uri_protocols[i].proto_len) == 0) {
  13539. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  13540. if (!hostend) {
  13541. return 0;
  13542. }
  13543. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  13544. if (!portbegin) {
  13545. return 3;
  13546. }
  13547. port = strtoul(portbegin + 1, &portend, 10);
  13548. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  13549. return 0;
  13550. }
  13551. return 4;
  13552. }
  13553. }
  13554. return 0;
  13555. }
  13556. /* Return NULL or the relative uri at the current server */
  13557. static const char *
  13558. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  13559. {
  13560. const char *server_domain;
  13561. size_t server_domain_len;
  13562. size_t request_domain_len = 0;
  13563. unsigned long port = 0;
  13564. int i, auth_domain_check_enabled;
  13565. const char *hostbegin = NULL;
  13566. const char *hostend = NULL;
  13567. const char *portbegin;
  13568. char *portend;
  13569. auth_domain_check_enabled =
  13570. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  13571. /* DNS is case insensitive, so use case insensitive string compare here
  13572. */
  13573. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13574. if (mg_strncasecmp(uri,
  13575. abs_uri_protocols[i].proto,
  13576. abs_uri_protocols[i].proto_len) == 0) {
  13577. hostbegin = uri + abs_uri_protocols[i].proto_len;
  13578. hostend = strchr(hostbegin, '/');
  13579. if (!hostend) {
  13580. return 0;
  13581. }
  13582. portbegin = strchr(hostbegin, ':');
  13583. if ((!portbegin) || (portbegin > hostend)) {
  13584. port = abs_uri_protocols[i].default_port;
  13585. request_domain_len = (size_t)(hostend - hostbegin);
  13586. } else {
  13587. port = strtoul(portbegin + 1, &portend, 10);
  13588. if ((portend != hostend) || (port <= 0)
  13589. || !is_valid_port(port)) {
  13590. return 0;
  13591. }
  13592. request_domain_len = (size_t)(portbegin - hostbegin);
  13593. }
  13594. /* protocol found, port set */
  13595. break;
  13596. }
  13597. }
  13598. if (!port) {
  13599. /* port remains 0 if the protocol is not found */
  13600. return 0;
  13601. }
  13602. /* Check if the request is directed to a different server. */
  13603. /* First check if the port is the same (IPv4 and IPv6). */
  13604. #if defined(USE_IPV6)
  13605. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  13606. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  13607. /* Request is directed to a different port */
  13608. return 0;
  13609. }
  13610. } else
  13611. #endif
  13612. {
  13613. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  13614. /* Request is directed to a different port */
  13615. return 0;
  13616. }
  13617. }
  13618. /* Finally check if the server corresponds to the authentication
  13619. * domain of the server (the server domain).
  13620. * Allow full matches (like http://mydomain.com/path/file.ext), and
  13621. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  13622. * but do not allow substrings (like
  13623. * http://notmydomain.com/path/file.ext
  13624. * or http://mydomain.com.fake/path/file.ext).
  13625. */
  13626. if (auth_domain_check_enabled) {
  13627. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  13628. server_domain_len = strlen(server_domain);
  13629. if (!server_domain_len) {
  13630. return 0;
  13631. }
  13632. if ((request_domain_len == server_domain_len)
  13633. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  13634. /* Request is directed to this server - full name match. */
  13635. } else {
  13636. if (request_domain_len < (server_domain_len + 2)) {
  13637. /* Request is directed to another server: The server name is
  13638. * longer
  13639. * than
  13640. * the request name. Drop this case here to avoid overflows
  13641. * in
  13642. * the
  13643. * following checks. */
  13644. return 0;
  13645. }
  13646. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  13647. /* Request is directed to another server: It could be a
  13648. * substring
  13649. * like notmyserver.com */
  13650. return 0;
  13651. }
  13652. if (0 != memcmp(server_domain,
  13653. hostbegin + request_domain_len - server_domain_len,
  13654. server_domain_len)) {
  13655. /* Request is directed to another server:
  13656. * The server name is different. */
  13657. return 0;
  13658. }
  13659. }
  13660. }
  13661. return hostend;
  13662. }
  13663. static int
  13664. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13665. {
  13666. if (ebuf_len > 0) {
  13667. ebuf[0] = '\0';
  13668. }
  13669. *err = 0;
  13670. reset_per_request_attributes(conn);
  13671. if (!conn) {
  13672. mg_snprintf(conn,
  13673. NULL, /* No truncation check for ebuf */
  13674. ebuf,
  13675. ebuf_len,
  13676. "%s",
  13677. "Internal error");
  13678. *err = 500;
  13679. return 0;
  13680. }
  13681. /* Set the time the request was received. This value should be used for
  13682. * timeouts. */
  13683. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  13684. conn->request_len =
  13685. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  13686. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  13687. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  13688. mg_snprintf(conn,
  13689. NULL, /* No truncation check for ebuf */
  13690. ebuf,
  13691. ebuf_len,
  13692. "%s",
  13693. "Invalid message size");
  13694. *err = 500;
  13695. return 0;
  13696. }
  13697. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  13698. mg_snprintf(conn,
  13699. NULL, /* No truncation check for ebuf */
  13700. ebuf,
  13701. ebuf_len,
  13702. "%s",
  13703. "Message too large");
  13704. *err = 413;
  13705. return 0;
  13706. }
  13707. if (conn->request_len <= 0) {
  13708. if (conn->data_len > 0) {
  13709. mg_snprintf(conn,
  13710. NULL, /* No truncation check for ebuf */
  13711. ebuf,
  13712. ebuf_len,
  13713. "%s",
  13714. "Malformed message");
  13715. *err = 400;
  13716. } else {
  13717. /* Server did not recv anything -> just close the connection */
  13718. conn->must_close = 1;
  13719. mg_snprintf(conn,
  13720. NULL, /* No truncation check for ebuf */
  13721. ebuf,
  13722. ebuf_len,
  13723. "%s",
  13724. "No data received");
  13725. *err = 0;
  13726. }
  13727. return 0;
  13728. }
  13729. return 1;
  13730. }
  13731. static int
  13732. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13733. {
  13734. const char *cl;
  13735. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13736. return 0;
  13737. }
  13738. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  13739. <= 0) {
  13740. mg_snprintf(conn,
  13741. NULL, /* No truncation check for ebuf */
  13742. ebuf,
  13743. ebuf_len,
  13744. "%s",
  13745. "Bad request");
  13746. *err = 400;
  13747. return 0;
  13748. }
  13749. /* Message is a valid request */
  13750. /* Is there a "host" ? */
  13751. conn->host = alloc_get_host(conn);
  13752. if (!conn->host) {
  13753. mg_snprintf(conn,
  13754. NULL, /* No truncation check for ebuf */
  13755. ebuf,
  13756. ebuf_len,
  13757. "%s",
  13758. "Bad request: Host mismatch");
  13759. *err = 400;
  13760. return 0;
  13761. }
  13762. /* Do we know the content length? */
  13763. if ((cl = get_header(conn->request_info.http_headers,
  13764. conn->request_info.num_headers,
  13765. "Content-Length")) != NULL) {
  13766. /* Request/response has content length set */
  13767. char *endptr = NULL;
  13768. conn->content_len = strtoll(cl, &endptr, 10);
  13769. if (endptr == cl) {
  13770. mg_snprintf(conn,
  13771. NULL, /* No truncation check for ebuf */
  13772. ebuf,
  13773. ebuf_len,
  13774. "%s",
  13775. "Bad request");
  13776. *err = 411;
  13777. return 0;
  13778. }
  13779. /* Publish the content length back to the request info. */
  13780. conn->request_info.content_length = conn->content_len;
  13781. } else if ((cl = get_header(conn->request_info.http_headers,
  13782. conn->request_info.num_headers,
  13783. "Transfer-Encoding")) != NULL
  13784. && !mg_strcasecmp(cl, "chunked")) {
  13785. conn->is_chunked = 1;
  13786. conn->content_len = -1; /* unknown content length */
  13787. } else if (get_http_method_info(conn->request_info.request_method)
  13788. ->request_has_body) {
  13789. /* POST or PUT request without content length set */
  13790. conn->content_len = -1; /* unknown content length */
  13791. } else {
  13792. /* Other request */
  13793. conn->content_len = 0; /* No content */
  13794. }
  13795. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  13796. return 1;
  13797. }
  13798. /* conn is assumed to be valid in this internal function */
  13799. static int
  13800. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13801. {
  13802. const char *cl;
  13803. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13804. return 0;
  13805. }
  13806. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  13807. <= 0) {
  13808. mg_snprintf(conn,
  13809. NULL, /* No truncation check for ebuf */
  13810. ebuf,
  13811. ebuf_len,
  13812. "%s",
  13813. "Bad response");
  13814. *err = 400;
  13815. return 0;
  13816. }
  13817. /* Message is a valid response */
  13818. /* Do we know the content length? */
  13819. if ((cl = get_header(conn->response_info.http_headers,
  13820. conn->response_info.num_headers,
  13821. "Content-Length")) != NULL) {
  13822. /* Request/response has content length set */
  13823. char *endptr = NULL;
  13824. conn->content_len = strtoll(cl, &endptr, 10);
  13825. if (endptr == cl) {
  13826. mg_snprintf(conn,
  13827. NULL, /* No truncation check for ebuf */
  13828. ebuf,
  13829. ebuf_len,
  13830. "%s",
  13831. "Bad request");
  13832. *err = 411;
  13833. return 0;
  13834. }
  13835. /* Publish the content length back to the response info. */
  13836. conn->response_info.content_length = conn->content_len;
  13837. /* TODO: check if it is still used in response_info */
  13838. conn->request_info.content_length = conn->content_len;
  13839. } else if ((cl = get_header(conn->response_info.http_headers,
  13840. conn->response_info.num_headers,
  13841. "Transfer-Encoding")) != NULL
  13842. && !mg_strcasecmp(cl, "chunked")) {
  13843. conn->is_chunked = 1;
  13844. conn->content_len = -1; /* unknown content length */
  13845. } else {
  13846. conn->content_len = -1; /* unknown content length */
  13847. }
  13848. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  13849. return 1;
  13850. }
  13851. int
  13852. mg_get_response(struct mg_connection *conn,
  13853. char *ebuf,
  13854. size_t ebuf_len,
  13855. int timeout)
  13856. {
  13857. int err, ret;
  13858. char txt[32]; /* will not overflow */
  13859. char *save_timeout;
  13860. char *new_timeout;
  13861. if (ebuf_len > 0) {
  13862. ebuf[0] = '\0';
  13863. }
  13864. if (!conn) {
  13865. mg_snprintf(conn,
  13866. NULL, /* No truncation check for ebuf */
  13867. ebuf,
  13868. ebuf_len,
  13869. "%s",
  13870. "Parameter error");
  13871. return -1;
  13872. }
  13873. /* Implementation of API function for HTTP clients */
  13874. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  13875. if (timeout >= 0) {
  13876. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  13877. new_timeout = txt;
  13878. /* Not required for non-blocking sockets.
  13879. set_sock_timeout(conn->client.sock, timeout);
  13880. */
  13881. } else {
  13882. new_timeout = NULL;
  13883. }
  13884. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  13885. ret = get_response(conn, ebuf, ebuf_len, &err);
  13886. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  13887. #if defined(MG_LEGACY_INTERFACE)
  13888. /* TODO: 1) uri is deprecated;
  13889. * 2) here, ri.uri is the http response code */
  13890. conn->request_info.uri = conn->request_info.request_uri;
  13891. #endif
  13892. conn->request_info.local_uri = conn->request_info.request_uri;
  13893. /* TODO (mid): Define proper return values - maybe return length?
  13894. * For the first test use <0 for error and >0 for OK */
  13895. return (ret == 0) ? -1 : +1;
  13896. }
  13897. struct mg_connection *
  13898. mg_download(const char *host,
  13899. int port,
  13900. int use_ssl,
  13901. char *ebuf,
  13902. size_t ebuf_len,
  13903. const char *fmt,
  13904. ...)
  13905. {
  13906. struct mg_connection *conn;
  13907. va_list ap;
  13908. int i;
  13909. int reqerr;
  13910. if (ebuf_len > 0) {
  13911. ebuf[0] = '\0';
  13912. }
  13913. va_start(ap, fmt);
  13914. /* open a connection */
  13915. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  13916. if (conn != NULL) {
  13917. i = mg_vprintf(conn, fmt, ap);
  13918. if (i <= 0) {
  13919. mg_snprintf(conn,
  13920. NULL, /* No truncation check for ebuf */
  13921. ebuf,
  13922. ebuf_len,
  13923. "%s",
  13924. "Error sending request");
  13925. } else {
  13926. get_response(conn, ebuf, ebuf_len, &reqerr);
  13927. #if defined(MG_LEGACY_INTERFACE)
  13928. /* TODO: 1) uri is deprecated;
  13929. * 2) here, ri.uri is the http response code */
  13930. conn->request_info.uri = conn->request_info.request_uri;
  13931. #endif
  13932. conn->request_info.local_uri = conn->request_info.request_uri;
  13933. }
  13934. }
  13935. /* if an error occurred, close the connection */
  13936. if ((ebuf[0] != '\0') && (conn != NULL)) {
  13937. mg_close_connection(conn);
  13938. conn = NULL;
  13939. }
  13940. va_end(ap);
  13941. return conn;
  13942. }
  13943. struct websocket_client_thread_data {
  13944. struct mg_connection *conn;
  13945. mg_websocket_data_handler data_handler;
  13946. mg_websocket_close_handler close_handler;
  13947. void *callback_data;
  13948. };
  13949. #if defined(USE_WEBSOCKET)
  13950. #ifdef _WIN32
  13951. static unsigned __stdcall websocket_client_thread(void *data)
  13952. #else
  13953. static void *
  13954. websocket_client_thread(void *data)
  13955. #endif
  13956. {
  13957. struct websocket_client_thread_data *cdata =
  13958. (struct websocket_client_thread_data *)data;
  13959. #if !defined(_WIN32)
  13960. struct sigaction sa;
  13961. /* Ignore SIGPIPE */
  13962. memset(&sa, 0, sizeof(sa));
  13963. sa.sa_handler = SIG_IGN;
  13964. sigaction(SIGPIPE, &sa, NULL);
  13965. #endif
  13966. mg_set_thread_name("ws-clnt");
  13967. if (cdata->conn->phys_ctx) {
  13968. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  13969. /* 3 indicates a websocket client thread */
  13970. /* TODO: check if conn->phys_ctx can be set */
  13971. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  13972. 3);
  13973. }
  13974. }
  13975. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  13976. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  13977. if (cdata->close_handler != NULL) {
  13978. cdata->close_handler(cdata->conn, cdata->callback_data);
  13979. }
  13980. /* The websocket_client context has only this thread. If it runs out,
  13981. set the stop_flag to 2 (= "stopped"). */
  13982. cdata->conn->phys_ctx->stop_flag = 2;
  13983. mg_free((void *)cdata);
  13984. #ifdef _WIN32
  13985. return 0;
  13986. #else
  13987. return NULL;
  13988. #endif
  13989. }
  13990. #endif
  13991. struct mg_connection *
  13992. mg_connect_websocket_client(const char *host,
  13993. int port,
  13994. int use_ssl,
  13995. char *error_buffer,
  13996. size_t error_buffer_size,
  13997. const char *path,
  13998. const char *origin,
  13999. mg_websocket_data_handler data_func,
  14000. mg_websocket_close_handler close_func,
  14001. void *user_data)
  14002. {
  14003. struct mg_connection *conn = NULL;
  14004. #if defined(USE_WEBSOCKET)
  14005. struct mg_context *newctx = NULL;
  14006. struct websocket_client_thread_data *thread_data;
  14007. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14008. static const char *handshake_req;
  14009. if (origin != NULL) {
  14010. handshake_req = "GET %s HTTP/1.1\r\n"
  14011. "Host: %s\r\n"
  14012. "Upgrade: websocket\r\n"
  14013. "Connection: Upgrade\r\n"
  14014. "Sec-WebSocket-Key: %s\r\n"
  14015. "Sec-WebSocket-Version: 13\r\n"
  14016. "Origin: %s\r\n"
  14017. "\r\n";
  14018. } else {
  14019. handshake_req = "GET %s HTTP/1.1\r\n"
  14020. "Host: %s\r\n"
  14021. "Upgrade: websocket\r\n"
  14022. "Connection: Upgrade\r\n"
  14023. "Sec-WebSocket-Key: %s\r\n"
  14024. "Sec-WebSocket-Version: 13\r\n"
  14025. "\r\n";
  14026. }
  14027. /* Establish the client connection and request upgrade */
  14028. conn = mg_download(host,
  14029. port,
  14030. use_ssl,
  14031. error_buffer,
  14032. error_buffer_size,
  14033. handshake_req,
  14034. path,
  14035. host,
  14036. magic,
  14037. origin);
  14038. /* Connection object will be null if something goes wrong */
  14039. if (conn == NULL) {
  14040. if (!*error_buffer) {
  14041. /* There should be already an error message */
  14042. mg_snprintf(conn,
  14043. NULL, /* No truncation check for ebuf */
  14044. error_buffer,
  14045. error_buffer_size,
  14046. "Unexpected error");
  14047. }
  14048. return NULL;
  14049. }
  14050. if (conn->response_info.status_code != 101) {
  14051. /* We sent an "upgrade" request. For a correct websocket
  14052. * protocol handshake, we expect a "101 Continue" response.
  14053. * Otherwise it is a protocol violation. Maybe the HTTP
  14054. * Server does not know websockets. */
  14055. if (!*error_buffer) {
  14056. /* set an error, if not yet set */
  14057. mg_snprintf(conn,
  14058. NULL, /* No truncation check for ebuf */
  14059. error_buffer,
  14060. error_buffer_size,
  14061. "Unexpected server reply");
  14062. }
  14063. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14064. mg_free(conn);
  14065. return NULL;
  14066. }
  14067. /* For client connections, mg_context is fake. Since we need to set a
  14068. * callback function, we need to create a copy and modify it. */
  14069. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14070. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14071. newctx->user_data = user_data;
  14072. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14073. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14074. newctx->worker_threadids =
  14075. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14076. sizeof(pthread_t),
  14077. newctx);
  14078. conn->phys_ctx = newctx;
  14079. conn->dom_ctx = &(newctx->dd);
  14080. thread_data = (struct websocket_client_thread_data *)
  14081. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14082. thread_data->conn = conn;
  14083. thread_data->data_handler = data_func;
  14084. thread_data->close_handler = close_func;
  14085. thread_data->callback_data = user_data;
  14086. /* Start a thread to read the websocket client connection
  14087. * This thread will automatically stop when mg_disconnect is
  14088. * called on the client connection */
  14089. if (mg_start_thread_with_id(websocket_client_thread,
  14090. (void *)thread_data,
  14091. newctx->worker_threadids) != 0) {
  14092. mg_free((void *)thread_data);
  14093. mg_free((void *)newctx->worker_threadids);
  14094. mg_free((void *)newctx);
  14095. mg_free((void *)conn);
  14096. conn = NULL;
  14097. DEBUG_TRACE("%s",
  14098. "Websocket client connect thread could not be started\r\n");
  14099. }
  14100. #else
  14101. /* Appease "unused parameter" warnings */
  14102. (void)host;
  14103. (void)port;
  14104. (void)use_ssl;
  14105. (void)error_buffer;
  14106. (void)error_buffer_size;
  14107. (void)path;
  14108. (void)origin;
  14109. (void)user_data;
  14110. (void)data_func;
  14111. (void)close_func;
  14112. #endif
  14113. return conn;
  14114. }
  14115. /* Prepare connection data structure */
  14116. static void
  14117. init_connection(struct mg_connection *conn)
  14118. {
  14119. /* Is keep alive allowed by the server */
  14120. int keep_alive_enabled =
  14121. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  14122. if (!keep_alive_enabled) {
  14123. conn->must_close = 1;
  14124. }
  14125. /* Important: on new connection, reset the receiving buffer. Credit
  14126. * goes to crule42. */
  14127. conn->data_len = 0;
  14128. conn->handled_requests = 0;
  14129. mg_set_user_connection_data(conn, NULL);
  14130. #if defined(USE_SERVER_STATS)
  14131. conn->conn_state = 2; /* init */
  14132. #endif
  14133. /* call the init_connection callback if assigned */
  14134. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  14135. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14136. void *conn_data = NULL;
  14137. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  14138. mg_set_user_connection_data(conn, conn_data);
  14139. }
  14140. }
  14141. }
  14142. /* Process a connection - may handle multiple requests
  14143. * using the same connection.
  14144. * Must be called with a valid connection (conn and
  14145. * conn->phys_ctx must be valid).
  14146. */
  14147. static void
  14148. process_new_connection(struct mg_connection *conn)
  14149. {
  14150. struct mg_request_info *ri = &conn->request_info;
  14151. int keep_alive, discard_len;
  14152. char ebuf[100];
  14153. const char *hostend;
  14154. int reqerr, uri_type;
  14155. #if defined(USE_SERVER_STATS)
  14156. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  14157. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  14158. if (mcon > (conn->phys_ctx->max_connections)) {
  14159. /* could use atomic compare exchange, but this
  14160. * seems overkill for statistics data */
  14161. conn->phys_ctx->max_connections = mcon;
  14162. }
  14163. #endif
  14164. init_connection(conn);
  14165. DEBUG_TRACE("Start processing connection from %s",
  14166. conn->request_info.remote_addr);
  14167. /* Loop over multiple requests sent using the same connection
  14168. * (while "keep alive"). */
  14169. do {
  14170. DEBUG_TRACE("calling get_request (%i times for this connection)",
  14171. conn->handled_requests + 1);
  14172. #if defined(USE_SERVER_STATS)
  14173. conn->conn_state = 3; /* ready */
  14174. #endif
  14175. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  14176. /* The request sent by the client could not be understood by
  14177. * the server, or it was incomplete or a timeout. Send an
  14178. * error message and close the connection. */
  14179. if (reqerr > 0) {
  14180. DEBUG_ASSERT(ebuf[0] != '\0');
  14181. mg_send_http_error(conn, reqerr, "%s", ebuf);
  14182. }
  14183. } else if (strcmp(ri->http_version, "1.0")
  14184. && strcmp(ri->http_version, "1.1")) {
  14185. mg_snprintf(conn,
  14186. NULL, /* No truncation check for ebuf */
  14187. ebuf,
  14188. sizeof(ebuf),
  14189. "Bad HTTP version: [%s]",
  14190. ri->http_version);
  14191. mg_send_http_error(conn, 505, "%s", ebuf);
  14192. }
  14193. if (ebuf[0] == '\0') {
  14194. uri_type = get_uri_type(conn->request_info.request_uri);
  14195. switch (uri_type) {
  14196. case 1:
  14197. /* Asterisk */
  14198. conn->request_info.local_uri = NULL;
  14199. break;
  14200. case 2:
  14201. /* relative uri */
  14202. conn->request_info.local_uri = conn->request_info.request_uri;
  14203. break;
  14204. case 3:
  14205. case 4:
  14206. /* absolute uri (with/without port) */
  14207. hostend = get_rel_url_at_current_server(
  14208. conn->request_info.request_uri, conn);
  14209. if (hostend) {
  14210. conn->request_info.local_uri = hostend;
  14211. } else {
  14212. conn->request_info.local_uri = NULL;
  14213. }
  14214. break;
  14215. default:
  14216. mg_snprintf(conn,
  14217. NULL, /* No truncation check for ebuf */
  14218. ebuf,
  14219. sizeof(ebuf),
  14220. "Invalid URI");
  14221. mg_send_http_error(conn, 400, "%s", ebuf);
  14222. conn->request_info.local_uri = NULL;
  14223. break;
  14224. }
  14225. #if defined(MG_LEGACY_INTERFACE)
  14226. /* Legacy before split into local_uri and request_uri */
  14227. conn->request_info.uri = conn->request_info.local_uri;
  14228. #endif
  14229. }
  14230. DEBUG_TRACE("http: %s, error: %s",
  14231. (ri->http_version ? ri->http_version : "none"),
  14232. (ebuf[0] ? ebuf : "none"));
  14233. if (ebuf[0] == '\0') {
  14234. if (conn->request_info.local_uri) {
  14235. /* handle request to local server */
  14236. #if defined(USE_SERVER_STATS)
  14237. conn->conn_state = 4; /* processing */
  14238. #endif
  14239. handle_request(conn);
  14240. #if defined(USE_SERVER_STATS)
  14241. conn->conn_state = 5; /* processed */
  14242. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  14243. conn->consumed_content);
  14244. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  14245. conn->num_bytes_sent);
  14246. #endif
  14247. DEBUG_TRACE("%s", "handle_request done");
  14248. if (conn->phys_ctx->callbacks.end_request != NULL) {
  14249. conn->phys_ctx->callbacks.end_request(conn,
  14250. conn->status_code);
  14251. DEBUG_TRACE("%s", "end_request callback done");
  14252. }
  14253. log_access(conn);
  14254. } else {
  14255. /* TODO: handle non-local request (PROXY) */
  14256. conn->must_close = 1;
  14257. }
  14258. } else {
  14259. conn->must_close = 1;
  14260. }
  14261. if (ri->remote_user != NULL) {
  14262. mg_free((void *)ri->remote_user);
  14263. /* Important! When having connections with and without auth
  14264. * would cause double free and then crash */
  14265. ri->remote_user = NULL;
  14266. }
  14267. /* NOTE(lsm): order is important here. should_keep_alive() call
  14268. * is using parsed request, which will be invalid after
  14269. * memmove's below.
  14270. * Therefore, memorize should_keep_alive() result now for later
  14271. * use in loop exit condition. */
  14272. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  14273. && (conn->content_len >= 0);
  14274. /* Discard all buffered data for this request */
  14275. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  14276. && ((conn->request_len + conn->content_len)
  14277. < (int64_t)conn->data_len))
  14278. ? (int)(conn->request_len + conn->content_len)
  14279. : conn->data_len;
  14280. DEBUG_ASSERT(discard_len >= 0);
  14281. if (discard_len < 0) {
  14282. DEBUG_TRACE("internal error: discard_len = %li",
  14283. (long int)discard_len);
  14284. break;
  14285. }
  14286. conn->data_len -= discard_len;
  14287. if (conn->data_len > 0) {
  14288. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  14289. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  14290. }
  14291. DEBUG_ASSERT(conn->data_len >= 0);
  14292. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  14293. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  14294. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  14295. (long int)conn->data_len,
  14296. (long int)conn->buf_size);
  14297. break;
  14298. }
  14299. conn->handled_requests++;
  14300. } while (keep_alive);
  14301. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  14302. conn->request_info.remote_addr,
  14303. difftime(time(NULL), conn->conn_birth_time));
  14304. close_connection(conn);
  14305. #if defined(USE_SERVER_STATS)
  14306. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  14307. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  14308. #endif
  14309. }
  14310. #if defined(ALTERNATIVE_QUEUE)
  14311. static void
  14312. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14313. {
  14314. unsigned int i;
  14315. while (!ctx->stop_flag) {
  14316. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14317. /* find a free worker slot and signal it */
  14318. if (ctx->client_socks[i].in_use == 0) {
  14319. ctx->client_socks[i] = *sp;
  14320. ctx->client_socks[i].in_use = 1;
  14321. event_signal(ctx->client_wait_events[i]);
  14322. return;
  14323. }
  14324. }
  14325. /* queue is full */
  14326. mg_sleep(1);
  14327. }
  14328. }
  14329. static int
  14330. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14331. {
  14332. DEBUG_TRACE("%s", "going idle");
  14333. ctx->client_socks[thread_index].in_use = 0;
  14334. event_wait(ctx->client_wait_events[thread_index]);
  14335. *sp = ctx->client_socks[thread_index];
  14336. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14337. return !ctx->stop_flag;
  14338. }
  14339. #else /* ALTERNATIVE_QUEUE */
  14340. /* Worker threads take accepted socket from the queue */
  14341. static int
  14342. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14343. {
  14344. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14345. (void)thread_index;
  14346. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14347. DEBUG_TRACE("%s", "going idle");
  14348. /* If the queue is empty, wait. We're idle at this point. */
  14349. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  14350. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  14351. }
  14352. /* If we're stopping, sq_head may be equal to sq_tail. */
  14353. if (ctx->sq_head > ctx->sq_tail) {
  14354. /* Copy socket from the queue and increment tail */
  14355. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  14356. ctx->sq_tail++;
  14357. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14358. /* Wrap pointers if needed */
  14359. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  14360. ctx->sq_tail -= QUEUE_SIZE(ctx);
  14361. ctx->sq_head -= QUEUE_SIZE(ctx);
  14362. }
  14363. }
  14364. (void)pthread_cond_signal(&ctx->sq_empty);
  14365. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14366. return !ctx->stop_flag;
  14367. #undef QUEUE_SIZE
  14368. }
  14369. /* Master thread adds accepted socket to a queue */
  14370. static void
  14371. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14372. {
  14373. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14374. if (!ctx) {
  14375. return;
  14376. }
  14377. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14378. /* If the queue is full, wait */
  14379. while ((ctx->stop_flag == 0)
  14380. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  14381. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  14382. }
  14383. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  14384. /* Copy socket to the queue and increment head */
  14385. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  14386. ctx->sq_head++;
  14387. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  14388. }
  14389. (void)pthread_cond_signal(&ctx->sq_full);
  14390. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14391. #undef QUEUE_SIZE
  14392. }
  14393. #endif /* ALTERNATIVE_QUEUE */
  14394. struct worker_thread_args {
  14395. struct mg_context *ctx;
  14396. int index;
  14397. };
  14398. static void *
  14399. worker_thread_run(struct worker_thread_args *thread_args)
  14400. {
  14401. struct mg_context *ctx = thread_args->ctx;
  14402. struct mg_connection *conn;
  14403. struct mg_workerTLS tls;
  14404. #if defined(MG_LEGACY_INTERFACE)
  14405. uint32_t addr;
  14406. #endif
  14407. mg_set_thread_name("worker");
  14408. tls.is_master = 0;
  14409. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14410. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14411. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14412. #endif
  14413. /* Initialize thread local storage before calling any callback */
  14414. pthread_setspecific(sTlsKey, &tls);
  14415. if (ctx->callbacks.init_thread) {
  14416. /* call init_thread for a worker thread (type 1) */
  14417. ctx->callbacks.init_thread(ctx, 1);
  14418. }
  14419. /* Connection structure has been pre-allocated */
  14420. if (((int)thread_args->index < 0)
  14421. || ((unsigned)thread_args->index
  14422. >= (unsigned)ctx->cfg_worker_threads)) {
  14423. mg_cry_internal(fc(ctx),
  14424. "Internal error: Invalid worker index %i",
  14425. (int)thread_args->index);
  14426. return NULL;
  14427. }
  14428. conn = ctx->worker_connections + thread_args->index;
  14429. /* Request buffers are not pre-allocated. They are private to the
  14430. * request and do not contain any state information that might be
  14431. * of interest to anyone observing a server status. */
  14432. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  14433. if (conn->buf == NULL) {
  14434. mg_cry_internal(fc(ctx),
  14435. "Out of memory: Cannot allocate buffer for worker %i",
  14436. (int)thread_args->index);
  14437. return NULL;
  14438. }
  14439. conn->buf_size = (int)ctx->max_request_size;
  14440. conn->phys_ctx = ctx;
  14441. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  14442. conn->host = NULL; /* until we have more information. */
  14443. conn->thread_index = thread_args->index;
  14444. conn->request_info.user_data = ctx->user_data;
  14445. /* Allocate a mutex for this connection to allow communication both
  14446. * within the request handler and from elsewhere in the application
  14447. */
  14448. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  14449. #if defined(USE_SERVER_STATS)
  14450. conn->conn_state = 1; /* not consumed */
  14451. #endif
  14452. #if defined(ALTERNATIVE_QUEUE)
  14453. while ((ctx->stop_flag == 0)
  14454. && consume_socket(ctx, &conn->client, conn->thread_index)) {
  14455. #else
  14456. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  14457. * signal sq_empty condvar to wake up the master waiting in
  14458. * produce_socket() */
  14459. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  14460. #endif
  14461. conn->conn_birth_time = time(NULL);
  14462. /* Fill in IP, port info early so even if SSL setup below fails,
  14463. * error handler would have the corresponding info.
  14464. * Thanks to Johannes Winkelmann for the patch.
  14465. */
  14466. #if defined(USE_IPV6)
  14467. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  14468. conn->request_info.remote_port =
  14469. ntohs(conn->client.rsa.sin6.sin6_port);
  14470. } else
  14471. #endif
  14472. {
  14473. conn->request_info.remote_port =
  14474. ntohs(conn->client.rsa.sin.sin_port);
  14475. }
  14476. sockaddr_to_string(conn->request_info.remote_addr,
  14477. sizeof(conn->request_info.remote_addr),
  14478. &conn->client.rsa);
  14479. DEBUG_TRACE("Start processing connection from %s",
  14480. conn->request_info.remote_addr);
  14481. conn->request_info.is_ssl = conn->client.is_ssl;
  14482. if (conn->client.is_ssl) {
  14483. #ifndef NO_SSL
  14484. /* HTTPS connection */
  14485. if (sslize(conn,
  14486. conn->dom_ctx->ssl_ctx,
  14487. SSL_accept,
  14488. &(conn->phys_ctx->stop_flag))) {
  14489. /* conn->dom_ctx is set in get_request */
  14490. /* Get SSL client certificate information (if set) */
  14491. ssl_get_client_cert_info(conn);
  14492. /* process HTTPS connection */
  14493. process_new_connection(conn);
  14494. /* Free client certificate info */
  14495. if (conn->request_info.client_cert) {
  14496. mg_free((void *)(conn->request_info.client_cert->subject));
  14497. mg_free((void *)(conn->request_info.client_cert->issuer));
  14498. mg_free((void *)(conn->request_info.client_cert->serial));
  14499. mg_free((void *)(conn->request_info.client_cert->finger));
  14500. /* Free certificate memory */
  14501. X509_free(
  14502. (X509 *)conn->request_info.client_cert->peer_cert);
  14503. conn->request_info.client_cert->peer_cert = 0;
  14504. conn->request_info.client_cert->subject = 0;
  14505. conn->request_info.client_cert->issuer = 0;
  14506. conn->request_info.client_cert->serial = 0;
  14507. conn->request_info.client_cert->finger = 0;
  14508. mg_free(conn->request_info.client_cert);
  14509. conn->request_info.client_cert = 0;
  14510. }
  14511. }
  14512. #endif
  14513. } else {
  14514. /* process HTTP connection */
  14515. process_new_connection(conn);
  14516. }
  14517. DEBUG_TRACE("%s", "Connection closed");
  14518. }
  14519. pthread_setspecific(sTlsKey, NULL);
  14520. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14521. CloseHandle(tls.pthread_cond_helper_mutex);
  14522. #endif
  14523. pthread_mutex_destroy(&conn->mutex);
  14524. /* Free the request buffer. */
  14525. conn->buf_size = 0;
  14526. mg_free(conn->buf);
  14527. conn->buf = NULL;
  14528. #if defined(USE_SERVER_STATS)
  14529. conn->conn_state = 9; /* done */
  14530. #endif
  14531. DEBUG_TRACE("%s", "exiting");
  14532. return NULL;
  14533. }
  14534. /* Threads have different return types on Windows and Unix. */
  14535. #ifdef _WIN32
  14536. static unsigned __stdcall worker_thread(void *thread_func_param)
  14537. {
  14538. struct worker_thread_args *pwta =
  14539. (struct worker_thread_args *)thread_func_param;
  14540. worker_thread_run(pwta);
  14541. mg_free(thread_func_param);
  14542. return 0;
  14543. }
  14544. #else
  14545. static void *
  14546. worker_thread(void *thread_func_param)
  14547. {
  14548. struct worker_thread_args *pwta =
  14549. (struct worker_thread_args *)thread_func_param;
  14550. struct sigaction sa;
  14551. /* Ignore SIGPIPE */
  14552. memset(&sa, 0, sizeof(sa));
  14553. sa.sa_handler = SIG_IGN;
  14554. sigaction(SIGPIPE, &sa, NULL);
  14555. worker_thread_run(pwta);
  14556. mg_free(thread_func_param);
  14557. return NULL;
  14558. }
  14559. #endif /* _WIN32 */
  14560. /* This is an internal function, thus all arguments are expected to be
  14561. * valid - a NULL check is not required. */
  14562. static void
  14563. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  14564. {
  14565. struct socket so;
  14566. char src_addr[IP_ADDR_STR_LEN];
  14567. socklen_t len = sizeof(so.rsa);
  14568. int on = 1;
  14569. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  14570. == INVALID_SOCKET) {
  14571. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  14572. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  14573. mg_cry_internal(fc(ctx),
  14574. "%s: %s is not allowed to connect",
  14575. __func__,
  14576. src_addr);
  14577. closesocket(so.sock);
  14578. } else {
  14579. /* Put so socket structure into the queue */
  14580. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  14581. set_close_on_exec(so.sock, fc(ctx));
  14582. so.is_ssl = listener->is_ssl;
  14583. so.ssl_redir = listener->ssl_redir;
  14584. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  14585. mg_cry_internal(fc(ctx),
  14586. "%s: getsockname() failed: %s",
  14587. __func__,
  14588. strerror(ERRNO));
  14589. }
  14590. /* Set TCP keep-alive. This is needed because if HTTP-level
  14591. * keep-alive
  14592. * is enabled, and client resets the connection, server won't get
  14593. * TCP FIN or RST and will keep the connection open forever. With
  14594. * TCP keep-alive, next keep-alive handshake will figure out that
  14595. * the client is down and will close the server end.
  14596. * Thanks to Igor Klopov who suggested the patch. */
  14597. if (setsockopt(so.sock,
  14598. SOL_SOCKET,
  14599. SO_KEEPALIVE,
  14600. (SOCK_OPT_TYPE)&on,
  14601. sizeof(on)) != 0) {
  14602. mg_cry_internal(
  14603. fc(ctx),
  14604. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  14605. __func__,
  14606. strerror(ERRNO));
  14607. }
  14608. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  14609. * to effectively fill up the underlying IP packet payload and
  14610. * reduce the overhead of sending lots of small buffers. However
  14611. * this hurts the server's throughput (ie. operations per second)
  14612. * when HTTP 1.1 persistent connections are used and the responses
  14613. * are relatively small (eg. less than 1400 bytes).
  14614. */
  14615. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  14616. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  14617. if (set_tcp_nodelay(so.sock, 1) != 0) {
  14618. mg_cry_internal(
  14619. fc(ctx),
  14620. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  14621. __func__,
  14622. strerror(ERRNO));
  14623. }
  14624. }
  14625. /* We are using non-blocking sockets. Thus, the
  14626. * set_sock_timeout(so.sock, timeout);
  14627. * call is no longer required. */
  14628. /* The "non blocking" property should already be
  14629. * inherited from the parent socket. Set it for
  14630. * non-compliant socket implementations. */
  14631. set_non_blocking_mode(so.sock);
  14632. so.in_use = 0;
  14633. produce_socket(ctx, &so);
  14634. }
  14635. }
  14636. static void
  14637. master_thread_run(void *thread_func_param)
  14638. {
  14639. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  14640. struct mg_workerTLS tls;
  14641. struct pollfd *pfd;
  14642. unsigned int i;
  14643. unsigned int workerthreadcount;
  14644. if (!ctx) {
  14645. return;
  14646. }
  14647. mg_set_thread_name("master");
  14648. /* Increase priority of the master thread */
  14649. #if defined(_WIN32)
  14650. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  14651. #elif defined(USE_MASTER_THREAD_PRIORITY)
  14652. int min_prio = sched_get_priority_min(SCHED_RR);
  14653. int max_prio = sched_get_priority_max(SCHED_RR);
  14654. if ((min_prio >= 0) && (max_prio >= 0)
  14655. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  14656. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  14657. struct sched_param sched_param = {0};
  14658. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  14659. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  14660. }
  14661. #endif
  14662. /* Initialize thread local storage */
  14663. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14664. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14665. #endif
  14666. tls.is_master = 1;
  14667. pthread_setspecific(sTlsKey, &tls);
  14668. if (ctx->callbacks.init_thread) {
  14669. /* Callback for the master thread (type 0) */
  14670. ctx->callbacks.init_thread(ctx, 0);
  14671. }
  14672. /* Server starts *now* */
  14673. ctx->start_time = time(NULL);
  14674. /* Start the server */
  14675. pfd = ctx->listening_socket_fds;
  14676. while (ctx->stop_flag == 0) {
  14677. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14678. pfd[i].fd = ctx->listening_sockets[i].sock;
  14679. pfd[i].events = POLLIN;
  14680. }
  14681. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  14682. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14683. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  14684. * successful poll, and POLLIN is defined as
  14685. * (POLLRDNORM | POLLRDBAND)
  14686. * Therefore, we're checking pfd[i].revents & POLLIN, not
  14687. * pfd[i].revents == POLLIN. */
  14688. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  14689. accept_new_connection(&ctx->listening_sockets[i], ctx);
  14690. }
  14691. }
  14692. }
  14693. }
  14694. /* Here stop_flag is 1 - Initiate shutdown. */
  14695. DEBUG_TRACE("%s", "stopping workers");
  14696. /* Stop signal received: somebody called mg_stop. Quit. */
  14697. close_all_listening_sockets(ctx);
  14698. /* Wakeup workers that are waiting for connections to handle. */
  14699. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14700. #if defined(ALTERNATIVE_QUEUE)
  14701. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14702. event_signal(ctx->client_wait_events[i]);
  14703. /* Since we know all sockets, we can shutdown the connections. */
  14704. if (ctx->client_socks[i].in_use) {
  14705. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  14706. }
  14707. }
  14708. #else
  14709. pthread_cond_broadcast(&ctx->sq_full);
  14710. #endif
  14711. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14712. /* Join all worker threads to avoid leaking threads. */
  14713. workerthreadcount = ctx->cfg_worker_threads;
  14714. for (i = 0; i < workerthreadcount; i++) {
  14715. if (ctx->worker_threadids[i] != 0) {
  14716. mg_join_thread(ctx->worker_threadids[i]);
  14717. }
  14718. }
  14719. #if defined(USE_LUA)
  14720. /* Free Lua state of lua background task */
  14721. if (ctx->lua_background_state) {
  14722. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14723. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  14724. if (lua_istable(lstate, -1)) {
  14725. reg_boolean(lstate, "shutdown", 1);
  14726. lua_pop(lstate, 1);
  14727. mg_sleep(2);
  14728. }
  14729. lua_close(lstate);
  14730. ctx->lua_background_state = 0;
  14731. }
  14732. #endif
  14733. DEBUG_TRACE("%s", "exiting");
  14734. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14735. CloseHandle(tls.pthread_cond_helper_mutex);
  14736. #endif
  14737. pthread_setspecific(sTlsKey, NULL);
  14738. /* Signal mg_stop() that we're done.
  14739. * WARNING: This must be the very last thing this
  14740. * thread does, as ctx becomes invalid after this line. */
  14741. ctx->stop_flag = 2;
  14742. }
  14743. /* Threads have different return types on Windows and Unix. */
  14744. #ifdef _WIN32
  14745. static unsigned __stdcall master_thread(void *thread_func_param)
  14746. {
  14747. master_thread_run(thread_func_param);
  14748. return 0;
  14749. }
  14750. #else
  14751. static void *
  14752. master_thread(void *thread_func_param)
  14753. {
  14754. struct sigaction sa;
  14755. /* Ignore SIGPIPE */
  14756. memset(&sa, 0, sizeof(sa));
  14757. sa.sa_handler = SIG_IGN;
  14758. sigaction(SIGPIPE, &sa, NULL);
  14759. master_thread_run(thread_func_param);
  14760. return NULL;
  14761. }
  14762. #endif /* _WIN32 */
  14763. static void
  14764. free_context(struct mg_context *ctx)
  14765. {
  14766. int i;
  14767. struct mg_handler_info *tmp_rh;
  14768. if (ctx == NULL) {
  14769. return;
  14770. }
  14771. if (ctx->callbacks.exit_context) {
  14772. ctx->callbacks.exit_context(ctx);
  14773. }
  14774. /* All threads exited, no sync is needed. Destroy thread mutex and
  14775. * condvars
  14776. */
  14777. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  14778. #if defined(ALTERNATIVE_QUEUE)
  14779. mg_free(ctx->client_socks);
  14780. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14781. event_destroy(ctx->client_wait_events[i]);
  14782. }
  14783. mg_free(ctx->client_wait_events);
  14784. #else
  14785. (void)pthread_cond_destroy(&ctx->sq_empty);
  14786. (void)pthread_cond_destroy(&ctx->sq_full);
  14787. #endif
  14788. /* Destroy other context global data structures mutex */
  14789. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  14790. #if defined(USE_TIMERS)
  14791. timers_exit(ctx);
  14792. #endif
  14793. /* Deallocate config parameters */
  14794. for (i = 0; i < NUM_OPTIONS; i++) {
  14795. if (ctx->dd.config[i] != NULL) {
  14796. #if defined(_MSC_VER)
  14797. #pragma warning(suppress : 6001)
  14798. #endif
  14799. mg_free(ctx->dd.config[i]);
  14800. }
  14801. }
  14802. /* Deallocate request handlers */
  14803. while (ctx->dd.handlers) {
  14804. tmp_rh = ctx->dd.handlers;
  14805. ctx->dd.handlers = tmp_rh->next;
  14806. mg_free(tmp_rh->uri);
  14807. mg_free(tmp_rh);
  14808. }
  14809. #ifndef NO_SSL
  14810. /* Deallocate SSL context */
  14811. if (ctx->dd.ssl_ctx != NULL) {
  14812. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  14813. int callback_ret =
  14814. (ctx->callbacks.external_ssl_ctx == NULL)
  14815. ? 0
  14816. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  14817. if (callback_ret == 0) {
  14818. SSL_CTX_free(ctx->dd.ssl_ctx);
  14819. }
  14820. /* else: ignore error and ommit SSL_CTX_free in case
  14821. * callback_ret is 1 */
  14822. }
  14823. #endif /* !NO_SSL */
  14824. /* Deallocate worker thread ID array */
  14825. if (ctx->worker_threadids != NULL) {
  14826. mg_free(ctx->worker_threadids);
  14827. }
  14828. /* Deallocate worker thread ID array */
  14829. if (ctx->worker_connections != NULL) {
  14830. mg_free(ctx->worker_connections);
  14831. }
  14832. /* deallocate system name string */
  14833. mg_free(ctx->systemName);
  14834. /* Deallocate context itself */
  14835. mg_free(ctx);
  14836. }
  14837. void
  14838. mg_stop(struct mg_context *ctx)
  14839. {
  14840. pthread_t mt;
  14841. if (!ctx) {
  14842. return;
  14843. }
  14844. /* We don't use a lock here. Calling mg_stop with the same ctx from
  14845. * two threads is not allowed. */
  14846. mt = ctx->masterthreadid;
  14847. if (mt == 0) {
  14848. return;
  14849. }
  14850. ctx->masterthreadid = 0;
  14851. /* Set stop flag, so all threads know they have to exit. */
  14852. ctx->stop_flag = 1;
  14853. /* Wait until everything has stopped. */
  14854. while (ctx->stop_flag != 2) {
  14855. (void)mg_sleep(10);
  14856. }
  14857. mg_join_thread(mt);
  14858. free_context(ctx);
  14859. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14860. (void)WSACleanup();
  14861. #endif /* _WIN32 && !__SYMBIAN32__ */
  14862. }
  14863. static void
  14864. get_system_name(char **sysName)
  14865. {
  14866. #if defined(_WIN32)
  14867. #if !defined(__SYMBIAN32__)
  14868. #if defined(_WIN32_WCE)
  14869. *sysName = mg_strdup("WinCE");
  14870. #else
  14871. char name[128];
  14872. DWORD dwVersion = 0;
  14873. DWORD dwMajorVersion = 0;
  14874. DWORD dwMinorVersion = 0;
  14875. DWORD dwBuild = 0;
  14876. BOOL wowRet, isWoW = FALSE;
  14877. #ifdef _MSC_VER
  14878. #pragma warning(push)
  14879. /* GetVersion was declared deprecated */
  14880. #pragma warning(disable : 4996)
  14881. #endif
  14882. dwVersion = GetVersion();
  14883. #ifdef _MSC_VER
  14884. #pragma warning(pop)
  14885. #endif
  14886. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14887. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14888. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  14889. (void)dwBuild;
  14890. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  14891. sprintf(name,
  14892. "Windows %u.%u%s",
  14893. (unsigned)dwMajorVersion,
  14894. (unsigned)dwMinorVersion,
  14895. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  14896. *sysName = mg_strdup(name);
  14897. #endif
  14898. #else
  14899. *sysName = mg_strdup("Symbian");
  14900. #endif
  14901. #else
  14902. struct utsname name;
  14903. memset(&name, 0, sizeof(name));
  14904. uname(&name);
  14905. *sysName = mg_strdup(name.sysname);
  14906. #endif
  14907. }
  14908. struct mg_context *
  14909. mg_start(const struct mg_callbacks *callbacks,
  14910. void *user_data,
  14911. const char **options)
  14912. {
  14913. struct mg_context *ctx;
  14914. const char *name, *value, *default_value;
  14915. int idx, ok, workerthreadcount;
  14916. unsigned int i;
  14917. int itmp;
  14918. void (*exit_callback)(const struct mg_context *ctx) = 0;
  14919. struct mg_workerTLS tls;
  14920. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14921. WSADATA data;
  14922. WSAStartup(MAKEWORD(2, 2), &data);
  14923. #endif /* _WIN32 && !__SYMBIAN32__ */
  14924. /* Allocate context and initialize reasonable general case defaults. */
  14925. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  14926. return NULL;
  14927. }
  14928. /* Random number generator will initialize at the first call */
  14929. ctx->dd.auth_nonce_mask =
  14930. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  14931. if (mg_init_library_called == 0) {
  14932. /* Legacy INIT, if mg_start is called without mg_init_library.
  14933. * Note: This may cause a memory leak */
  14934. const char *ports_option =
  14935. config_options[LISTENING_PORTS].default_value;
  14936. if (options) {
  14937. const char **run_options = options;
  14938. const char *optname = config_options[LISTENING_PORTS].name;
  14939. /* Try to find the "listening_ports" option */
  14940. while (*run_options) {
  14941. if (!strcmp(*run_options, optname)) {
  14942. ports_option = run_options[1];
  14943. }
  14944. run_options += 2;
  14945. }
  14946. }
  14947. if (is_ssl_port_used(ports_option)) {
  14948. /* Initialize with SSL support */
  14949. mg_init_library(MG_FEATURES_TLS);
  14950. } else {
  14951. /* Initialize without SSL support */
  14952. mg_init_library(MG_FEATURES_DEFAULT);
  14953. }
  14954. }
  14955. tls.is_master = -1;
  14956. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14957. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14958. tls.pthread_cond_helper_mutex = NULL;
  14959. #endif
  14960. pthread_setspecific(sTlsKey, &tls);
  14961. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  14962. #if !defined(ALTERNATIVE_QUEUE)
  14963. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  14964. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  14965. #endif
  14966. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  14967. if (!ok) {
  14968. /* Fatal error - abort start. However, this situation should never
  14969. * occur in practice. */
  14970. mg_cry_internal(fc(ctx),
  14971. "%s",
  14972. "Cannot initialize thread synchronization objects");
  14973. mg_free(ctx);
  14974. pthread_setspecific(sTlsKey, NULL);
  14975. return NULL;
  14976. }
  14977. if (callbacks) {
  14978. ctx->callbacks = *callbacks;
  14979. exit_callback = callbacks->exit_context;
  14980. ctx->callbacks.exit_context = 0;
  14981. }
  14982. ctx->user_data = user_data;
  14983. ctx->dd.handlers = NULL;
  14984. ctx->dd.next = NULL;
  14985. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14986. ctx->dd.shared_lua_websockets = NULL;
  14987. #endif
  14988. /* Store options */
  14989. while (options && (name = *options++) != NULL) {
  14990. if ((idx = get_option_index(name)) == -1) {
  14991. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  14992. free_context(ctx);
  14993. pthread_setspecific(sTlsKey, NULL);
  14994. return NULL;
  14995. } else if ((value = *options++) == NULL) {
  14996. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  14997. free_context(ctx);
  14998. pthread_setspecific(sTlsKey, NULL);
  14999. return NULL;
  15000. }
  15001. if (ctx->dd.config[idx] != NULL) {
  15002. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15003. mg_free(ctx->dd.config[idx]);
  15004. }
  15005. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15006. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15007. }
  15008. /* Set default value if needed */
  15009. for (i = 0; config_options[i].name != NULL; i++) {
  15010. default_value = config_options[i].default_value;
  15011. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15012. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15013. }
  15014. }
  15015. /* Request size option */
  15016. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15017. if (itmp < 1024) {
  15018. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15019. free_context(ctx);
  15020. pthread_setspecific(sTlsKey, NULL);
  15021. return NULL;
  15022. }
  15023. ctx->max_request_size = (unsigned)itmp;
  15024. /* Worker thread count option */
  15025. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15026. if (workerthreadcount > MAX_WORKER_THREADS) {
  15027. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15028. free_context(ctx);
  15029. pthread_setspecific(sTlsKey, NULL);
  15030. return NULL;
  15031. }
  15032. if (workerthreadcount <= 0) {
  15033. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15034. free_context(ctx);
  15035. pthread_setspecific(sTlsKey, NULL);
  15036. return NULL;
  15037. }
  15038. /* Document root */
  15039. #if defined(NO_FILES)
  15040. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15041. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15042. free_context(ctx);
  15043. pthread_setspecific(sTlsKey, NULL);
  15044. return NULL;
  15045. }
  15046. #endif
  15047. get_system_name(&ctx->systemName);
  15048. #if defined(USE_LUA)
  15049. /* If a Lua background script has been configured, start it. */
  15050. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15051. char ebuf[256];
  15052. struct vec opt_vec;
  15053. struct vec eq_vec;
  15054. const char *sparams;
  15055. lua_State *state = mg_prepare_lua_context_script(
  15056. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15057. if (!state) {
  15058. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15059. free_context(ctx);
  15060. pthread_setspecific(sTlsKey, NULL);
  15061. return NULL;
  15062. }
  15063. ctx->lua_background_state = (void *)state;
  15064. lua_newtable(state);
  15065. reg_boolean(state, "shutdown", 0);
  15066. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15067. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15068. reg_llstring(
  15069. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15070. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15071. break;
  15072. }
  15073. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15074. } else {
  15075. ctx->lua_background_state = 0;
  15076. }
  15077. #endif
  15078. /* NOTE(lsm): order is important here. SSL certificates must
  15079. * be initialized before listening ports. UID must be set last. */
  15080. if (!set_gpass_option(ctx, NULL) ||
  15081. #if !defined(NO_SSL)
  15082. !init_ssl_ctx(ctx, NULL) ||
  15083. #endif
  15084. !set_ports_option(ctx) ||
  15085. #if !defined(_WIN32)
  15086. !set_uid_option(ctx) ||
  15087. #endif
  15088. !set_acl_option(ctx)) {
  15089. free_context(ctx);
  15090. pthread_setspecific(sTlsKey, NULL);
  15091. return NULL;
  15092. }
  15093. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  15094. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15095. sizeof(pthread_t),
  15096. ctx);
  15097. if (ctx->worker_threadids == NULL) {
  15098. mg_cry_internal(fc(ctx),
  15099. "%s",
  15100. "Not enough memory for worker thread ID array");
  15101. free_context(ctx);
  15102. pthread_setspecific(sTlsKey, NULL);
  15103. return NULL;
  15104. }
  15105. ctx->worker_connections =
  15106. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15107. sizeof(struct mg_connection),
  15108. ctx);
  15109. if (ctx->worker_connections == NULL) {
  15110. mg_cry_internal(fc(ctx),
  15111. "%s",
  15112. "Not enough memory for worker thread connection array");
  15113. free_context(ctx);
  15114. pthread_setspecific(sTlsKey, NULL);
  15115. return NULL;
  15116. }
  15117. #if defined(ALTERNATIVE_QUEUE)
  15118. ctx->client_wait_events =
  15119. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  15120. ctx->cfg_worker_threads,
  15121. ctx);
  15122. if (ctx->client_wait_events == NULL) {
  15123. mg_cry_internal(fc(ctx),
  15124. "%s",
  15125. "Not enough memory for worker event array");
  15126. mg_free(ctx->worker_threadids);
  15127. free_context(ctx);
  15128. pthread_setspecific(sTlsKey, NULL);
  15129. return NULL;
  15130. }
  15131. ctx->client_socks =
  15132. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  15133. ctx->cfg_worker_threads,
  15134. ctx);
  15135. if (ctx->client_wait_events == NULL) {
  15136. mg_cry_internal(fc(ctx),
  15137. "%s",
  15138. "Not enough memory for worker socket array");
  15139. mg_free(ctx->client_socks);
  15140. mg_free(ctx->worker_threadids);
  15141. free_context(ctx);
  15142. pthread_setspecific(sTlsKey, NULL);
  15143. return NULL;
  15144. }
  15145. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15146. ctx->client_wait_events[i] = event_create();
  15147. if (ctx->client_wait_events[i] == 0) {
  15148. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  15149. while (i > 0) {
  15150. i--;
  15151. event_destroy(ctx->client_wait_events[i]);
  15152. }
  15153. mg_free(ctx->client_socks);
  15154. mg_free(ctx->worker_threadids);
  15155. free_context(ctx);
  15156. pthread_setspecific(sTlsKey, NULL);
  15157. return NULL;
  15158. }
  15159. }
  15160. #endif
  15161. #if defined(USE_TIMERS)
  15162. if (timers_init(ctx) != 0) {
  15163. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  15164. free_context(ctx);
  15165. pthread_setspecific(sTlsKey, NULL);
  15166. return NULL;
  15167. }
  15168. #endif
  15169. /* Context has been created - init user libraries */
  15170. if (ctx->callbacks.init_context) {
  15171. ctx->callbacks.init_context(ctx);
  15172. }
  15173. ctx->callbacks.exit_context = exit_callback;
  15174. ctx->context_type = CONTEXT_SERVER; /* server context */
  15175. /* Start master (listening) thread */
  15176. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  15177. /* Start worker threads */
  15178. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15179. struct worker_thread_args *wta = (struct worker_thread_args *)
  15180. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  15181. if (wta) {
  15182. wta->ctx = ctx;
  15183. wta->index = (int)i;
  15184. }
  15185. if ((wta == NULL)
  15186. || (mg_start_thread_with_id(worker_thread,
  15187. wta,
  15188. &ctx->worker_threadids[i]) != 0)) {
  15189. /* thread was not created */
  15190. if (wta != NULL) {
  15191. mg_free(wta);
  15192. }
  15193. if (i > 0) {
  15194. mg_cry_internal(fc(ctx),
  15195. "Cannot start worker thread %i: error %ld",
  15196. i + 1,
  15197. (long)ERRNO);
  15198. } else {
  15199. mg_cry_internal(fc(ctx),
  15200. "Cannot create threads: error %ld",
  15201. (long)ERRNO);
  15202. free_context(ctx);
  15203. pthread_setspecific(sTlsKey, NULL);
  15204. return NULL;
  15205. }
  15206. break;
  15207. }
  15208. }
  15209. pthread_setspecific(sTlsKey, NULL);
  15210. return ctx;
  15211. }
  15212. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15213. /* Add an additional domain to an already running web server. */
  15214. int
  15215. mg_start_domain(struct mg_context *ctx, const char **options)
  15216. {
  15217. const char *name;
  15218. const char *value;
  15219. const char *default_value;
  15220. struct mg_domain_context *new_dom;
  15221. struct mg_domain_context *dom;
  15222. int idx, i;
  15223. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  15224. return -1;
  15225. }
  15226. new_dom = (struct mg_domain_context *)
  15227. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  15228. if (!new_dom) {
  15229. /* Out of memory */
  15230. return -6;
  15231. }
  15232. /* Store options - TODO: unite duplicate code */
  15233. while (options && (name = *options++) != NULL) {
  15234. if ((idx = get_option_index(name)) == -1) {
  15235. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15236. mg_free(new_dom);
  15237. return -2;
  15238. } else if ((value = *options++) == NULL) {
  15239. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15240. mg_free(new_dom);
  15241. return -2;
  15242. }
  15243. if (new_dom->config[idx] != NULL) {
  15244. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15245. mg_free(new_dom->config[idx]);
  15246. }
  15247. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  15248. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15249. }
  15250. /* Authentication domain is mandatory */
  15251. /* TODO: Maybe use a new option hostname? */
  15252. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  15253. return -4;
  15254. }
  15255. /* Set default value if needed. Take the config value from
  15256. * ctx as a default value. */
  15257. for (i = 0; config_options[i].name != NULL; i++) {
  15258. default_value = ctx->dd.config[i];
  15259. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  15260. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  15261. }
  15262. }
  15263. new_dom->handlers = NULL;
  15264. new_dom->next = NULL;
  15265. new_dom->nonce_count = 0;
  15266. new_dom->auth_nonce_mask =
  15267. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  15268. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15269. new_dom->shared_lua_websockets = NULL;
  15270. #endif
  15271. if (!init_ssl_ctx(ctx, new_dom)) {
  15272. /* Init SSL failed */
  15273. mg_free(new_dom);
  15274. return -3;
  15275. }
  15276. /* Add element to linked list. */
  15277. mg_lock_context(ctx);
  15278. idx = 0;
  15279. dom = &(ctx->dd);
  15280. for (;;) {
  15281. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  15282. dom->config[AUTHENTICATION_DOMAIN])) {
  15283. /* Domain collision */
  15284. mg_cry_internal(fc(ctx),
  15285. "domain %s already in use",
  15286. new_dom->config[AUTHENTICATION_DOMAIN]);
  15287. mg_free(new_dom);
  15288. return -5;
  15289. }
  15290. /* Count number of domains */
  15291. idx++;
  15292. if (dom->next == NULL) {
  15293. dom->next = new_dom;
  15294. break;
  15295. }
  15296. dom = dom->next;
  15297. }
  15298. mg_unlock_context(ctx);
  15299. /* Return domain number */
  15300. return idx;
  15301. }
  15302. #endif
  15303. /* Feature check API function */
  15304. unsigned
  15305. mg_check_feature(unsigned feature)
  15306. {
  15307. static const unsigned feature_set = 0
  15308. /* Set bits for available features according to API documentation.
  15309. * This bit mask is created at compile time, according to the active
  15310. * preprocessor defines. It is a single const value at runtime. */
  15311. #if !defined(NO_FILES)
  15312. | MG_FEATURES_FILES
  15313. #endif
  15314. #if !defined(NO_SSL)
  15315. | MG_FEATURES_SSL
  15316. #endif
  15317. #if !defined(NO_CGI)
  15318. | MG_FEATURES_CGI
  15319. #endif
  15320. #if defined(USE_IPV6)
  15321. | MG_FEATURES_IPV6
  15322. #endif
  15323. #if defined(USE_WEBSOCKET)
  15324. | MG_FEATURES_WEBSOCKET
  15325. #endif
  15326. #if defined(USE_LUA)
  15327. | MG_FEATURES_LUA
  15328. #endif
  15329. #if defined(USE_DUKTAPE)
  15330. | MG_FEATURES_SSJS
  15331. #endif
  15332. #if !defined(NO_CACHING)
  15333. | MG_FEATURES_CACHE
  15334. #endif
  15335. #if defined(USE_SERVER_STATS)
  15336. | MG_FEATURES_STATS
  15337. #endif
  15338. /* Set some extra bits not defined in the API documentation.
  15339. * These bits may change without further notice. */
  15340. #if defined(MG_LEGACY_INTERFACE)
  15341. | 0x8000u
  15342. #endif
  15343. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15344. | 0x4000u
  15345. #endif
  15346. #if defined(MEMORY_DEBUGGING)
  15347. | 0x1000u
  15348. #endif
  15349. #if defined(USE_TIMERS)
  15350. | 0x0200u
  15351. #endif
  15352. #if !defined(NO_NONCE_CHECK)
  15353. | 0x0400u
  15354. #endif
  15355. #if !defined(NO_POPEN)
  15356. | 0x0800u
  15357. #endif
  15358. ;
  15359. return (feature & feature_set);
  15360. }
  15361. /* strcat with additional NULL check to avoid clang scan-build warning. */
  15362. #define strcat0(a, b) \
  15363. { \
  15364. if ((a != NULL) && (b != NULL)) { \
  15365. strcat(a, b); \
  15366. } \
  15367. }
  15368. /* Get system information. It can be printed or stored by the caller.
  15369. * Return the size of available information. */
  15370. static int
  15371. mg_get_system_info_impl(char *buffer, int buflen)
  15372. {
  15373. char block[256];
  15374. int system_info_length = 0;
  15375. #if defined(_WIN32)
  15376. const char *eol = "\r\n";
  15377. #else
  15378. const char *eol = "\n";
  15379. #endif
  15380. const char *eoobj = "}";
  15381. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15382. if ((buffer == NULL) || (buflen < 1)) {
  15383. buflen = 0;
  15384. } else {
  15385. *buffer = 0;
  15386. }
  15387. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15388. system_info_length += (int)strlen(block);
  15389. if (system_info_length < buflen) {
  15390. strcat0(buffer, block);
  15391. }
  15392. /* Server version */
  15393. {
  15394. const char *version = mg_version();
  15395. mg_snprintf(NULL,
  15396. NULL,
  15397. block,
  15398. sizeof(block),
  15399. "\"version\" : \"%s\",%s",
  15400. version,
  15401. eol);
  15402. system_info_length += (int)strlen(block);
  15403. if (system_info_length < buflen) {
  15404. strcat0(buffer, block);
  15405. }
  15406. }
  15407. /* System info */
  15408. {
  15409. #if defined(_WIN32)
  15410. #if !defined(__SYMBIAN32__)
  15411. DWORD dwVersion = 0;
  15412. DWORD dwMajorVersion = 0;
  15413. DWORD dwMinorVersion = 0;
  15414. SYSTEM_INFO si;
  15415. GetSystemInfo(&si);
  15416. #ifdef _MSC_VER
  15417. #pragma warning(push)
  15418. /* GetVersion was declared deprecated */
  15419. #pragma warning(disable : 4996)
  15420. #endif
  15421. dwVersion = GetVersion();
  15422. #ifdef _MSC_VER
  15423. #pragma warning(pop)
  15424. #endif
  15425. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15426. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15427. mg_snprintf(NULL,
  15428. NULL,
  15429. block,
  15430. sizeof(block),
  15431. "\"os\" : \"Windows %u.%u\",%s",
  15432. (unsigned)dwMajorVersion,
  15433. (unsigned)dwMinorVersion,
  15434. eol);
  15435. system_info_length += (int)strlen(block);
  15436. if (system_info_length < buflen) {
  15437. strcat0(buffer, block);
  15438. }
  15439. mg_snprintf(NULL,
  15440. NULL,
  15441. block,
  15442. sizeof(block),
  15443. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  15444. (unsigned)si.wProcessorArchitecture,
  15445. (unsigned)si.dwNumberOfProcessors,
  15446. (unsigned)si.dwActiveProcessorMask,
  15447. eol);
  15448. system_info_length += (int)strlen(block);
  15449. if (system_info_length < buflen) {
  15450. strcat0(buffer, block);
  15451. }
  15452. #else
  15453. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  15454. system_info_length += (int)strlen(block);
  15455. if (system_info_length < buflen) {
  15456. strcat0(buffer, block);
  15457. }
  15458. #endif
  15459. #else
  15460. struct utsname name;
  15461. memset(&name, 0, sizeof(name));
  15462. uname(&name);
  15463. mg_snprintf(NULL,
  15464. NULL,
  15465. block,
  15466. sizeof(block),
  15467. "\"os\" : \"%s %s (%s) - %s\",%s",
  15468. name.sysname,
  15469. name.version,
  15470. name.release,
  15471. name.machine,
  15472. eol);
  15473. system_info_length += (int)strlen(block);
  15474. if (system_info_length < buflen) {
  15475. strcat0(buffer, block);
  15476. }
  15477. #endif
  15478. }
  15479. /* Features */
  15480. {
  15481. mg_snprintf(NULL,
  15482. NULL,
  15483. block,
  15484. sizeof(block),
  15485. "\"features\" : %lu,%s"
  15486. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  15487. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  15488. eol,
  15489. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  15490. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  15491. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  15492. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  15493. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  15494. : "",
  15495. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  15496. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  15497. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  15498. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  15499. eol);
  15500. system_info_length += (int)strlen(block);
  15501. if (system_info_length < buflen) {
  15502. strcat0(buffer, block);
  15503. }
  15504. #ifdef USE_LUA
  15505. mg_snprintf(NULL,
  15506. NULL,
  15507. block,
  15508. sizeof(block),
  15509. "\"lua_version\" : \"%u (%s)\",%s",
  15510. (unsigned)LUA_VERSION_NUM,
  15511. LUA_RELEASE,
  15512. eol);
  15513. system_info_length += (int)strlen(block);
  15514. if (system_info_length < buflen) {
  15515. strcat0(buffer, block);
  15516. }
  15517. #endif
  15518. #if defined(USE_DUKTAPE)
  15519. mg_snprintf(NULL,
  15520. NULL,
  15521. block,
  15522. sizeof(block),
  15523. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  15524. (unsigned)DUK_VERSION / 10000,
  15525. ((unsigned)DUK_VERSION / 100) % 100,
  15526. (unsigned)DUK_VERSION % 100,
  15527. eol);
  15528. system_info_length += (int)strlen(block);
  15529. if (system_info_length < buflen) {
  15530. strcat0(buffer, block);
  15531. }
  15532. #endif
  15533. }
  15534. /* Build date */
  15535. {
  15536. #if defined(__GNUC__)
  15537. #pragma GCC diagnostic push
  15538. /* Disable bogus compiler warning -Wdate-time */
  15539. /* TODO: The obvious flags do not know:
  15540. * #pragma GCC diagnostic ignored "-Wdate-time"
  15541. * If someone knows other flags, please tell me. See also #561.
  15542. */
  15543. #endif
  15544. mg_snprintf(NULL,
  15545. NULL,
  15546. block,
  15547. sizeof(block),
  15548. "\"build\" : \"%s\",%s",
  15549. __DATE__,
  15550. eol);
  15551. #if defined(__GNUC__)
  15552. #pragma GCC diagnostic pop
  15553. #endif
  15554. system_info_length += (int)strlen(block);
  15555. if (system_info_length < buflen) {
  15556. strcat0(buffer, block);
  15557. }
  15558. }
  15559. /* Compiler information */
  15560. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  15561. {
  15562. #if defined(_MSC_VER)
  15563. mg_snprintf(NULL,
  15564. NULL,
  15565. block,
  15566. sizeof(block),
  15567. "\"compiler\" : \"MSC: %u (%u)\",%s",
  15568. (unsigned)_MSC_VER,
  15569. (unsigned)_MSC_FULL_VER,
  15570. eol);
  15571. system_info_length += (int)strlen(block);
  15572. if (system_info_length < buflen) {
  15573. strcat0(buffer, block);
  15574. }
  15575. #elif defined(__MINGW64__)
  15576. mg_snprintf(NULL,
  15577. NULL,
  15578. block,
  15579. sizeof(block),
  15580. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  15581. (unsigned)__MINGW64_VERSION_MAJOR,
  15582. (unsigned)__MINGW64_VERSION_MINOR,
  15583. eol);
  15584. system_info_length += (int)strlen(block);
  15585. if (system_info_length < buflen) {
  15586. strcat0(buffer, block);
  15587. }
  15588. mg_snprintf(NULL,
  15589. NULL,
  15590. block,
  15591. sizeof(block),
  15592. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15593. (unsigned)__MINGW32_MAJOR_VERSION,
  15594. (unsigned)__MINGW32_MINOR_VERSION,
  15595. eol);
  15596. system_info_length += (int)strlen(block);
  15597. if (system_info_length < buflen) {
  15598. strcat0(buffer, block);
  15599. }
  15600. #elif defined(__MINGW32__)
  15601. mg_snprintf(NULL,
  15602. NULL,
  15603. block,
  15604. sizeof(block),
  15605. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15606. (unsigned)__MINGW32_MAJOR_VERSION,
  15607. (unsigned)__MINGW32_MINOR_VERSION,
  15608. eol);
  15609. system_info_length += (int)strlen(block);
  15610. if (system_info_length < buflen) {
  15611. strcat0(buffer, block);
  15612. }
  15613. #elif defined(__clang__)
  15614. mg_snprintf(NULL,
  15615. NULL,
  15616. block,
  15617. sizeof(block),
  15618. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  15619. __clang_major__,
  15620. __clang_minor__,
  15621. __clang_patchlevel__,
  15622. __clang_version__,
  15623. eol);
  15624. system_info_length += (int)strlen(block);
  15625. if (system_info_length < buflen) {
  15626. strcat0(buffer, block);
  15627. }
  15628. #elif defined(__GNUC__)
  15629. mg_snprintf(NULL,
  15630. NULL,
  15631. block,
  15632. sizeof(block),
  15633. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  15634. (unsigned)__GNUC__,
  15635. (unsigned)__GNUC_MINOR__,
  15636. (unsigned)__GNUC_PATCHLEVEL__,
  15637. eol);
  15638. system_info_length += (int)strlen(block);
  15639. if (system_info_length < buflen) {
  15640. strcat0(buffer, block);
  15641. }
  15642. #elif defined(__INTEL_COMPILER)
  15643. mg_snprintf(NULL,
  15644. NULL,
  15645. block,
  15646. sizeof(block),
  15647. "\"compiler\" : \"Intel C/C++: %u\",%s",
  15648. (unsigned)__INTEL_COMPILER,
  15649. eol);
  15650. system_info_length += (int)strlen(block);
  15651. if (system_info_length < buflen) {
  15652. strcat0(buffer, block);
  15653. }
  15654. #elif defined(__BORLANDC__)
  15655. mg_snprintf(NULL,
  15656. NULL,
  15657. block,
  15658. sizeof(block),
  15659. "\"compiler\" : \"Borland C: 0x%x\",%s",
  15660. (unsigned)__BORLANDC__,
  15661. eol);
  15662. system_info_length += (int)strlen(block);
  15663. if (system_info_length < buflen) {
  15664. strcat0(buffer, block);
  15665. }
  15666. #elif defined(__SUNPRO_C)
  15667. mg_snprintf(NULL,
  15668. NULL,
  15669. block,
  15670. sizeof(block),
  15671. "\"compiler\" : \"Solaris: 0x%x\",%s",
  15672. (unsigned)__SUNPRO_C,
  15673. eol);
  15674. system_info_length += (int)strlen(block);
  15675. if (system_info_length < buflen) {
  15676. strcat0(buffer, block);
  15677. }
  15678. #else
  15679. mg_snprintf(NULL,
  15680. NULL,
  15681. block,
  15682. sizeof(block),
  15683. "\"compiler\" : \"other\",%s",
  15684. eol);
  15685. system_info_length += (int)strlen(block);
  15686. if (system_info_length < buflen) {
  15687. strcat0(buffer, block);
  15688. }
  15689. #endif
  15690. }
  15691. /* Determine 32/64 bit data mode.
  15692. * see https://en.wikipedia.org/wiki/64-bit_computing */
  15693. {
  15694. mg_snprintf(NULL,
  15695. NULL,
  15696. block,
  15697. sizeof(block),
  15698. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  15699. "char:%u/%u, "
  15700. "ptr:%u, size:%u, time:%u\"%s",
  15701. (unsigned)sizeof(short),
  15702. (unsigned)sizeof(int),
  15703. (unsigned)sizeof(long),
  15704. (unsigned)sizeof(long long),
  15705. (unsigned)sizeof(float),
  15706. (unsigned)sizeof(double),
  15707. (unsigned)sizeof(long double),
  15708. (unsigned)sizeof(char),
  15709. (unsigned)sizeof(wchar_t),
  15710. (unsigned)sizeof(void *),
  15711. (unsigned)sizeof(size_t),
  15712. (unsigned)sizeof(time_t),
  15713. eol);
  15714. system_info_length += (int)strlen(block);
  15715. if (system_info_length < buflen) {
  15716. strcat0(buffer, block);
  15717. }
  15718. }
  15719. /* Terminate string */
  15720. if ((buflen > 0) && buffer && buffer[0]) {
  15721. if (system_info_length < buflen) {
  15722. strcat0(buffer, eoobj);
  15723. strcat0(buffer, eol);
  15724. }
  15725. }
  15726. system_info_length += reserved_len;
  15727. return system_info_length;
  15728. }
  15729. #if defined(USE_SERVER_STATS)
  15730. /* Get context information. It can be printed or stored by the caller.
  15731. * Return the size of available information. */
  15732. static int
  15733. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  15734. {
  15735. char block[256];
  15736. int context_info_length = 0;
  15737. #if defined(_WIN32)
  15738. const char *eol = "\r\n";
  15739. #else
  15740. const char *eol = "\n";
  15741. #endif
  15742. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  15743. const char *eoobj = "}";
  15744. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15745. if ((buffer == NULL) || (buflen < 1)) {
  15746. buflen = 0;
  15747. } else {
  15748. *buffer = 0;
  15749. }
  15750. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15751. context_info_length += (int)strlen(block);
  15752. if (context_info_length < buflen) {
  15753. strcat0(buffer, block);
  15754. }
  15755. /* Memory information */
  15756. if (ms) {
  15757. mg_snprintf(NULL,
  15758. NULL,
  15759. block,
  15760. sizeof(block),
  15761. "\"memory\" : {%s"
  15762. "\"blocks\" : %i,%s"
  15763. "\"used\" : %" INT64_FMT ",%s"
  15764. "\"maxUsed\" : %" INT64_FMT "%s"
  15765. "}%s%s",
  15766. eol,
  15767. ms->blockCount,
  15768. eol,
  15769. ms->totalMemUsed,
  15770. eol,
  15771. ms->maxMemUsed,
  15772. eol,
  15773. (ctx ? "," : ""),
  15774. eol);
  15775. context_info_length += (int)strlen(block);
  15776. if (context_info_length + reserved_len < buflen) {
  15777. strcat0(buffer, block);
  15778. }
  15779. }
  15780. /* Connections information */
  15781. if (ctx) {
  15782. mg_snprintf(NULL,
  15783. NULL,
  15784. block,
  15785. sizeof(block),
  15786. "\"connections\" : {%s"
  15787. "\"active\" : %i,%s"
  15788. "\"maxActive\" : %i,%s"
  15789. "\"total\" : %" INT64_FMT "%s"
  15790. "},%s",
  15791. eol,
  15792. ctx->active_connections,
  15793. eol,
  15794. ctx->max_connections,
  15795. eol,
  15796. ctx->total_connections,
  15797. eol,
  15798. eol);
  15799. context_info_length += (int)strlen(block);
  15800. if (context_info_length + reserved_len < buflen) {
  15801. strcat0(buffer, block);
  15802. }
  15803. }
  15804. /* Requests information */
  15805. if (ctx) {
  15806. mg_snprintf(NULL,
  15807. NULL,
  15808. block,
  15809. sizeof(block),
  15810. "\"requests\" : {%s"
  15811. "\"total\" : %" INT64_FMT "%s"
  15812. "},%s",
  15813. eol,
  15814. ctx->total_requests,
  15815. eol,
  15816. eol);
  15817. context_info_length += (int)strlen(block);
  15818. if (context_info_length + reserved_len < buflen) {
  15819. strcat0(buffer, block);
  15820. }
  15821. }
  15822. /* Data information */
  15823. if (ctx) {
  15824. mg_snprintf(NULL,
  15825. NULL,
  15826. block,
  15827. sizeof(block),
  15828. "\"data\" : {%s"
  15829. "\"read\" : %" INT64_FMT "%s,"
  15830. "\"written\" : %" INT64_FMT "%s"
  15831. "},%s",
  15832. eol,
  15833. ctx->total_data_read,
  15834. eol,
  15835. ctx->total_data_written,
  15836. eol,
  15837. eol);
  15838. context_info_length += (int)strlen(block);
  15839. if (context_info_length + reserved_len < buflen) {
  15840. strcat0(buffer, block);
  15841. }
  15842. }
  15843. /* Execution time information */
  15844. if (ctx) {
  15845. char start_time_str[64] = {0};
  15846. char now_str[64] = {0};
  15847. time_t start_time = ctx->start_time;
  15848. time_t now = time(NULL);
  15849. gmt_time_string(start_time_str,
  15850. sizeof(start_time_str) - 1,
  15851. &start_time);
  15852. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15853. mg_snprintf(NULL,
  15854. NULL,
  15855. block,
  15856. sizeof(block),
  15857. "\"time\" : {%s"
  15858. "\"uptime\" : %.0f,%s"
  15859. "\"start\" : \"%s\",%s"
  15860. "\"now\" : \"%s\"%s"
  15861. "}%s",
  15862. eol,
  15863. difftime(now, start_time),
  15864. eol,
  15865. start_time_str,
  15866. eol,
  15867. now_str,
  15868. eol,
  15869. eol);
  15870. context_info_length += (int)strlen(block);
  15871. if (context_info_length + reserved_len < buflen) {
  15872. strcat0(buffer, block);
  15873. }
  15874. }
  15875. /* Terminate string */
  15876. if ((buflen > 0) && buffer && buffer[0]) {
  15877. if (context_info_length < buflen) {
  15878. strcat0(buffer, eoobj);
  15879. strcat0(buffer, eol);
  15880. }
  15881. }
  15882. context_info_length += reserved_len;
  15883. return context_info_length;
  15884. }
  15885. #endif
  15886. #ifdef MG_EXPERIMENTAL_INTERFACES
  15887. /* Get connection information. It can be printed or stored by the caller.
  15888. * Return the size of available information. */
  15889. static int
  15890. mg_get_connection_info_impl(const struct mg_context *ctx,
  15891. int idx,
  15892. char *buffer,
  15893. int buflen)
  15894. {
  15895. const struct mg_connection *conn;
  15896. const struct mg_request_info *ri;
  15897. char block[256];
  15898. int connection_info_length = 0;
  15899. int state = 0;
  15900. const char *state_str = "unknown";
  15901. #if defined(_WIN32)
  15902. const char *eol = "\r\n";
  15903. #else
  15904. const char *eol = "\n";
  15905. #endif
  15906. const char *eoobj = "}";
  15907. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15908. if ((buffer == NULL) || (buflen < 1)) {
  15909. buflen = 0;
  15910. } else {
  15911. *buffer = 0;
  15912. }
  15913. if ((ctx == NULL) || (idx < 0)) {
  15914. /* Parameter error */
  15915. return 0;
  15916. }
  15917. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  15918. /* Out of range */
  15919. return 0;
  15920. }
  15921. /* Take connection [idx]. This connection is not locked in
  15922. * any way, so some other thread might use it. */
  15923. conn = (ctx->worker_connections) + idx;
  15924. /* Initialize output string */
  15925. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15926. connection_info_length += (int)strlen(block);
  15927. if (connection_info_length < buflen) {
  15928. strcat0(buffer, block);
  15929. }
  15930. /* Init variables */
  15931. ri = &(conn->request_info);
  15932. #if defined(USE_SERVER_STATS)
  15933. state = conn->conn_state;
  15934. /* State as string */
  15935. switch (state) {
  15936. case 0:
  15937. state_str = "undefined";
  15938. break;
  15939. case 1:
  15940. state_str = "not used";
  15941. break;
  15942. case 2:
  15943. state_str = "init";
  15944. break;
  15945. case 3:
  15946. state_str = "ready";
  15947. break;
  15948. case 4:
  15949. state_str = "processing";
  15950. break;
  15951. case 5:
  15952. state_str = "processed";
  15953. break;
  15954. case 6:
  15955. state_str = "to close";
  15956. break;
  15957. case 7:
  15958. state_str = "closing";
  15959. break;
  15960. case 8:
  15961. state_str = "closed";
  15962. break;
  15963. case 9:
  15964. state_str = "done";
  15965. break;
  15966. }
  15967. #endif
  15968. /* Connection info */
  15969. if ((state >= 3) && (state < 9)) {
  15970. mg_snprintf(NULL,
  15971. NULL,
  15972. block,
  15973. sizeof(block),
  15974. "\"connection\" : {%s"
  15975. "\"remote\" : {%s"
  15976. "\"protocol\" : \"%s\",%s"
  15977. "\"addr\" : \"%s\",%s"
  15978. "\"port\" : %u%s"
  15979. "},%s"
  15980. "\"handled_requests\" : %u%s"
  15981. "},%s",
  15982. eol,
  15983. eol,
  15984. get_proto_name(conn),
  15985. eol,
  15986. ri->remote_addr,
  15987. eol,
  15988. ri->remote_port,
  15989. eol,
  15990. eol,
  15991. conn->handled_requests,
  15992. eol,
  15993. eol);
  15994. connection_info_length += (int)strlen(block);
  15995. if (connection_info_length + reserved_len < buflen) {
  15996. strcat0(buffer, block);
  15997. }
  15998. }
  15999. /* Request info */
  16000. if ((state >= 4) && (state < 6)) {
  16001. mg_snprintf(NULL,
  16002. NULL,
  16003. block,
  16004. sizeof(block),
  16005. "\"request_info\" : {%s"
  16006. "\"method\" : \"%s\",%s"
  16007. "\"uri\" : \"%s\",%s"
  16008. "\"query\" : %s%s%s%s"
  16009. "},%s",
  16010. eol,
  16011. ri->request_method,
  16012. eol,
  16013. ri->request_uri,
  16014. eol,
  16015. ri->query_string ? "\"" : "",
  16016. ri->query_string ? ri->query_string : "null",
  16017. ri->query_string ? "\"" : "",
  16018. eol,
  16019. eol);
  16020. connection_info_length += (int)strlen(block);
  16021. if (connection_info_length + reserved_len < buflen) {
  16022. strcat0(buffer, block);
  16023. }
  16024. }
  16025. /* Execution time information */
  16026. if ((state >= 2) && (state < 9)) {
  16027. char start_time_str[64] = {0};
  16028. char now_str[64] = {0};
  16029. time_t start_time = conn->conn_birth_time;
  16030. time_t now = time(NULL);
  16031. gmt_time_string(start_time_str,
  16032. sizeof(start_time_str) - 1,
  16033. &start_time);
  16034. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16035. mg_snprintf(NULL,
  16036. NULL,
  16037. block,
  16038. sizeof(block),
  16039. "\"time\" : {%s"
  16040. "\"uptime\" : %.0f,%s"
  16041. "\"start\" : \"%s\",%s"
  16042. "\"now\" : \"%s\"%s"
  16043. "},%s",
  16044. eol,
  16045. difftime(now, start_time),
  16046. eol,
  16047. start_time_str,
  16048. eol,
  16049. now_str,
  16050. eol,
  16051. eol);
  16052. connection_info_length += (int)strlen(block);
  16053. if (connection_info_length + reserved_len < buflen) {
  16054. strcat0(buffer, block);
  16055. }
  16056. }
  16057. /* Remote user name */
  16058. if ((ri->remote_user) && (state < 9)) {
  16059. mg_snprintf(NULL,
  16060. NULL,
  16061. block,
  16062. sizeof(block),
  16063. "\"user\" : {%s"
  16064. "\"name\" : \"%s\",%s"
  16065. "},%s",
  16066. eol,
  16067. ri->remote_user,
  16068. eol,
  16069. eol);
  16070. connection_info_length += (int)strlen(block);
  16071. if (connection_info_length + reserved_len < buflen) {
  16072. strcat0(buffer, block);
  16073. }
  16074. }
  16075. /* Data block */
  16076. if (state >= 3) {
  16077. mg_snprintf(NULL,
  16078. NULL,
  16079. block,
  16080. sizeof(block),
  16081. "\"data\" : {%s"
  16082. "\"read\" : %" INT64_FMT ",%s"
  16083. "\"written\" : %" INT64_FMT "%s"
  16084. "},%s",
  16085. eol,
  16086. conn->consumed_content,
  16087. eol,
  16088. conn->num_bytes_sent,
  16089. eol,
  16090. eol);
  16091. connection_info_length += (int)strlen(block);
  16092. if (connection_info_length + reserved_len < buflen) {
  16093. strcat0(buffer, block);
  16094. }
  16095. }
  16096. /* State */
  16097. mg_snprintf(NULL,
  16098. NULL,
  16099. block,
  16100. sizeof(block),
  16101. "\"state\" : \"%s\"%s",
  16102. state_str,
  16103. eol);
  16104. connection_info_length += (int)strlen(block);
  16105. if (connection_info_length + reserved_len < buflen) {
  16106. strcat0(buffer, block);
  16107. }
  16108. /* Terminate string */
  16109. if ((buflen > 0) && buffer && buffer[0]) {
  16110. if (connection_info_length < buflen) {
  16111. strcat0(buffer, eoobj);
  16112. strcat0(buffer, eol);
  16113. }
  16114. }
  16115. connection_info_length += reserved_len;
  16116. return connection_info_length;
  16117. }
  16118. #endif
  16119. /* Get system information. It can be printed or stored by the caller.
  16120. * Return the size of available information. */
  16121. int
  16122. mg_get_system_info(char *buffer, int buflen)
  16123. {
  16124. if ((buffer == NULL) || (buflen < 1)) {
  16125. return mg_get_system_info_impl(NULL, 0);
  16126. } else {
  16127. /* Reset buffer, so we can always use strcat. */
  16128. buffer[0] = 0;
  16129. return mg_get_system_info_impl(buffer, buflen);
  16130. }
  16131. }
  16132. /* Get context information. It can be printed or stored by the caller.
  16133. * Return the size of available information. */
  16134. int
  16135. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16136. {
  16137. #if defined(USE_SERVER_STATS)
  16138. if ((buffer == NULL) || (buflen < 1)) {
  16139. return mg_get_context_info_impl(ctx, NULL, 0);
  16140. } else {
  16141. /* Reset buffer, so we can always use strcat. */
  16142. buffer[0] = 0;
  16143. return mg_get_context_info_impl(ctx, buffer, buflen);
  16144. }
  16145. #else
  16146. (void)ctx;
  16147. if ((buffer != NULL) && (buflen > 0)) {
  16148. buffer[0] = 0;
  16149. }
  16150. return 0;
  16151. #endif
  16152. }
  16153. #ifdef MG_EXPERIMENTAL_INTERFACES
  16154. int
  16155. mg_get_connection_info(const struct mg_context *ctx,
  16156. int idx,
  16157. char *buffer,
  16158. int buflen)
  16159. {
  16160. if ((buffer == NULL) || (buflen < 1)) {
  16161. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  16162. } else {
  16163. /* Reset buffer, so we can always use strcat. */
  16164. buffer[0] = 0;
  16165. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  16166. }
  16167. }
  16168. #endif
  16169. /* Initialize this library. This function does not need to be thread safe.
  16170. */
  16171. unsigned
  16172. mg_init_library(unsigned features)
  16173. {
  16174. #if !defined(NO_SSL)
  16175. char ebuf[128];
  16176. #endif
  16177. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  16178. unsigned features_inited = features_to_init;
  16179. if (mg_init_library_called <= 0) {
  16180. /* Not initialized yet */
  16181. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  16182. return 0;
  16183. }
  16184. }
  16185. mg_global_lock();
  16186. if (mg_init_library_called <= 0) {
  16187. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  16188. /* Fatal error - abort start. However, this situation should
  16189. * never occur in practice. */
  16190. mg_global_unlock();
  16191. return 0;
  16192. }
  16193. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16194. InitializeCriticalSection(&global_log_file_lock);
  16195. #endif /* _WIN32 && !__SYMBIAN32__ */
  16196. #if !defined(_WIN32)
  16197. pthread_mutexattr_init(&pthread_mutex_attr);
  16198. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  16199. #endif
  16200. #if defined(USE_LUA)
  16201. lua_init_optional_libraries();
  16202. #endif
  16203. }
  16204. mg_global_unlock();
  16205. #if !defined(NO_SSL)
  16206. if (features_to_init & MG_FEATURES_SSL) {
  16207. if (!mg_ssl_initialized) {
  16208. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  16209. mg_ssl_initialized = 1;
  16210. } else {
  16211. (void)ebuf;
  16212. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  16213. features_inited &= ~(2u);
  16214. }
  16215. } else {
  16216. /* ssl already initialized */
  16217. }
  16218. }
  16219. #endif
  16220. /* Start WinSock for Windows */
  16221. mg_global_lock();
  16222. if (mg_init_library_called <= 0) {
  16223. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16224. WSADATA data;
  16225. WSAStartup(MAKEWORD(2, 2), &data);
  16226. #endif /* _WIN32 && !__SYMBIAN32__ */
  16227. mg_init_library_called = 1;
  16228. } else {
  16229. mg_init_library_called++;
  16230. }
  16231. mg_global_unlock();
  16232. return features_inited;
  16233. }
  16234. /* Un-initialize this library. */
  16235. unsigned
  16236. mg_exit_library(void)
  16237. {
  16238. if (mg_init_library_called <= 0) {
  16239. return 0;
  16240. }
  16241. mg_global_lock();
  16242. mg_init_library_called--;
  16243. if (mg_init_library_called == 0) {
  16244. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16245. (void)WSACleanup();
  16246. #endif /* _WIN32 && !__SYMBIAN32__ */
  16247. #if !defined(NO_SSL)
  16248. if (mg_ssl_initialized) {
  16249. uninitialize_ssl();
  16250. mg_ssl_initialized = 0;
  16251. }
  16252. #endif
  16253. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16254. (void)DeleteCriticalSection(&global_log_file_lock);
  16255. #endif /* _WIN32 && !__SYMBIAN32__ */
  16256. #if !defined(_WIN32)
  16257. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  16258. #endif
  16259. (void)pthread_key_delete(sTlsKey);
  16260. #if defined(USE_LUA)
  16261. lua_exit_optional_libraries();
  16262. #endif
  16263. mg_global_unlock();
  16264. (void)pthread_mutex_destroy(&global_lock_mutex);
  16265. return 1;
  16266. }
  16267. mg_global_unlock();
  16268. return 1;
  16269. }
  16270. /* End of civetweb.c */