civetweb.c 478 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215
  1. /* Copyright (c) 2013-2017 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* Alternative queue is well tested and should be the new default */
  92. #ifdef NO_ALTERNATIVE_QUEUE
  93. #ifdef ALTERNATIVE_QUEUE
  94. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  95. #endif
  96. #else
  97. #define ALTERNATIVE_QUEUE
  98. #endif
  99. /* DTL -- including winsock2.h works better if lean and mean */
  100. #ifndef WIN32_LEAN_AND_MEAN
  101. #define WIN32_LEAN_AND_MEAN
  102. #endif
  103. #if defined(__SYMBIAN32__)
  104. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  105. * Symbian is no longer maintained since 2014-01-01.
  106. * Recent versions of CivetWeb are no longer tested for Symbian.
  107. * It makes no sense, to support an abandoned operating system.
  108. * All remaining "#ifdef __SYMBIAN__" cases will be droped from
  109. * the code sooner or later.
  110. */
  111. #pragma message \
  112. "Symbian is no longer maintained. CivetWeb will drop Symbian support."
  113. #define NO_SSL /* SSL is not supported */
  114. #define NO_CGI /* CGI is not supported */
  115. #define PATH_MAX FILENAME_MAX
  116. #endif /* __SYMBIAN32__ */
  117. #ifndef CIVETWEB_HEADER_INCLUDED
  118. /* Include the header file here, so the CivetWeb interface is defined for the
  119. * entire implementation, including the following forward definitions. */
  120. #include "civetweb.h"
  121. #endif
  122. #ifndef IGNORE_UNUSED_RESULT
  123. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  124. #endif
  125. #if defined(__GNUC__) || defined(__MINGW32__)
  126. /* GCC unused function attribute seems fundamentally broken.
  127. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  128. * OR UNUSED" for individual functions failed.
  129. * Either the compiler creates an "unused-function" warning if a
  130. * function is not marked with __attribute__((unused)).
  131. * On the other hand, if the function is marked with this attribute,
  132. * but is used, the compiler raises a completely idiotic
  133. * "used-but-marked-unused" warning - and
  134. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  135. * raises error: unknown option after ‘#pragma GCC diagnostic’.
  136. * Disable this warning completely, until the GCC guys sober up
  137. * again.
  138. */
  139. #pragma GCC diagnostic ignored "-Wunused-function"
  140. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  141. #else
  142. #define FUNCTION_MAY_BE_UNUSED
  143. #endif
  144. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  145. #include <sys/types.h>
  146. #include <sys/stat.h>
  147. #include <errno.h>
  148. #include <signal.h>
  149. #include <fcntl.h>
  150. #endif /* !_WIN32_WCE */
  151. #ifdef __clang__
  152. /* When using -Weverything, clang does not accept it's own headers
  153. * in a release build configuration. Disable what is too much in
  154. * -Weverything. */
  155. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  156. #endif
  157. #if defined(__GNUC__) || defined(__MINGW32__)
  158. /* Who on earth came to the conclusion, using __DATE__ should rise
  159. * an "expansion of date or time macro is not reproducible"
  160. * warning. That's exactly what was intended by using this macro.
  161. * Just disable this nonsense warning. */
  162. /* And disabling them does not work either:
  163. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  164. * #pragma clang diagnostic ignored "-Wdate-time"
  165. * So we just have to disable ALL warnings for some lines
  166. * of code.
  167. */
  168. #endif
  169. #ifdef __MACH__ /* Apple OSX section */
  170. #ifdef __clang__
  171. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  172. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  173. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  174. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  175. #endif
  176. #endif
  177. #define CLOCK_MONOTONIC (1)
  178. #define CLOCK_REALTIME (2)
  179. #include <sys/errno.h>
  180. #include <sys/time.h>
  181. #include <mach/clock.h>
  182. #include <mach/mach.h>
  183. #include <mach/mach_time.h>
  184. #include <assert.h>
  185. /* clock_gettime is not implemented on OSX prior to 10.12 */
  186. static int
  187. _civet_clock_gettime(int clk_id, struct timespec *t)
  188. {
  189. memset(t, 0, sizeof(*t));
  190. if (clk_id == CLOCK_REALTIME) {
  191. struct timeval now;
  192. int rv = gettimeofday(&now, NULL);
  193. if (rv) {
  194. return rv;
  195. }
  196. t->tv_sec = now.tv_sec;
  197. t->tv_nsec = now.tv_usec * 1000;
  198. return 0;
  199. } else if (clk_id == CLOCK_MONOTONIC) {
  200. static uint64_t clock_start_time = 0;
  201. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  202. uint64_t now = mach_absolute_time();
  203. if (clock_start_time == 0) {
  204. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  205. #if defined(DEBUG)
  206. assert(mach_status == KERN_SUCCESS);
  207. #else
  208. /* appease "unused variable" warning for release builds */
  209. (void)mach_status;
  210. #endif
  211. clock_start_time = now;
  212. }
  213. now = (uint64_t)((double)(now - clock_start_time)
  214. * (double)timebase_ifo.numer
  215. / (double)timebase_ifo.denom);
  216. t->tv_sec = now / 1000000000;
  217. t->tv_nsec = now % 1000000000;
  218. return 0;
  219. }
  220. return -1; /* EINVAL - Clock ID is unknown */
  221. }
  222. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  223. #ifdef __CLOCK_AVAILABILITY
  224. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  225. * declared but it may be NULL at runtime. So we need to check before using
  226. * it. */
  227. static int
  228. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  229. {
  230. if (clock_gettime) {
  231. return clock_gettime(clk_id, t);
  232. }
  233. return _civet_clock_gettime(clk_id, t);
  234. }
  235. #define clock_gettime _civet_safe_clock_gettime
  236. #else
  237. #define clock_gettime _civet_clock_gettime
  238. #endif
  239. #endif
  240. #include <time.h>
  241. #include <stdlib.h>
  242. #include <stdarg.h>
  243. #include <assert.h>
  244. #include <string.h>
  245. #include <ctype.h>
  246. #include <limits.h>
  247. #include <stddef.h>
  248. #include <stdio.h>
  249. #include <stdint.h>
  250. #ifndef INT64_MAX
  251. #define INT64_MAX (9223372036854775807)
  252. #endif
  253. #ifndef MAX_WORKER_THREADS
  254. #define MAX_WORKER_THREADS (1024 * 64)
  255. #endif
  256. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  257. #define SOCKET_TIMEOUT_QUANTUM (2000)
  258. #endif
  259. #define SHUTDOWN_RD (0)
  260. #define SHUTDOWN_WR (1)
  261. #define SHUTDOWN_BOTH (2)
  262. mg_static_assert(MAX_WORKER_THREADS >= 1,
  263. "worker threads must be a positive number");
  264. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  265. "size_t data type size check");
  266. #if defined(_WIN32) \
  267. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  268. #include <windows.h>
  269. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  270. #include <ws2tcpip.h>
  271. typedef const char *SOCK_OPT_TYPE;
  272. #if !defined(PATH_MAX)
  273. #define PATH_MAX (MAX_PATH)
  274. #endif
  275. #if !defined(PATH_MAX)
  276. #define PATH_MAX (4096)
  277. #endif
  278. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  279. #ifndef _IN_PORT_T
  280. #ifndef in_port_t
  281. #define in_port_t u_short
  282. #endif
  283. #endif
  284. #ifndef _WIN32_WCE
  285. #include <process.h>
  286. #include <direct.h>
  287. #include <io.h>
  288. #else /* _WIN32_WCE */
  289. #define NO_CGI /* WinCE has no pipes */
  290. #define NO_POPEN /* WinCE has no popen */
  291. typedef long off_t;
  292. #define errno ((int)(GetLastError()))
  293. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  294. #endif /* _WIN32_WCE */
  295. #define MAKEUQUAD(lo, hi) \
  296. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  297. #define RATE_DIFF (10000000) /* 100 nsecs */
  298. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  299. #define SYS2UNIX_TIME(lo, hi) \
  300. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  301. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  302. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  303. * Also use _strtoui64 on modern M$ compilers */
  304. #if defined(_MSC_VER)
  305. #if (_MSC_VER < 1300)
  306. #define STRX(x) #x
  307. #define STR(x) STRX(x)
  308. #define __func__ __FILE__ ":" STR(__LINE__)
  309. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  310. #define strtoll(x, y, z) (_atoi64(x))
  311. #else
  312. #define __func__ __FUNCTION__
  313. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  314. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  315. #endif
  316. #endif /* _MSC_VER */
  317. #define ERRNO ((int)(GetLastError()))
  318. #define NO_SOCKLEN_T
  319. #if defined(_WIN64) || defined(__MINGW64__)
  320. #define SSL_LIB "ssleay64.dll"
  321. #define CRYPTO_LIB "libeay64.dll"
  322. #else
  323. #define SSL_LIB "ssleay32.dll"
  324. #define CRYPTO_LIB "libeay32.dll"
  325. #endif
  326. #define O_NONBLOCK (0)
  327. #ifndef W_OK
  328. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  329. #endif
  330. #if !defined(EWOULDBLOCK)
  331. #define EWOULDBLOCK WSAEWOULDBLOCK
  332. #endif /* !EWOULDBLOCK */
  333. #define _POSIX_
  334. #define INT64_FMT "I64d"
  335. #define UINT64_FMT "I64u"
  336. #define WINCDECL __cdecl
  337. #define vsnprintf_impl _vsnprintf
  338. #define access _access
  339. #define mg_sleep(x) (Sleep(x))
  340. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  341. #ifndef popen
  342. #define popen(x, y) (_popen(x, y))
  343. #endif
  344. #ifndef pclose
  345. #define pclose(x) (_pclose(x))
  346. #endif
  347. #define close(x) (_close(x))
  348. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  349. #define RTLD_LAZY (0)
  350. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  351. #define fdopen(x, y) (_fdopen((x), (y)))
  352. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  353. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  354. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  355. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  356. #define sleep(x) (Sleep((x)*1000))
  357. #define rmdir(x) (_rmdir(x))
  358. #define timegm(x) (_mkgmtime(x))
  359. #if !defined(fileno)
  360. #define fileno(x) (_fileno(x))
  361. #endif /* !fileno MINGW #defines fileno */
  362. typedef HANDLE pthread_mutex_t;
  363. typedef DWORD pthread_key_t;
  364. typedef HANDLE pthread_t;
  365. typedef struct {
  366. CRITICAL_SECTION threadIdSec;
  367. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  368. } pthread_cond_t;
  369. #ifndef __clockid_t_defined
  370. typedef DWORD clockid_t;
  371. #endif
  372. #ifndef CLOCK_MONOTONIC
  373. #define CLOCK_MONOTONIC (1)
  374. #endif
  375. #ifndef CLOCK_REALTIME
  376. #define CLOCK_REALTIME (2)
  377. #endif
  378. #ifndef CLOCK_THREAD
  379. #define CLOCK_THREAD (3)
  380. #endif
  381. #ifndef CLOCK_PROCESS
  382. #define CLOCK_PROCESS (4)
  383. #endif
  384. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  385. #define _TIMESPEC_DEFINED
  386. #endif
  387. #ifndef _TIMESPEC_DEFINED
  388. struct timespec {
  389. time_t tv_sec; /* seconds */
  390. long tv_nsec; /* nanoseconds */
  391. };
  392. #endif
  393. #if !defined(WIN_PTHREADS_TIME_H)
  394. #define MUST_IMPLEMENT_CLOCK_GETTIME
  395. #endif
  396. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  397. #define clock_gettime mg_clock_gettime
  398. static int
  399. clock_gettime(clockid_t clk_id, struct timespec *tp)
  400. {
  401. FILETIME ft;
  402. ULARGE_INTEGER li, li2;
  403. BOOL ok = FALSE;
  404. double d;
  405. static double perfcnt_per_sec = 0.0;
  406. if (tp) {
  407. memset(tp, 0, sizeof(*tp));
  408. if (clk_id == CLOCK_REALTIME) {
  409. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  410. GetSystemTimeAsFileTime(&ft);
  411. li.LowPart = ft.dwLowDateTime;
  412. li.HighPart = ft.dwHighDateTime;
  413. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  414. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  415. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  416. ok = TRUE;
  417. /* END: CLOCK_REALTIME */
  418. } else if (clk_id == CLOCK_MONOTONIC) {
  419. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  420. if (perfcnt_per_sec == 0.0) {
  421. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  422. perfcnt_per_sec = 1.0 / li.QuadPart;
  423. }
  424. if (perfcnt_per_sec != 0.0) {
  425. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  426. d = li.QuadPart * perfcnt_per_sec;
  427. tp->tv_sec = (time_t)d;
  428. d -= tp->tv_sec;
  429. tp->tv_nsec = (long)(d * 1.0E9);
  430. ok = TRUE;
  431. }
  432. /* END: CLOCK_MONOTONIC */
  433. } else if (clk_id == CLOCK_THREAD) {
  434. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  435. FILETIME t_create, t_exit, t_kernel, t_user;
  436. if (GetThreadTimes(GetCurrentThread(),
  437. &t_create,
  438. &t_exit,
  439. &t_kernel,
  440. &t_user)) {
  441. li.LowPart = t_user.dwLowDateTime;
  442. li.HighPart = t_user.dwHighDateTime;
  443. li2.LowPart = t_kernel.dwLowDateTime;
  444. li2.HighPart = t_kernel.dwHighDateTime;
  445. li.QuadPart += li2.QuadPart;
  446. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  447. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  448. ok = TRUE;
  449. }
  450. /* END: CLOCK_THREAD */
  451. } else if (clk_id == CLOCK_PROCESS) {
  452. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  453. FILETIME t_create, t_exit, t_kernel, t_user;
  454. if (GetProcessTimes(GetCurrentProcess(),
  455. &t_create,
  456. &t_exit,
  457. &t_kernel,
  458. &t_user)) {
  459. li.LowPart = t_user.dwLowDateTime;
  460. li.HighPart = t_user.dwHighDateTime;
  461. li2.LowPart = t_kernel.dwLowDateTime;
  462. li2.HighPart = t_kernel.dwHighDateTime;
  463. li.QuadPart += li2.QuadPart;
  464. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  465. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  466. ok = TRUE;
  467. }
  468. /* END: CLOCK_PROCESS */
  469. } else {
  470. /* BEGIN: unknown clock */
  471. /* ok = FALSE; already set by init */
  472. /* END: unknown clock */
  473. }
  474. }
  475. return ok ? 0 : -1;
  476. }
  477. #endif
  478. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  479. static int pthread_mutex_lock(pthread_mutex_t *);
  480. static int pthread_mutex_unlock(pthread_mutex_t *);
  481. static void path_to_unicode(const struct mg_connection *conn,
  482. const char *path,
  483. wchar_t *wbuf,
  484. size_t wbuf_len);
  485. /* All file operations need to be rewritten to solve #246. */
  486. #include "file_ops.inl"
  487. struct mg_file;
  488. static const char *
  489. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  490. /* POSIX dirent interface */
  491. struct dirent {
  492. char d_name[PATH_MAX];
  493. };
  494. typedef struct DIR {
  495. HANDLE handle;
  496. WIN32_FIND_DATAW info;
  497. struct dirent result;
  498. } DIR;
  499. #if defined(_WIN32) && !defined(POLLIN)
  500. #ifndef HAVE_POLL
  501. struct pollfd {
  502. SOCKET fd;
  503. short events;
  504. short revents;
  505. };
  506. #define POLLIN (0x0300)
  507. #endif
  508. #endif
  509. /* Mark required libraries */
  510. #if defined(_MSC_VER)
  511. #pragma comment(lib, "Ws2_32.lib")
  512. #endif
  513. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  514. WINDOWS / UNIX include block */
  515. #include <sys/wait.h>
  516. #include <sys/socket.h>
  517. #include <sys/poll.h>
  518. #include <netinet/in.h>
  519. #include <arpa/inet.h>
  520. #include <sys/time.h>
  521. #include <sys/utsname.h>
  522. #include <stdint.h>
  523. #include <inttypes.h>
  524. #include <netdb.h>
  525. #include <netinet/tcp.h>
  526. typedef const void *SOCK_OPT_TYPE;
  527. #if defined(ANDROID)
  528. typedef unsigned short int in_port_t;
  529. #endif
  530. #include <pwd.h>
  531. #include <unistd.h>
  532. #include <grp.h>
  533. #include <dirent.h>
  534. #define vsnprintf_impl vsnprintf
  535. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  536. #include <dlfcn.h>
  537. #endif
  538. #include <pthread.h>
  539. #if defined(__MACH__)
  540. #define SSL_LIB "libssl.dylib"
  541. #define CRYPTO_LIB "libcrypto.dylib"
  542. #else
  543. #if !defined(SSL_LIB)
  544. #define SSL_LIB "libssl.so"
  545. #endif
  546. #if !defined(CRYPTO_LIB)
  547. #define CRYPTO_LIB "libcrypto.so"
  548. #endif
  549. #endif
  550. #ifndef O_BINARY
  551. #define O_BINARY (0)
  552. #endif /* O_BINARY */
  553. #define closesocket(a) (close(a))
  554. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  555. #define mg_remove(conn, x) (remove(x))
  556. #define mg_sleep(x) (usleep((x)*1000))
  557. #define mg_opendir(conn, x) (opendir(x))
  558. #define mg_closedir(x) (closedir(x))
  559. #define mg_readdir(x) (readdir(x))
  560. #define ERRNO (errno)
  561. #define INVALID_SOCKET (-1)
  562. #define INT64_FMT PRId64
  563. #define UINT64_FMT PRIu64
  564. typedef int SOCKET;
  565. #define WINCDECL
  566. #if defined(__hpux)
  567. /* HPUX 11 does not have monotonic, fall back to realtime */
  568. #ifndef CLOCK_MONOTONIC
  569. #define CLOCK_MONOTONIC CLOCK_REALTIME
  570. #endif
  571. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  572. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  573. * the prototypes use int* rather than socklen_t* which matches the
  574. * actual library expectation. When called with the wrong size arg
  575. * accept() returns a zero client inet addr and check_acl() always
  576. * fails. Since socklen_t is widely used below, just force replace
  577. * their typedef with int. - DTL
  578. */
  579. #define socklen_t int
  580. #endif /* hpux */
  581. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  582. WINDOWS / UNIX include block */
  583. /* va_copy should always be a macro, C99 and C++11 - DTL */
  584. #ifndef va_copy
  585. #define va_copy(x, y) ((x) = (y))
  586. #endif
  587. #ifdef _WIN32
  588. /* Create substitutes for POSIX functions in Win32. */
  589. #if defined(__MINGW32__)
  590. /* Show no warning in case system functions are not used. */
  591. #pragma GCC diagnostic push
  592. #pragma GCC diagnostic ignored "-Wunused-function"
  593. #endif
  594. static CRITICAL_SECTION global_log_file_lock;
  595. FUNCTION_MAY_BE_UNUSED
  596. static DWORD
  597. pthread_self(void)
  598. {
  599. return GetCurrentThreadId();
  600. }
  601. FUNCTION_MAY_BE_UNUSED
  602. static int
  603. pthread_key_create(
  604. pthread_key_t *key,
  605. void (*_ignored)(void *) /* destructor not supported for Windows */
  606. )
  607. {
  608. (void)_ignored;
  609. if ((key != 0)) {
  610. *key = TlsAlloc();
  611. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  612. }
  613. return -2;
  614. }
  615. FUNCTION_MAY_BE_UNUSED
  616. static int
  617. pthread_key_delete(pthread_key_t key)
  618. {
  619. return TlsFree(key) ? 0 : 1;
  620. }
  621. FUNCTION_MAY_BE_UNUSED
  622. static int
  623. pthread_setspecific(pthread_key_t key, void *value)
  624. {
  625. return TlsSetValue(key, value) ? 0 : 1;
  626. }
  627. FUNCTION_MAY_BE_UNUSED
  628. static void *
  629. pthread_getspecific(pthread_key_t key)
  630. {
  631. return TlsGetValue(key);
  632. }
  633. #if defined(__MINGW32__)
  634. /* Enable unused function warning again */
  635. #pragma GCC diagnostic pop
  636. #endif
  637. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  638. #else
  639. static pthread_mutexattr_t pthread_mutex_attr;
  640. #endif /* _WIN32 */
  641. #define PASSWORDS_FILE_NAME ".htpasswd"
  642. #define CGI_ENVIRONMENT_SIZE (4096)
  643. #define MAX_CGI_ENVIR_VARS (256)
  644. #define MG_BUF_LEN (8192)
  645. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  646. #if defined(_WIN32_WCE)
  647. /* Create substitutes for POSIX functions in Win32. */
  648. #if defined(__MINGW32__)
  649. /* Show no warning in case system functions are not used. */
  650. #pragma GCC diagnostic push
  651. #pragma GCC diagnostic ignored "-Wunused-function"
  652. #endif
  653. FUNCTION_MAY_BE_UNUSED
  654. static time_t
  655. time(time_t *ptime)
  656. {
  657. time_t t;
  658. SYSTEMTIME st;
  659. FILETIME ft;
  660. GetSystemTime(&st);
  661. SystemTimeToFileTime(&st, &ft);
  662. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  663. if (ptime != NULL) {
  664. *ptime = t;
  665. }
  666. return t;
  667. }
  668. FUNCTION_MAY_BE_UNUSED
  669. static struct tm *
  670. localtime_s(const time_t *ptime, struct tm *ptm)
  671. {
  672. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  673. FILETIME ft, lft;
  674. SYSTEMTIME st;
  675. TIME_ZONE_INFORMATION tzinfo;
  676. if (ptm == NULL) {
  677. return NULL;
  678. }
  679. *(int64_t *)&ft = t;
  680. FileTimeToLocalFileTime(&ft, &lft);
  681. FileTimeToSystemTime(&lft, &st);
  682. ptm->tm_year = st.wYear - 1900;
  683. ptm->tm_mon = st.wMonth - 1;
  684. ptm->tm_wday = st.wDayOfWeek;
  685. ptm->tm_mday = st.wDay;
  686. ptm->tm_hour = st.wHour;
  687. ptm->tm_min = st.wMinute;
  688. ptm->tm_sec = st.wSecond;
  689. ptm->tm_yday = 0; /* hope nobody uses this */
  690. ptm->tm_isdst =
  691. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  692. return ptm;
  693. }
  694. FUNCTION_MAY_BE_UNUSED
  695. static struct tm *
  696. gmtime_s(const time_t *ptime, struct tm *ptm)
  697. {
  698. /* FIXME(lsm): fix this. */
  699. return localtime_s(ptime, ptm);
  700. }
  701. static int mg_atomic_inc(volatile int *addr);
  702. static struct tm tm_array[MAX_WORKER_THREADS];
  703. static int tm_index = 0;
  704. FUNCTION_MAY_BE_UNUSED
  705. static struct tm *
  706. localtime(const time_t *ptime)
  707. {
  708. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  709. return localtime_s(ptime, tm_array + i);
  710. }
  711. FUNCTION_MAY_BE_UNUSED
  712. static struct tm *
  713. gmtime(const time_t *ptime)
  714. {
  715. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  716. return gmtime_s(ptime, tm_array + i);
  717. }
  718. FUNCTION_MAY_BE_UNUSED
  719. static size_t
  720. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  721. {
  722. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  723. * for WinCE"); */
  724. return 0;
  725. }
  726. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  727. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  728. #define remove(f) mg_remove(NULL, f)
  729. FUNCTION_MAY_BE_UNUSED
  730. static int
  731. rename(const char *a, const char *b)
  732. {
  733. wchar_t wa[PATH_MAX];
  734. wchar_t wb[PATH_MAX];
  735. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  736. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  737. return MoveFileW(wa, wb) ? 0 : -1;
  738. }
  739. struct stat {
  740. int64_t st_size;
  741. time_t st_mtime;
  742. };
  743. FUNCTION_MAY_BE_UNUSED
  744. static int
  745. stat(const char *name, struct stat *st)
  746. {
  747. wchar_t wbuf[PATH_MAX];
  748. WIN32_FILE_ATTRIBUTE_DATA attr;
  749. time_t creation_time, write_time;
  750. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  751. memset(&attr, 0, sizeof(attr));
  752. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  753. st->st_size =
  754. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  755. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  756. attr.ftLastWriteTime.dwHighDateTime);
  757. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  758. attr.ftCreationTime.dwHighDateTime);
  759. if (creation_time > write_time) {
  760. st->st_mtime = creation_time;
  761. } else {
  762. st->st_mtime = write_time;
  763. }
  764. return 0;
  765. }
  766. #define access(x, a) 1 /* not required anyway */
  767. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  768. /* Values from errno.h in Windows SDK (Visual Studio). */
  769. #define EEXIST 17
  770. #define EACCES 13
  771. #define ENOENT 2
  772. #if defined(__MINGW32__)
  773. /* Enable unused function warning again */
  774. #pragma GCC diagnostic pop
  775. #endif
  776. #endif /* defined(_WIN32_WCE) */
  777. #if defined(__GNUC__) || defined(__MINGW32__)
  778. /* Show no warning in case system functions are not used. */
  779. #define GCC_VERSION \
  780. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  781. #if GCC_VERSION >= 40500
  782. #pragma GCC diagnostic push
  783. #pragma GCC diagnostic ignored "-Wunused-function"
  784. #endif /* GCC_VERSION >= 40500 */
  785. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  786. #if defined(__clang__)
  787. /* Show no warning in case system functions are not used. */
  788. #pragma clang diagnostic push
  789. #pragma clang diagnostic ignored "-Wunused-function"
  790. #endif
  791. static pthread_mutex_t global_lock_mutex;
  792. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  793. /* Forward declaration for Windows */
  794. FUNCTION_MAY_BE_UNUSED
  795. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  796. FUNCTION_MAY_BE_UNUSED
  797. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  798. #endif
  799. FUNCTION_MAY_BE_UNUSED
  800. static void
  801. mg_global_lock(void)
  802. {
  803. (void)pthread_mutex_lock(&global_lock_mutex);
  804. }
  805. FUNCTION_MAY_BE_UNUSED
  806. static void
  807. mg_global_unlock(void)
  808. {
  809. (void)pthread_mutex_unlock(&global_lock_mutex);
  810. }
  811. FUNCTION_MAY_BE_UNUSED
  812. static int
  813. mg_atomic_inc(volatile int *addr)
  814. {
  815. int ret;
  816. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  817. /* Depending on the SDK, this function uses either
  818. * (volatile unsigned int *) or (volatile LONG *),
  819. * so whatever you use, the other SDK is likely to raise a warning. */
  820. ret = InterlockedIncrement((volatile long *)addr);
  821. #elif defined(__GNUC__) \
  822. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  823. && !defined(NO_ATOMICS)
  824. ret = __sync_add_and_fetch(addr, 1);
  825. #else
  826. mg_global_lock();
  827. ret = (++(*addr));
  828. mg_global_unlock();
  829. #endif
  830. return ret;
  831. }
  832. FUNCTION_MAY_BE_UNUSED
  833. static int
  834. mg_atomic_dec(volatile int *addr)
  835. {
  836. int ret;
  837. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  838. /* Depending on the SDK, this function uses either
  839. * (volatile unsigned int *) or (volatile LONG *),
  840. * so whatever you use, the other SDK is likely to raise a warning. */
  841. ret = InterlockedDecrement((volatile long *)addr);
  842. #elif defined(__GNUC__) \
  843. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  844. && !defined(NO_ATOMICS)
  845. ret = __sync_sub_and_fetch(addr, 1);
  846. #else
  847. mg_global_lock();
  848. ret = (--(*addr));
  849. mg_global_unlock();
  850. #endif
  851. return ret;
  852. }
  853. #if defined(USE_SERVER_STATS)
  854. static int64_t
  855. mg_atomic_add(volatile int64_t *addr, int64_t value)
  856. {
  857. int64_t ret;
  858. #if defined(_WIN64) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  859. ret = InterlockedAdd64(addr, value);
  860. #elif defined(__GNUC__) \
  861. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  862. && !defined(NO_ATOMICS)
  863. ret = __sync_add_and_fetch(addr, value);
  864. #else
  865. mg_global_lock();
  866. *addr += value;
  867. ret = (*addr);
  868. mg_global_unlock();
  869. #endif
  870. return ret;
  871. }
  872. #endif
  873. #if defined(__GNUC__)
  874. /* Show no warning in case system functions are not used. */
  875. #if GCC_VERSION >= 40500
  876. #pragma GCC diagnostic pop
  877. #endif /* GCC_VERSION >= 40500 */
  878. #endif /* defined(__GNUC__) */
  879. #if defined(__clang__)
  880. /* Show no warning in case system functions are not used. */
  881. #pragma clang diagnostic pop
  882. #endif
  883. #if defined(USE_SERVER_STATS)
  884. struct mg_memory_stat {
  885. volatile int64_t totalMemUsed;
  886. volatile int64_t maxMemUsed;
  887. volatile int blockCount;
  888. };
  889. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  890. static void *
  891. mg_malloc_ex(size_t size,
  892. struct mg_context *ctx,
  893. const char *file,
  894. unsigned line)
  895. {
  896. void *data = malloc(size + 2 * sizeof(uintptr_t));
  897. void *memory = 0;
  898. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  899. #if defined(MEMORY_DEBUGGING)
  900. char mallocStr[256];
  901. #else
  902. (void)file;
  903. (void)line;
  904. #endif
  905. if (data) {
  906. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  907. if (mmem > mstat->maxMemUsed) {
  908. /* could use atomic compare exchange, but this
  909. * seems overkill for statistics data */
  910. mstat->maxMemUsed = mmem;
  911. }
  912. mg_atomic_inc(&mstat->blockCount);
  913. ((uintptr_t *)data)[0] = size;
  914. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  915. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  916. }
  917. #if defined(MEMORY_DEBUGGING)
  918. sprintf(mallocStr,
  919. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  920. memory,
  921. (unsigned long)size,
  922. (unsigned long)mstat->totalMemUsed,
  923. (unsigned long)mstat->blockCount,
  924. file,
  925. line);
  926. #if defined(_WIN32)
  927. OutputDebugStringA(mallocStr);
  928. #else
  929. DEBUG_TRACE("%s", mallocStr);
  930. #endif
  931. #endif
  932. return memory;
  933. }
  934. static void *
  935. mg_calloc_ex(size_t count,
  936. size_t size,
  937. struct mg_context *ctx,
  938. const char *file,
  939. unsigned line)
  940. {
  941. void *data = mg_malloc_ex(size * count, ctx, file, line);
  942. if (data) {
  943. memset(data, 0, size * count);
  944. }
  945. return data;
  946. }
  947. static void
  948. mg_free_ex(void *memory, const char *file, unsigned line)
  949. {
  950. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  951. #if defined(MEMORY_DEBUGGING)
  952. char mallocStr[256];
  953. #else
  954. (void)file;
  955. (void)line;
  956. #endif
  957. if (memory) {
  958. uintptr_t size = ((uintptr_t *)data)[0];
  959. struct mg_memory_stat *mstat =
  960. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  961. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  962. mg_atomic_dec(&mstat->blockCount);
  963. #if defined(MEMORY_DEBUGGING)
  964. sprintf(mallocStr,
  965. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  966. memory,
  967. (unsigned long)size,
  968. (unsigned long)mstat->totalMemUsed,
  969. (unsigned long)mstat->blockCount,
  970. file,
  971. line);
  972. #if defined(_WIN32)
  973. OutputDebugStringA(mallocStr);
  974. #else
  975. DEBUG_TRACE("%s", mallocStr);
  976. #endif
  977. #endif
  978. free(data);
  979. }
  980. }
  981. static void *
  982. mg_realloc_ex(void *memory,
  983. size_t newsize,
  984. struct mg_context *ctx,
  985. const char *file,
  986. unsigned line)
  987. {
  988. void *data;
  989. void *_realloc;
  990. uintptr_t oldsize;
  991. #if defined(MEMORY_DEBUGGING)
  992. char mallocStr[256];
  993. #else
  994. (void)file;
  995. (void)line;
  996. #endif
  997. if (newsize) {
  998. if (memory) {
  999. /* Reallocate existing block */
  1000. struct mg_memory_stat *mstat;
  1001. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1002. oldsize = ((uintptr_t *)data)[0];
  1003. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1004. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1005. if (_realloc) {
  1006. data = _realloc;
  1007. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1008. #if defined(MEMORY_DEBUGGING)
  1009. sprintf(mallocStr,
  1010. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1011. memory,
  1012. (unsigned long)oldsize,
  1013. (unsigned long)mstat->totalMemUsed,
  1014. (unsigned long)mstat->blockCount,
  1015. file,
  1016. line);
  1017. #if defined(_WIN32)
  1018. OutputDebugStringA(mallocStr);
  1019. #else
  1020. DEBUG_TRACE("%s", mallocStr);
  1021. #endif
  1022. #endif
  1023. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1024. #if defined(MEMORY_DEBUGGING)
  1025. sprintf(mallocStr,
  1026. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1027. memory,
  1028. (unsigned long)newsize,
  1029. (unsigned long)mstat->totalMemUsed,
  1030. (unsigned long)mstat->blockCount,
  1031. file,
  1032. line);
  1033. #if defined(_WIN32)
  1034. OutputDebugStringA(mallocStr);
  1035. #else
  1036. DEBUG_TRACE("%s", mallocStr);
  1037. #endif
  1038. #endif
  1039. *(uintptr_t *)data = newsize;
  1040. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1041. } else {
  1042. #if defined(MEMORY_DEBUGGING)
  1043. #if defined(_WIN32)
  1044. OutputDebugStringA("MEM: realloc failed\n");
  1045. #else
  1046. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1047. #endif
  1048. #endif
  1049. return _realloc;
  1050. }
  1051. } else {
  1052. /* Allocate new block */
  1053. data = mg_malloc_ex(newsize, ctx, file, line);
  1054. }
  1055. } else {
  1056. /* Free existing block */
  1057. data = 0;
  1058. mg_free_ex(memory, file, line);
  1059. }
  1060. return data;
  1061. }
  1062. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1063. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1064. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1065. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1066. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1067. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1068. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1069. #else /* USE_SERVER_STATS */
  1070. static __inline void *
  1071. mg_malloc(size_t a)
  1072. {
  1073. return malloc(a);
  1074. }
  1075. static __inline void *
  1076. mg_calloc(size_t a, size_t b)
  1077. {
  1078. return calloc(a, b);
  1079. }
  1080. static __inline void *
  1081. mg_realloc(void *a, size_t b)
  1082. {
  1083. return realloc(a, b);
  1084. }
  1085. static __inline void
  1086. mg_free(void *a)
  1087. {
  1088. free(a);
  1089. }
  1090. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1091. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1092. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1093. #define mg_free_ctx(a, c) mg_free(a)
  1094. #endif /* USE_SERVER_STATS */
  1095. static void mg_vsnprintf(const struct mg_connection *conn,
  1096. int *truncated,
  1097. char *buf,
  1098. size_t buflen,
  1099. const char *fmt,
  1100. va_list ap);
  1101. static void mg_snprintf(const struct mg_connection *conn,
  1102. int *truncated,
  1103. char *buf,
  1104. size_t buflen,
  1105. PRINTF_FORMAT_STRING(const char *fmt),
  1106. ...) PRINTF_ARGS(5, 6);
  1107. /* This following lines are just meant as a reminder to use the mg-functions
  1108. * for memory management */
  1109. #ifdef malloc
  1110. #undef malloc
  1111. #endif
  1112. #ifdef calloc
  1113. #undef calloc
  1114. #endif
  1115. #ifdef realloc
  1116. #undef realloc
  1117. #endif
  1118. #ifdef free
  1119. #undef free
  1120. #endif
  1121. #ifdef snprintf
  1122. #undef snprintf
  1123. #endif
  1124. #ifdef vsnprintf
  1125. #undef vsnprintf
  1126. #endif
  1127. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1128. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1129. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1130. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1131. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1132. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  1133. * but this define only works well for Windows. */
  1134. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1135. #endif
  1136. /* mg_init_library counter */
  1137. static int mg_init_library_called = 0;
  1138. #if !defined(NO_SSL)
  1139. static int mg_ssl_initialized = 0;
  1140. #endif
  1141. static pthread_key_t sTlsKey; /* Thread local storage index */
  1142. static int thread_idx_max = 0;
  1143. struct mg_workerTLS {
  1144. int is_master;
  1145. unsigned long thread_idx;
  1146. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1147. HANDLE pthread_cond_helper_mutex;
  1148. struct mg_workerTLS *next_waiting_thread;
  1149. #endif
  1150. };
  1151. #if defined(__GNUC__) || defined(__MINGW32__)
  1152. /* Show no warning in case system functions are not used. */
  1153. #if GCC_VERSION >= 40500
  1154. #pragma GCC diagnostic push
  1155. #pragma GCC diagnostic ignored "-Wunused-function"
  1156. #endif /* GCC_VERSION >= 40500 */
  1157. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1158. #if defined(__clang__)
  1159. /* Show no warning in case system functions are not used. */
  1160. #pragma clang diagnostic push
  1161. #pragma clang diagnostic ignored "-Wunused-function"
  1162. #endif
  1163. /* Get a unique thread ID as unsigned long, independent from the data type
  1164. * of thread IDs defined by the operating system API.
  1165. * If two calls to mg_current_thread_id return the same value, they calls
  1166. * are done from the same thread. If they return different values, they are
  1167. * done from different threads. (Provided this function is used in the same
  1168. * process context and threads are not repeatedly created and deleted, but
  1169. * CivetWeb does not do that).
  1170. * This function must match the signature required for SSL id callbacks:
  1171. * CRYPTO_set_id_callback
  1172. */
  1173. FUNCTION_MAY_BE_UNUSED
  1174. static unsigned long
  1175. mg_current_thread_id(void)
  1176. {
  1177. #ifdef _WIN32
  1178. return GetCurrentThreadId();
  1179. #else
  1180. #ifdef __clang__
  1181. #pragma clang diagnostic push
  1182. #pragma clang diagnostic ignored "-Wunreachable-code"
  1183. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1184. * or not, so one of the two conditions will be unreachable by construction.
  1185. * Unfortunately the C standard does not define a way to check this at
  1186. * compile time, since the #if preprocessor conditions can not use the sizeof
  1187. * operator as an argument. */
  1188. #endif
  1189. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1190. /* This is the problematic case for CRYPTO_set_id_callback:
  1191. * The OS pthread_t can not be cast to unsigned long. */
  1192. struct mg_workerTLS *tls =
  1193. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1194. if (tls == NULL) {
  1195. /* SSL called from an unknown thread: Create some thread index.
  1196. */
  1197. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1198. tls->is_master = -2; /* -2 means "3rd party thread" */
  1199. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1200. pthread_setspecific(sTlsKey, tls);
  1201. }
  1202. return tls->thread_idx;
  1203. } else {
  1204. /* pthread_t may be any data type, so a simple cast to unsigned long
  1205. * can rise a warning/error, depending on the platform.
  1206. * Here memcpy is used as an anything-to-anything cast. */
  1207. unsigned long ret = 0;
  1208. pthread_t t = pthread_self();
  1209. memcpy(&ret, &t, sizeof(pthread_t));
  1210. return ret;
  1211. }
  1212. #ifdef __clang__
  1213. #pragma clang diagnostic pop
  1214. #endif
  1215. #endif
  1216. }
  1217. FUNCTION_MAY_BE_UNUSED
  1218. static uint64_t
  1219. mg_get_current_time_ns(void)
  1220. {
  1221. struct timespec tsnow;
  1222. clock_gettime(CLOCK_REALTIME, &tsnow);
  1223. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1224. }
  1225. #if defined(__GNUC__)
  1226. /* Show no warning in case system functions are not used. */
  1227. #if GCC_VERSION >= 40500
  1228. #pragma GCC diagnostic pop
  1229. #endif /* GCC_VERSION >= 40500 */
  1230. #endif /* defined(__GNUC__) */
  1231. #if defined(__clang__)
  1232. /* Show no warning in case system functions are not used. */
  1233. #pragma clang diagnostic pop
  1234. #endif
  1235. #if !defined(DEBUG_TRACE)
  1236. #if defined(DEBUG)
  1237. static void DEBUG_TRACE_FUNC(const char *func,
  1238. unsigned line,
  1239. PRINTF_FORMAT_STRING(const char *fmt),
  1240. ...) PRINTF_ARGS(3, 4);
  1241. static void
  1242. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1243. {
  1244. va_list args;
  1245. uint64_t nsnow;
  1246. static uint64_t nslast;
  1247. struct timespec tsnow;
  1248. /* Get some operating system independent thread id */
  1249. unsigned long thread_id = mg_current_thread_id();
  1250. clock_gettime(CLOCK_REALTIME, &tsnow);
  1251. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1252. + ((uint64_t)tsnow.tv_nsec);
  1253. if (!nslast) {
  1254. nslast = nsnow;
  1255. }
  1256. flockfile(stdout);
  1257. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1258. (unsigned long)tsnow.tv_sec,
  1259. (unsigned long)tsnow.tv_nsec,
  1260. nsnow - nslast,
  1261. thread_id,
  1262. func,
  1263. line);
  1264. va_start(args, fmt);
  1265. vprintf(fmt, args);
  1266. va_end(args);
  1267. putchar('\n');
  1268. fflush(stdout);
  1269. funlockfile(stdout);
  1270. nslast = nsnow;
  1271. }
  1272. #define DEBUG_TRACE(fmt, ...) \
  1273. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1274. #else
  1275. #define DEBUG_TRACE(fmt, ...) \
  1276. do { \
  1277. } while (0)
  1278. #endif /* DEBUG */
  1279. #endif /* DEBUG_TRACE */
  1280. #define MD5_STATIC static
  1281. #include "md5.inl"
  1282. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1283. #ifdef NO_SOCKLEN_T
  1284. typedef int socklen_t;
  1285. #endif /* NO_SOCKLEN_T */
  1286. #define _DARWIN_UNLIMITED_SELECT
  1287. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1288. #if !defined(MSG_NOSIGNAL)
  1289. #define MSG_NOSIGNAL (0)
  1290. #endif
  1291. #if !defined(SOMAXCONN)
  1292. #define SOMAXCONN (100)
  1293. #endif
  1294. /* Size of the accepted socket queue */
  1295. #if !defined(MGSQLEN)
  1296. #define MGSQLEN (20)
  1297. #endif
  1298. #if defined(NO_SSL)
  1299. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1300. typedef struct SSL_CTX SSL_CTX;
  1301. #else
  1302. #if defined(NO_SSL_DL)
  1303. #include <openssl/ssl.h>
  1304. #include <openssl/err.h>
  1305. #include <openssl/crypto.h>
  1306. #include <openssl/x509.h>
  1307. #include <openssl/pem.h>
  1308. #include <openssl/engine.h>
  1309. #include <openssl/conf.h>
  1310. #include <openssl/dh.h>
  1311. #include <openssl/bn.h>
  1312. #include <openssl/opensslv.h>
  1313. #else
  1314. /* SSL loaded dynamically from DLL.
  1315. * I put the prototypes here to be independent from OpenSSL source
  1316. * installation. */
  1317. typedef struct ssl_st SSL;
  1318. typedef struct ssl_method_st SSL_METHOD;
  1319. typedef struct ssl_ctx_st SSL_CTX;
  1320. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1321. typedef struct x509_name X509_NAME;
  1322. typedef struct asn1_integer ASN1_INTEGER;
  1323. typedef struct bignum BIGNUM;
  1324. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1325. typedef struct evp_md EVP_MD;
  1326. typedef struct x509 X509;
  1327. #define SSL_CTRL_OPTIONS (32)
  1328. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1329. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1330. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1331. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1332. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1333. #define SSL_VERIFY_NONE (0)
  1334. #define SSL_VERIFY_PEER (1)
  1335. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1336. #define SSL_VERIFY_CLIENT_ONCE (4)
  1337. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1338. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1339. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1340. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1341. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1342. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1343. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1344. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1345. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1346. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1347. #define SSL_CB_HANDSHAKE_START (0x10)
  1348. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1349. #define SSL_ERROR_NONE (0)
  1350. #define SSL_ERROR_SSL (1)
  1351. #define SSL_ERROR_WANT_READ (2)
  1352. #define SSL_ERROR_WANT_WRITE (3)
  1353. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1354. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1355. #define SSL_ERROR_ZERO_RETURN (6)
  1356. #define SSL_ERROR_WANT_CONNECT (7)
  1357. #define SSL_ERROR_WANT_ACCEPT (8)
  1358. struct ssl_func {
  1359. const char *name; /* SSL function name */
  1360. void (*ptr)(void); /* Function pointer */
  1361. };
  1362. #ifdef OPENSSL_API_1_1
  1363. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1364. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1365. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1366. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1367. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1368. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1369. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1370. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1371. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1372. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1373. #define OPENSSL_init_ssl \
  1374. (*(int (*)(uint64_t opts, \
  1375. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1376. #define SSL_CTX_use_PrivateKey_file \
  1377. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1378. #define SSL_CTX_use_certificate_file \
  1379. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1380. #define SSL_CTX_set_default_passwd_cb \
  1381. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1382. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1383. #define SSL_CTX_use_certificate_chain_file \
  1384. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1385. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1386. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1387. #define SSL_CTX_set_verify \
  1388. (*(void (*)(SSL_CTX *, \
  1389. int, \
  1390. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1391. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1392. #define SSL_CTX_load_verify_locations \
  1393. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1394. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1395. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1396. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1397. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1398. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1399. #define SSL_CIPHER_get_name \
  1400. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1401. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1402. #define SSL_CTX_set_session_id_context \
  1403. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1404. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1405. #define SSL_CTX_set_cipher_list \
  1406. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1407. #define SSL_CTX_set_options \
  1408. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1409. #define SSL_CTX_set_info_callback \
  1410. (*(void (*)(SSL_CTX * ctx, \
  1411. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1412. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1413. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1414. #define SSL_CTX_clear_options(ctx, op) \
  1415. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1416. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1417. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1418. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1419. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1420. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1421. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1422. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1423. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1424. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1425. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1426. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1427. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1428. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1429. #define X509_NAME_oneline \
  1430. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1431. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1432. #define EVP_get_digestbyname \
  1433. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1434. #define EVP_Digest \
  1435. (*(int (*)( \
  1436. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1437. crypto_sw[10].ptr)
  1438. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1439. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1440. #define ASN1_INTEGER_to_BN \
  1441. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1442. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1443. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1444. #define OPENSSL_free(a) CRYPTO_free(a)
  1445. /* set_ssl_option() function updates this array.
  1446. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1447. * of respective functions. The macros above (like SSL_connect()) are really
  1448. * just calling these functions indirectly via the pointer. */
  1449. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1450. {"SSL_accept", NULL},
  1451. {"SSL_connect", NULL},
  1452. {"SSL_read", NULL},
  1453. {"SSL_write", NULL},
  1454. {"SSL_get_error", NULL},
  1455. {"SSL_set_fd", NULL},
  1456. {"SSL_new", NULL},
  1457. {"SSL_CTX_new", NULL},
  1458. {"TLS_server_method", NULL},
  1459. {"OPENSSL_init_ssl", NULL},
  1460. {"SSL_CTX_use_PrivateKey_file", NULL},
  1461. {"SSL_CTX_use_certificate_file", NULL},
  1462. {"SSL_CTX_set_default_passwd_cb", NULL},
  1463. {"SSL_CTX_free", NULL},
  1464. {"SSL_CTX_use_certificate_chain_file", NULL},
  1465. {"TLS_client_method", NULL},
  1466. {"SSL_pending", NULL},
  1467. {"SSL_CTX_set_verify", NULL},
  1468. {"SSL_shutdown", NULL},
  1469. {"SSL_CTX_load_verify_locations", NULL},
  1470. {"SSL_CTX_set_default_verify_paths", NULL},
  1471. {"SSL_CTX_set_verify_depth", NULL},
  1472. {"SSL_get_peer_certificate", NULL},
  1473. {"SSL_get_version", NULL},
  1474. {"SSL_get_current_cipher", NULL},
  1475. {"SSL_CIPHER_get_name", NULL},
  1476. {"SSL_CTX_check_private_key", NULL},
  1477. {"SSL_CTX_set_session_id_context", NULL},
  1478. {"SSL_CTX_ctrl", NULL},
  1479. {"SSL_CTX_set_cipher_list", NULL},
  1480. {"SSL_CTX_set_options", NULL},
  1481. {"SSL_CTX_set_info_callback", NULL},
  1482. {"SSL_get_ex_data", NULL},
  1483. {"SSL_set_ex_data", NULL},
  1484. {NULL, NULL}};
  1485. /* Similar array as ssl_sw. These functions could be located in different
  1486. * lib. */
  1487. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1488. {"ERR_error_string", NULL},
  1489. {"ERR_remove_state", NULL},
  1490. {"CONF_modules_unload", NULL},
  1491. {"X509_free", NULL},
  1492. {"X509_get_subject_name", NULL},
  1493. {"X509_get_issuer_name", NULL},
  1494. {"X509_NAME_oneline", NULL},
  1495. {"X509_get_serialNumber", NULL},
  1496. {"EVP_get_digestbyname", NULL},
  1497. {"EVP_Digest", NULL},
  1498. {"i2d_X509", NULL},
  1499. {"BN_bn2hex", NULL},
  1500. {"ASN1_INTEGER_to_BN", NULL},
  1501. {"BN_free", NULL},
  1502. {"CRYPTO_free", NULL},
  1503. {NULL, NULL}};
  1504. #else
  1505. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1506. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1507. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1508. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1509. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1510. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1511. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1512. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1513. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1514. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1515. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1516. #define SSL_CTX_use_PrivateKey_file \
  1517. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1518. #define SSL_CTX_use_certificate_file \
  1519. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1520. #define SSL_CTX_set_default_passwd_cb \
  1521. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1522. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1523. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1524. #define SSL_CTX_use_certificate_chain_file \
  1525. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1526. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1527. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1528. #define SSL_CTX_set_verify \
  1529. (*(void (*)(SSL_CTX *, \
  1530. int, \
  1531. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1532. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1533. #define SSL_CTX_load_verify_locations \
  1534. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1535. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1536. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1537. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1538. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1539. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1540. #define SSL_CIPHER_get_name \
  1541. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1542. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1543. #define SSL_CTX_set_session_id_context \
  1544. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1545. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1546. #define SSL_CTX_set_cipher_list \
  1547. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1548. #define SSL_CTX_set_info_callback \
  1549. (*(void (*)(SSL_CTX * ctx, \
  1550. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1551. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1552. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1553. #define SSL_CTX_set_options(ctx, op) \
  1554. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1555. #define SSL_CTX_clear_options(ctx, op) \
  1556. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1557. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1558. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1559. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1560. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1561. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1562. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1563. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1564. #define CRYPTO_set_locking_callback \
  1565. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1566. #define CRYPTO_set_id_callback \
  1567. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1568. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1569. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1570. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1571. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1572. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1573. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1574. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1575. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1576. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1577. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1578. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1579. #define X509_NAME_oneline \
  1580. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1581. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1582. #define i2c_ASN1_INTEGER \
  1583. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1584. #define EVP_get_digestbyname \
  1585. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1586. #define EVP_Digest \
  1587. (*(int (*)( \
  1588. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1589. crypto_sw[18].ptr)
  1590. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1591. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1592. #define ASN1_INTEGER_to_BN \
  1593. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1594. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1595. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1596. #define OPENSSL_free(a) CRYPTO_free(a)
  1597. /* set_ssl_option() function updates this array.
  1598. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1599. * of respective functions. The macros above (like SSL_connect()) are really
  1600. * just calling these functions indirectly via the pointer. */
  1601. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1602. {"SSL_accept", NULL},
  1603. {"SSL_connect", NULL},
  1604. {"SSL_read", NULL},
  1605. {"SSL_write", NULL},
  1606. {"SSL_get_error", NULL},
  1607. {"SSL_set_fd", NULL},
  1608. {"SSL_new", NULL},
  1609. {"SSL_CTX_new", NULL},
  1610. {"SSLv23_server_method", NULL},
  1611. {"SSL_library_init", NULL},
  1612. {"SSL_CTX_use_PrivateKey_file", NULL},
  1613. {"SSL_CTX_use_certificate_file", NULL},
  1614. {"SSL_CTX_set_default_passwd_cb", NULL},
  1615. {"SSL_CTX_free", NULL},
  1616. {"SSL_load_error_strings", NULL},
  1617. {"SSL_CTX_use_certificate_chain_file", NULL},
  1618. {"SSLv23_client_method", NULL},
  1619. {"SSL_pending", NULL},
  1620. {"SSL_CTX_set_verify", NULL},
  1621. {"SSL_shutdown", NULL},
  1622. {"SSL_CTX_load_verify_locations", NULL},
  1623. {"SSL_CTX_set_default_verify_paths", NULL},
  1624. {"SSL_CTX_set_verify_depth", NULL},
  1625. {"SSL_get_peer_certificate", NULL},
  1626. {"SSL_get_version", NULL},
  1627. {"SSL_get_current_cipher", NULL},
  1628. {"SSL_CIPHER_get_name", NULL},
  1629. {"SSL_CTX_check_private_key", NULL},
  1630. {"SSL_CTX_set_session_id_context", NULL},
  1631. {"SSL_CTX_ctrl", NULL},
  1632. {"SSL_CTX_set_cipher_list", NULL},
  1633. {"SSL_CTX_set_info_callback", NULL},
  1634. {"SSL_get_ex_data", NULL},
  1635. {"SSL_set_ex_data", NULL},
  1636. {NULL, NULL}};
  1637. /* Similar array as ssl_sw. These functions could be located in different
  1638. * lib. */
  1639. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1640. {"CRYPTO_set_locking_callback", NULL},
  1641. {"CRYPTO_set_id_callback", NULL},
  1642. {"ERR_get_error", NULL},
  1643. {"ERR_error_string", NULL},
  1644. {"ERR_remove_state", NULL},
  1645. {"ERR_free_strings", NULL},
  1646. {"ENGINE_cleanup", NULL},
  1647. {"CONF_modules_unload", NULL},
  1648. {"CRYPTO_cleanup_all_ex_data", NULL},
  1649. {"EVP_cleanup", NULL},
  1650. {"X509_free", NULL},
  1651. {"X509_get_subject_name", NULL},
  1652. {"X509_get_issuer_name", NULL},
  1653. {"X509_NAME_oneline", NULL},
  1654. {"X509_get_serialNumber", NULL},
  1655. {"i2c_ASN1_INTEGER", NULL},
  1656. {"EVP_get_digestbyname", NULL},
  1657. {"EVP_Digest", NULL},
  1658. {"i2d_X509", NULL},
  1659. {"BN_bn2hex", NULL},
  1660. {"ASN1_INTEGER_to_BN", NULL},
  1661. {"BN_free", NULL},
  1662. {"CRYPTO_free", NULL},
  1663. {NULL, NULL}};
  1664. #endif /* OPENSSL_API_1_1 */
  1665. #endif /* NO_SSL_DL */
  1666. #endif /* NO_SSL */
  1667. #if !defined(NO_CACHING)
  1668. static const char *month_names[] = {"Jan",
  1669. "Feb",
  1670. "Mar",
  1671. "Apr",
  1672. "May",
  1673. "Jun",
  1674. "Jul",
  1675. "Aug",
  1676. "Sep",
  1677. "Oct",
  1678. "Nov",
  1679. "Dec"};
  1680. #endif /* !NO_CACHING */
  1681. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1682. * the
  1683. * union u. */
  1684. union usa {
  1685. struct sockaddr sa;
  1686. struct sockaddr_in sin;
  1687. #if defined(USE_IPV6)
  1688. struct sockaddr_in6 sin6;
  1689. #endif
  1690. };
  1691. /* Describes a string (chunk of memory). */
  1692. struct vec {
  1693. const char *ptr;
  1694. size_t len;
  1695. };
  1696. struct mg_file_stat {
  1697. /* File properties filled by mg_stat: */
  1698. uint64_t size;
  1699. time_t last_modified;
  1700. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1701. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1702. * case we need a "Content-Eencoding: gzip" header */
  1703. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1704. };
  1705. struct mg_file_in_memory {
  1706. char *p;
  1707. uint32_t pos;
  1708. char mode;
  1709. };
  1710. struct mg_file_access {
  1711. /* File properties filled by mg_fopen: */
  1712. FILE *fp;
  1713. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1714. * support library. Use some struct mg_file_in_memory *mf; instead of
  1715. * membuf char pointer. */
  1716. const char *membuf;
  1717. };
  1718. struct mg_file {
  1719. struct mg_file_stat stat;
  1720. struct mg_file_access access;
  1721. };
  1722. #define STRUCT_FILE_INITIALIZER \
  1723. { \
  1724. { \
  1725. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1726. } \
  1727. , \
  1728. { \
  1729. (FILE *) NULL, (const char *)NULL \
  1730. } \
  1731. }
  1732. /* Describes listening socket, or socket which was accept()-ed by the master
  1733. * thread and queued for future handling by the worker thread. */
  1734. struct socket {
  1735. SOCKET sock; /* Listening socket */
  1736. union usa lsa; /* Local socket address */
  1737. union usa rsa; /* Remote socket address */
  1738. unsigned char is_ssl; /* Is port SSL-ed */
  1739. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1740. * port */
  1741. unsigned char in_use; /* Is valid */
  1742. };
  1743. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1744. enum {
  1745. CGI_EXTENSIONS,
  1746. CGI_ENVIRONMENT,
  1747. PUT_DELETE_PASSWORDS_FILE,
  1748. CGI_INTERPRETER,
  1749. PROTECT_URI,
  1750. AUTHENTICATION_DOMAIN,
  1751. ENABLE_AUTH_DOMAIN_CHECK,
  1752. SSI_EXTENSIONS,
  1753. THROTTLE,
  1754. ACCESS_LOG_FILE,
  1755. ENABLE_DIRECTORY_LISTING,
  1756. ERROR_LOG_FILE,
  1757. GLOBAL_PASSWORDS_FILE,
  1758. INDEX_FILES,
  1759. ENABLE_KEEP_ALIVE,
  1760. ACCESS_CONTROL_LIST,
  1761. EXTRA_MIME_TYPES,
  1762. LISTENING_PORTS,
  1763. DOCUMENT_ROOT,
  1764. SSL_CERTIFICATE,
  1765. SSL_CERTIFICATE_CHAIN,
  1766. NUM_THREADS,
  1767. RUN_AS_USER,
  1768. URL_REWRITE_PATTERN,
  1769. HIDE_FILES,
  1770. REQUEST_TIMEOUT,
  1771. KEEP_ALIVE_TIMEOUT,
  1772. LINGER_TIMEOUT,
  1773. SSL_DO_VERIFY_PEER,
  1774. SSL_CA_PATH,
  1775. SSL_CA_FILE,
  1776. SSL_VERIFY_DEPTH,
  1777. SSL_DEFAULT_VERIFY_PATHS,
  1778. SSL_CIPHER_LIST,
  1779. SSL_PROTOCOL_VERSION,
  1780. SSL_SHORT_TRUST,
  1781. #if defined(USE_WEBSOCKET)
  1782. WEBSOCKET_TIMEOUT,
  1783. #endif
  1784. DECODE_URL,
  1785. #if defined(USE_LUA)
  1786. LUA_PRELOAD_FILE,
  1787. LUA_SCRIPT_EXTENSIONS,
  1788. LUA_SERVER_PAGE_EXTENSIONS,
  1789. #endif
  1790. #if defined(USE_DUKTAPE)
  1791. DUKTAPE_SCRIPT_EXTENSIONS,
  1792. #endif
  1793. #if defined(USE_WEBSOCKET)
  1794. WEBSOCKET_ROOT,
  1795. #endif
  1796. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1797. LUA_WEBSOCKET_EXTENSIONS,
  1798. #endif
  1799. ACCESS_CONTROL_ALLOW_ORIGIN,
  1800. ACCESS_CONTROL_ALLOW_METHODS,
  1801. ACCESS_CONTROL_ALLOW_HEADERS,
  1802. ERROR_PAGES,
  1803. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1804. * socket option typedef TCP_NODELAY. */
  1805. #if !defined(NO_CACHING)
  1806. STATIC_FILE_MAX_AGE,
  1807. #endif
  1808. #if !defined(NO_SSL)
  1809. STRICT_HTTPS_MAX_AGE,
  1810. #endif
  1811. #if defined(__linux__)
  1812. ALLOW_SENDFILE_CALL,
  1813. #endif
  1814. #if defined(_WIN32)
  1815. CASE_SENSITIVE_FILES,
  1816. #endif
  1817. #if defined(USE_LUA)
  1818. LUA_BACKGROUND_SCRIPT,
  1819. LUA_BACKGROUND_SCRIPT_PARAMS,
  1820. #endif
  1821. ADDITIONAL_HEADER,
  1822. MAX_REQUEST_SIZE,
  1823. ALLOW_INDEX_SCRIPT_SUB_RES,
  1824. NUM_OPTIONS
  1825. };
  1826. /* Config option name, config types, default value */
  1827. static struct mg_option config_options[] = {
  1828. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1829. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1830. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1831. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1832. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1833. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1834. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1835. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1836. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1837. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1838. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1839. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1840. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1841. {"index_files",
  1842. MG_CONFIG_TYPE_STRING_LIST,
  1843. #ifdef USE_LUA
  1844. "index.xhtml,index.html,index.htm,"
  1845. "index.lp,index.lsp,index.lua,index.cgi,"
  1846. "index.shtml,index.php"},
  1847. #else
  1848. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1849. #endif
  1850. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1851. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1852. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1853. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1854. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1855. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1856. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1857. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1858. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1859. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1860. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1861. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1862. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1863. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1864. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1865. {"ssl_verify_peer", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1866. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1867. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1868. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1869. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1870. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1871. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  1872. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1873. #if defined(USE_WEBSOCKET)
  1874. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1875. #endif
  1876. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1877. #if defined(USE_LUA)
  1878. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1879. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1880. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1881. #endif
  1882. #if defined(USE_DUKTAPE)
  1883. /* The support for duktape is still in alpha version state.
  1884. * The name of this config option might change. */
  1885. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1886. #endif
  1887. #if defined(USE_WEBSOCKET)
  1888. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1889. #endif
  1890. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1891. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1892. #endif
  1893. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1894. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1895. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1896. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1897. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1898. #if !defined(NO_CACHING)
  1899. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1900. #endif
  1901. #if !defined(NO_SSL)
  1902. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1903. #endif
  1904. #if defined(__linux__)
  1905. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1906. #endif
  1907. #if defined(_WIN32)
  1908. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1909. #endif
  1910. #if defined(USE_LUA)
  1911. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1912. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1913. #endif
  1914. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1915. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1916. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1917. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1918. /* Check if the config_options and the corresponding enum have compatible
  1919. * sizes. */
  1920. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1921. == (NUM_OPTIONS + 1),
  1922. "config_options and enum not sync");
  1923. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1924. struct mg_handler_info {
  1925. /* Name/Pattern of the URI. */
  1926. char *uri;
  1927. size_t uri_len;
  1928. /* handler type */
  1929. int handler_type;
  1930. /* Handler for http/https or authorization requests. */
  1931. mg_request_handler handler;
  1932. /* Handler for ws/wss (websocket) requests. */
  1933. mg_websocket_connect_handler connect_handler;
  1934. mg_websocket_ready_handler ready_handler;
  1935. mg_websocket_data_handler data_handler;
  1936. mg_websocket_close_handler close_handler;
  1937. /* accepted subprotocols for ws/wss requests. */
  1938. struct mg_websocket_subprotocols *subprotocols;
  1939. /* Handler for authorization requests */
  1940. mg_authorization_handler auth_handler;
  1941. /* User supplied argument for the handler function. */
  1942. void *cbdata;
  1943. /* next handler in a linked list */
  1944. struct mg_handler_info *next;
  1945. };
  1946. enum {
  1947. CONTEXT_INVALID,
  1948. CONTEXT_SERVER,
  1949. CONTEXT_HTTP_CLIENT,
  1950. CONTEXT_WS_CLIENT
  1951. };
  1952. struct mg_context {
  1953. volatile int stop_flag; /* Should we stop event loop */
  1954. SSL_CTX *ssl_ctx; /* SSL context */
  1955. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1956. struct mg_callbacks callbacks; /* User-defined callback function */
  1957. void *user_data; /* User-defined data */
  1958. int context_type; /* See CONTEXT_* above */
  1959. struct socket *listening_sockets;
  1960. struct pollfd *listening_socket_fds;
  1961. unsigned int num_listening_sockets;
  1962. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1963. #ifdef ALTERNATIVE_QUEUE
  1964. struct socket *client_socks;
  1965. void **client_wait_events;
  1966. #else
  1967. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1968. volatile int sq_head; /* Head of the socket queue */
  1969. volatile int sq_tail; /* Tail of the socket queue */
  1970. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1971. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1972. #endif
  1973. unsigned int max_request_size; /* The max request size */
  1974. pthread_t masterthreadid; /* The master thread ID */
  1975. unsigned int
  1976. cfg_worker_threads; /* The number of configured worker threads. */
  1977. pthread_t *worker_threadids; /* The worker thread IDs */
  1978. struct mg_connection *worker_connections; /* The connection struct, pre-
  1979. * allocated for each worker */
  1980. time_t start_time; /* Server start time, used for authentication
  1981. * and for diagnstics. */
  1982. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1983. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1984. unsigned long nonce_count; /* Used nonces, used for authentication */
  1985. char *systemName; /* What operating system is running */
  1986. /* linked list of uri handlers */
  1987. struct mg_handler_info *handlers;
  1988. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1989. /* linked list of shared lua websockets */
  1990. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1991. #endif
  1992. #if defined(USE_TIMERS)
  1993. struct ttimers *timers;
  1994. #endif
  1995. #if defined(USE_LUA)
  1996. void *lua_background_state;
  1997. #endif
  1998. #if defined(USE_SERVER_STATS)
  1999. int active_connections;
  2000. int max_connections;
  2001. int64_t total_connections;
  2002. int64_t total_requests;
  2003. struct mg_memory_stat ctx_memory;
  2004. int64_t total_data_read;
  2005. int64_t total_data_written;
  2006. #endif
  2007. };
  2008. #if defined(USE_SERVER_STATS)
  2009. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2010. static struct mg_memory_stat *
  2011. get_memory_stat(struct mg_context *ctx)
  2012. {
  2013. if (ctx) {
  2014. return &(ctx->ctx_memory);
  2015. }
  2016. return &mg_common_memory;
  2017. }
  2018. #endif
  2019. enum {
  2020. CONNECTION_TYPE_INVALID,
  2021. CONNECTION_TYPE_REQUEST,
  2022. CONNECTION_TYPE_RESPONSE
  2023. };
  2024. struct mg_connection {
  2025. int connection_type; /* see CONNECTION_TYPE_* above */
  2026. struct mg_request_info request_info;
  2027. struct mg_response_info response_info;
  2028. struct mg_context *ctx;
  2029. #if defined(USE_SERVER_STATS)
  2030. int conn_state; /* 0 = undef, numerical value may change in different
  2031. * versions. For the current definition, see
  2032. * mg_get_connection_info_impl */
  2033. #endif
  2034. SSL *ssl; /* SSL descriptor */
  2035. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2036. struct socket client; /* Connected client */
  2037. time_t conn_birth_time; /* Time (wall clock) when connection was
  2038. * established */
  2039. struct timespec req_time; /* Time (since system start) when the request
  2040. * was received */
  2041. int64_t num_bytes_sent; /* Total bytes sent to client */
  2042. int64_t content_len; /* Content-Length header value */
  2043. int64_t consumed_content; /* How many bytes of content have been read */
  2044. int is_chunked; /* Transfer-Encoding is chunked:
  2045. * 0 = not chunked,
  2046. * 1 = chunked, do data read yet,
  2047. * 2 = chunked, some data read,
  2048. * 3 = chunked, all data read
  2049. */
  2050. size_t chunk_remainder; /* Unread data from the last chunk */
  2051. char *buf; /* Buffer for received data */
  2052. char *path_info; /* PATH_INFO part of the URL */
  2053. int must_close; /* 1 if connection must be closed */
  2054. int accept_gzip; /* 1 if gzip encoding is accepted */
  2055. int in_error_handler; /* 1 if in handler for user defined error
  2056. * pages */
  2057. #if defined(USE_WEBSOCKET)
  2058. int in_websocket_handling; /* 1 if in read_websocket */
  2059. #endif
  2060. int handled_requests; /* Number of requests handled by this connection
  2061. */
  2062. int buf_size; /* Buffer size */
  2063. int request_len; /* Size of the request + headers in a buffer */
  2064. int data_len; /* Total size of data in a buffer */
  2065. int status_code; /* HTTP reply status code, e.g. 200 */
  2066. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2067. * throttle */
  2068. time_t last_throttle_time; /* Last time throttled data was sent */
  2069. int64_t last_throttle_bytes; /* Bytes sent this second */
  2070. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2071. * atomic transmissions for websockets */
  2072. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2073. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2074. #endif
  2075. int thread_index; /* Thread index within ctx */
  2076. };
  2077. /* Directory entry */
  2078. struct de {
  2079. struct mg_connection *conn;
  2080. char *file_name;
  2081. struct mg_file_stat file;
  2082. };
  2083. #if defined(USE_WEBSOCKET)
  2084. static int is_websocket_protocol(const struct mg_connection *conn);
  2085. #else
  2086. #define is_websocket_protocol(conn) (0)
  2087. #endif
  2088. #if !defined(NO_THREAD_NAME)
  2089. #if defined(_WIN32) && defined(_MSC_VER)
  2090. /* Set the thread name for debugging purposes in Visual Studio
  2091. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2092. */
  2093. #pragma pack(push, 8)
  2094. typedef struct tagTHREADNAME_INFO {
  2095. DWORD dwType; /* Must be 0x1000. */
  2096. LPCSTR szName; /* Pointer to name (in user addr space). */
  2097. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2098. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2099. } THREADNAME_INFO;
  2100. #pragma pack(pop)
  2101. #elif defined(__linux__)
  2102. #include <sys/prctl.h>
  2103. #include <sys/sendfile.h>
  2104. #ifdef ALTERNATIVE_QUEUE
  2105. #include <sys/eventfd.h>
  2106. #endif /* ALTERNATIVE_QUEUE */
  2107. #if defined(ALTERNATIVE_QUEUE)
  2108. #ifdef __clang__
  2109. #pragma clang diagnostic push
  2110. #pragma clang diagnostic ignored "-Wunreachable-code"
  2111. /* For every system, "(sizeof(int) == sizeof(void *))" is either always
  2112. * true or always false. One of the two branches is unreachable in any case.
  2113. * Unfortunately the C standard does not define a way to check this at
  2114. * compile time, since the #if preprocessor conditions can not use the sizeof
  2115. * operator as an argument. */
  2116. #endif
  2117. #if defined(__GNUC__) || defined(__MINGW32__)
  2118. /* GCC does not realize one branch is unreachable, so it raises some
  2119. * pointer cast warning within the unreachable branch.
  2120. */
  2121. #pragma GCC diagnostic push
  2122. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
  2123. #pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
  2124. #endif
  2125. static void *
  2126. event_create(void)
  2127. {
  2128. int evhdl = eventfd(0, EFD_CLOEXEC);
  2129. int *ret;
  2130. if (evhdl == -1) {
  2131. /* Linux uses -1 on error, Windows NULL. */
  2132. /* However, Linux does not return 0 on success either. */
  2133. return 0;
  2134. }
  2135. if (sizeof(int) == sizeof(void *)) {
  2136. ret = (void *)evhdl;
  2137. } else {
  2138. ret = (int *)mg_malloc(sizeof(int));
  2139. if (ret) {
  2140. *ret = evhdl;
  2141. } else {
  2142. (void)close(evhdl);
  2143. }
  2144. }
  2145. return (void *)ret;
  2146. }
  2147. static int
  2148. event_wait(void *eventhdl)
  2149. {
  2150. uint64_t u;
  2151. int evhdl, s;
  2152. if (sizeof(int) == sizeof(void *)) {
  2153. evhdl = (int)eventhdl;
  2154. } else {
  2155. if (!eventhdl) {
  2156. /* error */
  2157. return 0;
  2158. }
  2159. evhdl = *(int *)eventhdl;
  2160. }
  2161. s = (int)read(evhdl, &u, sizeof(u));
  2162. if (s != sizeof(uint64_t)) {
  2163. /* error */
  2164. return 0;
  2165. }
  2166. (void)u; /* the value is not required */
  2167. return 1;
  2168. }
  2169. static int
  2170. event_signal(void *eventhdl)
  2171. {
  2172. uint64_t u = 1;
  2173. int evhdl, s;
  2174. if (sizeof(int) == sizeof(void *)) {
  2175. evhdl = (int)eventhdl;
  2176. } else {
  2177. if (!eventhdl) {
  2178. /* error */
  2179. return 0;
  2180. }
  2181. evhdl = *(int *)eventhdl;
  2182. }
  2183. s = (int)write(evhdl, &u, sizeof(u));
  2184. if (s != sizeof(uint64_t)) {
  2185. /* error */
  2186. return 0;
  2187. }
  2188. return 1;
  2189. }
  2190. static void
  2191. event_destroy(void *eventhdl)
  2192. {
  2193. int evhdl;
  2194. if (sizeof(int) == sizeof(void *)) {
  2195. evhdl = (int)eventhdl;
  2196. close(evhdl);
  2197. } else {
  2198. if (!eventhdl) {
  2199. /* error */
  2200. return;
  2201. }
  2202. evhdl = *(int *)eventhdl;
  2203. close(evhdl);
  2204. mg_free(eventhdl);
  2205. }
  2206. }
  2207. #if defined(__GNUC__) || defined(__MINGW32__)
  2208. #pragma GCC diagnostic pop
  2209. #endif
  2210. #ifdef __clang__
  2211. #pragma clang diagnostic pop
  2212. #endif
  2213. #endif
  2214. #endif
  2215. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2216. struct posix_event {
  2217. pthread_mutex_t mutex;
  2218. pthread_cond_t cond;
  2219. };
  2220. static void *
  2221. event_create(void)
  2222. {
  2223. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2224. if (ret == 0) {
  2225. /* out of memory */
  2226. return 0;
  2227. }
  2228. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2229. /* pthread mutex not available */
  2230. mg_free(ret);
  2231. return 0;
  2232. }
  2233. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2234. /* pthread cond not available */
  2235. pthread_mutex_destroy(&(ret->mutex));
  2236. mg_free(ret);
  2237. return 0;
  2238. }
  2239. return (void *)ret;
  2240. }
  2241. static int
  2242. event_wait(void *eventhdl)
  2243. {
  2244. struct posix_event *ev = (struct posix_event *)eventhdl;
  2245. pthread_mutex_lock(&(ev->mutex));
  2246. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2247. pthread_mutex_unlock(&(ev->mutex));
  2248. return 1;
  2249. }
  2250. static int
  2251. event_signal(void *eventhdl)
  2252. {
  2253. struct posix_event *ev = (struct posix_event *)eventhdl;
  2254. pthread_mutex_lock(&(ev->mutex));
  2255. pthread_cond_signal(&(ev->cond));
  2256. pthread_mutex_unlock(&(ev->mutex));
  2257. return 1;
  2258. }
  2259. static void
  2260. event_destroy(void *eventhdl)
  2261. {
  2262. struct posix_event *ev = (struct posix_event *)eventhdl;
  2263. pthread_cond_destroy(&(ev->cond));
  2264. pthread_mutex_destroy(&(ev->mutex));
  2265. mg_free(ev);
  2266. }
  2267. #endif
  2268. static void
  2269. mg_set_thread_name(const char *name)
  2270. {
  2271. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2272. mg_snprintf(
  2273. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2274. #if defined(_WIN32)
  2275. #if defined(_MSC_VER)
  2276. /* Windows and Visual Studio Compiler */
  2277. __try
  2278. {
  2279. THREADNAME_INFO info;
  2280. info.dwType = 0x1000;
  2281. info.szName = threadName;
  2282. info.dwThreadID = ~0U;
  2283. info.dwFlags = 0;
  2284. RaiseException(0x406D1388,
  2285. 0,
  2286. sizeof(info) / sizeof(ULONG_PTR),
  2287. (ULONG_PTR *)&info);
  2288. }
  2289. __except(EXCEPTION_EXECUTE_HANDLER)
  2290. {
  2291. }
  2292. #elif defined(__MINGW32__)
  2293. /* No option known to set thread name for MinGW */
  2294. #endif
  2295. #elif defined(__GLIBC__) \
  2296. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2297. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2298. (void)pthread_setname_np(pthread_self(), threadName);
  2299. #elif defined(__linux__)
  2300. /* on linux we can use the old prctl function */
  2301. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2302. #endif
  2303. }
  2304. #else /* !defined(NO_THREAD_NAME) */
  2305. void
  2306. mg_set_thread_name(const char *threadName)
  2307. {
  2308. }
  2309. #endif
  2310. #if defined(MG_LEGACY_INTERFACE)
  2311. const char **
  2312. mg_get_valid_option_names(void)
  2313. {
  2314. /* This function is deprecated. Use mg_get_valid_options instead. */
  2315. static const char *
  2316. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2317. int i;
  2318. for (i = 0; config_options[i].name != NULL; i++) {
  2319. data[i * 2] = config_options[i].name;
  2320. data[i * 2 + 1] = config_options[i].default_value;
  2321. }
  2322. return data;
  2323. }
  2324. #endif
  2325. const struct mg_option *
  2326. mg_get_valid_options(void)
  2327. {
  2328. return config_options;
  2329. }
  2330. /* Do not open file (used in is_file_in_memory) */
  2331. #define MG_FOPEN_MODE_NONE (0)
  2332. /* Open file for read only access */
  2333. #define MG_FOPEN_MODE_READ (1)
  2334. /* Open file for writing, create and overwrite */
  2335. #define MG_FOPEN_MODE_WRITE (2)
  2336. /* Open file for writing, create and append */
  2337. #define MG_FOPEN_MODE_APPEND (4)
  2338. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2339. * output filep and return 1, otherwise return 0 and don't modify anything.
  2340. */
  2341. static int
  2342. open_file_in_memory(const struct mg_connection *conn,
  2343. const char *path,
  2344. struct mg_file *filep,
  2345. int mode)
  2346. {
  2347. #if defined(MG_USE_OPEN_FILE)
  2348. size_t size = 0;
  2349. const char *buf = NULL;
  2350. if (!conn) {
  2351. return 0;
  2352. }
  2353. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2354. return 0;
  2355. }
  2356. if (conn->ctx->callbacks.open_file) {
  2357. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2358. if (buf != NULL) {
  2359. if (filep == NULL) {
  2360. /* This is a file in memory, but we cannot store the
  2361. * properties
  2362. * now.
  2363. * Called from "is_file_in_memory" function. */
  2364. return 1;
  2365. }
  2366. /* NOTE: override filep->size only on success. Otherwise, it
  2367. * might
  2368. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2369. filep->access.membuf = buf;
  2370. filep->access.fp = NULL;
  2371. /* Size was set by the callback */
  2372. filep->stat.size = size;
  2373. /* Assume the data may change during runtime by setting
  2374. * last_modified = now */
  2375. filep->stat.last_modified = time(NULL);
  2376. filep->stat.is_directory = 0;
  2377. filep->stat.is_gzipped = 0;
  2378. }
  2379. }
  2380. return (buf != NULL);
  2381. #else
  2382. (void)conn;
  2383. (void)path;
  2384. (void)filep;
  2385. (void)mode;
  2386. return 0;
  2387. #endif
  2388. }
  2389. static int
  2390. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2391. {
  2392. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2393. }
  2394. static int
  2395. is_file_opened(const struct mg_file_access *fileacc)
  2396. {
  2397. if (!fileacc) {
  2398. return 0;
  2399. }
  2400. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2401. }
  2402. static int mg_stat(const struct mg_connection *conn,
  2403. const char *path,
  2404. struct mg_file_stat *filep);
  2405. /* mg_fopen will open a file either in memory or on the disk.
  2406. * The input parameter path is a string in UTF-8 encoding.
  2407. * The input parameter mode is MG_FOPEN_MODE_*
  2408. * On success, either fp or membuf will be set in the output
  2409. * struct file. All status members will also be set.
  2410. * The function returns 1 on success, 0 on error. */
  2411. static int
  2412. mg_fopen(const struct mg_connection *conn,
  2413. const char *path,
  2414. int mode,
  2415. struct mg_file *filep)
  2416. {
  2417. int found;
  2418. if (!filep) {
  2419. return 0;
  2420. }
  2421. filep->access.fp = NULL;
  2422. filep->access.membuf = NULL;
  2423. if (!is_file_in_memory(conn, path)) {
  2424. /* filep is initialized in mg_stat: all fields with memset to,
  2425. * some fields like size and modification date with values */
  2426. found = mg_stat(conn, path, &(filep->stat));
  2427. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2428. /* file does not exist and will not be created */
  2429. return 0;
  2430. }
  2431. #ifdef _WIN32
  2432. {
  2433. wchar_t wbuf[PATH_MAX];
  2434. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2435. switch (mode) {
  2436. case MG_FOPEN_MODE_READ:
  2437. filep->access.fp = _wfopen(wbuf, L"rb");
  2438. break;
  2439. case MG_FOPEN_MODE_WRITE:
  2440. filep->access.fp = _wfopen(wbuf, L"wb");
  2441. break;
  2442. case MG_FOPEN_MODE_APPEND:
  2443. filep->access.fp = _wfopen(wbuf, L"ab");
  2444. break;
  2445. }
  2446. }
  2447. #else
  2448. /* Linux et al already use unicode. No need to convert. */
  2449. switch (mode) {
  2450. case MG_FOPEN_MODE_READ:
  2451. filep->access.fp = fopen(path, "r");
  2452. break;
  2453. case MG_FOPEN_MODE_WRITE:
  2454. filep->access.fp = fopen(path, "w");
  2455. break;
  2456. case MG_FOPEN_MODE_APPEND:
  2457. filep->access.fp = fopen(path, "a");
  2458. break;
  2459. }
  2460. #endif
  2461. if (!found) {
  2462. /* File did not exist before fopen was called.
  2463. * Maybe it has been created now. Get stat info
  2464. * like creation time now. */
  2465. found = mg_stat(conn, path, &(filep->stat));
  2466. (void)found;
  2467. }
  2468. /* file is on disk */
  2469. return (filep->access.fp != NULL);
  2470. } else {
  2471. /* is_file_in_memory returned true */
  2472. if (open_file_in_memory(conn, path, filep, mode)) {
  2473. /* file is in memory */
  2474. return (filep->access.membuf != NULL);
  2475. }
  2476. }
  2477. /* Open failed */
  2478. return 0;
  2479. }
  2480. /* return 0 on success, just like fclose */
  2481. static int
  2482. mg_fclose(struct mg_file_access *fileacc)
  2483. {
  2484. int ret = -1;
  2485. if (fileacc != NULL) {
  2486. if (fileacc->fp != NULL) {
  2487. ret = fclose(fileacc->fp);
  2488. } else if (fileacc->membuf != NULL) {
  2489. ret = 0;
  2490. }
  2491. /* reset all members of fileacc */
  2492. memset(fileacc, 0, sizeof(*fileacc));
  2493. }
  2494. return ret;
  2495. }
  2496. static void
  2497. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2498. {
  2499. for (; *src != '\0' && n > 1; n--) {
  2500. *dst++ = *src++;
  2501. }
  2502. *dst = '\0';
  2503. }
  2504. static int
  2505. lowercase(const char *s)
  2506. {
  2507. return tolower(*(const unsigned char *)s);
  2508. }
  2509. int
  2510. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2511. {
  2512. int diff = 0;
  2513. if (len > 0) {
  2514. do {
  2515. diff = lowercase(s1++) - lowercase(s2++);
  2516. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2517. }
  2518. return diff;
  2519. }
  2520. int
  2521. mg_strcasecmp(const char *s1, const char *s2)
  2522. {
  2523. int diff;
  2524. do {
  2525. diff = lowercase(s1++) - lowercase(s2++);
  2526. } while (diff == 0 && s1[-1] != '\0');
  2527. return diff;
  2528. }
  2529. static char *
  2530. mg_strndup(const char *ptr, size_t len)
  2531. {
  2532. char *p;
  2533. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2534. mg_strlcpy(p, ptr, len + 1);
  2535. }
  2536. return p;
  2537. }
  2538. static char *
  2539. mg_strdup(const char *str)
  2540. {
  2541. return mg_strndup(str, strlen(str));
  2542. }
  2543. static const char *
  2544. mg_strcasestr(const char *big_str, const char *small_str)
  2545. {
  2546. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2547. if (big_len >= small_len) {
  2548. for (i = 0; i <= (big_len - small_len); i++) {
  2549. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2550. return big_str + i;
  2551. }
  2552. }
  2553. }
  2554. return NULL;
  2555. }
  2556. /* Return null terminated string of given maximum length.
  2557. * Report errors if length is exceeded. */
  2558. static void
  2559. mg_vsnprintf(const struct mg_connection *conn,
  2560. int *truncated,
  2561. char *buf,
  2562. size_t buflen,
  2563. const char *fmt,
  2564. va_list ap)
  2565. {
  2566. int n, ok;
  2567. if (buflen == 0) {
  2568. if (truncated) {
  2569. *truncated = 1;
  2570. }
  2571. return;
  2572. }
  2573. #ifdef __clang__
  2574. #pragma clang diagnostic push
  2575. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2576. /* Using fmt as a non-literal is intended here, since it is mostly called
  2577. * indirectly by mg_snprintf */
  2578. #endif
  2579. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2580. ok = (n >= 0) && ((size_t)n < buflen);
  2581. #ifdef __clang__
  2582. #pragma clang diagnostic pop
  2583. #endif
  2584. if (ok) {
  2585. if (truncated) {
  2586. *truncated = 0;
  2587. }
  2588. } else {
  2589. if (truncated) {
  2590. *truncated = 1;
  2591. }
  2592. mg_cry(conn,
  2593. "truncating vsnprintf buffer: [%.*s]",
  2594. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2595. buf);
  2596. n = (int)buflen - 1;
  2597. }
  2598. buf[n] = '\0';
  2599. }
  2600. static void
  2601. mg_snprintf(const struct mg_connection *conn,
  2602. int *truncated,
  2603. char *buf,
  2604. size_t buflen,
  2605. const char *fmt,
  2606. ...)
  2607. {
  2608. va_list ap;
  2609. va_start(ap, fmt);
  2610. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2611. va_end(ap);
  2612. }
  2613. static int
  2614. get_option_index(const char *name)
  2615. {
  2616. int i;
  2617. for (i = 0; config_options[i].name != NULL; i++) {
  2618. if (strcmp(config_options[i].name, name) == 0) {
  2619. return i;
  2620. }
  2621. }
  2622. return -1;
  2623. }
  2624. const char *
  2625. mg_get_option(const struct mg_context *ctx, const char *name)
  2626. {
  2627. int i;
  2628. if ((i = get_option_index(name)) == -1) {
  2629. return NULL;
  2630. } else if (!ctx || ctx->config[i] == NULL) {
  2631. return "";
  2632. } else {
  2633. return ctx->config[i];
  2634. }
  2635. }
  2636. struct mg_context *
  2637. mg_get_context(const struct mg_connection *conn)
  2638. {
  2639. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2640. }
  2641. void *
  2642. mg_get_user_data(const struct mg_context *ctx)
  2643. {
  2644. return (ctx == NULL) ? NULL : ctx->user_data;
  2645. }
  2646. void
  2647. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2648. {
  2649. if (conn != NULL) {
  2650. conn->request_info.conn_data = data;
  2651. }
  2652. }
  2653. void *
  2654. mg_get_user_connection_data(const struct mg_connection *conn)
  2655. {
  2656. if (conn != NULL) {
  2657. return conn->request_info.conn_data;
  2658. }
  2659. return NULL;
  2660. }
  2661. #if defined(MG_LEGACY_INTERFACE)
  2662. /* Deprecated: Use mg_get_server_ports instead. */
  2663. size_t
  2664. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2665. {
  2666. size_t i;
  2667. if (!ctx) {
  2668. return 0;
  2669. }
  2670. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2671. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2672. ports[i] =
  2673. #if defined(USE_IPV6)
  2674. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2675. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2676. :
  2677. #endif
  2678. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2679. }
  2680. return i;
  2681. }
  2682. #endif
  2683. int
  2684. mg_get_server_ports(const struct mg_context *ctx,
  2685. int size,
  2686. struct mg_server_ports *ports)
  2687. {
  2688. int i, cnt = 0;
  2689. if (size <= 0) {
  2690. return -1;
  2691. }
  2692. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2693. if (!ctx) {
  2694. return -1;
  2695. }
  2696. if (!ctx->listening_sockets) {
  2697. return -1;
  2698. }
  2699. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2700. ports[cnt].port =
  2701. #if defined(USE_IPV6)
  2702. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2703. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2704. :
  2705. #endif
  2706. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2707. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2708. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2709. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2710. /* IPv4 */
  2711. ports[cnt].protocol = 1;
  2712. cnt++;
  2713. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2714. /* IPv6 */
  2715. ports[cnt].protocol = 3;
  2716. cnt++;
  2717. }
  2718. }
  2719. return cnt;
  2720. }
  2721. static void
  2722. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2723. {
  2724. buf[0] = '\0';
  2725. if (!usa) {
  2726. return;
  2727. }
  2728. if (usa->sa.sa_family == AF_INET) {
  2729. getnameinfo(&usa->sa,
  2730. sizeof(usa->sin),
  2731. buf,
  2732. (unsigned)len,
  2733. NULL,
  2734. 0,
  2735. NI_NUMERICHOST);
  2736. }
  2737. #if defined(USE_IPV6)
  2738. else if (usa->sa.sa_family == AF_INET6) {
  2739. getnameinfo(&usa->sa,
  2740. sizeof(usa->sin6),
  2741. buf,
  2742. (unsigned)len,
  2743. NULL,
  2744. 0,
  2745. NI_NUMERICHOST);
  2746. }
  2747. #endif
  2748. }
  2749. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2750. * included in all responses other than 100, 101, 5xx. */
  2751. static void
  2752. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2753. {
  2754. struct tm *tm;
  2755. tm = ((t != NULL) ? gmtime(t) : NULL);
  2756. if (tm != NULL) {
  2757. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2758. } else {
  2759. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2760. buf[buf_len - 1] = '\0';
  2761. }
  2762. }
  2763. /* difftime for struct timespec. Return value is in seconds. */
  2764. static double
  2765. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2766. {
  2767. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2768. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2769. }
  2770. /* Print error message to the opened error log stream. */
  2771. void
  2772. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2773. {
  2774. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2775. va_list ap;
  2776. struct mg_file fi;
  2777. time_t timestamp;
  2778. va_start(ap, fmt);
  2779. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2780. va_end(ap);
  2781. buf[sizeof(buf) - 1] = 0;
  2782. DEBUG_TRACE("mg_cry: %s", buf);
  2783. if (!conn) {
  2784. puts(buf);
  2785. return;
  2786. }
  2787. /* Do not lock when getting the callback value, here and below.
  2788. * I suppose this is fine, since function cannot disappear in the
  2789. * same way string option can. */
  2790. if ((conn->ctx->callbacks.log_message == NULL)
  2791. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2792. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2793. if (mg_fopen(conn,
  2794. conn->ctx->config[ERROR_LOG_FILE],
  2795. MG_FOPEN_MODE_APPEND,
  2796. &fi) == 0) {
  2797. fi.access.fp = NULL;
  2798. }
  2799. } else {
  2800. fi.access.fp = NULL;
  2801. }
  2802. if (fi.access.fp != NULL) {
  2803. flockfile(fi.access.fp);
  2804. timestamp = time(NULL);
  2805. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2806. fprintf(fi.access.fp,
  2807. "[%010lu] [error] [client %s] ",
  2808. (unsigned long)timestamp,
  2809. src_addr);
  2810. if (conn->request_info.request_method != NULL) {
  2811. fprintf(fi.access.fp,
  2812. "%s %s: ",
  2813. conn->request_info.request_method,
  2814. conn->request_info.request_uri
  2815. ? conn->request_info.request_uri
  2816. : "");
  2817. }
  2818. fprintf(fi.access.fp, "%s", buf);
  2819. fputc('\n', fi.access.fp);
  2820. fflush(fi.access.fp);
  2821. funlockfile(fi.access.fp);
  2822. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2823. * mg_cry here anyway ;-) */
  2824. }
  2825. }
  2826. }
  2827. /* Return fake connection structure. Used for logging, if connection
  2828. * is not applicable at the moment of logging. */
  2829. static struct mg_connection *
  2830. fc(struct mg_context *ctx)
  2831. {
  2832. static struct mg_connection fake_connection;
  2833. fake_connection.ctx = ctx;
  2834. return &fake_connection;
  2835. }
  2836. const char *
  2837. mg_version(void)
  2838. {
  2839. return CIVETWEB_VERSION;
  2840. }
  2841. const struct mg_request_info *
  2842. mg_get_request_info(const struct mg_connection *conn)
  2843. {
  2844. if (!conn) {
  2845. return NULL;
  2846. }
  2847. #if 1 /* TODO: deal with legacy */
  2848. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2849. static char txt[16];
  2850. sprintf(txt, "%03i", conn->response_info.status_code);
  2851. ((struct mg_connection *)conn)->request_info.local_uri =
  2852. ((struct mg_connection *)conn)->request_info.request_uri =
  2853. txt; /* TODO: not thread safe */
  2854. ((struct mg_connection *)conn)->request_info.num_headers =
  2855. conn->response_info.num_headers;
  2856. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2857. conn->response_info.http_headers,
  2858. sizeof(conn->response_info.http_headers));
  2859. } else
  2860. #endif
  2861. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2862. return NULL;
  2863. }
  2864. return &conn->request_info;
  2865. }
  2866. const struct mg_response_info *
  2867. mg_get_response_info(const struct mg_connection *conn)
  2868. {
  2869. if (!conn) {
  2870. return NULL;
  2871. }
  2872. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2873. return NULL;
  2874. }
  2875. return &conn->response_info;
  2876. }
  2877. static const char *
  2878. get_proto_name(const struct mg_connection *conn)
  2879. {
  2880. #ifdef __clang__
  2881. #pragma clang diagnostic push
  2882. #pragma clang diagnostic ignored "-Wunreachable-code"
  2883. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2884. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2885. * unreachable, but splitting into four different #ifdef clauses here is more
  2886. * complicated.
  2887. */
  2888. #endif
  2889. const struct mg_request_info *ri = &conn->request_info;
  2890. const char *proto =
  2891. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2892. : (ri->is_ssl ? "https" : "http"));
  2893. return proto;
  2894. #ifdef __clang__
  2895. #pragma clang diagnostic pop
  2896. #endif
  2897. }
  2898. int
  2899. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2900. {
  2901. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2902. return -1;
  2903. } else {
  2904. int truncated = 0;
  2905. const struct mg_request_info *ri = &conn->request_info;
  2906. const char *proto = get_proto_name(conn);
  2907. if (ri->local_uri == NULL) {
  2908. return -1;
  2909. }
  2910. if ((ri->request_uri != NULL)
  2911. && strcmp(ri->local_uri, ri->request_uri)) {
  2912. mg_snprintf(conn,
  2913. &truncated,
  2914. buf,
  2915. buflen,
  2916. "%s://%s",
  2917. proto,
  2918. ri->request_uri);
  2919. if (truncated) {
  2920. return -1;
  2921. }
  2922. return 0;
  2923. } else {
  2924. #if defined(USE_IPV6)
  2925. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2926. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2927. : htons(conn->client.lsa.sin.sin_port);
  2928. #else
  2929. int port = htons(conn->client.lsa.sin.sin_port);
  2930. #endif
  2931. int def_port = ri->is_ssl ? 443 : 80;
  2932. int auth_domain_check_enabled =
  2933. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2934. && (!mg_strcasecmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2935. "yes"));
  2936. const char *server_domain =
  2937. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2938. char portstr[16];
  2939. char server_ip[48];
  2940. if (port != def_port) {
  2941. sprintf(portstr, ":%u", (unsigned)port);
  2942. } else {
  2943. portstr[0] = 0;
  2944. }
  2945. if (!auth_domain_check_enabled || !server_domain) {
  2946. sockaddr_to_string(server_ip,
  2947. sizeof(server_ip),
  2948. &conn->client.lsa);
  2949. server_domain = server_ip;
  2950. }
  2951. mg_snprintf(conn,
  2952. &truncated,
  2953. buf,
  2954. buflen,
  2955. "%s://%s%s%s",
  2956. proto,
  2957. server_domain,
  2958. portstr,
  2959. ri->local_uri);
  2960. if (truncated) {
  2961. return -1;
  2962. }
  2963. return 0;
  2964. }
  2965. }
  2966. }
  2967. /* Skip the characters until one of the delimiters characters found.
  2968. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2969. * Advance pointer to buffer to the next word. Return found 0-terminated
  2970. * word.
  2971. * Delimiters can be quoted with quotechar. */
  2972. static char *
  2973. skip_quoted(char **buf,
  2974. const char *delimiters,
  2975. const char *whitespace,
  2976. char quotechar)
  2977. {
  2978. char *p, *begin_word, *end_word, *end_whitespace;
  2979. begin_word = *buf;
  2980. end_word = begin_word + strcspn(begin_word, delimiters);
  2981. /* Check for quotechar */
  2982. if (end_word > begin_word) {
  2983. p = end_word - 1;
  2984. while (*p == quotechar) {
  2985. /* While the delimiter is quoted, look for the next delimiter.
  2986. */
  2987. /* This happens, e.g., in calls from parse_auth_header,
  2988. * if the user name contains a " character. */
  2989. /* If there is anything beyond end_word, copy it. */
  2990. if (*end_word != '\0') {
  2991. size_t end_off = strcspn(end_word + 1, delimiters);
  2992. memmove(p, end_word, end_off + 1);
  2993. p += end_off; /* p must correspond to end_word - 1 */
  2994. end_word += end_off + 1;
  2995. } else {
  2996. *p = '\0';
  2997. break;
  2998. }
  2999. }
  3000. for (p++; p < end_word; p++) {
  3001. *p = '\0';
  3002. }
  3003. }
  3004. if (*end_word == '\0') {
  3005. *buf = end_word;
  3006. } else {
  3007. #if defined(__GNUC__) || defined(__MINGW32__)
  3008. /* Disable spurious conversion warning for GCC */
  3009. #if GCC_VERSION >= 40500
  3010. #pragma GCC diagnostic push
  3011. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3012. #endif /* GCC_VERSION >= 40500 */
  3013. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3014. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3015. #if defined(__GNUC__) || defined(__MINGW32__)
  3016. #if GCC_VERSION >= 40500
  3017. #pragma GCC diagnostic pop
  3018. #endif /* GCC_VERSION >= 40500 */
  3019. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3020. for (p = end_word; p < end_whitespace; p++) {
  3021. *p = '\0';
  3022. }
  3023. *buf = end_whitespace;
  3024. }
  3025. return begin_word;
  3026. }
  3027. /* Return HTTP header value, or NULL if not found. */
  3028. static const char *
  3029. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3030. {
  3031. int i;
  3032. for (i = 0; i < num_hdr; i++) {
  3033. if (!mg_strcasecmp(name, hdr[i].name)) {
  3034. return hdr[i].value;
  3035. }
  3036. }
  3037. return NULL;
  3038. }
  3039. #if defined(USE_WEBSOCKET)
  3040. /* Retrieve requested HTTP header multiple values, and return the number of
  3041. * found occurences */
  3042. static int
  3043. get_req_headers(const struct mg_request_info *ri,
  3044. const char *name,
  3045. const char **output,
  3046. int output_max_size)
  3047. {
  3048. int i;
  3049. int cnt = 0;
  3050. if (ri) {
  3051. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3052. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3053. output[cnt++] = ri->http_headers[i].value;
  3054. }
  3055. }
  3056. }
  3057. return cnt;
  3058. }
  3059. #endif
  3060. const char *
  3061. mg_get_header(const struct mg_connection *conn, const char *name)
  3062. {
  3063. if (!conn) {
  3064. return NULL;
  3065. }
  3066. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3067. return get_header(conn->request_info.http_headers,
  3068. conn->request_info.num_headers,
  3069. name);
  3070. }
  3071. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3072. return get_header(conn->response_info.http_headers,
  3073. conn->response_info.num_headers,
  3074. name);
  3075. }
  3076. return NULL;
  3077. }
  3078. static const char *
  3079. get_http_version(const struct mg_connection *conn)
  3080. {
  3081. if (!conn) {
  3082. return NULL;
  3083. }
  3084. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3085. return conn->request_info.http_version;
  3086. }
  3087. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3088. return conn->response_info.http_version;
  3089. }
  3090. return NULL;
  3091. }
  3092. /* A helper function for traversing a comma separated list of values.
  3093. * It returns a list pointer shifted to the next value, or NULL if the end
  3094. * of the list found.
  3095. * Value is stored in val vector. If value has form "x=y", then eq_val
  3096. * vector is initialized to point to the "y" part, and val vector length
  3097. * is adjusted to point only to "x". */
  3098. static const char *
  3099. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3100. {
  3101. int end;
  3102. reparse:
  3103. if (val == NULL || list == NULL || *list == '\0') {
  3104. /* End of the list */
  3105. return NULL;
  3106. }
  3107. /* Skip over leading LWS */
  3108. while (*list == ' ' || *list == '\t')
  3109. list++;
  3110. val->ptr = list;
  3111. if ((list = strchr(val->ptr, ',')) != NULL) {
  3112. /* Comma found. Store length and shift the list ptr */
  3113. val->len = ((size_t)(list - val->ptr));
  3114. list++;
  3115. } else {
  3116. /* This value is the last one */
  3117. list = val->ptr + strlen(val->ptr);
  3118. val->len = ((size_t)(list - val->ptr));
  3119. }
  3120. /* Adjust length for trailing LWS */
  3121. end = (int)val->len - 1;
  3122. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3123. end--;
  3124. val->len = (size_t)(end + 1);
  3125. if (val->len == 0) {
  3126. /* Ignore any empty entries. */
  3127. goto reparse;
  3128. }
  3129. if (eq_val != NULL) {
  3130. /* Value has form "x=y", adjust pointers and lengths
  3131. * so that val points to "x", and eq_val points to "y". */
  3132. eq_val->len = 0;
  3133. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3134. if (eq_val->ptr != NULL) {
  3135. eq_val->ptr++; /* Skip over '=' character */
  3136. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3137. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3138. }
  3139. }
  3140. return list;
  3141. }
  3142. /* A helper function for checking if a comma separated list of values
  3143. * contains
  3144. * the given option (case insensitvely).
  3145. * 'header' can be NULL, in which case false is returned. */
  3146. static int
  3147. header_has_option(const char *header, const char *option)
  3148. {
  3149. struct vec opt_vec;
  3150. struct vec eq_vec;
  3151. /*
  3152. assert(option != NULL);
  3153. assert(option[0] != '\0');
  3154. */
  3155. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3156. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3157. return 1;
  3158. }
  3159. return 0;
  3160. }
  3161. /* Perform case-insensitive match of string against pattern */
  3162. static int
  3163. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3164. {
  3165. const char *or_str;
  3166. size_t i;
  3167. int j, len, res;
  3168. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3169. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3170. return (res > 0) ? res : match_prefix(or_str + 1,
  3171. (size_t)((pattern + pattern_len)
  3172. - (or_str + 1)),
  3173. str);
  3174. }
  3175. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  3176. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3177. continue;
  3178. } else if (pattern[i] == '$') {
  3179. return (str[j] == '\0') ? j : -1;
  3180. } else if (pattern[i] == '*') {
  3181. i++;
  3182. if (pattern[i] == '*') {
  3183. i++;
  3184. len = (int)strlen(str + j);
  3185. } else {
  3186. len = (int)strcspn(str + j, "/");
  3187. }
  3188. if (i == pattern_len) {
  3189. return j + len;
  3190. }
  3191. do {
  3192. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3193. } while (res == -1 && len-- > 0);
  3194. return (res == -1) ? -1 : j + res + len;
  3195. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3196. return -1;
  3197. }
  3198. }
  3199. return j;
  3200. }
  3201. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3202. * This function must tolerate situations when connection info is not
  3203. * set up, for example if request parsing failed. */
  3204. static int
  3205. should_keep_alive(const struct mg_connection *conn)
  3206. {
  3207. const char *http_version;
  3208. const char *header;
  3209. /* First satisfy needs of the server */
  3210. if ((conn == NULL) || conn->must_close) {
  3211. /* Close, if civetweb framework needs to close */
  3212. return 0;
  3213. }
  3214. if (mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3215. /* Close, if keep alive is not enabled */
  3216. return 0;
  3217. }
  3218. /* Check explicit wish of the client */
  3219. header = mg_get_header(conn, "Connection");
  3220. if (header) {
  3221. /* If there is a connection header from the client, obey */
  3222. if (header_has_option(header, "keep-alive")) {
  3223. return 1;
  3224. }
  3225. return 0;
  3226. }
  3227. /* Use default of the standard */
  3228. http_version = get_http_version(conn);
  3229. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3230. /* HTTP 1.1 default is keep alive */
  3231. return 1;
  3232. }
  3233. /* HTTP 1.0 (and earlier) default is to close the connection */
  3234. return 0;
  3235. }
  3236. static int
  3237. should_decode_url(const struct mg_connection *conn)
  3238. {
  3239. if (!conn || !conn->ctx) {
  3240. return 0;
  3241. }
  3242. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  3243. }
  3244. static const char *
  3245. suggest_connection_header(const struct mg_connection *conn)
  3246. {
  3247. return should_keep_alive(conn) ? "keep-alive" : "close";
  3248. }
  3249. static int
  3250. send_no_cache_header(struct mg_connection *conn)
  3251. {
  3252. /* Send all current and obsolete cache opt-out directives. */
  3253. return mg_printf(conn,
  3254. "Cache-Control: no-cache, no-store, "
  3255. "must-revalidate, private, max-age=0\r\n"
  3256. "Pragma: no-cache\r\n"
  3257. "Expires: 0\r\n");
  3258. }
  3259. static int
  3260. send_static_cache_header(struct mg_connection *conn)
  3261. {
  3262. #if !defined(NO_CACHING)
  3263. /* Read the server config to check how long a file may be cached.
  3264. * The configuration is in seconds. */
  3265. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  3266. if (max_age <= 0) {
  3267. /* 0 means "do not cache". All values <0 are reserved
  3268. * and may be used differently in the future. */
  3269. /* If a file should not be cached, do not only send
  3270. * max-age=0, but also pragmas and Expires headers. */
  3271. return send_no_cache_header(conn);
  3272. }
  3273. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3274. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3275. /* See also https://www.mnot.net/cache_docs/ */
  3276. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3277. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3278. * leap
  3279. * year to 31622400 seconds. For the moment, we just send whatever has
  3280. * been configured, still the behavior for >1 year should be considered
  3281. * as undefined. */
  3282. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3283. #else /* NO_CACHING */
  3284. return send_no_cache_header(conn);
  3285. #endif /* !NO_CACHING */
  3286. }
  3287. static int
  3288. send_additional_header(struct mg_connection *conn)
  3289. {
  3290. int i = 0;
  3291. const char *header = conn->ctx->config[ADDITIONAL_HEADER];
  3292. #if !defined(NO_SSL)
  3293. if (conn->ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3294. int max_age = atoi(conn->ctx->config[STRICT_HTTPS_MAX_AGE]);
  3295. if (max_age >= 0) {
  3296. i += mg_printf(conn,
  3297. "Strict-Transport-Security: max-age=%u\r\n",
  3298. (unsigned)max_age);
  3299. }
  3300. }
  3301. #endif
  3302. if (header && header[0]) {
  3303. i += mg_printf(conn, "%s\r\n", header);
  3304. }
  3305. return i;
  3306. }
  3307. static void handle_file_based_request(struct mg_connection *conn,
  3308. const char *path,
  3309. struct mg_file *filep);
  3310. const char *
  3311. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3312. {
  3313. /* See IANA HTTP status code assignment:
  3314. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3315. */
  3316. switch (response_code) {
  3317. /* RFC2616 Section 10.1 - Informational 1xx */
  3318. case 100:
  3319. return "Continue"; /* RFC2616 Section 10.1.1 */
  3320. case 101:
  3321. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3322. case 102:
  3323. return "Processing"; /* RFC2518 Section 10.1 */
  3324. /* RFC2616 Section 10.2 - Successful 2xx */
  3325. case 200:
  3326. return "OK"; /* RFC2616 Section 10.2.1 */
  3327. case 201:
  3328. return "Created"; /* RFC2616 Section 10.2.2 */
  3329. case 202:
  3330. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3331. case 203:
  3332. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3333. case 204:
  3334. return "No Content"; /* RFC2616 Section 10.2.5 */
  3335. case 205:
  3336. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3337. case 206:
  3338. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3339. case 207:
  3340. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3341. */
  3342. case 208:
  3343. return "Already Reported"; /* RFC5842 Section 7.1 */
  3344. case 226:
  3345. return "IM used"; /* RFC3229 Section 10.4.1 */
  3346. /* RFC2616 Section 10.3 - Redirection 3xx */
  3347. case 300:
  3348. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3349. case 301:
  3350. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3351. case 302:
  3352. return "Found"; /* RFC2616 Section 10.3.3 */
  3353. case 303:
  3354. return "See Other"; /* RFC2616 Section 10.3.4 */
  3355. case 304:
  3356. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3357. case 305:
  3358. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3359. case 307:
  3360. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3361. case 308:
  3362. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3363. /* RFC2616 Section 10.4 - Client Error 4xx */
  3364. case 400:
  3365. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3366. case 401:
  3367. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3368. case 402:
  3369. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3370. case 403:
  3371. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3372. case 404:
  3373. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3374. case 405:
  3375. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3376. case 406:
  3377. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3378. case 407:
  3379. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3380. case 408:
  3381. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3382. case 409:
  3383. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3384. case 410:
  3385. return "Gone"; /* RFC2616 Section 10.4.11 */
  3386. case 411:
  3387. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3388. case 412:
  3389. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3390. case 413:
  3391. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3392. case 414:
  3393. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3394. case 415:
  3395. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3396. case 416:
  3397. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3398. */
  3399. case 417:
  3400. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3401. case 421:
  3402. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3403. case 422:
  3404. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3405. * Section 11.2 */
  3406. case 423:
  3407. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3408. case 424:
  3409. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3410. * Section 11.4 */
  3411. case 426:
  3412. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3413. case 428:
  3414. return "Precondition Required"; /* RFC 6585, Section 3 */
  3415. case 429:
  3416. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3417. case 431:
  3418. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3419. case 451:
  3420. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3421. * Section 3 */
  3422. /* RFC2616 Section 10.5 - Server Error 5xx */
  3423. case 500:
  3424. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3425. case 501:
  3426. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3427. case 502:
  3428. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3429. case 503:
  3430. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3431. case 504:
  3432. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3433. case 505:
  3434. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3435. case 506:
  3436. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3437. case 507:
  3438. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3439. * Section 11.5 */
  3440. case 508:
  3441. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3442. case 510:
  3443. return "Not Extended"; /* RFC 2774, Section 7 */
  3444. case 511:
  3445. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3446. /* Other status codes, not shown in the IANA HTTP status code
  3447. * assignment.
  3448. * E.g., "de facto" standards due to common use, ... */
  3449. case 418:
  3450. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3451. case 419:
  3452. return "Authentication Timeout"; /* common use */
  3453. case 420:
  3454. return "Enhance Your Calm"; /* common use */
  3455. case 440:
  3456. return "Login Timeout"; /* common use */
  3457. case 509:
  3458. return "Bandwidth Limit Exceeded"; /* common use */
  3459. default:
  3460. /* This error code is unknown. This should not happen. */
  3461. if (conn) {
  3462. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3463. }
  3464. /* Return at least a category according to RFC 2616 Section 10. */
  3465. if (response_code >= 100 && response_code < 200) {
  3466. /* Unknown informational status code */
  3467. return "Information";
  3468. }
  3469. if (response_code >= 200 && response_code < 300) {
  3470. /* Unknown success code */
  3471. return "Success";
  3472. }
  3473. if (response_code >= 300 && response_code < 400) {
  3474. /* Unknown redirection code */
  3475. return "Redirection";
  3476. }
  3477. if (response_code >= 400 && response_code < 500) {
  3478. /* Unknown request error code */
  3479. return "Client Error";
  3480. }
  3481. if (response_code >= 500 && response_code < 600) {
  3482. /* Unknown server error code */
  3483. return "Server Error";
  3484. }
  3485. /* Response code not even within reasonable range */
  3486. return "";
  3487. }
  3488. }
  3489. void
  3490. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3491. {
  3492. char buf[MG_BUF_LEN];
  3493. va_list ap;
  3494. int len, i, page_handler_found, scope, truncated, has_body;
  3495. char date[64];
  3496. time_t curtime = time(NULL);
  3497. const char *error_handler = NULL;
  3498. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3499. const char *error_page_file_ext, *tstr;
  3500. const char *status_text = mg_get_response_code_text(conn, status);
  3501. if (conn == NULL) {
  3502. return;
  3503. }
  3504. conn->status_code = status;
  3505. if (conn->in_error_handler || (conn->ctx->callbacks.http_error == NULL)
  3506. || conn->ctx->callbacks.http_error(conn, status)) {
  3507. /* Check for recursion */
  3508. if (conn->in_error_handler) {
  3509. DEBUG_TRACE(
  3510. "Recursion when handling error %u - fall back to default",
  3511. status);
  3512. } else {
  3513. /* Send user defined error pages, if defined */
  3514. error_handler = conn->ctx->config[ERROR_PAGES];
  3515. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3516. page_handler_found = 0;
  3517. if (error_handler != NULL) {
  3518. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3519. switch (scope) {
  3520. case 1: /* Handler for specific error, e.g. 404 error */
  3521. mg_snprintf(conn,
  3522. &truncated,
  3523. buf,
  3524. sizeof(buf) - 32,
  3525. "%serror%03u.",
  3526. error_handler,
  3527. status);
  3528. break;
  3529. case 2: /* Handler for error group, e.g., 5xx error
  3530. * handler
  3531. * for all server errors (500-599) */
  3532. mg_snprintf(conn,
  3533. &truncated,
  3534. buf,
  3535. sizeof(buf) - 32,
  3536. "%serror%01uxx.",
  3537. error_handler,
  3538. status / 100);
  3539. break;
  3540. default: /* Handler for all errors */
  3541. mg_snprintf(conn,
  3542. &truncated,
  3543. buf,
  3544. sizeof(buf) - 32,
  3545. "%serror.",
  3546. error_handler);
  3547. break;
  3548. }
  3549. /* String truncation in buf may only occur if
  3550. * error_handler is too long. This string is
  3551. * from the config, not from a client. */
  3552. (void)truncated;
  3553. len = (int)strlen(buf);
  3554. tstr = strchr(error_page_file_ext, '.');
  3555. while (tstr) {
  3556. for (i = 1;
  3557. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3558. i++)
  3559. buf[len + i - 1] = tstr[i];
  3560. buf[len + i - 1] = 0;
  3561. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3562. DEBUG_TRACE("Check error page %s - found", buf);
  3563. page_handler_found = 1;
  3564. break;
  3565. }
  3566. DEBUG_TRACE("Check error page %s - not found", buf);
  3567. tstr = strchr(tstr + i, '.');
  3568. }
  3569. }
  3570. }
  3571. if (page_handler_found) {
  3572. conn->in_error_handler = 1;
  3573. handle_file_based_request(conn, buf, &error_page_file);
  3574. conn->in_error_handler = 0;
  3575. return;
  3576. }
  3577. }
  3578. /* No custom error page. Send default error page. */
  3579. gmt_time_string(date, sizeof(date), &curtime);
  3580. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3581. has_body = ((status > 199) && (status != 204) && (status != 304));
  3582. conn->must_close = 1;
  3583. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3584. send_no_cache_header(conn);
  3585. send_additional_header(conn);
  3586. if (has_body) {
  3587. mg_printf(conn,
  3588. "%s",
  3589. "Content-Type: text/plain; charset=utf-8\r\n");
  3590. }
  3591. mg_printf(conn,
  3592. "Date: %s\r\n"
  3593. "Connection: close\r\n\r\n",
  3594. date);
  3595. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3596. if (has_body) {
  3597. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3598. if (fmt != NULL) {
  3599. va_start(ap, fmt);
  3600. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3601. va_end(ap);
  3602. mg_write(conn, buf, strlen(buf));
  3603. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3604. }
  3605. } else {
  3606. /* No body allowed. Close the connection. */
  3607. DEBUG_TRACE("Error %i", status);
  3608. }
  3609. }
  3610. }
  3611. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3612. /* Create substitutes for POSIX functions in Win32. */
  3613. #if defined(__MINGW32__)
  3614. /* Show no warning in case system functions are not used. */
  3615. #pragma GCC diagnostic push
  3616. #pragma GCC diagnostic ignored "-Wunused-function"
  3617. #endif
  3618. FUNCTION_MAY_BE_UNUSED
  3619. static int
  3620. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3621. {
  3622. (void)unused;
  3623. *mutex = CreateMutex(NULL, FALSE, NULL);
  3624. return (*mutex == NULL) ? -1 : 0;
  3625. }
  3626. FUNCTION_MAY_BE_UNUSED
  3627. static int
  3628. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3629. {
  3630. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3631. }
  3632. FUNCTION_MAY_BE_UNUSED
  3633. static int
  3634. pthread_mutex_lock(pthread_mutex_t *mutex)
  3635. {
  3636. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  3637. : -1;
  3638. }
  3639. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3640. FUNCTION_MAY_BE_UNUSED
  3641. static int
  3642. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3643. {
  3644. switch (WaitForSingleObject(*mutex, 0)) {
  3645. case WAIT_OBJECT_0:
  3646. return 0;
  3647. case WAIT_TIMEOUT:
  3648. return -2; /* EBUSY */
  3649. }
  3650. return -1;
  3651. }
  3652. #endif
  3653. FUNCTION_MAY_BE_UNUSED
  3654. static int
  3655. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3656. {
  3657. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3658. }
  3659. FUNCTION_MAY_BE_UNUSED
  3660. static int
  3661. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3662. {
  3663. (void)unused;
  3664. InitializeCriticalSection(&cv->threadIdSec);
  3665. cv->waiting_thread = NULL;
  3666. return 0;
  3667. }
  3668. FUNCTION_MAY_BE_UNUSED
  3669. static int
  3670. pthread_cond_timedwait(pthread_cond_t *cv,
  3671. pthread_mutex_t *mutex,
  3672. const struct timespec *abstime)
  3673. {
  3674. struct mg_workerTLS **ptls,
  3675. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3676. int ok;
  3677. int64_t nsnow, nswaitabs, nswaitrel;
  3678. DWORD mswaitrel;
  3679. EnterCriticalSection(&cv->threadIdSec);
  3680. /* Add this thread to cv's waiting list */
  3681. ptls = &cv->waiting_thread;
  3682. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3683. ;
  3684. tls->next_waiting_thread = NULL;
  3685. *ptls = tls;
  3686. LeaveCriticalSection(&cv->threadIdSec);
  3687. if (abstime) {
  3688. nsnow = mg_get_current_time_ns();
  3689. nswaitabs =
  3690. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3691. nswaitrel = nswaitabs - nsnow;
  3692. if (nswaitrel < 0) {
  3693. nswaitrel = 0;
  3694. }
  3695. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3696. } else {
  3697. mswaitrel = (DWORD)INFINITE;
  3698. }
  3699. pthread_mutex_unlock(mutex);
  3700. ok = (WAIT_OBJECT_0
  3701. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3702. if (!ok) {
  3703. ok = 1;
  3704. EnterCriticalSection(&cv->threadIdSec);
  3705. ptls = &cv->waiting_thread;
  3706. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3707. if (*ptls == tls) {
  3708. *ptls = tls->next_waiting_thread;
  3709. ok = 0;
  3710. break;
  3711. }
  3712. }
  3713. LeaveCriticalSection(&cv->threadIdSec);
  3714. if (ok) {
  3715. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  3716. (DWORD)INFINITE);
  3717. }
  3718. }
  3719. /* This thread has been removed from cv's waiting list */
  3720. pthread_mutex_lock(mutex);
  3721. return ok ? 0 : -1;
  3722. }
  3723. FUNCTION_MAY_BE_UNUSED
  3724. static int
  3725. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3726. {
  3727. return pthread_cond_timedwait(cv, mutex, NULL);
  3728. }
  3729. FUNCTION_MAY_BE_UNUSED
  3730. static int
  3731. pthread_cond_signal(pthread_cond_t *cv)
  3732. {
  3733. HANDLE wkup = NULL;
  3734. BOOL ok = FALSE;
  3735. EnterCriticalSection(&cv->threadIdSec);
  3736. if (cv->waiting_thread) {
  3737. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3738. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3739. ok = SetEvent(wkup);
  3740. assert(ok);
  3741. }
  3742. LeaveCriticalSection(&cv->threadIdSec);
  3743. return ok ? 0 : 1;
  3744. }
  3745. FUNCTION_MAY_BE_UNUSED
  3746. static int
  3747. pthread_cond_broadcast(pthread_cond_t *cv)
  3748. {
  3749. EnterCriticalSection(&cv->threadIdSec);
  3750. while (cv->waiting_thread) {
  3751. pthread_cond_signal(cv);
  3752. }
  3753. LeaveCriticalSection(&cv->threadIdSec);
  3754. return 0;
  3755. }
  3756. FUNCTION_MAY_BE_UNUSED
  3757. static int
  3758. pthread_cond_destroy(pthread_cond_t *cv)
  3759. {
  3760. EnterCriticalSection(&cv->threadIdSec);
  3761. assert(cv->waiting_thread == NULL);
  3762. LeaveCriticalSection(&cv->threadIdSec);
  3763. DeleteCriticalSection(&cv->threadIdSec);
  3764. return 0;
  3765. }
  3766. #ifdef ALTERNATIVE_QUEUE
  3767. FUNCTION_MAY_BE_UNUSED
  3768. static void *
  3769. event_create(void)
  3770. {
  3771. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3772. }
  3773. FUNCTION_MAY_BE_UNUSED
  3774. static int
  3775. event_wait(void *eventhdl)
  3776. {
  3777. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  3778. return (res == WAIT_OBJECT_0);
  3779. }
  3780. FUNCTION_MAY_BE_UNUSED
  3781. static int
  3782. event_signal(void *eventhdl)
  3783. {
  3784. return (int)SetEvent((HANDLE)eventhdl);
  3785. }
  3786. FUNCTION_MAY_BE_UNUSED
  3787. static void
  3788. event_destroy(void *eventhdl)
  3789. {
  3790. CloseHandle((HANDLE)eventhdl);
  3791. }
  3792. #endif
  3793. #if defined(__MINGW32__)
  3794. /* Enable unused function warning again */
  3795. #pragma GCC diagnostic pop
  3796. #endif
  3797. /* For Windows, change all slashes to backslashes in path names. */
  3798. static void
  3799. change_slashes_to_backslashes(char *path)
  3800. {
  3801. int i;
  3802. for (i = 0; path[i] != '\0'; i++) {
  3803. if (path[i] == '/') {
  3804. path[i] = '\\';
  3805. }
  3806. /* remove double backslash (check i > 0 to preserve UNC paths,
  3807. * like \\server\file.txt) */
  3808. if ((path[i] == '\\') && (i > 0)) {
  3809. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3810. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3811. }
  3812. }
  3813. }
  3814. }
  3815. static int
  3816. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3817. {
  3818. int diff;
  3819. do {
  3820. diff = tolower(*s1) - tolower(*s2);
  3821. s1++;
  3822. s2++;
  3823. } while ((diff == 0) && (s1[-1] != '\0'));
  3824. return diff;
  3825. }
  3826. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3827. * wbuf and wbuf_len is a target buffer and its length. */
  3828. static void
  3829. path_to_unicode(const struct mg_connection *conn,
  3830. const char *path,
  3831. wchar_t *wbuf,
  3832. size_t wbuf_len)
  3833. {
  3834. char buf[PATH_MAX], buf2[PATH_MAX];
  3835. wchar_t wbuf2[MAX_PATH + 1];
  3836. DWORD long_len, err;
  3837. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3838. mg_strlcpy(buf, path, sizeof(buf));
  3839. change_slashes_to_backslashes(buf);
  3840. /* Convert to Unicode and back. If doubly-converted string does not
  3841. * match the original, something is fishy, reject. */
  3842. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3843. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3844. WideCharToMultiByte(
  3845. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3846. if (strcmp(buf, buf2) != 0) {
  3847. wbuf[0] = L'\0';
  3848. }
  3849. /* Windows file systems are not case sensitive, but you can still use
  3850. * uppercase and lowercase letters (on all modern file systems).
  3851. * The server can check if the URI uses the same upper/lowercase
  3852. * letters an the file system, effectively making Windows servers
  3853. * case sensitive (like Linux servers are). It is still not possible
  3854. * to use two files with the same name in different cases on Windows
  3855. * (like /a and /A) - this would be possible in Linux.
  3856. * As a default, Windows is not case sensitive, but the case sensitive
  3857. * file name check can be activated by an additional configuration. */
  3858. if (conn) {
  3859. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3860. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3861. /* Use case sensitive compare function */
  3862. fcompare = wcscmp;
  3863. }
  3864. }
  3865. (void)conn; /* conn is currently unused */
  3866. #if !defined(_WIN32_WCE)
  3867. /* Only accept a full file path, not a Windows short (8.3) path. */
  3868. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3869. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3870. if (long_len == 0) {
  3871. err = GetLastError();
  3872. if (err == ERROR_FILE_NOT_FOUND) {
  3873. /* File does not exist. This is not always a problem here. */
  3874. return;
  3875. }
  3876. }
  3877. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3878. /* Short name is used. */
  3879. wbuf[0] = L'\0';
  3880. }
  3881. #else
  3882. (void)long_len;
  3883. (void)wbuf2;
  3884. (void)err;
  3885. if (strchr(path, '~')) {
  3886. wbuf[0] = L'\0';
  3887. }
  3888. #endif
  3889. }
  3890. /* Windows happily opens files with some garbage at the end of file name.
  3891. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3892. * "a.cgi", despite one would expect an error back.
  3893. * This function returns non-0 if path ends with some garbage. */
  3894. static int
  3895. path_cannot_disclose_cgi(const char *path)
  3896. {
  3897. static const char *allowed_last_characters = "_-";
  3898. int last = path[strlen(path) - 1];
  3899. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3900. }
  3901. static int
  3902. mg_stat(const struct mg_connection *conn,
  3903. const char *path,
  3904. struct mg_file_stat *filep)
  3905. {
  3906. wchar_t wbuf[PATH_MAX];
  3907. WIN32_FILE_ATTRIBUTE_DATA info;
  3908. time_t creation_time;
  3909. if (!filep) {
  3910. return 0;
  3911. }
  3912. memset(filep, 0, sizeof(*filep));
  3913. if (conn && is_file_in_memory(conn, path)) {
  3914. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3915. * memset */
  3916. /* Quick fix (for 1.9.x): */
  3917. /* mg_stat must fill all fields, also for files in memory */
  3918. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3919. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3920. filep->size = tmp_file.stat.size;
  3921. filep->location = 2;
  3922. /* TODO: for 1.10: restructure how files in memory are handled */
  3923. /* The "file in memory" feature is a candidate for deletion.
  3924. * Please join the discussion at
  3925. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3926. */
  3927. filep->last_modified = time(NULL); /* TODO */
  3928. /* last_modified = now ... assumes the file may change during
  3929. * runtime,
  3930. * so every mg_fopen call may return different data */
  3931. /* last_modified = conn->ctx.start_time;
  3932. * May be used it the data does not change during runtime. This
  3933. * allows
  3934. * browser caching. Since we do not know, we have to assume the file
  3935. * in memory may change. */
  3936. return 1;
  3937. }
  3938. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3939. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3940. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3941. filep->last_modified =
  3942. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3943. info.ftLastWriteTime.dwHighDateTime);
  3944. /* On Windows, the file creation time can be higher than the
  3945. * modification time, e.g. when a file is copied.
  3946. * Since the Last-Modified timestamp is used for caching
  3947. * it should be based on the most recent timestamp. */
  3948. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3949. info.ftCreationTime.dwHighDateTime);
  3950. if (creation_time > filep->last_modified) {
  3951. filep->last_modified = creation_time;
  3952. }
  3953. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3954. /* If file name is fishy, reset the file structure and return
  3955. * error.
  3956. * Note it is important to reset, not just return the error, cause
  3957. * functions like is_file_opened() check the struct. */
  3958. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3959. memset(filep, 0, sizeof(*filep));
  3960. return 0;
  3961. }
  3962. return 1;
  3963. }
  3964. return 0;
  3965. }
  3966. static int
  3967. mg_remove(const struct mg_connection *conn, const char *path)
  3968. {
  3969. wchar_t wbuf[PATH_MAX];
  3970. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3971. return DeleteFileW(wbuf) ? 0 : -1;
  3972. }
  3973. static int
  3974. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3975. {
  3976. wchar_t wbuf[PATH_MAX];
  3977. (void)mode;
  3978. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3979. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3980. }
  3981. /* Create substitutes for POSIX functions in Win32. */
  3982. #if defined(__MINGW32__)
  3983. /* Show no warning in case system functions are not used. */
  3984. #pragma GCC diagnostic push
  3985. #pragma GCC diagnostic ignored "-Wunused-function"
  3986. #endif
  3987. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3988. FUNCTION_MAY_BE_UNUSED
  3989. static DIR *
  3990. mg_opendir(const struct mg_connection *conn, const char *name)
  3991. {
  3992. DIR *dir = NULL;
  3993. wchar_t wpath[PATH_MAX];
  3994. DWORD attrs;
  3995. if (name == NULL) {
  3996. SetLastError(ERROR_BAD_ARGUMENTS);
  3997. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3998. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3999. } else {
  4000. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4001. attrs = GetFileAttributesW(wpath);
  4002. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  4003. == FILE_ATTRIBUTE_DIRECTORY)) {
  4004. (void)wcscat(wpath, L"\\*");
  4005. dir->handle = FindFirstFileW(wpath, &dir->info);
  4006. dir->result.d_name[0] = '\0';
  4007. } else {
  4008. mg_free(dir);
  4009. dir = NULL;
  4010. }
  4011. }
  4012. return dir;
  4013. }
  4014. FUNCTION_MAY_BE_UNUSED
  4015. static int
  4016. mg_closedir(DIR *dir)
  4017. {
  4018. int result = 0;
  4019. if (dir != NULL) {
  4020. if (dir->handle != INVALID_HANDLE_VALUE)
  4021. result = FindClose(dir->handle) ? 0 : -1;
  4022. mg_free(dir);
  4023. } else {
  4024. result = -1;
  4025. SetLastError(ERROR_BAD_ARGUMENTS);
  4026. }
  4027. return result;
  4028. }
  4029. FUNCTION_MAY_BE_UNUSED
  4030. static struct dirent *
  4031. mg_readdir(DIR *dir)
  4032. {
  4033. struct dirent *result = 0;
  4034. if (dir) {
  4035. if (dir->handle != INVALID_HANDLE_VALUE) {
  4036. result = &dir->result;
  4037. (void)WideCharToMultiByte(CP_UTF8,
  4038. 0,
  4039. dir->info.cFileName,
  4040. -1,
  4041. result->d_name,
  4042. sizeof(result->d_name),
  4043. NULL,
  4044. NULL);
  4045. if (!FindNextFileW(dir->handle, &dir->info)) {
  4046. (void)FindClose(dir->handle);
  4047. dir->handle = INVALID_HANDLE_VALUE;
  4048. }
  4049. } else {
  4050. SetLastError(ERROR_FILE_NOT_FOUND);
  4051. }
  4052. } else {
  4053. SetLastError(ERROR_BAD_ARGUMENTS);
  4054. }
  4055. return result;
  4056. }
  4057. #ifndef HAVE_POLL
  4058. FUNCTION_MAY_BE_UNUSED
  4059. static int
  4060. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4061. {
  4062. struct timeval tv;
  4063. fd_set set;
  4064. unsigned int i;
  4065. int result;
  4066. SOCKET maxfd = 0;
  4067. memset(&tv, 0, sizeof(tv));
  4068. tv.tv_sec = milliseconds / 1000;
  4069. tv.tv_usec = (milliseconds % 1000) * 1000;
  4070. FD_ZERO(&set);
  4071. for (i = 0; i < n; i++) {
  4072. FD_SET((SOCKET)pfd[i].fd, &set);
  4073. pfd[i].revents = 0;
  4074. if (pfd[i].fd > maxfd) {
  4075. maxfd = pfd[i].fd;
  4076. }
  4077. }
  4078. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4079. for (i = 0; i < n; i++) {
  4080. if (FD_ISSET(pfd[i].fd, &set)) {
  4081. pfd[i].revents = POLLIN;
  4082. }
  4083. }
  4084. }
  4085. /* We should subtract the time used in select from remaining
  4086. * "milliseconds", in particular if called from mg_poll with a
  4087. * timeout quantum.
  4088. * Unfortunately, the remaining time is not stored in "tv" in all
  4089. * implementations, so the result in "tv" must be considered undefined.
  4090. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4091. return result;
  4092. }
  4093. #endif /* HAVE_POLL */
  4094. #if defined(__MINGW32__)
  4095. /* Enable unused function warning again */
  4096. #pragma GCC diagnostic pop
  4097. #endif
  4098. static void
  4099. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4100. {
  4101. (void)conn; /* Unused. */
  4102. #if defined(_WIN32_WCE)
  4103. (void)sock;
  4104. #else
  4105. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4106. #endif
  4107. }
  4108. int
  4109. mg_start_thread(mg_thread_func_t f, void *p)
  4110. {
  4111. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4112. /* Compile-time option to control stack size, e.g.
  4113. * -DUSE_STACK_SIZE=16384
  4114. */
  4115. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4116. == ((uintptr_t)(-1L)))
  4117. ? -1
  4118. : 0);
  4119. #else
  4120. return (
  4121. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4122. ? -1
  4123. : 0);
  4124. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4125. }
  4126. /* Start a thread storing the thread context. */
  4127. static int
  4128. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4129. void *p,
  4130. pthread_t *threadidptr)
  4131. {
  4132. uintptr_t uip;
  4133. HANDLE threadhandle;
  4134. int result = -1;
  4135. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4136. threadhandle = (HANDLE)uip;
  4137. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4138. *threadidptr = threadhandle;
  4139. result = 0;
  4140. }
  4141. return result;
  4142. }
  4143. /* Wait for a thread to finish. */
  4144. static int
  4145. mg_join_thread(pthread_t threadid)
  4146. {
  4147. int result;
  4148. DWORD dwevent;
  4149. result = -1;
  4150. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4151. if (dwevent == WAIT_FAILED) {
  4152. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4153. } else {
  4154. if (dwevent == WAIT_OBJECT_0) {
  4155. CloseHandle(threadid);
  4156. result = 0;
  4157. }
  4158. }
  4159. return result;
  4160. }
  4161. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4162. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4163. /* Create substitutes for POSIX functions in Win32. */
  4164. #if defined(__MINGW32__)
  4165. /* Show no warning in case system functions are not used. */
  4166. #pragma GCC diagnostic push
  4167. #pragma GCC diagnostic ignored "-Wunused-function"
  4168. #endif
  4169. FUNCTION_MAY_BE_UNUSED
  4170. static HANDLE
  4171. dlopen(const char *dll_name, int flags)
  4172. {
  4173. wchar_t wbuf[PATH_MAX];
  4174. (void)flags;
  4175. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4176. return LoadLibraryW(wbuf);
  4177. }
  4178. FUNCTION_MAY_BE_UNUSED
  4179. static int
  4180. dlclose(void *handle)
  4181. {
  4182. int result;
  4183. if (FreeLibrary((HMODULE)handle) != 0) {
  4184. result = 0;
  4185. } else {
  4186. result = -1;
  4187. }
  4188. return result;
  4189. }
  4190. #if defined(__MINGW32__)
  4191. /* Enable unused function warning again */
  4192. #pragma GCC diagnostic pop
  4193. #endif
  4194. #endif
  4195. #if !defined(NO_CGI)
  4196. #define SIGKILL (0)
  4197. static int
  4198. kill(pid_t pid, int sig_num)
  4199. {
  4200. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4201. (void)CloseHandle((HANDLE)pid);
  4202. return 0;
  4203. }
  4204. static void
  4205. trim_trailing_whitespaces(char *s)
  4206. {
  4207. char *e = s + strlen(s) - 1;
  4208. while ((e > s) && isspace(*(unsigned char *)e)) {
  4209. *e-- = '\0';
  4210. }
  4211. }
  4212. static pid_t
  4213. spawn_process(struct mg_connection *conn,
  4214. const char *prog,
  4215. char *envblk,
  4216. char *envp[],
  4217. int fdin[2],
  4218. int fdout[2],
  4219. int fderr[2],
  4220. const char *dir)
  4221. {
  4222. HANDLE me;
  4223. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4224. cmdline[PATH_MAX], buf[PATH_MAX];
  4225. int truncated;
  4226. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4227. STARTUPINFOA si;
  4228. PROCESS_INFORMATION pi = {0};
  4229. (void)envp;
  4230. memset(&si, 0, sizeof(si));
  4231. si.cb = sizeof(si);
  4232. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4233. si.wShowWindow = SW_HIDE;
  4234. me = GetCurrentProcess();
  4235. DuplicateHandle(me,
  4236. (HANDLE)_get_osfhandle(fdin[0]),
  4237. me,
  4238. &si.hStdInput,
  4239. 0,
  4240. TRUE,
  4241. DUPLICATE_SAME_ACCESS);
  4242. DuplicateHandle(me,
  4243. (HANDLE)_get_osfhandle(fdout[1]),
  4244. me,
  4245. &si.hStdOutput,
  4246. 0,
  4247. TRUE,
  4248. DUPLICATE_SAME_ACCESS);
  4249. DuplicateHandle(me,
  4250. (HANDLE)_get_osfhandle(fderr[1]),
  4251. me,
  4252. &si.hStdError,
  4253. 0,
  4254. TRUE,
  4255. DUPLICATE_SAME_ACCESS);
  4256. /* Mark handles that should not be inherited. See
  4257. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4258. */
  4259. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4260. HANDLE_FLAG_INHERIT,
  4261. 0);
  4262. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4263. HANDLE_FLAG_INHERIT,
  4264. 0);
  4265. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4266. HANDLE_FLAG_INHERIT,
  4267. 0);
  4268. /* If CGI file is a script, try to read the interpreter line */
  4269. interp = conn->ctx->config[CGI_INTERPRETER];
  4270. if (interp == NULL) {
  4271. buf[0] = buf[1] = '\0';
  4272. /* Read the first line of the script into the buffer */
  4273. mg_snprintf(
  4274. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4275. if (truncated) {
  4276. pi.hProcess = (pid_t)-1;
  4277. goto spawn_cleanup;
  4278. }
  4279. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4280. p = (char *)file.access.membuf;
  4281. mg_fgets(buf, sizeof(buf), &file, &p);
  4282. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4283. buf[sizeof(buf) - 1] = '\0';
  4284. }
  4285. if ((buf[0] == '#') && (buf[1] == '!')) {
  4286. trim_trailing_whitespaces(buf + 2);
  4287. } else {
  4288. buf[2] = '\0';
  4289. }
  4290. interp = buf + 2;
  4291. }
  4292. if (interp[0] != '\0') {
  4293. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4294. interp = full_interp;
  4295. }
  4296. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4297. if (interp[0] != '\0') {
  4298. mg_snprintf(conn,
  4299. &truncated,
  4300. cmdline,
  4301. sizeof(cmdline),
  4302. "\"%s\" \"%s\\%s\"",
  4303. interp,
  4304. full_dir,
  4305. prog);
  4306. } else {
  4307. mg_snprintf(conn,
  4308. &truncated,
  4309. cmdline,
  4310. sizeof(cmdline),
  4311. "\"%s\\%s\"",
  4312. full_dir,
  4313. prog);
  4314. }
  4315. if (truncated) {
  4316. pi.hProcess = (pid_t)-1;
  4317. goto spawn_cleanup;
  4318. }
  4319. DEBUG_TRACE("Running [%s]", cmdline);
  4320. if (CreateProcessA(NULL,
  4321. cmdline,
  4322. NULL,
  4323. NULL,
  4324. TRUE,
  4325. CREATE_NEW_PROCESS_GROUP,
  4326. envblk,
  4327. NULL,
  4328. &si,
  4329. &pi) == 0) {
  4330. mg_cry(
  4331. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4332. pi.hProcess = (pid_t)-1;
  4333. /* goto spawn_cleanup; */
  4334. }
  4335. spawn_cleanup:
  4336. (void)CloseHandle(si.hStdOutput);
  4337. (void)CloseHandle(si.hStdError);
  4338. (void)CloseHandle(si.hStdInput);
  4339. if (pi.hThread != NULL) {
  4340. (void)CloseHandle(pi.hThread);
  4341. }
  4342. return (pid_t)pi.hProcess;
  4343. }
  4344. #endif /* !NO_CGI */
  4345. static int
  4346. set_blocking_mode(SOCKET sock)
  4347. {
  4348. unsigned long non_blocking = 0;
  4349. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4350. }
  4351. static int
  4352. set_non_blocking_mode(SOCKET sock)
  4353. {
  4354. unsigned long non_blocking = 1;
  4355. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4356. }
  4357. #else
  4358. static int
  4359. mg_stat(const struct mg_connection *conn,
  4360. const char *path,
  4361. struct mg_file_stat *filep)
  4362. {
  4363. struct stat st;
  4364. if (!filep) {
  4365. return 0;
  4366. }
  4367. memset(filep, 0, sizeof(*filep));
  4368. if (conn && is_file_in_memory(conn, path)) {
  4369. /* Quick fix (for 1.9.x): */
  4370. /* mg_stat must fill all fields, also for files in memory */
  4371. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4372. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4373. filep->size = tmp_file.stat.size;
  4374. filep->last_modified = time(NULL);
  4375. filep->location = 2;
  4376. /* TODO: for 1.10: restructure how files in memory are handled */
  4377. return 1;
  4378. }
  4379. if (0 == stat(path, &st)) {
  4380. filep->size = (uint64_t)(st.st_size);
  4381. filep->last_modified = st.st_mtime;
  4382. filep->is_directory = S_ISDIR(st.st_mode);
  4383. return 1;
  4384. }
  4385. return 0;
  4386. }
  4387. static void
  4388. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4389. {
  4390. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4391. if (conn) {
  4392. mg_cry(conn,
  4393. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4394. __func__,
  4395. strerror(ERRNO));
  4396. }
  4397. }
  4398. }
  4399. int
  4400. mg_start_thread(mg_thread_func_t func, void *param)
  4401. {
  4402. pthread_t thread_id;
  4403. pthread_attr_t attr;
  4404. int result;
  4405. (void)pthread_attr_init(&attr);
  4406. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4407. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4408. /* Compile-time option to control stack size,
  4409. * e.g. -DUSE_STACK_SIZE=16384 */
  4410. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4411. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4412. result = pthread_create(&thread_id, &attr, func, param);
  4413. pthread_attr_destroy(&attr);
  4414. return result;
  4415. }
  4416. /* Start a thread storing the thread context. */
  4417. static int
  4418. mg_start_thread_with_id(mg_thread_func_t func,
  4419. void *param,
  4420. pthread_t *threadidptr)
  4421. {
  4422. pthread_t thread_id;
  4423. pthread_attr_t attr;
  4424. int result;
  4425. (void)pthread_attr_init(&attr);
  4426. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4427. /* Compile-time option to control stack size,
  4428. * e.g. -DUSE_STACK_SIZE=16384 */
  4429. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4430. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4431. result = pthread_create(&thread_id, &attr, func, param);
  4432. pthread_attr_destroy(&attr);
  4433. if ((result == 0) && (threadidptr != NULL)) {
  4434. *threadidptr = thread_id;
  4435. }
  4436. return result;
  4437. }
  4438. /* Wait for a thread to finish. */
  4439. static int
  4440. mg_join_thread(pthread_t threadid)
  4441. {
  4442. int result;
  4443. result = pthread_join(threadid, NULL);
  4444. return result;
  4445. }
  4446. #ifndef NO_CGI
  4447. static pid_t
  4448. spawn_process(struct mg_connection *conn,
  4449. const char *prog,
  4450. char *envblk,
  4451. char *envp[],
  4452. int fdin[2],
  4453. int fdout[2],
  4454. int fderr[2],
  4455. const char *dir)
  4456. {
  4457. pid_t pid;
  4458. const char *interp;
  4459. (void)envblk;
  4460. if (conn == NULL) {
  4461. return 0;
  4462. }
  4463. if ((pid = fork()) == -1) {
  4464. /* Parent */
  4465. mg_send_http_error(conn,
  4466. 500,
  4467. "Error: Creating CGI process\nfork(): %s",
  4468. strerror(ERRNO));
  4469. } else if (pid == 0) {
  4470. /* Child */
  4471. if (chdir(dir) != 0) {
  4472. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4473. } else if (dup2(fdin[0], 0) == -1) {
  4474. mg_cry(conn,
  4475. "%s: dup2(%d, 0): %s",
  4476. __func__,
  4477. fdin[0],
  4478. strerror(ERRNO));
  4479. } else if (dup2(fdout[1], 1) == -1) {
  4480. mg_cry(conn,
  4481. "%s: dup2(%d, 1): %s",
  4482. __func__,
  4483. fdout[1],
  4484. strerror(ERRNO));
  4485. } else if (dup2(fderr[1], 2) == -1) {
  4486. mg_cry(conn,
  4487. "%s: dup2(%d, 2): %s",
  4488. __func__,
  4489. fderr[1],
  4490. strerror(ERRNO));
  4491. } else {
  4492. /* Keep stderr and stdout in two different pipes.
  4493. * Stdout will be sent back to the client,
  4494. * stderr should go into a server error log. */
  4495. (void)close(fdin[0]);
  4496. (void)close(fdout[1]);
  4497. (void)close(fderr[1]);
  4498. /* Close write end fdin and read end fdout and fderr */
  4499. (void)close(fdin[1]);
  4500. (void)close(fdout[0]);
  4501. (void)close(fderr[0]);
  4502. /* After exec, all signal handlers are restored to their default
  4503. * values, with one exception of SIGCHLD. According to
  4504. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4505. * leave unchanged after exec if it was set to be ignored. Restore
  4506. * it to default action. */
  4507. signal(SIGCHLD, SIG_DFL);
  4508. interp = conn->ctx->config[CGI_INTERPRETER];
  4509. if (interp == NULL) {
  4510. (void)execle(prog, prog, NULL, envp);
  4511. mg_cry(conn,
  4512. "%s: execle(%s): %s",
  4513. __func__,
  4514. prog,
  4515. strerror(ERRNO));
  4516. } else {
  4517. (void)execle(interp, interp, prog, NULL, envp);
  4518. mg_cry(conn,
  4519. "%s: execle(%s %s): %s",
  4520. __func__,
  4521. interp,
  4522. prog,
  4523. strerror(ERRNO));
  4524. }
  4525. }
  4526. exit(EXIT_FAILURE);
  4527. }
  4528. return pid;
  4529. }
  4530. #endif /* !NO_CGI */
  4531. static int
  4532. set_non_blocking_mode(SOCKET sock)
  4533. {
  4534. int flags = fcntl(sock, F_GETFL, 0);
  4535. if (flags < 0) {
  4536. return -1;
  4537. }
  4538. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4539. return -1;
  4540. }
  4541. return 0;
  4542. }
  4543. static int
  4544. set_blocking_mode(SOCKET sock)
  4545. {
  4546. int flags = fcntl(sock, F_GETFL, 0);
  4547. if (flags < 0) {
  4548. return -1;
  4549. }
  4550. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4551. return -1;
  4552. }
  4553. return 0;
  4554. }
  4555. #endif /* _WIN32 / else */
  4556. /* End of initial operating system specific define block. */
  4557. /* Get a random number (independent of C rand function) */
  4558. static uint64_t
  4559. get_random(void)
  4560. {
  4561. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4562. static uint64_t lcg = 0; /* Linear congruential generator */
  4563. uint64_t now = mg_get_current_time_ns();
  4564. if (lfsr == 0) {
  4565. /* lfsr will be only 0 if has not been initialized,
  4566. * so this code is called only once. */
  4567. lfsr = mg_get_current_time_ns();
  4568. lcg = mg_get_current_time_ns();
  4569. } else {
  4570. /* Get the next step of both random number generators. */
  4571. lfsr = (lfsr >> 1)
  4572. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4573. << 63);
  4574. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4575. }
  4576. /* Combining two pseudo-random number generators and a high resolution
  4577. * part
  4578. * of the current server time will make it hard (impossible?) to guess
  4579. * the
  4580. * next number. */
  4581. return (lfsr ^ lcg ^ now);
  4582. }
  4583. static int
  4584. mg_poll(struct pollfd *pfd,
  4585. unsigned int n,
  4586. int milliseconds,
  4587. volatile int *stop_server)
  4588. {
  4589. /* Call poll, but only for a maximum time of a few seconds.
  4590. * This will allow to stop the server after some seconds, instead
  4591. * of having to wait for a long socket timeout. */
  4592. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4593. do {
  4594. int result;
  4595. if (*stop_server) {
  4596. /* Shut down signal */
  4597. return -2;
  4598. }
  4599. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4600. ms_now = milliseconds;
  4601. }
  4602. result = poll(pfd, n, ms_now);
  4603. if (result != 0) {
  4604. /* Poll returned either success (1) or error (-1).
  4605. * Forward both to the caller. */
  4606. return result;
  4607. }
  4608. /* Poll returned timeout (0). */
  4609. if (milliseconds > 0) {
  4610. milliseconds -= ms_now;
  4611. }
  4612. } while (milliseconds != 0);
  4613. /* timeout: return 0 */
  4614. return 0;
  4615. }
  4616. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4617. * descriptor.
  4618. * Return value:
  4619. * >=0 .. number of bytes successfully written
  4620. * -1 .. timeout
  4621. * -2 .. error
  4622. */
  4623. static int
  4624. push_inner(struct mg_context *ctx,
  4625. FILE *fp,
  4626. SOCKET sock,
  4627. SSL *ssl,
  4628. const char *buf,
  4629. int len,
  4630. double timeout)
  4631. {
  4632. uint64_t start = 0, now = 0, timeout_ns = 0;
  4633. int n, err;
  4634. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4635. #ifdef _WIN32
  4636. typedef int len_t;
  4637. #else
  4638. typedef size_t len_t;
  4639. #endif
  4640. if (timeout > 0) {
  4641. now = mg_get_current_time_ns();
  4642. start = now;
  4643. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4644. }
  4645. if (ctx == NULL) {
  4646. return -2;
  4647. }
  4648. #ifdef NO_SSL
  4649. if (ssl) {
  4650. return -2;
  4651. }
  4652. #endif
  4653. /* Try to read until it succeeds, fails, times out, or the server
  4654. * shuts down. */
  4655. for (;;) {
  4656. #ifndef NO_SSL
  4657. if (ssl != NULL) {
  4658. n = SSL_write(ssl, buf, len);
  4659. if (n <= 0) {
  4660. err = SSL_get_error(ssl, n);
  4661. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4662. err = ERRNO;
  4663. } else if ((err == SSL_ERROR_WANT_READ)
  4664. || (err == SSL_ERROR_WANT_WRITE)) {
  4665. n = 0;
  4666. } else {
  4667. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4668. return -2;
  4669. }
  4670. } else {
  4671. err = 0;
  4672. }
  4673. } else
  4674. #endif
  4675. if (fp != NULL) {
  4676. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4677. if (ferror(fp)) {
  4678. n = -1;
  4679. err = ERRNO;
  4680. } else {
  4681. err = 0;
  4682. }
  4683. } else {
  4684. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4685. err = (n < 0) ? ERRNO : 0;
  4686. #ifdef _WIN32
  4687. if (err == WSAEWOULDBLOCK) {
  4688. err = 0;
  4689. n = 0;
  4690. }
  4691. #else
  4692. if (err == EWOULDBLOCK) {
  4693. err = 0;
  4694. n = 0;
  4695. }
  4696. #endif
  4697. if (n < 0) {
  4698. /* shutdown of the socket at client side */
  4699. return -2;
  4700. }
  4701. }
  4702. if (ctx->stop_flag) {
  4703. return -2;
  4704. }
  4705. if ((n > 0) || ((n == 0) && (len == 0))) {
  4706. /* some data has been read, or no data was requested */
  4707. return n;
  4708. }
  4709. if (n < 0) {
  4710. /* socket error - check errno */
  4711. DEBUG_TRACE("send() failed, error %d", err);
  4712. /* TODO (mid): error handling depending on the error code.
  4713. * These codes are different between Windows and Linux.
  4714. * Currently there is no problem with failing send calls,
  4715. * if there is a reproducible situation, it should be
  4716. * investigated in detail.
  4717. */
  4718. return -2;
  4719. }
  4720. /* Only in case n=0 (timeout), repeat calling the write function */
  4721. /* If send failed, wait before retry */
  4722. if (fp != NULL) {
  4723. /* For files, just wait a fixed time,
  4724. * maybe an average disk seek time. */
  4725. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4726. } else {
  4727. /* For sockets, wait for the socket using select */
  4728. fd_set wfds;
  4729. struct timeval tv;
  4730. int sret;
  4731. #if defined(__GNUC__) || defined(__MINGW32__)
  4732. /* GCC seems to have a flaw with it's own socket macros:
  4733. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4734. */
  4735. #pragma GCC diagnostic push
  4736. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4737. #endif
  4738. FD_ZERO(&wfds);
  4739. FD_SET(sock, &wfds);
  4740. tv.tv_sec = (time_t)(ms_wait / 1000);
  4741. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4742. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4743. #if defined(__GNUC__) || defined(__MINGW32__)
  4744. #pragma GCC diagnostic pop
  4745. #endif
  4746. if (sret > 0) {
  4747. /* We got ready to write. Don't check the timeout
  4748. * but directly go back to write again. */
  4749. continue;
  4750. }
  4751. }
  4752. if (timeout > 0) {
  4753. now = mg_get_current_time_ns();
  4754. if ((now - start) > timeout_ns) {
  4755. /* Timeout */
  4756. break;
  4757. }
  4758. }
  4759. }
  4760. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4761. used */
  4762. return -1;
  4763. }
  4764. static int64_t
  4765. push_all(struct mg_context *ctx,
  4766. FILE *fp,
  4767. SOCKET sock,
  4768. SSL *ssl,
  4769. const char *buf,
  4770. int64_t len)
  4771. {
  4772. double timeout = -1.0;
  4773. int64_t n, nwritten = 0;
  4774. if (ctx == NULL) {
  4775. return -1;
  4776. }
  4777. if (ctx->config[REQUEST_TIMEOUT]) {
  4778. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4779. }
  4780. while ((len > 0) && (ctx->stop_flag == 0)) {
  4781. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4782. if (n < 0) {
  4783. if (nwritten == 0) {
  4784. nwritten = n; /* Propagate the error */
  4785. }
  4786. break;
  4787. } else if (n == 0) {
  4788. break; /* No more data to write */
  4789. } else {
  4790. nwritten += n;
  4791. len -= n;
  4792. }
  4793. }
  4794. return nwritten;
  4795. }
  4796. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4797. * Return value:
  4798. * >=0 .. number of bytes successfully read
  4799. * -1 .. timeout
  4800. * -2 .. error
  4801. */
  4802. static int
  4803. pull_inner(FILE *fp,
  4804. struct mg_connection *conn,
  4805. char *buf,
  4806. int len,
  4807. double timeout)
  4808. {
  4809. int nread, err = 0;
  4810. #ifdef _WIN32
  4811. typedef int len_t;
  4812. #else
  4813. typedef size_t len_t;
  4814. #endif
  4815. #ifndef NO_SSL
  4816. int ssl_pending;
  4817. #endif
  4818. /* We need an additional wait loop around this, because in some cases
  4819. * with TLSwe may get data from the socket but not from SSL_read.
  4820. * In this case we need to repeat at least once.
  4821. */
  4822. if (fp != NULL) {
  4823. #if !defined(_WIN32_WCE)
  4824. /* Use read() instead of fread(), because if we're reading from the
  4825. * CGI pipe, fread() may block until IO buffer is filled up. We
  4826. * cannot afford to block and must pass all read bytes immediately
  4827. * to the client. */
  4828. nread = (int)read(fileno(fp), buf, (size_t)len);
  4829. #else
  4830. /* WinCE does not support CGI pipes */
  4831. nread = (int)fread(buf, 1, (size_t)len, fp);
  4832. #endif
  4833. err = (nread < 0) ? ERRNO : 0;
  4834. if ((nread == 0) && (len > 0)) {
  4835. /* Should get data, but got EOL */
  4836. return -2;
  4837. }
  4838. #ifndef NO_SSL
  4839. } else if ((conn->ssl != NULL)
  4840. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4841. /* We already know there is no more data buffered in conn->buf
  4842. * but there is more available in the SSL layer. So don't poll
  4843. * conn->client.sock yet. */
  4844. if (ssl_pending > len) {
  4845. ssl_pending = len;
  4846. }
  4847. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4848. if (nread <= 0) {
  4849. err = SSL_get_error(conn->ssl, nread);
  4850. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4851. err = ERRNO;
  4852. } else if ((err == SSL_ERROR_WANT_READ)
  4853. || (err == SSL_ERROR_WANT_WRITE)) {
  4854. nread = 0;
  4855. } else {
  4856. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4857. return -1;
  4858. }
  4859. } else {
  4860. err = 0;
  4861. }
  4862. } else if (conn->ssl != NULL) {
  4863. struct pollfd pfd[1];
  4864. int pollres;
  4865. pfd[0].fd = conn->client.sock;
  4866. pfd[0].events = POLLIN;
  4867. pollres =
  4868. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4869. if (conn->ctx->stop_flag) {
  4870. return -2;
  4871. }
  4872. if (pollres > 0) {
  4873. nread = SSL_read(conn->ssl, buf, len);
  4874. if (nread <= 0) {
  4875. err = SSL_get_error(conn->ssl, nread);
  4876. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4877. err = ERRNO;
  4878. } else if ((err == SSL_ERROR_WANT_READ)
  4879. || (err == SSL_ERROR_WANT_WRITE)) {
  4880. nread = 0;
  4881. } else {
  4882. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4883. return -2;
  4884. }
  4885. } else {
  4886. err = 0;
  4887. }
  4888. } else if (pollres < 0) {
  4889. /* Error */
  4890. return -2;
  4891. } else {
  4892. /* pollres = 0 means timeout */
  4893. nread = 0;
  4894. }
  4895. #endif
  4896. } else {
  4897. struct pollfd pfd[1];
  4898. int pollres;
  4899. pfd[0].fd = conn->client.sock;
  4900. pfd[0].events = POLLIN;
  4901. pollres =
  4902. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4903. if (conn->ctx->stop_flag) {
  4904. return -2;
  4905. }
  4906. if (pollres > 0) {
  4907. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4908. err = (nread < 0) ? ERRNO : 0;
  4909. if (nread <= 0) {
  4910. /* shutdown of the socket at client side */
  4911. return -2;
  4912. }
  4913. } else if (pollres < 0) {
  4914. /* error callint poll */
  4915. return -2;
  4916. } else {
  4917. /* pollres = 0 means timeout */
  4918. nread = 0;
  4919. }
  4920. }
  4921. if (conn->ctx->stop_flag) {
  4922. return -2;
  4923. }
  4924. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  4925. /* some data has been read, or no data was requested */
  4926. return nread;
  4927. }
  4928. if (nread < 0) {
  4929. /* socket error - check errno */
  4930. #ifdef _WIN32
  4931. if (err == WSAEWOULDBLOCK) {
  4932. /* TODO (low): check if this is still required */
  4933. /* standard case if called from close_socket_gracefully */
  4934. return -2;
  4935. } else if (err == WSAETIMEDOUT) {
  4936. /* TODO (low): check if this is still required */
  4937. /* timeout is handled by the while loop */
  4938. return 0;
  4939. } else if (err == WSAECONNABORTED) {
  4940. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4941. return -2;
  4942. } else {
  4943. DEBUG_TRACE("recv() failed, error %d", err);
  4944. return -2;
  4945. }
  4946. #else
  4947. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4948. * if the timeout is reached and if the socket was set to non-
  4949. * blocking in close_socket_gracefully, so we can not distinguish
  4950. * here. We have to wait for the timeout in both cases for now.
  4951. */
  4952. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  4953. /* TODO (low): check if this is still required */
  4954. /* EAGAIN/EWOULDBLOCK:
  4955. * standard case if called from close_socket_gracefully
  4956. * => should return -1 */
  4957. /* or timeout occured
  4958. * => the code must stay in the while loop */
  4959. /* EINTR can be generated on a socket with a timeout set even
  4960. * when SA_RESTART is effective for all relevant signals
  4961. * (see signal(7)).
  4962. * => stay in the while loop */
  4963. } else {
  4964. DEBUG_TRACE("recv() failed, error %d", err);
  4965. return -2;
  4966. }
  4967. #endif
  4968. }
  4969. /* Timeout occured, but no data available. */
  4970. return -1;
  4971. }
  4972. static int
  4973. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4974. {
  4975. int n, nread = 0;
  4976. double timeout = -1.0;
  4977. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4978. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4979. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4980. }
  4981. if (timeout >= 0.0) {
  4982. start_time = mg_get_current_time_ns();
  4983. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4984. }
  4985. while ((len > 0) && (conn->ctx->stop_flag == 0)) {
  4986. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4987. if (n == -2) {
  4988. if (nread == 0) {
  4989. nread = -1; /* Propagate the error */
  4990. }
  4991. break;
  4992. } else if (n == -1) {
  4993. /* timeout */
  4994. if (timeout >= 0.0) {
  4995. now = mg_get_current_time_ns();
  4996. if ((now - start_time) <= timeout_ns) {
  4997. continue;
  4998. }
  4999. }
  5000. break;
  5001. } else if (n == 0) {
  5002. break; /* No more data to read */
  5003. } else {
  5004. conn->consumed_content += n;
  5005. nread += n;
  5006. len -= n;
  5007. }
  5008. }
  5009. return nread;
  5010. }
  5011. static void
  5012. discard_unread_request_data(struct mg_connection *conn)
  5013. {
  5014. char buf[MG_BUF_LEN];
  5015. size_t to_read;
  5016. int nread;
  5017. if (conn == NULL) {
  5018. return;
  5019. }
  5020. to_read = sizeof(buf);
  5021. if (conn->is_chunked) {
  5022. /* Chunked encoding: 3=chunk read completely
  5023. * completely */
  5024. while (conn->is_chunked != 3) {
  5025. nread = mg_read(conn, buf, to_read);
  5026. if (nread <= 0) {
  5027. break;
  5028. }
  5029. }
  5030. } else {
  5031. /* Not chunked: content length is known */
  5032. while (conn->consumed_content < conn->content_len) {
  5033. if (to_read
  5034. > (size_t)(conn->content_len - conn->consumed_content)) {
  5035. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5036. }
  5037. nread = mg_read(conn, buf, to_read);
  5038. if (nread <= 0) {
  5039. break;
  5040. }
  5041. }
  5042. }
  5043. }
  5044. static int
  5045. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5046. {
  5047. int64_t n, buffered_len, nread;
  5048. int64_t len64 =
  5049. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5050. * int, we may not read more
  5051. * bytes */
  5052. const char *body;
  5053. if (conn == NULL) {
  5054. return 0;
  5055. }
  5056. /* If Content-Length is not set for a request with body data
  5057. * (e.g., a PUT or POST request), we do not know in advance
  5058. * how much data should be read. */
  5059. if (conn->consumed_content == 0) {
  5060. if (conn->is_chunked == 1) {
  5061. conn->content_len = len64;
  5062. conn->is_chunked = 2;
  5063. } else if (conn->content_len == -1) {
  5064. /* The body data is completed when the connection
  5065. * is closed. */
  5066. conn->content_len = INT64_MAX;
  5067. conn->must_close = 1;
  5068. }
  5069. }
  5070. nread = 0;
  5071. if (conn->consumed_content < conn->content_len) {
  5072. /* Adjust number of bytes to read. */
  5073. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5074. if (left_to_read < len64) {
  5075. /* Do not read more than the total content length of the
  5076. * request.
  5077. */
  5078. len64 = left_to_read;
  5079. }
  5080. /* Return buffered data */
  5081. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5082. - conn->consumed_content;
  5083. if (buffered_len > 0) {
  5084. if (len64 < buffered_len) {
  5085. buffered_len = len64;
  5086. }
  5087. body = conn->buf + conn->request_len + conn->consumed_content;
  5088. memcpy(buf, body, (size_t)buffered_len);
  5089. len64 -= buffered_len;
  5090. conn->consumed_content += buffered_len;
  5091. nread += buffered_len;
  5092. buf = (char *)buf + buffered_len;
  5093. }
  5094. /* We have returned all buffered data. Read new data from the remote
  5095. * socket.
  5096. */
  5097. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5098. nread += n;
  5099. } else {
  5100. nread = ((nread > 0) ? nread : n);
  5101. }
  5102. }
  5103. return (int)nread;
  5104. }
  5105. static char
  5106. mg_getc(struct mg_connection *conn)
  5107. {
  5108. char c;
  5109. if (conn == NULL) {
  5110. return 0;
  5111. }
  5112. if (mg_read_inner(conn, &c, 1) <= 0) {
  5113. return (char)0;
  5114. }
  5115. return c;
  5116. }
  5117. int
  5118. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5119. {
  5120. if (len > INT_MAX) {
  5121. len = INT_MAX;
  5122. }
  5123. if (conn == NULL) {
  5124. return 0;
  5125. }
  5126. if (conn->is_chunked) {
  5127. size_t all_read = 0;
  5128. while (len > 0) {
  5129. if (conn->is_chunked == 3) {
  5130. /* No more data left to read */
  5131. return 0;
  5132. }
  5133. if (conn->chunk_remainder) {
  5134. /* copy from the remainder of the last received chunk */
  5135. long read_ret;
  5136. size_t read_now =
  5137. ((conn->chunk_remainder > len) ? (len)
  5138. : (conn->chunk_remainder));
  5139. conn->content_len += (int)read_now;
  5140. read_ret =
  5141. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5142. if (read_ret < 1) {
  5143. /* read error */
  5144. return -1;
  5145. }
  5146. all_read += (size_t)read_ret;
  5147. conn->chunk_remainder -= (size_t)read_ret;
  5148. len -= (size_t)read_ret;
  5149. if (conn->chunk_remainder == 0) {
  5150. /* Add data bytes in the current chunk have been read,
  5151. * so we are expecting \r\n now. */
  5152. char x1, x2;
  5153. conn->content_len += 2;
  5154. x1 = mg_getc(conn);
  5155. x2 = mg_getc(conn);
  5156. if ((x1 != '\r') || (x2 != '\n')) {
  5157. /* Protocol violation */
  5158. return -1;
  5159. }
  5160. }
  5161. } else {
  5162. /* fetch a new chunk */
  5163. int i = 0;
  5164. char lenbuf[64];
  5165. char *end = 0;
  5166. unsigned long chunkSize = 0;
  5167. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5168. conn->content_len++;
  5169. lenbuf[i] = mg_getc(conn);
  5170. if ((i > 0) && (lenbuf[i] == '\r')
  5171. && (lenbuf[i - 1] != '\r')) {
  5172. continue;
  5173. }
  5174. if ((i > 1) && (lenbuf[i] == '\n')
  5175. && (lenbuf[i - 1] == '\r')) {
  5176. lenbuf[i + 1] = 0;
  5177. chunkSize = strtoul(lenbuf, &end, 16);
  5178. if (chunkSize == 0) {
  5179. /* regular end of content */
  5180. conn->is_chunked = 3;
  5181. }
  5182. break;
  5183. }
  5184. if (!isxdigit(lenbuf[i])) {
  5185. /* illegal character for chunk length */
  5186. return -1;
  5187. }
  5188. }
  5189. if ((end == NULL) || (*end != '\r')) {
  5190. /* chunksize not set correctly */
  5191. return -1;
  5192. }
  5193. if (chunkSize == 0) {
  5194. break;
  5195. }
  5196. conn->chunk_remainder = chunkSize;
  5197. }
  5198. }
  5199. return (int)all_read;
  5200. }
  5201. return mg_read_inner(conn, buf, len);
  5202. }
  5203. int
  5204. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5205. {
  5206. time_t now;
  5207. int64_t n, total, allowed;
  5208. if (conn == NULL) {
  5209. return 0;
  5210. }
  5211. if (conn->throttle > 0) {
  5212. if ((now = time(NULL)) != conn->last_throttle_time) {
  5213. conn->last_throttle_time = now;
  5214. conn->last_throttle_bytes = 0;
  5215. }
  5216. allowed = conn->throttle - conn->last_throttle_bytes;
  5217. if (allowed > (int64_t)len) {
  5218. allowed = (int64_t)len;
  5219. }
  5220. if ((total = push_all(conn->ctx,
  5221. NULL,
  5222. conn->client.sock,
  5223. conn->ssl,
  5224. (const char *)buf,
  5225. (int64_t)allowed)) == allowed) {
  5226. buf = (const char *)buf + total;
  5227. conn->last_throttle_bytes += total;
  5228. while ((total < (int64_t)len) && (conn->ctx->stop_flag == 0)) {
  5229. allowed = (conn->throttle > ((int64_t)len - total))
  5230. ? (int64_t)len - total
  5231. : conn->throttle;
  5232. if ((n = push_all(conn->ctx,
  5233. NULL,
  5234. conn->client.sock,
  5235. conn->ssl,
  5236. (const char *)buf,
  5237. (int64_t)allowed)) != allowed) {
  5238. break;
  5239. }
  5240. sleep(1);
  5241. conn->last_throttle_bytes = allowed;
  5242. conn->last_throttle_time = time(NULL);
  5243. buf = (const char *)buf + n;
  5244. total += n;
  5245. }
  5246. }
  5247. } else {
  5248. total = push_all(conn->ctx,
  5249. NULL,
  5250. conn->client.sock,
  5251. conn->ssl,
  5252. (const char *)buf,
  5253. (int64_t)len);
  5254. }
  5255. if (total > 0) {
  5256. conn->num_bytes_sent += total;
  5257. }
  5258. return (int)total;
  5259. }
  5260. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5261. int
  5262. mg_send_chunk(struct mg_connection *conn,
  5263. const char *chunk,
  5264. unsigned int chunk_len)
  5265. {
  5266. char lenbuf[16];
  5267. size_t lenbuf_len;
  5268. int ret;
  5269. int t;
  5270. /* First store the length information in a text buffer. */
  5271. sprintf(lenbuf, "%x\r\n", chunk_len);
  5272. lenbuf_len = strlen(lenbuf);
  5273. /* Then send length information, chunk and terminating \r\n. */
  5274. ret = mg_write(conn, lenbuf, lenbuf_len);
  5275. if (ret != (int)lenbuf_len) {
  5276. return -1;
  5277. }
  5278. t = ret;
  5279. ret = mg_write(conn, chunk, chunk_len);
  5280. if (ret != (int)chunk_len) {
  5281. return -1;
  5282. }
  5283. t += ret;
  5284. ret = mg_write(conn, "\r\n", 2);
  5285. if (ret != 2) {
  5286. return -1;
  5287. }
  5288. t += ret;
  5289. return t;
  5290. }
  5291. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5292. static int
  5293. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5294. {
  5295. va_list ap_copy;
  5296. size_t size = MG_BUF_LEN / 4;
  5297. int len = -1;
  5298. *buf = NULL;
  5299. while (len < 0) {
  5300. if (*buf) {
  5301. mg_free(*buf);
  5302. }
  5303. size *= 4;
  5304. *buf = (char *)mg_malloc(size);
  5305. if (!*buf) {
  5306. break;
  5307. }
  5308. va_copy(ap_copy, ap);
  5309. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5310. va_end(ap_copy);
  5311. (*buf)[size - 1] = 0;
  5312. }
  5313. return len;
  5314. }
  5315. /* Print message to buffer. If buffer is large enough to hold the message,
  5316. * return buffer. If buffer is to small, allocate large enough buffer on
  5317. * heap,
  5318. * and return allocated buffer. */
  5319. static int
  5320. alloc_vprintf(char **out_buf,
  5321. char *prealloc_buf,
  5322. size_t prealloc_size,
  5323. const char *fmt,
  5324. va_list ap)
  5325. {
  5326. va_list ap_copy;
  5327. int len;
  5328. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5329. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5330. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5331. * Therefore, we make two passes: on first pass, get required message
  5332. * length.
  5333. * On second pass, actually print the message. */
  5334. va_copy(ap_copy, ap);
  5335. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5336. va_end(ap_copy);
  5337. if (len < 0) {
  5338. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5339. * Switch to alternative code path that uses incremental
  5340. * allocations.
  5341. */
  5342. va_copy(ap_copy, ap);
  5343. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5344. va_end(ap_copy);
  5345. } else if ((size_t)(len) >= prealloc_size) {
  5346. /* The pre-allocated buffer not large enough. */
  5347. /* Allocate a new buffer. */
  5348. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5349. if (!*out_buf) {
  5350. /* Allocation failed. Return -1 as "out of memory" error. */
  5351. return -1;
  5352. }
  5353. /* Buffer allocation successful. Store the string there. */
  5354. va_copy(ap_copy, ap);
  5355. IGNORE_UNUSED_RESULT(
  5356. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5357. va_end(ap_copy);
  5358. } else {
  5359. /* The pre-allocated buffer is large enough.
  5360. * Use it to store the string and return the address. */
  5361. va_copy(ap_copy, ap);
  5362. IGNORE_UNUSED_RESULT(
  5363. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5364. va_end(ap_copy);
  5365. *out_buf = prealloc_buf;
  5366. }
  5367. return len;
  5368. }
  5369. static int
  5370. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5371. {
  5372. char mem[MG_BUF_LEN];
  5373. char *buf = NULL;
  5374. int len;
  5375. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5376. len = mg_write(conn, buf, (size_t)len);
  5377. }
  5378. if ((buf != mem) && (buf != NULL)) {
  5379. mg_free(buf);
  5380. }
  5381. return len;
  5382. }
  5383. int
  5384. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5385. {
  5386. va_list ap;
  5387. int result;
  5388. va_start(ap, fmt);
  5389. result = mg_vprintf(conn, fmt, ap);
  5390. va_end(ap);
  5391. return result;
  5392. }
  5393. int
  5394. mg_url_decode(const char *src,
  5395. int src_len,
  5396. char *dst,
  5397. int dst_len,
  5398. int is_form_url_encoded)
  5399. {
  5400. int i, j, a, b;
  5401. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5402. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5403. if ((i < src_len - 2) && (src[i] == '%')
  5404. && isxdigit(*(const unsigned char *)(src + i + 1))
  5405. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5406. a = tolower(*(const unsigned char *)(src + i + 1));
  5407. b = tolower(*(const unsigned char *)(src + i + 2));
  5408. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5409. i += 2;
  5410. } else if (is_form_url_encoded && (src[i] == '+')) {
  5411. dst[j] = ' ';
  5412. } else {
  5413. dst[j] = src[i];
  5414. }
  5415. }
  5416. dst[j] = '\0'; /* Null-terminate the destination */
  5417. return (i >= src_len) ? j : -1;
  5418. }
  5419. int
  5420. mg_get_var(const char *data,
  5421. size_t data_len,
  5422. const char *name,
  5423. char *dst,
  5424. size_t dst_len)
  5425. {
  5426. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5427. }
  5428. int
  5429. mg_get_var2(const char *data,
  5430. size_t data_len,
  5431. const char *name,
  5432. char *dst,
  5433. size_t dst_len,
  5434. size_t occurrence)
  5435. {
  5436. const char *p, *e, *s;
  5437. size_t name_len;
  5438. int len;
  5439. if ((dst == NULL) || (dst_len == 0)) {
  5440. len = -2;
  5441. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5442. len = -1;
  5443. dst[0] = '\0';
  5444. } else {
  5445. name_len = strlen(name);
  5446. e = data + data_len;
  5447. len = -1;
  5448. dst[0] = '\0';
  5449. /* data is "var1=val1&var2=val2...". Find variable first */
  5450. for (p = data; p + name_len < e; p++) {
  5451. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5452. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5453. /* Point p to variable value */
  5454. p += name_len + 1;
  5455. /* Point s to the end of the value */
  5456. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5457. if (s == NULL) {
  5458. s = e;
  5459. }
  5460. /* assert(s >= p); */
  5461. if (s < p) {
  5462. return -3;
  5463. }
  5464. /* Decode variable into destination buffer */
  5465. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5466. /* Redirect error code from -1 to -2 (destination buffer too
  5467. * small). */
  5468. if (len == -1) {
  5469. len = -2;
  5470. }
  5471. break;
  5472. }
  5473. }
  5474. }
  5475. return len;
  5476. }
  5477. /* HCP24: some changes to compare hole var_name */
  5478. int
  5479. mg_get_cookie(const char *cookie_header,
  5480. const char *var_name,
  5481. char *dst,
  5482. size_t dst_size)
  5483. {
  5484. const char *s, *p, *end;
  5485. int name_len, len = -1;
  5486. if ((dst == NULL) || (dst_size == 0)) {
  5487. return -2;
  5488. }
  5489. dst[0] = '\0';
  5490. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5491. return -1;
  5492. }
  5493. name_len = (int)strlen(var_name);
  5494. end = s + strlen(s);
  5495. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5496. if (s[name_len] == '=') {
  5497. /* HCP24: now check is it a substring or a full cookie name */
  5498. if ((s == cookie_header) || (s[-1] == ' ')) {
  5499. s += name_len + 1;
  5500. if ((p = strchr(s, ' ')) == NULL) {
  5501. p = end;
  5502. }
  5503. if (p[-1] == ';') {
  5504. p--;
  5505. }
  5506. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5507. s++;
  5508. p--;
  5509. }
  5510. if ((size_t)(p - s) < dst_size) {
  5511. len = (int)(p - s);
  5512. mg_strlcpy(dst, s, (size_t)len + 1);
  5513. } else {
  5514. len = -3;
  5515. }
  5516. break;
  5517. }
  5518. }
  5519. }
  5520. return len;
  5521. }
  5522. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5523. static void
  5524. base64_encode(const unsigned char *src, int src_len, char *dst)
  5525. {
  5526. static const char *b64 =
  5527. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5528. int i, j, a, b, c;
  5529. for (i = j = 0; i < src_len; i += 3) {
  5530. a = src[i];
  5531. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5532. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5533. dst[j++] = b64[a >> 2];
  5534. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5535. if (i + 1 < src_len) {
  5536. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5537. }
  5538. if (i + 2 < src_len) {
  5539. dst[j++] = b64[c & 63];
  5540. }
  5541. }
  5542. while (j % 4 != 0) {
  5543. dst[j++] = '=';
  5544. }
  5545. dst[j++] = '\0';
  5546. }
  5547. #endif
  5548. #if defined(USE_LUA)
  5549. static unsigned char
  5550. b64reverse(char letter)
  5551. {
  5552. if ((letter >= 'A') && (letter <= 'Z')) {
  5553. return letter - 'A';
  5554. }
  5555. if ((letter >= 'a') && (letter <= 'z')) {
  5556. return letter - 'a' + 26;
  5557. }
  5558. if ((letter >= '0') && (letter <= '9')) {
  5559. return letter - '0' + 52;
  5560. }
  5561. if (letter == '+') {
  5562. return 62;
  5563. }
  5564. if (letter == '/') {
  5565. return 63;
  5566. }
  5567. if (letter == '=') {
  5568. return 255; /* normal end */
  5569. }
  5570. return 254; /* error */
  5571. }
  5572. static int
  5573. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5574. {
  5575. int i;
  5576. unsigned char a, b, c, d;
  5577. *dst_len = 0;
  5578. for (i = 0; i < src_len; i += 4) {
  5579. a = b64reverse(src[i]);
  5580. if (a >= 254) {
  5581. return i;
  5582. }
  5583. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5584. if (b >= 254) {
  5585. return i + 1;
  5586. }
  5587. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5588. if (c == 254) {
  5589. return i + 2;
  5590. }
  5591. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5592. if (d == 254) {
  5593. return i + 3;
  5594. }
  5595. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5596. if (c != 255) {
  5597. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5598. if (d != 255) {
  5599. dst[(*dst_len)++] = (c << 6) + d;
  5600. }
  5601. }
  5602. }
  5603. return -1;
  5604. }
  5605. #endif
  5606. static int
  5607. is_put_or_delete_method(const struct mg_connection *conn)
  5608. {
  5609. if (conn) {
  5610. const char *s = conn->request_info.request_method;
  5611. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5612. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5613. }
  5614. return 0;
  5615. }
  5616. #if !defined(NO_FILES)
  5617. static int
  5618. extention_matches_script(
  5619. struct mg_connection *conn, /* in: request (must be valid) */
  5620. const char *filename /* in: filename (must be valid) */
  5621. )
  5622. {
  5623. #if !defined(NO_CGI)
  5624. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5625. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5626. filename) > 0) {
  5627. return 1;
  5628. }
  5629. #endif
  5630. #if defined(USE_LUA)
  5631. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5632. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5633. filename) > 0) {
  5634. return 1;
  5635. }
  5636. #endif
  5637. #if defined(USE_DUKTAPE)
  5638. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5639. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5640. filename) > 0) {
  5641. return 1;
  5642. }
  5643. #endif
  5644. /* filename and conn could be unused, if all preocessor conditions
  5645. * are false (no script language supported). */
  5646. (void)filename;
  5647. (void)conn;
  5648. return 0;
  5649. }
  5650. /* For given directory path, substitute it to valid index file.
  5651. * Return 1 if index file has been found, 0 if not found.
  5652. * If the file is found, it's stats is returned in stp. */
  5653. static int
  5654. substitute_index_file(struct mg_connection *conn,
  5655. char *path,
  5656. size_t path_len,
  5657. struct mg_file_stat *filestat)
  5658. {
  5659. const char *list = conn->ctx->config[INDEX_FILES];
  5660. struct vec filename_vec;
  5661. size_t n = strlen(path);
  5662. int found = 0;
  5663. /* The 'path' given to us points to the directory. Remove all trailing
  5664. * directory separator characters from the end of the path, and
  5665. * then append single directory separator character. */
  5666. while ((n > 0) && (path[n - 1] == '/')) {
  5667. n--;
  5668. }
  5669. path[n] = '/';
  5670. /* Traverse index files list. For each entry, append it to the given
  5671. * path and see if the file exists. If it exists, break the loop */
  5672. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5673. /* Ignore too long entries that may overflow path buffer */
  5674. if (filename_vec.len > (path_len - (n + 2))) {
  5675. continue;
  5676. }
  5677. /* Prepare full path to the index file */
  5678. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5679. /* Does it exist? */
  5680. if (mg_stat(conn, path, filestat)) {
  5681. /* Yes it does, break the loop */
  5682. found = 1;
  5683. break;
  5684. }
  5685. }
  5686. /* If no index file exists, restore directory path */
  5687. if (!found) {
  5688. path[n] = '\0';
  5689. }
  5690. return found;
  5691. }
  5692. #endif
  5693. static void
  5694. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  5695. char *filename, /* out: filename */
  5696. size_t filename_buf_len, /* in: size of filename buffer */
  5697. struct mg_file_stat *filestat, /* out: file status structure */
  5698. int *is_found, /* out: file found (directly) */
  5699. int *is_script_resource, /* out: handled by a script? */
  5700. int *is_websocket_request, /* out: websocket connetion? */
  5701. int *is_put_or_delete_request /* out: put/delete a file? */
  5702. )
  5703. {
  5704. char const *accept_encoding;
  5705. #if !defined(NO_FILES)
  5706. const char *uri = conn->request_info.local_uri;
  5707. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5708. const char *rewrite;
  5709. struct vec a, b;
  5710. int match_len;
  5711. char gz_path[PATH_MAX];
  5712. int truncated;
  5713. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5714. char *tmp_str;
  5715. size_t tmp_str_len, sep_pos;
  5716. int allow_substitute_script_subresources;
  5717. #endif
  5718. #else
  5719. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5720. #endif
  5721. /* Step 1: Set all initially unknown outputs to zero */
  5722. memset(filestat, 0, sizeof(*filestat));
  5723. *filename = 0;
  5724. *is_found = 0;
  5725. *is_script_resource = 0;
  5726. /* Step 2: Check if the request attempts to modify the file system */
  5727. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5728. /* Step 3: Check if it is a websocket request, and modify the document
  5729. * root if required */
  5730. #if defined(USE_WEBSOCKET)
  5731. *is_websocket_request = is_websocket_protocol(conn);
  5732. #if !defined(NO_FILES)
  5733. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5734. root = conn->ctx->config[WEBSOCKET_ROOT];
  5735. }
  5736. #endif /* !NO_FILES */
  5737. #else /* USE_WEBSOCKET */
  5738. *is_websocket_request = 0;
  5739. #endif /* USE_WEBSOCKET */
  5740. /* Step 4: Check if gzip encoded response is allowed */
  5741. conn->accept_gzip = 0;
  5742. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5743. if (strstr(accept_encoding, "gzip") != NULL) {
  5744. conn->accept_gzip = 1;
  5745. }
  5746. }
  5747. #if !defined(NO_FILES)
  5748. /* Step 5: If there is no root directory, don't look for files. */
  5749. /* Note that root == NULL is a regular use case here. This occurs,
  5750. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5751. * config is not required. */
  5752. if (root == NULL) {
  5753. /* all file related outputs have already been set to 0, just return
  5754. */
  5755. return;
  5756. }
  5757. /* Step 6: Determine the local file path from the root path and the
  5758. * request uri. */
  5759. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5760. * part of the path one byte on the right. */
  5761. mg_snprintf(
  5762. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5763. if (truncated) {
  5764. goto interpret_cleanup;
  5765. }
  5766. /* Step 7: URI rewriting */
  5767. rewrite = conn->ctx->config[URL_REWRITE_PATTERN];
  5768. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5769. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5770. mg_snprintf(conn,
  5771. &truncated,
  5772. filename,
  5773. filename_buf_len - 1,
  5774. "%.*s%s",
  5775. (int)b.len,
  5776. b.ptr,
  5777. uri + match_len);
  5778. break;
  5779. }
  5780. }
  5781. if (truncated) {
  5782. goto interpret_cleanup;
  5783. }
  5784. /* Step 8: Check if the file exists at the server */
  5785. /* Local file path and name, corresponding to requested URI
  5786. * is now stored in "filename" variable. */
  5787. if (mg_stat(conn, filename, filestat)) {
  5788. /* 8.1: File exists. */
  5789. *is_found = 1;
  5790. /* 8.2: Check if it is a script type. */
  5791. if (extention_matches_script(conn, filename)) {
  5792. /* The request addresses a CGI resource, Lua script or
  5793. * server-side javascript.
  5794. * The URI corresponds to the script itself (like
  5795. * /path/script.cgi), and there is no additional resource
  5796. * path (like /path/script.cgi/something).
  5797. * Requests that modify (replace or delete) a resource, like
  5798. * PUT and DELETE requests, should replace/delete the script
  5799. * file.
  5800. * Requests that read or write from/to a resource, like GET and
  5801. * POST requests, should call the script and return the
  5802. * generated response. */
  5803. *is_script_resource = (!*is_put_or_delete_request);
  5804. }
  5805. /* 8.3: If the request target is a directory, there could be
  5806. * a substitute file (index.html, index.cgi, ...). */
  5807. if (filestat->is_directory) {
  5808. /* Use a local copy here, since substitute_index_file will
  5809. * change the content of the file status */
  5810. struct mg_file_stat tmp_filestat;
  5811. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5812. if (substitute_index_file(
  5813. conn, filename, filename_buf_len, &tmp_filestat)) {
  5814. /* Substitute file found. Copy stat to the output, then
  5815. * check if the file is a script file */
  5816. *filestat = tmp_filestat;
  5817. if (extention_matches_script(conn, filename)) {
  5818. /* Substitute file is a script file */
  5819. *is_script_resource = 1;
  5820. } else {
  5821. /* Substitute file is a regular file */
  5822. *is_script_resource = 0;
  5823. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5824. }
  5825. }
  5826. /* If there is no substitute file, the server could return
  5827. * a directory listing in a later step */
  5828. }
  5829. return;
  5830. }
  5831. /* Step 9: Check for zipped files: */
  5832. /* If we can't find the actual file, look for the file
  5833. * with the same name but a .gz extension. If we find it,
  5834. * use that and set the gzipped flag in the file struct
  5835. * to indicate that the response need to have the content-
  5836. * encoding: gzip header.
  5837. * We can only do this if the browser declares support. */
  5838. if (conn->accept_gzip) {
  5839. mg_snprintf(
  5840. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5841. if (truncated) {
  5842. goto interpret_cleanup;
  5843. }
  5844. if (mg_stat(conn, gz_path, filestat)) {
  5845. if (filestat) {
  5846. filestat->is_gzipped = 1;
  5847. *is_found = 1;
  5848. }
  5849. /* Currently gz files can not be scripts. */
  5850. return;
  5851. }
  5852. }
  5853. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5854. /* Step 10: Script resources may handle sub-resources */
  5855. /* Support PATH_INFO for CGI scripts. */
  5856. tmp_str_len = strlen(filename);
  5857. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->ctx);
  5858. if (!tmp_str) {
  5859. /* Out of memory */
  5860. goto interpret_cleanup;
  5861. }
  5862. memcpy(tmp_str, filename, tmp_str_len + 1);
  5863. /* Check config, if index scripts may have sub-resources */
  5864. allow_substitute_script_subresources =
  5865. !mg_strcasecmp(conn->ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES], "yes");
  5866. sep_pos = tmp_str_len;
  5867. while (sep_pos > 0) {
  5868. sep_pos--;
  5869. if (tmp_str[sep_pos] == '/') {
  5870. int is_script = 0, does_exist = 0;
  5871. tmp_str[sep_pos] = 0;
  5872. if (tmp_str[0]) {
  5873. is_script = extention_matches_script(conn, tmp_str);
  5874. does_exist = mg_stat(conn, tmp_str, filestat);
  5875. }
  5876. if (does_exist && is_script) {
  5877. filename[sep_pos] = 0;
  5878. memmove(filename + sep_pos + 2,
  5879. filename + sep_pos + 1,
  5880. strlen(filename + sep_pos + 1) + 1);
  5881. conn->path_info = filename + sep_pos + 1;
  5882. filename[sep_pos + 1] = '/';
  5883. *is_script_resource = 1;
  5884. *is_found = 1;
  5885. break;
  5886. }
  5887. if (allow_substitute_script_subresources) {
  5888. if (substitute_index_file(
  5889. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5890. /* some intermediate directory has an index file */
  5891. if (extention_matches_script(conn, tmp_str)) {
  5892. char *tmp_str2;
  5893. DEBUG_TRACE("Substitute script %s serving path %s",
  5894. tmp_str,
  5895. filename);
  5896. /* this index file is a script */
  5897. tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5898. mg_snprintf(conn,
  5899. &truncated,
  5900. filename,
  5901. filename_buf_len,
  5902. "%s//%s",
  5903. tmp_str,
  5904. tmp_str2);
  5905. mg_free(tmp_str2);
  5906. if (truncated) {
  5907. mg_free(tmp_str);
  5908. goto interpret_cleanup;
  5909. }
  5910. sep_pos = strlen(tmp_str);
  5911. filename[sep_pos] = 0;
  5912. conn->path_info = filename + sep_pos + 1;
  5913. *is_script_resource = 1;
  5914. *is_found = 1;
  5915. break;
  5916. } else {
  5917. DEBUG_TRACE("Substitute file %s serving path %s",
  5918. tmp_str,
  5919. filename);
  5920. /* non-script files will not have sub-resources */
  5921. filename[sep_pos] = 0;
  5922. conn->path_info = 0;
  5923. *is_script_resource = 0;
  5924. *is_found = 0;
  5925. break;
  5926. }
  5927. }
  5928. }
  5929. tmp_str[sep_pos] = '/';
  5930. }
  5931. }
  5932. mg_free(tmp_str);
  5933. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5934. #endif /* !defined(NO_FILES) */
  5935. return;
  5936. #if !defined(NO_FILES)
  5937. /* Reset all outputs */
  5938. interpret_cleanup:
  5939. memset(filestat, 0, sizeof(*filestat));
  5940. *filename = 0;
  5941. *is_found = 0;
  5942. *is_script_resource = 0;
  5943. *is_websocket_request = 0;
  5944. *is_put_or_delete_request = 0;
  5945. #endif /* !defined(NO_FILES) */
  5946. }
  5947. /* Check whether full request is buffered. Return:
  5948. * -1 if request or response is malformed
  5949. * 0 if request or response is not yet fully buffered
  5950. * >0 actual request length, including last \r\n\r\n */
  5951. static int
  5952. get_http_header_len(const char *buf, int buflen)
  5953. {
  5954. int i;
  5955. for (i = 0; i < buflen; i++) {
  5956. /* Do an unsigned comparison in some conditions below */
  5957. const unsigned char c = ((const unsigned char *)buf)[i];
  5958. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  5959. && !isprint(c)) {
  5960. /* abort scan as soon as one malformed character is found */
  5961. return -1;
  5962. }
  5963. if (i < buflen - 1) {
  5964. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  5965. /* Two newline, no carriage return - not standard compliant,
  5966. * but
  5967. * it
  5968. * should be accepted */
  5969. return i + 2;
  5970. }
  5971. }
  5972. if (i < buflen - 3) {
  5973. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  5974. && (buf[i + 3] == '\n')) {
  5975. /* Two \r\n - standard compliant */
  5976. return i + 4;
  5977. }
  5978. }
  5979. }
  5980. return 0;
  5981. }
  5982. #if !defined(NO_CACHING)
  5983. /* Convert month to the month number. Return -1 on error, or month number */
  5984. static int
  5985. get_month_index(const char *s)
  5986. {
  5987. size_t i;
  5988. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5989. if (!strcmp(s, month_names[i])) {
  5990. return (int)i;
  5991. }
  5992. }
  5993. return -1;
  5994. }
  5995. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5996. static time_t
  5997. parse_date_string(const char *datetime)
  5998. {
  5999. char month_str[32] = {0};
  6000. int second, minute, hour, day, month, year;
  6001. time_t result = (time_t)0;
  6002. struct tm tm;
  6003. if ((sscanf(datetime,
  6004. "%d/%3s/%d %d:%d:%d",
  6005. &day,
  6006. month_str,
  6007. &year,
  6008. &hour,
  6009. &minute,
  6010. &second) == 6) || (sscanf(datetime,
  6011. "%d %3s %d %d:%d:%d",
  6012. &day,
  6013. month_str,
  6014. &year,
  6015. &hour,
  6016. &minute,
  6017. &second) == 6)
  6018. || (sscanf(datetime,
  6019. "%*3s, %d %3s %d %d:%d:%d",
  6020. &day,
  6021. month_str,
  6022. &year,
  6023. &hour,
  6024. &minute,
  6025. &second) == 6) || (sscanf(datetime,
  6026. "%d-%3s-%d %d:%d:%d",
  6027. &day,
  6028. month_str,
  6029. &year,
  6030. &hour,
  6031. &minute,
  6032. &second) == 6)) {
  6033. month = get_month_index(month_str);
  6034. if ((month >= 0) && (year >= 1970)) {
  6035. memset(&tm, 0, sizeof(tm));
  6036. tm.tm_year = year - 1900;
  6037. tm.tm_mon = month;
  6038. tm.tm_mday = day;
  6039. tm.tm_hour = hour;
  6040. tm.tm_min = minute;
  6041. tm.tm_sec = second;
  6042. result = timegm(&tm);
  6043. }
  6044. }
  6045. return result;
  6046. }
  6047. #endif /* !NO_CACHING */
  6048. /* Protect against directory disclosure attack by removing '..',
  6049. * excessive '/' and '\' characters */
  6050. static void
  6051. remove_double_dots_and_double_slashes(char *s)
  6052. {
  6053. char *p = s;
  6054. while ((s[0] == '.') && (s[1] == '.')) {
  6055. s++;
  6056. }
  6057. while (*s != '\0') {
  6058. *p++ = *s++;
  6059. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6060. /* Skip all following slashes, backslashes and double-dots */
  6061. while (s[0] != '\0') {
  6062. if ((s[0] == '/') || (s[0] == '\\')) {
  6063. s++;
  6064. } else if ((s[0] == '.') && (s[1] == '.')) {
  6065. s += 2;
  6066. } else {
  6067. break;
  6068. }
  6069. }
  6070. }
  6071. }
  6072. *p = '\0';
  6073. }
  6074. static const struct {
  6075. const char *extension;
  6076. size_t ext_len;
  6077. const char *mime_type;
  6078. } builtin_mime_types[] = {
  6079. /* IANA registered MIME types
  6080. * (http://www.iana.org/assignments/media-types)
  6081. * application types */
  6082. {".doc", 4, "application/msword"},
  6083. {".eps", 4, "application/postscript"},
  6084. {".exe", 4, "application/octet-stream"},
  6085. {".js", 3, "application/javascript"},
  6086. {".json", 5, "application/json"},
  6087. {".pdf", 4, "application/pdf"},
  6088. {".ps", 3, "application/postscript"},
  6089. {".rtf", 4, "application/rtf"},
  6090. {".xhtml", 6, "application/xhtml+xml"},
  6091. {".xsl", 4, "application/xml"},
  6092. {".xslt", 5, "application/xml"},
  6093. /* fonts */
  6094. {".ttf", 4, "application/font-sfnt"},
  6095. {".cff", 4, "application/font-sfnt"},
  6096. {".otf", 4, "application/font-sfnt"},
  6097. {".aat", 4, "application/font-sfnt"},
  6098. {".sil", 4, "application/font-sfnt"},
  6099. {".pfr", 4, "application/font-tdpfr"},
  6100. {".woff", 5, "application/font-woff"},
  6101. /* audio */
  6102. {".mp3", 4, "audio/mpeg"},
  6103. {".oga", 4, "audio/ogg"},
  6104. {".ogg", 4, "audio/ogg"},
  6105. /* image */
  6106. {".gif", 4, "image/gif"},
  6107. {".ief", 4, "image/ief"},
  6108. {".jpeg", 5, "image/jpeg"},
  6109. {".jpg", 4, "image/jpeg"},
  6110. {".jpm", 4, "image/jpm"},
  6111. {".jpx", 4, "image/jpx"},
  6112. {".png", 4, "image/png"},
  6113. {".svg", 4, "image/svg+xml"},
  6114. {".tif", 4, "image/tiff"},
  6115. {".tiff", 5, "image/tiff"},
  6116. /* model */
  6117. {".wrl", 4, "model/vrml"},
  6118. /* text */
  6119. {".css", 4, "text/css"},
  6120. {".csv", 4, "text/csv"},
  6121. {".htm", 4, "text/html"},
  6122. {".html", 5, "text/html"},
  6123. {".sgm", 4, "text/sgml"},
  6124. {".shtm", 5, "text/html"},
  6125. {".shtml", 6, "text/html"},
  6126. {".txt", 4, "text/plain"},
  6127. {".xml", 4, "text/xml"},
  6128. /* video */
  6129. {".mov", 4, "video/quicktime"},
  6130. {".mp4", 4, "video/mp4"},
  6131. {".mpeg", 5, "video/mpeg"},
  6132. {".mpg", 4, "video/mpeg"},
  6133. {".ogv", 4, "video/ogg"},
  6134. {".qt", 3, "video/quicktime"},
  6135. /* not registered types
  6136. * (http://reference.sitepoint.com/html/mime-types-full,
  6137. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6138. {".arj", 4, "application/x-arj-compressed"},
  6139. {".gz", 3, "application/x-gunzip"},
  6140. {".rar", 4, "application/x-arj-compressed"},
  6141. {".swf", 4, "application/x-shockwave-flash"},
  6142. {".tar", 4, "application/x-tar"},
  6143. {".tgz", 4, "application/x-tar-gz"},
  6144. {".torrent", 8, "application/x-bittorrent"},
  6145. {".ppt", 4, "application/x-mspowerpoint"},
  6146. {".xls", 4, "application/x-msexcel"},
  6147. {".zip", 4, "application/x-zip-compressed"},
  6148. {".aac",
  6149. 4,
  6150. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6151. {".aif", 4, "audio/x-aif"},
  6152. {".m3u", 4, "audio/x-mpegurl"},
  6153. {".mid", 4, "audio/x-midi"},
  6154. {".ra", 3, "audio/x-pn-realaudio"},
  6155. {".ram", 4, "audio/x-pn-realaudio"},
  6156. {".wav", 4, "audio/x-wav"},
  6157. {".bmp", 4, "image/bmp"},
  6158. {".ico", 4, "image/x-icon"},
  6159. {".pct", 4, "image/x-pct"},
  6160. {".pict", 5, "image/pict"},
  6161. {".rgb", 4, "image/x-rgb"},
  6162. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6163. {".asf", 4, "video/x-ms-asf"},
  6164. {".avi", 4, "video/x-msvideo"},
  6165. {".m4v", 4, "video/x-m4v"},
  6166. {NULL, 0, NULL}};
  6167. const char *
  6168. mg_get_builtin_mime_type(const char *path)
  6169. {
  6170. const char *ext;
  6171. size_t i, path_len;
  6172. path_len = strlen(path);
  6173. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6174. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6175. if ((path_len > builtin_mime_types[i].ext_len)
  6176. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6177. return builtin_mime_types[i].mime_type;
  6178. }
  6179. }
  6180. return "text/plain";
  6181. }
  6182. /* Look at the "path" extension and figure what mime type it has.
  6183. * Store mime type in the vector. */
  6184. static void
  6185. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  6186. {
  6187. struct vec ext_vec, mime_vec;
  6188. const char *list, *ext;
  6189. size_t path_len;
  6190. path_len = strlen(path);
  6191. if ((ctx == NULL) || (vec == NULL)) {
  6192. if (vec != NULL) {
  6193. memset(vec, '\0', sizeof(struct vec));
  6194. }
  6195. return;
  6196. }
  6197. /* Scan user-defined mime types first, in case user wants to
  6198. * override default mime types. */
  6199. list = ctx->config[EXTRA_MIME_TYPES];
  6200. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6201. /* ext now points to the path suffix */
  6202. ext = path + path_len - ext_vec.len;
  6203. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6204. *vec = mime_vec;
  6205. return;
  6206. }
  6207. }
  6208. vec->ptr = mg_get_builtin_mime_type(path);
  6209. vec->len = strlen(vec->ptr);
  6210. }
  6211. /* Stringify binary data. Output buffer must be twice as big as input,
  6212. * because each byte takes 2 bytes in string representation */
  6213. static void
  6214. bin2str(char *to, const unsigned char *p, size_t len)
  6215. {
  6216. static const char *hex = "0123456789abcdef";
  6217. for (; len--; p++) {
  6218. *to++ = hex[p[0] >> 4];
  6219. *to++ = hex[p[0] & 0x0f];
  6220. }
  6221. *to = '\0';
  6222. }
  6223. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6224. */
  6225. char *
  6226. mg_md5(char buf[33], ...)
  6227. {
  6228. md5_byte_t hash[16];
  6229. const char *p;
  6230. va_list ap;
  6231. md5_state_t ctx;
  6232. md5_init(&ctx);
  6233. va_start(ap, buf);
  6234. while ((p = va_arg(ap, const char *)) != NULL) {
  6235. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6236. }
  6237. va_end(ap);
  6238. md5_finish(&ctx, hash);
  6239. bin2str(buf, hash, sizeof(hash));
  6240. return buf;
  6241. }
  6242. /* Check the user's password, return 1 if OK */
  6243. static int
  6244. check_password(const char *method,
  6245. const char *ha1,
  6246. const char *uri,
  6247. const char *nonce,
  6248. const char *nc,
  6249. const char *cnonce,
  6250. const char *qop,
  6251. const char *response)
  6252. {
  6253. char ha2[32 + 1], expected_response[32 + 1];
  6254. /* Some of the parameters may be NULL */
  6255. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6256. || (qop == NULL) || (response == NULL)) {
  6257. return 0;
  6258. }
  6259. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6260. if (strlen(response) != 32) {
  6261. return 0;
  6262. }
  6263. mg_md5(ha2, method, ":", uri, NULL);
  6264. mg_md5(expected_response,
  6265. ha1,
  6266. ":",
  6267. nonce,
  6268. ":",
  6269. nc,
  6270. ":",
  6271. cnonce,
  6272. ":",
  6273. qop,
  6274. ":",
  6275. ha2,
  6276. NULL);
  6277. return mg_strcasecmp(response, expected_response) == 0;
  6278. }
  6279. /* Use the global passwords file, if specified by auth_gpass option,
  6280. * or search for .htpasswd in the requested directory. */
  6281. static void
  6282. open_auth_file(struct mg_connection *conn,
  6283. const char *path,
  6284. struct mg_file *filep)
  6285. {
  6286. if ((conn != NULL) && (conn->ctx != NULL)) {
  6287. char name[PATH_MAX];
  6288. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  6289. int truncated;
  6290. if (gpass != NULL) {
  6291. /* Use global passwords file */
  6292. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6293. #ifdef DEBUG
  6294. /* Use mg_cry here, since gpass has been configured. */
  6295. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6296. #endif
  6297. }
  6298. /* Important: using local struct mg_file to test path for
  6299. * is_directory flag. If filep is used, mg_stat() makes it
  6300. * appear as if auth file was opened.
  6301. * TODO(mid): Check if this is still required after rewriting
  6302. * mg_stat */
  6303. } else if (mg_stat(conn, path, &filep->stat)
  6304. && filep->stat.is_directory) {
  6305. mg_snprintf(conn,
  6306. &truncated,
  6307. name,
  6308. sizeof(name),
  6309. "%s/%s",
  6310. path,
  6311. PASSWORDS_FILE_NAME);
  6312. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6313. #ifdef DEBUG
  6314. /* Don't use mg_cry here, but only a trace, since this is
  6315. * a typical case. It will occur for every directory
  6316. * without a password file. */
  6317. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6318. #endif
  6319. }
  6320. } else {
  6321. /* Try to find .htpasswd in requested directory. */
  6322. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6323. if (e[0] == '/') {
  6324. break;
  6325. }
  6326. }
  6327. mg_snprintf(conn,
  6328. &truncated,
  6329. name,
  6330. sizeof(name),
  6331. "%.*s/%s",
  6332. (int)(e - p),
  6333. p,
  6334. PASSWORDS_FILE_NAME);
  6335. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6336. #ifdef DEBUG
  6337. /* Don't use mg_cry here, but only a trace, since this is
  6338. * a typical case. It will occur for every directory
  6339. * without a password file. */
  6340. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6341. #endif
  6342. }
  6343. }
  6344. }
  6345. }
  6346. /* Parsed Authorization header */
  6347. struct ah {
  6348. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6349. };
  6350. /* Return 1 on success. Always initializes the ah structure. */
  6351. static int
  6352. parse_auth_header(struct mg_connection *conn,
  6353. char *buf,
  6354. size_t buf_size,
  6355. struct ah *ah)
  6356. {
  6357. char *name, *value, *s;
  6358. const char *auth_header;
  6359. uint64_t nonce;
  6360. if (!ah || !conn) {
  6361. return 0;
  6362. }
  6363. (void)memset(ah, 0, sizeof(*ah));
  6364. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6365. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6366. return 0;
  6367. }
  6368. /* Make modifiable copy of the auth header */
  6369. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6370. s = buf;
  6371. /* Parse authorization header */
  6372. for (;;) {
  6373. /* Gobble initial spaces */
  6374. while (isspace(*(unsigned char *)s)) {
  6375. s++;
  6376. }
  6377. name = skip_quoted(&s, "=", " ", 0);
  6378. /* Value is either quote-delimited, or ends at first comma or space.
  6379. */
  6380. if (s[0] == '\"') {
  6381. s++;
  6382. value = skip_quoted(&s, "\"", " ", '\\');
  6383. if (s[0] == ',') {
  6384. s++;
  6385. }
  6386. } else {
  6387. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6388. * spaces */
  6389. }
  6390. if (*name == '\0') {
  6391. break;
  6392. }
  6393. if (!strcmp(name, "username")) {
  6394. ah->user = value;
  6395. } else if (!strcmp(name, "cnonce")) {
  6396. ah->cnonce = value;
  6397. } else if (!strcmp(name, "response")) {
  6398. ah->response = value;
  6399. } else if (!strcmp(name, "uri")) {
  6400. ah->uri = value;
  6401. } else if (!strcmp(name, "qop")) {
  6402. ah->qop = value;
  6403. } else if (!strcmp(name, "nc")) {
  6404. ah->nc = value;
  6405. } else if (!strcmp(name, "nonce")) {
  6406. ah->nonce = value;
  6407. }
  6408. }
  6409. #ifndef NO_NONCE_CHECK
  6410. /* Read the nonce from the response. */
  6411. if (ah->nonce == NULL) {
  6412. return 0;
  6413. }
  6414. s = NULL;
  6415. nonce = strtoull(ah->nonce, &s, 10);
  6416. if ((s == NULL) || (*s != 0)) {
  6417. return 0;
  6418. }
  6419. /* Convert the nonce from the client to a number. */
  6420. nonce ^= conn->ctx->auth_nonce_mask;
  6421. /* The converted number corresponds to the time the nounce has been
  6422. * created. This should not be earlier than the server start. */
  6423. /* Server side nonce check is valuable in all situations but one:
  6424. * if the server restarts frequently, but the client should not see
  6425. * that, so the server should accept nonces from previous starts. */
  6426. /* However, the reasonable default is to not accept a nonce from a
  6427. * previous start, so if anyone changed the access rights between
  6428. * two restarts, a new login is required. */
  6429. if (nonce < (uint64_t)conn->ctx->start_time) {
  6430. /* nonce is from a previous start of the server and no longer valid
  6431. * (replay attack?) */
  6432. return 0;
  6433. }
  6434. /* Check if the nonce is too high, so it has not (yet) been used by the
  6435. * server. */
  6436. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  6437. return 0;
  6438. }
  6439. #else
  6440. (void)nonce;
  6441. #endif
  6442. /* CGI needs it as REMOTE_USER */
  6443. if (ah->user != NULL) {
  6444. conn->request_info.remote_user = mg_strdup(ah->user);
  6445. } else {
  6446. return 0;
  6447. }
  6448. return 1;
  6449. }
  6450. static const char *
  6451. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6452. {
  6453. const char *eof;
  6454. size_t len;
  6455. const char *memend;
  6456. if (!filep) {
  6457. return NULL;
  6458. }
  6459. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6460. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6461. /* Search for \n from p till the end of stream */
  6462. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6463. if (eof != NULL) {
  6464. eof += 1; /* Include \n */
  6465. } else {
  6466. eof = memend; /* Copy remaining data */
  6467. }
  6468. len =
  6469. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6470. memcpy(buf, *p, len);
  6471. buf[len] = '\0';
  6472. *p += len;
  6473. return len ? eof : NULL;
  6474. } else if (filep->access.fp != NULL) {
  6475. return fgets(buf, (int)size, filep->access.fp);
  6476. } else {
  6477. return NULL;
  6478. }
  6479. }
  6480. /* Define the initial recursion depth for procesesing htpasswd files that
  6481. * include other htpasswd
  6482. * (or even the same) files. It is not difficult to provide a file or files
  6483. * s.t. they force civetweb
  6484. * to infinitely recurse and then crash.
  6485. */
  6486. #define INITIAL_DEPTH 9
  6487. #if INITIAL_DEPTH <= 0
  6488. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6489. #endif
  6490. struct read_auth_file_struct {
  6491. struct mg_connection *conn;
  6492. struct ah ah;
  6493. const char *domain;
  6494. char buf[256 + 256 + 40];
  6495. const char *f_user;
  6496. const char *f_domain;
  6497. const char *f_ha1;
  6498. };
  6499. static int
  6500. read_auth_file(struct mg_file *filep,
  6501. struct read_auth_file_struct *workdata,
  6502. int depth)
  6503. {
  6504. char *p;
  6505. int is_authorized = 0;
  6506. struct mg_file fp;
  6507. size_t l;
  6508. if (!filep || !workdata || (0 == depth)) {
  6509. return 0;
  6510. }
  6511. /* Loop over passwords file */
  6512. p = (char *)filep->access.membuf;
  6513. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6514. l = strlen(workdata->buf);
  6515. while (l > 0) {
  6516. if (isspace(workdata->buf[l - 1])
  6517. || iscntrl(workdata->buf[l - 1])) {
  6518. l--;
  6519. workdata->buf[l] = 0;
  6520. } else
  6521. break;
  6522. }
  6523. if (l < 1) {
  6524. continue;
  6525. }
  6526. workdata->f_user = workdata->buf;
  6527. if (workdata->f_user[0] == ':') {
  6528. /* user names may not contain a ':' and may not be empty,
  6529. * so lines starting with ':' may be used for a special purpose
  6530. */
  6531. if (workdata->f_user[1] == '#') {
  6532. /* :# is a comment */
  6533. continue;
  6534. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6535. if (mg_fopen(workdata->conn,
  6536. workdata->f_user + 9,
  6537. MG_FOPEN_MODE_READ,
  6538. &fp)) {
  6539. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6540. (void)mg_fclose(
  6541. &fp.access); /* ignore error on read only file */
  6542. /* No need to continue processing files once we have a
  6543. * match, since nothing will reset it back
  6544. * to 0.
  6545. */
  6546. if (is_authorized) {
  6547. return is_authorized;
  6548. }
  6549. } else {
  6550. mg_cry(workdata->conn,
  6551. "%s: cannot open authorization file: %s",
  6552. __func__,
  6553. workdata->buf);
  6554. }
  6555. continue;
  6556. }
  6557. /* everything is invalid for the moment (might change in the
  6558. * future) */
  6559. mg_cry(workdata->conn,
  6560. "%s: syntax error in authorization file: %s",
  6561. __func__,
  6562. workdata->buf);
  6563. continue;
  6564. }
  6565. workdata->f_domain = strchr(workdata->f_user, ':');
  6566. if (workdata->f_domain == NULL) {
  6567. mg_cry(workdata->conn,
  6568. "%s: syntax error in authorization file: %s",
  6569. __func__,
  6570. workdata->buf);
  6571. continue;
  6572. }
  6573. *(char *)(workdata->f_domain) = 0;
  6574. (workdata->f_domain)++;
  6575. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6576. if (workdata->f_ha1 == NULL) {
  6577. mg_cry(workdata->conn,
  6578. "%s: syntax error in authorization file: %s",
  6579. __func__,
  6580. workdata->buf);
  6581. continue;
  6582. }
  6583. *(char *)(workdata->f_ha1) = 0;
  6584. (workdata->f_ha1)++;
  6585. if (!strcmp(workdata->ah.user, workdata->f_user)
  6586. && !strcmp(workdata->domain, workdata->f_domain)) {
  6587. return check_password(workdata->conn->request_info.request_method,
  6588. workdata->f_ha1,
  6589. workdata->ah.uri,
  6590. workdata->ah.nonce,
  6591. workdata->ah.nc,
  6592. workdata->ah.cnonce,
  6593. workdata->ah.qop,
  6594. workdata->ah.response);
  6595. }
  6596. }
  6597. return is_authorized;
  6598. }
  6599. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6600. static int
  6601. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  6602. {
  6603. struct read_auth_file_struct workdata;
  6604. char buf[MG_BUF_LEN];
  6605. if (!conn || !conn->ctx) {
  6606. return 0;
  6607. }
  6608. memset(&workdata, 0, sizeof(workdata));
  6609. workdata.conn = conn;
  6610. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6611. return 0;
  6612. }
  6613. if (realm) {
  6614. workdata.domain = realm;
  6615. } else {
  6616. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6617. }
  6618. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6619. }
  6620. /* Public function to check http digest authentication header */
  6621. int
  6622. mg_check_digest_access_authentication(struct mg_connection *conn,
  6623. const char *realm,
  6624. const char *filename)
  6625. {
  6626. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6627. int auth;
  6628. if (!conn || !filename) {
  6629. return -1;
  6630. }
  6631. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  6632. return -2;
  6633. }
  6634. auth = authorize(conn, &file, realm);
  6635. mg_fclose(&file.access);
  6636. return auth;
  6637. }
  6638. /* Return 1 if request is authorised, 0 otherwise. */
  6639. static int
  6640. check_authorization(struct mg_connection *conn, const char *path)
  6641. {
  6642. char fname[PATH_MAX];
  6643. struct vec uri_vec, filename_vec;
  6644. const char *list;
  6645. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6646. int authorized = 1, truncated;
  6647. if (!conn || !conn->ctx) {
  6648. return 0;
  6649. }
  6650. list = conn->ctx->config[PROTECT_URI];
  6651. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6652. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6653. mg_snprintf(conn,
  6654. &truncated,
  6655. fname,
  6656. sizeof(fname),
  6657. "%.*s",
  6658. (int)filename_vec.len,
  6659. filename_vec.ptr);
  6660. if (truncated
  6661. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6662. mg_cry(conn,
  6663. "%s: cannot open %s: %s",
  6664. __func__,
  6665. fname,
  6666. strerror(errno));
  6667. }
  6668. break;
  6669. }
  6670. }
  6671. if (!is_file_opened(&file.access)) {
  6672. open_auth_file(conn, path, &file);
  6673. }
  6674. if (is_file_opened(&file.access)) {
  6675. authorized = authorize(conn, &file, NULL);
  6676. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6677. }
  6678. return authorized;
  6679. }
  6680. /* Internal function. Assumes conn is valid */
  6681. static void
  6682. send_authorization_request(struct mg_connection *conn, const char *realm)
  6683. {
  6684. char date[64];
  6685. time_t curtime = time(NULL);
  6686. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6687. if (!realm) {
  6688. realm = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6689. }
  6690. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6691. nonce += conn->ctx->nonce_count;
  6692. ++conn->ctx->nonce_count;
  6693. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6694. nonce ^= conn->ctx->auth_nonce_mask;
  6695. conn->status_code = 401;
  6696. conn->must_close = 1;
  6697. gmt_time_string(date, sizeof(date), &curtime);
  6698. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6699. send_no_cache_header(conn);
  6700. send_additional_header(conn);
  6701. mg_printf(conn,
  6702. "Date: %s\r\n"
  6703. "Connection: %s\r\n"
  6704. "Content-Length: 0\r\n"
  6705. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6706. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6707. date,
  6708. suggest_connection_header(conn),
  6709. realm,
  6710. nonce);
  6711. }
  6712. /* Interface function. Parameters are provided by the user, so do
  6713. * at least some basic checks.
  6714. */
  6715. int
  6716. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  6717. const char *realm)
  6718. {
  6719. if (conn && conn->ctx) {
  6720. send_authorization_request(conn, realm);
  6721. return 0;
  6722. }
  6723. return -1;
  6724. }
  6725. #if !defined(NO_FILES)
  6726. static int
  6727. is_authorized_for_put(struct mg_connection *conn)
  6728. {
  6729. if (conn) {
  6730. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6731. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6732. int ret = 0;
  6733. if (passfile != NULL
  6734. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6735. ret = authorize(conn, &file, NULL);
  6736. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6737. }
  6738. return ret;
  6739. }
  6740. return 0;
  6741. }
  6742. #endif
  6743. int
  6744. mg_modify_passwords_file(const char *fname,
  6745. const char *domain,
  6746. const char *user,
  6747. const char *pass)
  6748. {
  6749. int found, i;
  6750. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6751. FILE *fp, *fp2;
  6752. found = 0;
  6753. fp = fp2 = NULL;
  6754. /* Regard empty password as no password - remove user record. */
  6755. if ((pass != NULL) && (pass[0] == '\0')) {
  6756. pass = NULL;
  6757. }
  6758. /* Other arguments must not be empty */
  6759. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6760. return 0;
  6761. }
  6762. /* Using the given file format, user name and domain must not contain
  6763. * ':'
  6764. */
  6765. if (strchr(user, ':') != NULL) {
  6766. return 0;
  6767. }
  6768. if (strchr(domain, ':') != NULL) {
  6769. return 0;
  6770. }
  6771. /* Do not allow control characters like newline in user name and domain.
  6772. * Do not allow excessively long names either. */
  6773. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6774. if (iscntrl(user[i])) {
  6775. return 0;
  6776. }
  6777. }
  6778. if (user[i]) {
  6779. return 0;
  6780. }
  6781. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6782. if (iscntrl(domain[i])) {
  6783. return 0;
  6784. }
  6785. }
  6786. if (domain[i]) {
  6787. return 0;
  6788. }
  6789. /* The maximum length of the path to the password file is limited */
  6790. if ((strlen(fname) + 4) >= PATH_MAX) {
  6791. return 0;
  6792. }
  6793. /* Create a temporary file name. Length has been checked before. */
  6794. strcpy(tmp, fname);
  6795. strcat(tmp, ".tmp");
  6796. /* Create the file if does not exist */
  6797. /* Use of fopen here is OK, since fname is only ASCII */
  6798. if ((fp = fopen(fname, "a+")) != NULL) {
  6799. (void)fclose(fp);
  6800. }
  6801. /* Open the given file and temporary file */
  6802. if ((fp = fopen(fname, "r")) == NULL) {
  6803. return 0;
  6804. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6805. fclose(fp);
  6806. return 0;
  6807. }
  6808. /* Copy the stuff to temporary file */
  6809. while (fgets(line, sizeof(line), fp) != NULL) {
  6810. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6811. continue;
  6812. }
  6813. u[255] = 0;
  6814. d[255] = 0;
  6815. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6816. found++;
  6817. if (pass != NULL) {
  6818. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6819. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6820. }
  6821. } else {
  6822. fprintf(fp2, "%s", line);
  6823. }
  6824. }
  6825. /* If new user, just add it */
  6826. if (!found && (pass != NULL)) {
  6827. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6828. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6829. }
  6830. /* Close files */
  6831. fclose(fp);
  6832. fclose(fp2);
  6833. /* Put the temp file in place of real file */
  6834. IGNORE_UNUSED_RESULT(remove(fname));
  6835. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6836. return 1;
  6837. }
  6838. static int
  6839. is_valid_port(unsigned long port)
  6840. {
  6841. return (port <= 0xffff);
  6842. }
  6843. static int
  6844. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6845. {
  6846. struct addrinfo hints, *res, *ressave;
  6847. int func_ret = 0;
  6848. int gai_ret;
  6849. memset(&hints, 0, sizeof(struct addrinfo));
  6850. hints.ai_family = af;
  6851. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6852. if (gai_ret != 0) {
  6853. /* gai_strerror could be used to convert gai_ret to a string */
  6854. /* POSIX return values: see
  6855. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6856. */
  6857. /* Windows return values: see
  6858. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6859. */
  6860. return 0;
  6861. }
  6862. ressave = res;
  6863. while (res) {
  6864. if (dstlen >= (size_t)res->ai_addrlen) {
  6865. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6866. func_ret = 1;
  6867. }
  6868. res = res->ai_next;
  6869. }
  6870. freeaddrinfo(ressave);
  6871. return func_ret;
  6872. }
  6873. static int
  6874. connect_socket(struct mg_context *ctx /* may be NULL */,
  6875. const char *host,
  6876. int port,
  6877. int use_ssl,
  6878. char *ebuf,
  6879. size_t ebuf_len,
  6880. SOCKET *sock /* output: socket, must not be NULL */,
  6881. union usa *sa /* output: socket address, must not be NULL */
  6882. )
  6883. {
  6884. int ip_ver = 0;
  6885. int conn_ret = -1;
  6886. *sock = INVALID_SOCKET;
  6887. memset(sa, 0, sizeof(*sa));
  6888. if (ebuf_len > 0) {
  6889. *ebuf = 0;
  6890. }
  6891. if (host == NULL) {
  6892. mg_snprintf(NULL,
  6893. NULL, /* No truncation check for ebuf */
  6894. ebuf,
  6895. ebuf_len,
  6896. "%s",
  6897. "NULL host");
  6898. return 0;
  6899. }
  6900. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  6901. mg_snprintf(NULL,
  6902. NULL, /* No truncation check for ebuf */
  6903. ebuf,
  6904. ebuf_len,
  6905. "%s",
  6906. "invalid port");
  6907. return 0;
  6908. }
  6909. #if !defined(NO_SSL)
  6910. #if !defined(NO_SSL_DL)
  6911. #ifdef OPENSSL_API_1_1
  6912. if (use_ssl && (TLS_client_method == NULL)) {
  6913. mg_snprintf(NULL,
  6914. NULL, /* No truncation check for ebuf */
  6915. ebuf,
  6916. ebuf_len,
  6917. "%s",
  6918. "SSL is not initialized");
  6919. return 0;
  6920. }
  6921. #else
  6922. if (use_ssl && (SSLv23_client_method == NULL)) {
  6923. mg_snprintf(NULL,
  6924. NULL, /* No truncation check for ebuf */
  6925. ebuf,
  6926. ebuf_len,
  6927. "%s",
  6928. "SSL is not initialized");
  6929. return 0;
  6930. }
  6931. #endif /* OPENSSL_API_1_1 */
  6932. #else
  6933. (void)use_ssl;
  6934. #endif /* NO_SSL_DL */
  6935. #else
  6936. (void)use_ssl;
  6937. #endif /* !defined(NO_SSL) */
  6938. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6939. sa->sin.sin_family = AF_INET;
  6940. sa->sin.sin_port = htons((uint16_t)port);
  6941. ip_ver = 4;
  6942. #ifdef USE_IPV6
  6943. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6944. sa->sin6.sin6_family = AF_INET6;
  6945. sa->sin6.sin6_port = htons((uint16_t)port);
  6946. ip_ver = 6;
  6947. } else if (host[0] == '[') {
  6948. /* While getaddrinfo on Windows will work with [::1],
  6949. * getaddrinfo on Linux only works with ::1 (without []). */
  6950. size_t l = strlen(host + 1);
  6951. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6952. if (h) {
  6953. h[l - 1] = 0;
  6954. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6955. sa->sin6.sin6_family = AF_INET6;
  6956. sa->sin6.sin6_port = htons((uint16_t)port);
  6957. ip_ver = 6;
  6958. }
  6959. mg_free(h);
  6960. }
  6961. #endif
  6962. }
  6963. if (ip_ver == 0) {
  6964. mg_snprintf(NULL,
  6965. NULL, /* No truncation check for ebuf */
  6966. ebuf,
  6967. ebuf_len,
  6968. "%s",
  6969. "host not found");
  6970. return 0;
  6971. }
  6972. if (ip_ver == 4) {
  6973. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6974. }
  6975. #ifdef USE_IPV6
  6976. else if (ip_ver == 6) {
  6977. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6978. }
  6979. #endif
  6980. if (*sock == INVALID_SOCKET) {
  6981. mg_snprintf(NULL,
  6982. NULL, /* No truncation check for ebuf */
  6983. ebuf,
  6984. ebuf_len,
  6985. "socket(): %s",
  6986. strerror(ERRNO));
  6987. return 0;
  6988. }
  6989. if (0 != set_non_blocking_mode(*sock)) {
  6990. mg_snprintf(NULL,
  6991. NULL, /* No truncation check for ebuf */
  6992. ebuf,
  6993. ebuf_len,
  6994. "Cannot set socket to non-blocking: %s",
  6995. strerror(ERRNO));
  6996. closesocket(*sock);
  6997. *sock = INVALID_SOCKET;
  6998. return 0;
  6999. }
  7000. set_close_on_exec(*sock, fc(ctx));
  7001. if (ip_ver == 4) {
  7002. /* connected with IPv4 */
  7003. conn_ret = connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin));
  7004. }
  7005. #ifdef USE_IPV6
  7006. else if (ip_ver == 6) {
  7007. /* connected with IPv6 */
  7008. conn_ret =
  7009. connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6));
  7010. }
  7011. #endif
  7012. if (conn_ret != 0) {
  7013. fd_set fdset;
  7014. struct timeval timeout;
  7015. int sockerr = -1;
  7016. #if defined(_WIN32)
  7017. int len = (int)sizeof(sockerr);
  7018. #else
  7019. socklen_t len = (socklen_t)sizeof(sockerr);
  7020. #endif
  7021. FD_ZERO(&fdset);
  7022. FD_SET(*sock, &fdset);
  7023. timeout.tv_sec = 10; /* 10 second timeout */
  7024. timeout.tv_usec = 0;
  7025. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7026. /* Not connected */
  7027. mg_snprintf(NULL,
  7028. NULL, /* No truncation check for ebuf */
  7029. ebuf,
  7030. ebuf_len,
  7031. "connect(%s:%d): timeout",
  7032. host,
  7033. port);
  7034. closesocket(*sock);
  7035. *sock = INVALID_SOCKET;
  7036. return 0;
  7037. }
  7038. #if defined(_WIN32)
  7039. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)&sockerr, &len);
  7040. #else
  7041. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &len);
  7042. #endif
  7043. if (sockerr != 0) {
  7044. /* Not connected */
  7045. mg_snprintf(NULL,
  7046. NULL, /* No truncation check for ebuf */
  7047. ebuf,
  7048. ebuf_len,
  7049. "connect(%s:%d): error %s",
  7050. host,
  7051. port,
  7052. strerror(sockerr));
  7053. closesocket(*sock);
  7054. *sock = INVALID_SOCKET;
  7055. return 0;
  7056. }
  7057. }
  7058. return 1;
  7059. }
  7060. int
  7061. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7062. {
  7063. static const char *dont_escape = "._-$,;~()";
  7064. static const char *hex = "0123456789abcdef";
  7065. char *pos = dst;
  7066. const char *end = dst + dst_len - 1;
  7067. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7068. if (isalnum(*(const unsigned char *)src)
  7069. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7070. *pos = *src;
  7071. } else if (pos + 2 < end) {
  7072. pos[0] = '%';
  7073. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7074. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7075. pos += 2;
  7076. } else {
  7077. break;
  7078. }
  7079. }
  7080. *pos = '\0';
  7081. return (*src == '\0') ? (int)(pos - dst) : -1;
  7082. }
  7083. /* Return 0 on success, non-zero if an error occurs. */
  7084. static int
  7085. print_dir_entry(struct de *de)
  7086. {
  7087. size_t hrefsize;
  7088. char *href;
  7089. char size[64], mod[64];
  7090. struct tm *tm;
  7091. hrefsize = PATH_MAX * 3; /* worst case */
  7092. href = (char *)mg_malloc(hrefsize);
  7093. if (href == NULL) {
  7094. return -1;
  7095. }
  7096. if (de->file.is_directory) {
  7097. mg_snprintf(de->conn,
  7098. NULL, /* Buffer is big enough */
  7099. size,
  7100. sizeof(size),
  7101. "%s",
  7102. "[DIRECTORY]");
  7103. } else {
  7104. /* We use (signed) cast below because MSVC 6 compiler cannot
  7105. * convert unsigned __int64 to double. Sigh. */
  7106. if (de->file.size < 1024) {
  7107. mg_snprintf(de->conn,
  7108. NULL, /* Buffer is big enough */
  7109. size,
  7110. sizeof(size),
  7111. "%d",
  7112. (int)de->file.size);
  7113. } else if (de->file.size < 0x100000) {
  7114. mg_snprintf(de->conn,
  7115. NULL, /* Buffer is big enough */
  7116. size,
  7117. sizeof(size),
  7118. "%.1fk",
  7119. (double)de->file.size / 1024.0);
  7120. } else if (de->file.size < 0x40000000) {
  7121. mg_snprintf(de->conn,
  7122. NULL, /* Buffer is big enough */
  7123. size,
  7124. sizeof(size),
  7125. "%.1fM",
  7126. (double)de->file.size / 1048576);
  7127. } else {
  7128. mg_snprintf(de->conn,
  7129. NULL, /* Buffer is big enough */
  7130. size,
  7131. sizeof(size),
  7132. "%.1fG",
  7133. (double)de->file.size / 1073741824);
  7134. }
  7135. }
  7136. /* Note: mg_snprintf will not cause a buffer overflow above.
  7137. * So, string truncation checks are not required here. */
  7138. tm = localtime(&de->file.last_modified);
  7139. if (tm != NULL) {
  7140. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7141. } else {
  7142. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7143. mod[sizeof(mod) - 1] = '\0';
  7144. }
  7145. mg_url_encode(de->file_name, href, hrefsize);
  7146. mg_printf(de->conn,
  7147. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7148. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7149. de->conn->request_info.local_uri,
  7150. href,
  7151. de->file.is_directory ? "/" : "",
  7152. de->file_name,
  7153. de->file.is_directory ? "/" : "",
  7154. mod,
  7155. size);
  7156. mg_free(href);
  7157. return 0;
  7158. }
  7159. /* This function is called from send_directory() and used for
  7160. * sorting directory entries by size, or name, or modification time.
  7161. * On windows, __cdecl specification is needed in case if project is built
  7162. * with __stdcall convention. qsort always requires __cdels callback. */
  7163. static int WINCDECL
  7164. compare_dir_entries(const void *p1, const void *p2)
  7165. {
  7166. if (p1 && p2) {
  7167. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7168. const char *query_string = a->conn->request_info.query_string;
  7169. int cmp_result = 0;
  7170. if (query_string == NULL) {
  7171. query_string = "na";
  7172. }
  7173. if (a->file.is_directory && !b->file.is_directory) {
  7174. return -1; /* Always put directories on top */
  7175. } else if (!a->file.is_directory && b->file.is_directory) {
  7176. return 1; /* Always put directories on top */
  7177. } else if (*query_string == 'n') {
  7178. cmp_result = strcmp(a->file_name, b->file_name);
  7179. } else if (*query_string == 's') {
  7180. cmp_result = (a->file.size == b->file.size)
  7181. ? 0
  7182. : ((a->file.size > b->file.size) ? 1 : -1);
  7183. } else if (*query_string == 'd') {
  7184. cmp_result =
  7185. (a->file.last_modified == b->file.last_modified)
  7186. ? 0
  7187. : ((a->file.last_modified > b->file.last_modified) ? 1
  7188. : -1);
  7189. }
  7190. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7191. }
  7192. return 0;
  7193. }
  7194. static int
  7195. must_hide_file(struct mg_connection *conn, const char *path)
  7196. {
  7197. if (conn && conn->ctx) {
  7198. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7199. const char *pattern = conn->ctx->config[HIDE_FILES];
  7200. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7201. || ((pattern != NULL)
  7202. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7203. }
  7204. return 0;
  7205. }
  7206. static int
  7207. scan_directory(struct mg_connection *conn,
  7208. const char *dir,
  7209. void *data,
  7210. int (*cb)(struct de *, void *))
  7211. {
  7212. char path[PATH_MAX];
  7213. struct dirent *dp;
  7214. DIR *dirp;
  7215. struct de de;
  7216. int truncated;
  7217. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7218. return 0;
  7219. } else {
  7220. de.conn = conn;
  7221. while ((dp = mg_readdir(dirp)) != NULL) {
  7222. /* Do not show current dir and hidden files */
  7223. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7224. || must_hide_file(conn, dp->d_name)) {
  7225. continue;
  7226. }
  7227. mg_snprintf(
  7228. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7229. /* If we don't memset stat structure to zero, mtime will have
  7230. * garbage and strftime() will segfault later on in
  7231. * print_dir_entry(). memset is required only if mg_stat()
  7232. * fails. For more details, see
  7233. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7234. memset(&de.file, 0, sizeof(de.file));
  7235. if (truncated) {
  7236. /* If the path is not complete, skip processing. */
  7237. continue;
  7238. }
  7239. if (!mg_stat(conn, path, &de.file)) {
  7240. mg_cry(conn,
  7241. "%s: mg_stat(%s) failed: %s",
  7242. __func__,
  7243. path,
  7244. strerror(ERRNO));
  7245. }
  7246. de.file_name = dp->d_name;
  7247. cb(&de, data);
  7248. }
  7249. (void)mg_closedir(dirp);
  7250. }
  7251. return 1;
  7252. }
  7253. #if !defined(NO_FILES)
  7254. static int
  7255. remove_directory(struct mg_connection *conn, const char *dir)
  7256. {
  7257. char path[PATH_MAX];
  7258. struct dirent *dp;
  7259. DIR *dirp;
  7260. struct de de;
  7261. int truncated;
  7262. int ok = 1;
  7263. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7264. return 0;
  7265. } else {
  7266. de.conn = conn;
  7267. while ((dp = mg_readdir(dirp)) != NULL) {
  7268. /* Do not show current dir (but show hidden files as they will
  7269. * also be removed) */
  7270. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7271. continue;
  7272. }
  7273. mg_snprintf(
  7274. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7275. /* If we don't memset stat structure to zero, mtime will have
  7276. * garbage and strftime() will segfault later on in
  7277. * print_dir_entry(). memset is required only if mg_stat()
  7278. * fails. For more details, see
  7279. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7280. memset(&de.file, 0, sizeof(de.file));
  7281. if (truncated) {
  7282. /* Do not delete anything shorter */
  7283. ok = 0;
  7284. continue;
  7285. }
  7286. if (!mg_stat(conn, path, &de.file)) {
  7287. mg_cry(conn,
  7288. "%s: mg_stat(%s) failed: %s",
  7289. __func__,
  7290. path,
  7291. strerror(ERRNO));
  7292. ok = 0;
  7293. }
  7294. if (de.file.is_directory) {
  7295. if (remove_directory(conn, path) == 0) {
  7296. ok = 0;
  7297. }
  7298. } else {
  7299. /* This will fail file is the file is in memory */
  7300. if (mg_remove(conn, path) == 0) {
  7301. ok = 0;
  7302. }
  7303. }
  7304. }
  7305. (void)mg_closedir(dirp);
  7306. IGNORE_UNUSED_RESULT(rmdir(dir));
  7307. }
  7308. return ok;
  7309. }
  7310. #endif
  7311. struct dir_scan_data {
  7312. struct de *entries;
  7313. unsigned int num_entries;
  7314. unsigned int arr_size;
  7315. };
  7316. /* Behaves like realloc(), but frees original pointer on failure */
  7317. static void *
  7318. realloc2(void *ptr, size_t size)
  7319. {
  7320. void *new_ptr = mg_realloc(ptr, size);
  7321. if (new_ptr == NULL) {
  7322. mg_free(ptr);
  7323. }
  7324. return new_ptr;
  7325. }
  7326. static int
  7327. dir_scan_callback(struct de *de, void *data)
  7328. {
  7329. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7330. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7331. dsd->arr_size *= 2;
  7332. dsd->entries =
  7333. (struct de *)realloc2(dsd->entries,
  7334. dsd->arr_size * sizeof(dsd->entries[0]));
  7335. }
  7336. if (dsd->entries == NULL) {
  7337. /* TODO(lsm, low): propagate an error to the caller */
  7338. dsd->num_entries = 0;
  7339. } else {
  7340. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7341. dsd->entries[dsd->num_entries].file = de->file;
  7342. dsd->entries[dsd->num_entries].conn = de->conn;
  7343. dsd->num_entries++;
  7344. }
  7345. return 0;
  7346. }
  7347. static void
  7348. handle_directory_request(struct mg_connection *conn, const char *dir)
  7349. {
  7350. unsigned int i;
  7351. int sort_direction;
  7352. struct dir_scan_data data = {NULL, 0, 128};
  7353. char date[64];
  7354. time_t curtime = time(NULL);
  7355. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7356. mg_send_http_error(conn,
  7357. 500,
  7358. "Error: Cannot open directory\nopendir(%s): %s",
  7359. dir,
  7360. strerror(ERRNO));
  7361. return;
  7362. }
  7363. gmt_time_string(date, sizeof(date), &curtime);
  7364. if (!conn) {
  7365. return;
  7366. }
  7367. sort_direction = ((conn->request_info.query_string != NULL)
  7368. && (conn->request_info.query_string[1] == 'd'))
  7369. ? 'a'
  7370. : 'd';
  7371. conn->must_close = 1;
  7372. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7373. send_static_cache_header(conn);
  7374. send_additional_header(conn);
  7375. mg_printf(conn,
  7376. "Date: %s\r\n"
  7377. "Connection: close\r\n"
  7378. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7379. date);
  7380. mg_printf(conn,
  7381. "<html><head><title>Index of %s</title>"
  7382. "<style>th {text-align: left;}</style></head>"
  7383. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7384. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7385. "<th><a href=\"?d%c\">Modified</a></th>"
  7386. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7387. "<tr><td colspan=\"3\"><hr></td></tr>",
  7388. conn->request_info.local_uri,
  7389. conn->request_info.local_uri,
  7390. sort_direction,
  7391. sort_direction,
  7392. sort_direction);
  7393. /* Print first entry - link to a parent directory */
  7394. mg_printf(conn,
  7395. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7396. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7397. conn->request_info.local_uri,
  7398. "..",
  7399. "Parent directory",
  7400. "-",
  7401. "-");
  7402. /* Sort and print directory entries */
  7403. if (data.entries != NULL) {
  7404. qsort(data.entries,
  7405. (size_t)data.num_entries,
  7406. sizeof(data.entries[0]),
  7407. compare_dir_entries);
  7408. for (i = 0; i < data.num_entries; i++) {
  7409. print_dir_entry(&data.entries[i]);
  7410. mg_free(data.entries[i].file_name);
  7411. }
  7412. mg_free(data.entries);
  7413. }
  7414. mg_printf(conn, "%s", "</table></body></html>");
  7415. conn->status_code = 200;
  7416. }
  7417. /* Send len bytes from the opened file to the client. */
  7418. static void
  7419. send_file_data(struct mg_connection *conn,
  7420. struct mg_file *filep,
  7421. int64_t offset,
  7422. int64_t len)
  7423. {
  7424. char buf[MG_BUF_LEN];
  7425. int to_read, num_read, num_written;
  7426. int64_t size;
  7427. if (!filep || !conn) {
  7428. return;
  7429. }
  7430. /* Sanity check the offset */
  7431. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7432. : (int64_t)(filep->stat.size);
  7433. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7434. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7435. /* file stored in memory */
  7436. if (len > size - offset) {
  7437. len = size - offset;
  7438. }
  7439. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7440. } else if (len > 0 && filep->access.fp != NULL) {
  7441. /* file stored on disk */
  7442. #if defined(__linux__)
  7443. /* sendfile is only available for Linux */
  7444. if ((conn->ssl == 0) && (conn->throttle == 0)
  7445. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  7446. "yes"))) {
  7447. off_t sf_offs = (off_t)offset;
  7448. ssize_t sf_sent;
  7449. int sf_file = fileno(filep->access.fp);
  7450. int loop_cnt = 0;
  7451. do {
  7452. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7453. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7454. size_t sf_tosend =
  7455. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7456. sf_sent =
  7457. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7458. if (sf_sent > 0) {
  7459. len -= sf_sent;
  7460. offset += sf_sent;
  7461. } else if (loop_cnt == 0) {
  7462. /* This file can not be sent using sendfile.
  7463. * This might be the case for pseudo-files in the
  7464. * /sys/ and /proc/ file system.
  7465. * Use the regular user mode copy code instead. */
  7466. break;
  7467. } else if (sf_sent == 0) {
  7468. /* No error, but 0 bytes sent. May be EOF? */
  7469. return;
  7470. }
  7471. loop_cnt++;
  7472. } while ((len > 0) && (sf_sent >= 0));
  7473. if (sf_sent > 0) {
  7474. return; /* OK */
  7475. }
  7476. /* sf_sent<0 means error, thus fall back to the classic way */
  7477. /* This is always the case, if sf_file is not a "normal" file,
  7478. * e.g., for sending data from the output of a CGI process. */
  7479. offset = (int64_t)sf_offs;
  7480. }
  7481. #endif
  7482. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7483. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  7484. mg_send_http_error(
  7485. conn,
  7486. 500,
  7487. "%s",
  7488. "Error: Unable to access file at requested position.");
  7489. } else {
  7490. while (len > 0) {
  7491. /* Calculate how much to read from the file in the buffer */
  7492. to_read = sizeof(buf);
  7493. if ((int64_t)to_read > len) {
  7494. to_read = (int)len;
  7495. }
  7496. /* Read from file, exit the loop on error */
  7497. if ((num_read =
  7498. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7499. <= 0) {
  7500. break;
  7501. }
  7502. /* Send read bytes to the client, exit the loop on error */
  7503. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7504. != num_read) {
  7505. break;
  7506. }
  7507. /* Both read and were successful, adjust counters */
  7508. len -= num_written;
  7509. }
  7510. }
  7511. }
  7512. }
  7513. static int
  7514. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7515. {
  7516. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7517. }
  7518. static void
  7519. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7520. {
  7521. if ((filestat != NULL) && (buf != NULL)) {
  7522. mg_snprintf(NULL,
  7523. NULL, /* All calls to construct_etag use 64 byte buffer */
  7524. buf,
  7525. buf_len,
  7526. "\"%lx.%" INT64_FMT "\"",
  7527. (unsigned long)filestat->last_modified,
  7528. filestat->size);
  7529. }
  7530. }
  7531. static void
  7532. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7533. {
  7534. if (filep != NULL && filep->fp != NULL) {
  7535. #ifdef _WIN32
  7536. (void)conn; /* Unused. */
  7537. #else
  7538. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7539. mg_cry(conn,
  7540. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7541. __func__,
  7542. strerror(ERRNO));
  7543. }
  7544. #endif
  7545. }
  7546. }
  7547. static void
  7548. handle_static_file_request(struct mg_connection *conn,
  7549. const char *path,
  7550. struct mg_file *filep,
  7551. const char *mime_type,
  7552. const char *additional_headers)
  7553. {
  7554. char date[64], lm[64], etag[64];
  7555. char range[128]; /* large enough, so there will be no overflow */
  7556. const char *msg = "OK", *hdr;
  7557. time_t curtime = time(NULL);
  7558. int64_t cl, r1, r2;
  7559. struct vec mime_vec;
  7560. int n, truncated;
  7561. char gz_path[PATH_MAX];
  7562. const char *encoding = "";
  7563. const char *cors1, *cors2, *cors3;
  7564. int allow_on_the_fly_compression;
  7565. if ((conn == NULL) || (conn->ctx == NULL) || (filep == NULL)) {
  7566. return;
  7567. }
  7568. if (mime_type == NULL) {
  7569. get_mime_type(conn->ctx, path, &mime_vec);
  7570. } else {
  7571. mime_vec.ptr = mime_type;
  7572. mime_vec.len = strlen(mime_type);
  7573. }
  7574. if (filep->stat.size > INT64_MAX) {
  7575. mg_send_http_error(conn,
  7576. 500,
  7577. "Error: File size is too large to send\n%" INT64_FMT,
  7578. filep->stat.size);
  7579. return;
  7580. }
  7581. cl = (int64_t)filep->stat.size;
  7582. conn->status_code = 200;
  7583. range[0] = '\0';
  7584. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7585. * it's important to rewrite the filename after resolving
  7586. * the mime type from it, to preserve the actual file's type */
  7587. allow_on_the_fly_compression = conn->accept_gzip;
  7588. if (filep->stat.is_gzipped) {
  7589. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7590. if (truncated) {
  7591. mg_send_http_error(conn,
  7592. 500,
  7593. "Error: Path of zipped file too long (%s)",
  7594. path);
  7595. return;
  7596. }
  7597. path = gz_path;
  7598. encoding = "Content-Encoding: gzip\r\n";
  7599. /* File is already compressed. No "on the fly" compression. */
  7600. allow_on_the_fly_compression = 0;
  7601. }
  7602. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7603. mg_send_http_error(conn,
  7604. 500,
  7605. "Error: Cannot open file\nfopen(%s): %s",
  7606. path,
  7607. strerror(ERRNO));
  7608. return;
  7609. }
  7610. fclose_on_exec(&filep->access, conn);
  7611. /* If Range: header specified, act accordingly */
  7612. r1 = r2 = 0;
  7613. hdr = mg_get_header(conn, "Range");
  7614. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7615. && (r1 >= 0) && (r2 >= 0)) {
  7616. /* actually, range requests don't play well with a pre-gzipped
  7617. * file (since the range is specified in the uncompressed space) */
  7618. if (filep->stat.is_gzipped) {
  7619. mg_send_http_error(
  7620. conn,
  7621. 416, /* 416 = Range Not Satisfiable */
  7622. "%s",
  7623. "Error: Range requests in gzipped files are not supported");
  7624. (void)mg_fclose(
  7625. &filep->access); /* ignore error on read only file */
  7626. return;
  7627. }
  7628. conn->status_code = 206;
  7629. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7630. mg_snprintf(conn,
  7631. NULL, /* range buffer is big enough */
  7632. range,
  7633. sizeof(range),
  7634. "Content-Range: bytes "
  7635. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7636. r1,
  7637. r1 + cl - 1,
  7638. filep->stat.size);
  7639. msg = "Partial Content";
  7640. /* Do not compress ranges. */
  7641. allow_on_the_fly_compression = 0;
  7642. }
  7643. hdr = mg_get_header(conn, "Origin");
  7644. if (hdr) {
  7645. /* Cross-origin resource sharing (CORS), see
  7646. * http://www.html5rocks.com/en/tutorials/cors/,
  7647. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7648. * -
  7649. * preflight is not supported for files. */
  7650. cors1 = "Access-Control-Allow-Origin: ";
  7651. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7652. cors3 = "\r\n";
  7653. } else {
  7654. cors1 = cors2 = cors3 = "";
  7655. }
  7656. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  7657. * according to
  7658. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7659. gmt_time_string(date, sizeof(date), &curtime);
  7660. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7661. construct_etag(etag, sizeof(etag), &filep->stat);
  7662. /* On the fly compression allowed */
  7663. if (allow_on_the_fly_compression) {
  7664. ;
  7665. /* TODO: add interface to compression module */
  7666. /* e.g., def from https://zlib.net/zlib_how.html */
  7667. /* Check license (zlib has a permissive license, but */
  7668. /* is still not MIT) and use dynamic binding like */
  7669. /* done with OpenSSL */
  7670. /* See #199 (https://github.com/civetweb/civetweb/issues/199) */
  7671. }
  7672. /* Send header */
  7673. (void)mg_printf(conn,
  7674. "HTTP/1.1 %d %s\r\n"
  7675. "%s%s%s"
  7676. "Date: %s\r\n",
  7677. conn->status_code,
  7678. msg,
  7679. cors1,
  7680. cors2,
  7681. cors3,
  7682. date);
  7683. send_static_cache_header(conn);
  7684. send_additional_header(conn);
  7685. (void)mg_printf(conn,
  7686. "Last-Modified: %s\r\n"
  7687. "Etag: %s\r\n"
  7688. "Content-Type: %.*s\r\n"
  7689. "Content-Length: %" INT64_FMT "\r\n"
  7690. "Connection: %s\r\n"
  7691. "Accept-Ranges: bytes\r\n"
  7692. "%s%s",
  7693. lm,
  7694. etag,
  7695. (int)mime_vec.len,
  7696. mime_vec.ptr,
  7697. cl,
  7698. suggest_connection_header(conn),
  7699. range,
  7700. encoding);
  7701. /* The previous code must not add any header starting with X- to make
  7702. * sure no one of the additional_headers is included twice */
  7703. if (additional_headers != NULL) {
  7704. (void)mg_printf(conn,
  7705. "%.*s\r\n\r\n",
  7706. (int)strlen(additional_headers),
  7707. additional_headers);
  7708. } else {
  7709. (void)mg_printf(conn, "\r\n");
  7710. }
  7711. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7712. send_file_data(conn, filep, r1, cl);
  7713. }
  7714. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7715. }
  7716. #if !defined(NO_CACHING)
  7717. static void
  7718. handle_not_modified_static_file_request(struct mg_connection *conn,
  7719. struct mg_file *filep)
  7720. {
  7721. char date[64], lm[64], etag[64];
  7722. time_t curtime = time(NULL);
  7723. if ((conn == NULL) || (filep == NULL)) {
  7724. return;
  7725. }
  7726. conn->status_code = 304;
  7727. gmt_time_string(date, sizeof(date), &curtime);
  7728. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7729. construct_etag(etag, sizeof(etag), &filep->stat);
  7730. (void)mg_printf(conn,
  7731. "HTTP/1.1 %d %s\r\n"
  7732. "Date: %s\r\n",
  7733. conn->status_code,
  7734. mg_get_response_code_text(conn, conn->status_code),
  7735. date);
  7736. send_static_cache_header(conn);
  7737. send_additional_header(conn);
  7738. (void)mg_printf(conn,
  7739. "Last-Modified: %s\r\n"
  7740. "Etag: %s\r\n"
  7741. "Connection: %s\r\n"
  7742. "\r\n",
  7743. lm,
  7744. etag,
  7745. suggest_connection_header(conn));
  7746. }
  7747. #endif
  7748. void
  7749. mg_send_file(struct mg_connection *conn, const char *path)
  7750. {
  7751. mg_send_mime_file(conn, path, NULL);
  7752. }
  7753. void
  7754. mg_send_mime_file(struct mg_connection *conn,
  7755. const char *path,
  7756. const char *mime_type)
  7757. {
  7758. mg_send_mime_file2(conn, path, mime_type, NULL);
  7759. }
  7760. void
  7761. mg_send_mime_file2(struct mg_connection *conn,
  7762. const char *path,
  7763. const char *mime_type,
  7764. const char *additional_headers)
  7765. {
  7766. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7767. if (!conn) {
  7768. /* No conn */
  7769. return;
  7770. }
  7771. if (mg_stat(conn, path, &file.stat)) {
  7772. if (file.stat.is_directory) {
  7773. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7774. "yes")) {
  7775. handle_directory_request(conn, path);
  7776. } else {
  7777. mg_send_http_error(conn,
  7778. 403,
  7779. "%s",
  7780. "Error: Directory listing denied");
  7781. }
  7782. } else {
  7783. handle_static_file_request(
  7784. conn, path, &file, mime_type, additional_headers);
  7785. }
  7786. } else {
  7787. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7788. }
  7789. }
  7790. /* For a given PUT path, create all intermediate subdirectories.
  7791. * Return 0 if the path itself is a directory.
  7792. * Return 1 if the path leads to a file.
  7793. * Return -1 for if the path is too long.
  7794. * Return -2 if path can not be created.
  7795. */
  7796. static int
  7797. put_dir(struct mg_connection *conn, const char *path)
  7798. {
  7799. char buf[PATH_MAX];
  7800. const char *s, *p;
  7801. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7802. size_t len;
  7803. int res = 1;
  7804. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7805. len = (size_t)(p - path);
  7806. if (len >= sizeof(buf)) {
  7807. /* path too long */
  7808. res = -1;
  7809. break;
  7810. }
  7811. memcpy(buf, path, len);
  7812. buf[len] = '\0';
  7813. /* Try to create intermediate directory */
  7814. DEBUG_TRACE("mkdir(%s)", buf);
  7815. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7816. /* path does not exixt and can not be created */
  7817. res = -2;
  7818. break;
  7819. }
  7820. /* Is path itself a directory? */
  7821. if (p[1] == '\0') {
  7822. res = 0;
  7823. }
  7824. }
  7825. return res;
  7826. }
  7827. static void
  7828. remove_bad_file(const struct mg_connection *conn, const char *path)
  7829. {
  7830. int r = mg_remove(conn, path);
  7831. if (r != 0) {
  7832. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7833. }
  7834. }
  7835. long long
  7836. mg_store_body(struct mg_connection *conn, const char *path)
  7837. {
  7838. char buf[MG_BUF_LEN];
  7839. long long len = 0;
  7840. int ret, n;
  7841. struct mg_file fi;
  7842. if (conn->consumed_content != 0) {
  7843. mg_cry(conn, "%s: Contents already consumed", __func__);
  7844. return -11;
  7845. }
  7846. ret = put_dir(conn, path);
  7847. if (ret < 0) {
  7848. /* -1 for path too long,
  7849. * -2 for path can not be created. */
  7850. return ret;
  7851. }
  7852. if (ret != 1) {
  7853. /* Return 0 means, path itself is a directory. */
  7854. return 0;
  7855. }
  7856. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7857. return -12;
  7858. }
  7859. ret = mg_read(conn, buf, sizeof(buf));
  7860. while (ret > 0) {
  7861. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7862. if (n != ret) {
  7863. (void)mg_fclose(
  7864. &fi.access); /* File is bad and will be removed anyway. */
  7865. remove_bad_file(conn, path);
  7866. return -13;
  7867. }
  7868. len += ret;
  7869. ret = mg_read(conn, buf, sizeof(buf));
  7870. }
  7871. /* File is open for writing. If fclose fails, there was probably an
  7872. * error flushing the buffer to disk, so the file on disk might be
  7873. * broken. Delete it and return an error to the caller. */
  7874. if (mg_fclose(&fi.access) != 0) {
  7875. remove_bad_file(conn, path);
  7876. return -14;
  7877. }
  7878. return len;
  7879. }
  7880. /* Parse a buffer:
  7881. * Forward the string pointer till the end of a word, then
  7882. * terminate it and forward till the begin of the next word.
  7883. */
  7884. static int
  7885. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  7886. {
  7887. /* Forward until a space is found - use isgraph here */
  7888. /* See http://www.cplusplus.com/reference/cctype/ */
  7889. while (isgraph(**ppw)) {
  7890. (*ppw)++;
  7891. }
  7892. /* Check end of word */
  7893. if (eol) {
  7894. /* must be a end of line */
  7895. if ((**ppw != '\r') && (**ppw != '\n')) {
  7896. return -1;
  7897. }
  7898. } else {
  7899. /* must be a end of a word, but not a line */
  7900. if (**ppw != ' ') {
  7901. return -1;
  7902. }
  7903. }
  7904. /* Terminate and forward to the next word */
  7905. do {
  7906. **ppw = 0;
  7907. (*ppw)++;
  7908. } while ((**ppw) && isspace(**ppw));
  7909. /* Check after term */
  7910. if (!eol) {
  7911. /* if it's not the end of line, there must be a next word */
  7912. if (!isgraph(**ppw)) {
  7913. return -1;
  7914. }
  7915. }
  7916. /* ok */
  7917. return 1;
  7918. }
  7919. /* Parse HTTP headers from the given buffer, advance buf pointer
  7920. * to the point where parsing stopped.
  7921. * All parameters must be valid pointers (not NULL).
  7922. * Return <0 on error. */
  7923. static int
  7924. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  7925. {
  7926. int i;
  7927. int num_headers = 0;
  7928. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  7929. char *dp = *buf;
  7930. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7931. dp++;
  7932. }
  7933. if (dp == *buf) {
  7934. /* End of headers reached. */
  7935. break;
  7936. }
  7937. if (*dp != ':') {
  7938. /* This is not a valid field. */
  7939. return -1;
  7940. }
  7941. /* End of header key (*dp == ':') */
  7942. /* Truncate here and set the key name */
  7943. *dp = 0;
  7944. hdr[i].name = *buf;
  7945. do {
  7946. dp++;
  7947. } while (*dp == ' ');
  7948. /* The rest of the line is the value */
  7949. hdr[i].value = dp;
  7950. *buf = dp + strcspn(dp, "\r\n");
  7951. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7952. *buf = NULL;
  7953. }
  7954. num_headers = i + 1;
  7955. if (*buf) {
  7956. (*buf)[0] = 0;
  7957. (*buf)[1] = 0;
  7958. *buf += 2;
  7959. } else {
  7960. *buf = dp;
  7961. break;
  7962. }
  7963. if ((*buf)[0] == '\r') {
  7964. /* This is the end of the header */
  7965. break;
  7966. }
  7967. }
  7968. return num_headers;
  7969. }
  7970. struct mg_http_method_info {
  7971. const char *name;
  7972. int request_has_body;
  7973. int response_has_body;
  7974. int is_safe;
  7975. int is_idempotent;
  7976. int is_cacheable;
  7977. };
  7978. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  7979. static struct mg_http_method_info http_methods[] = {
  7980. /* HTTP (RFC 2616) */
  7981. {"GET", 0, 1, 1, 1, 1},
  7982. {"POST", 1, 1, 0, 0, 0},
  7983. {"PUT", 1, 0, 0, 1, 0},
  7984. {"DELETE", 0, 0, 0, 1, 0},
  7985. {"HEAD", 0, 0, 1, 1, 1},
  7986. {"OPTIONS", 0, 0, 1, 1, 0},
  7987. {"CONNECT", 1, 1, 0, 0, 0},
  7988. /* TRACE method (RFC 2616) is not supported for security reasons */
  7989. /* PATCH method (RFC 5789) */
  7990. {"PATCH", 1, 0, 0, 0, 0},
  7991. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7992. /* WEBDAV (RFC 2518) */
  7993. {"PROPFIND", 0, 1, 1, 1, 0},
  7994. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  7995. * Some PROPFIND results MAY be cached, with care,
  7996. * as there is no cache validation mechanism for
  7997. * most properties. This method is both safe and
  7998. * idempotent (see Section 9.1 of [RFC2616]). */
  7999. {"MKCOL", 0, 0, 0, 1, 0},
  8000. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8001. * When MKCOL is invoked without a request body,
  8002. * the newly created collection SHOULD have no
  8003. * members. A MKCOL request message may contain
  8004. * a message body. The precise behavior of a MKCOL
  8005. * request when the body is present is undefined,
  8006. * ... ==> We do not support MKCOL with body data.
  8007. * This method is idempotent, but not safe (see
  8008. * Section 9.1 of [RFC2616]). Responses to this
  8009. * method MUST NOT be cached. */
  8010. /* Unsupported WEBDAV Methods: */
  8011. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8012. /* + 11 methods from RFC 3253 */
  8013. /* ORDERPATCH (RFC 3648) */
  8014. /* ACL (RFC 3744) */
  8015. /* SEARCH (RFC 5323) */
  8016. /* + MicroSoft extensions
  8017. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8018. /* REPORT method (RFC 3253) */
  8019. {"REPORT", 1, 1, 1, 1, 1},
  8020. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8021. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8022. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8023. * to be useful for REST in case a "GET request with body" is
  8024. * required. */
  8025. {NULL, 0, 0, 0, 0, 0}
  8026. /* end of list */
  8027. };
  8028. static const struct mg_http_method_info *
  8029. get_http_method_info(const char *method)
  8030. {
  8031. /* Check if the method is known to the server. The list of all known
  8032. * HTTP methods can be found here at
  8033. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8034. */
  8035. const struct mg_http_method_info *m = http_methods;
  8036. while (m->name) {
  8037. if (!strcmp(m->name, method)) {
  8038. return m;
  8039. }
  8040. m++;
  8041. }
  8042. return NULL;
  8043. }
  8044. static int
  8045. is_valid_http_method(const char *method)
  8046. {
  8047. return (get_http_method_info(method) != NULL);
  8048. }
  8049. /* Parse HTTP request, fill in mg_request_info structure.
  8050. * This function modifies the buffer by NUL-terminating
  8051. * HTTP request components, header names and header values.
  8052. * Parameters:
  8053. * buf (in/out): pointer to the HTTP header to parse and split
  8054. * len (in): length of HTTP header buffer
  8055. * re (out): parsed header as mg_request_info
  8056. * buf and ri must be valid pointers (not NULL), len>0.
  8057. * Returns <0 on error. */
  8058. static int
  8059. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8060. {
  8061. int request_length;
  8062. int init_skip = 0;
  8063. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  8064. * remote_port */
  8065. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8066. NULL;
  8067. ri->num_headers = 0;
  8068. /* RFC says that all initial whitespaces should be ingored */
  8069. /* This included all leading \r and \n (isspace) */
  8070. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8071. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8072. buf++;
  8073. len--;
  8074. init_skip++;
  8075. }
  8076. if (len == 0) {
  8077. /* Incomplete request */
  8078. return 0;
  8079. }
  8080. /* Control characters are not allowed, including zero */
  8081. if (iscntrl(*(unsigned char *)buf)) {
  8082. return -1;
  8083. }
  8084. /* Find end of HTTP header */
  8085. request_length = get_http_header_len(buf, len);
  8086. if (request_length <= 0) {
  8087. return request_length;
  8088. }
  8089. buf[request_length - 1] = '\0';
  8090. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8091. return -1;
  8092. }
  8093. /* The first word has to be the HTTP method */
  8094. ri->request_method = buf;
  8095. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8096. return -1;
  8097. }
  8098. /* Check for a valid http method */
  8099. if (!is_valid_http_method(ri->request_method)) {
  8100. return -1;
  8101. }
  8102. /* The second word is the URI */
  8103. ri->request_uri = buf;
  8104. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8105. return -1;
  8106. }
  8107. /* Next would be the HTTP version */
  8108. ri->http_version = buf;
  8109. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8110. return -1;
  8111. }
  8112. /* Check for a valid HTTP version key */
  8113. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8114. /* Invalid request */
  8115. return -1;
  8116. }
  8117. ri->http_version += 5;
  8118. /* Parse all HTTP headers */
  8119. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8120. if (ri->num_headers < 0) {
  8121. /* Error while parsing headers */
  8122. return -1;
  8123. }
  8124. return request_length + init_skip;
  8125. }
  8126. static int
  8127. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8128. {
  8129. int response_length;
  8130. int init_skip = 0;
  8131. char *tmp, *tmp2;
  8132. long l;
  8133. /* Initialize elements. */
  8134. ri->http_version = ri->status_text = NULL;
  8135. ri->num_headers = ri->status_code = 0;
  8136. /* RFC says that all initial whitespaces should be ingored */
  8137. /* This included all leading \r and \n (isspace) */
  8138. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8139. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8140. buf++;
  8141. len--;
  8142. init_skip++;
  8143. }
  8144. if (len == 0) {
  8145. /* Incomplete request */
  8146. return 0;
  8147. }
  8148. /* Control characters are not allowed, including zero */
  8149. if (iscntrl(*(unsigned char *)buf)) {
  8150. return -1;
  8151. }
  8152. /* Find end of HTTP header */
  8153. response_length = get_http_header_len(buf, len);
  8154. if (response_length <= 0) {
  8155. return response_length;
  8156. }
  8157. buf[response_length - 1] = '\0';
  8158. /* TODO: Define mg_response_info and implement parsing */
  8159. (void)buf;
  8160. (void)len;
  8161. (void)ri;
  8162. /* RFC says that all initial whitespaces should be ingored */
  8163. while ((*buf != '\0') && isspace(*(unsigned char *)buf)) {
  8164. buf++;
  8165. }
  8166. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8167. return -1;
  8168. }
  8169. /* The first word is the HTTP version */
  8170. /* Check for a valid HTTP version key */
  8171. if (strncmp(buf, "HTTP/", 5) != 0) {
  8172. /* Invalid request */
  8173. return -1;
  8174. }
  8175. buf += 5;
  8176. if (!isgraph(buf[0])) {
  8177. /* Invalid request */
  8178. return -1;
  8179. }
  8180. ri->http_version = buf;
  8181. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8182. return -1;
  8183. }
  8184. /* The second word is the status as a number */
  8185. tmp = buf;
  8186. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8187. return -1;
  8188. }
  8189. l = strtol(tmp, &tmp2, 10);
  8190. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8191. /* Everything else but a 3 digit code is invalid */
  8192. return -1;
  8193. }
  8194. ri->status_code = (int)l;
  8195. /* The rest of the line is the status text */
  8196. ri->status_text = buf;
  8197. /* Find end of status text */
  8198. /* isgraph or isspace = isprint */
  8199. while (isprint(*buf)) {
  8200. buf++;
  8201. }
  8202. if ((*buf != '\r') && (*buf != '\n')) {
  8203. return -1;
  8204. }
  8205. /* Terminate string and forward buf to next line */
  8206. do {
  8207. *buf = 0;
  8208. buf++;
  8209. } while ((*buf) && isspace(*buf));
  8210. /* Parse all HTTP headers */
  8211. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8212. if (ri->num_headers < 0) {
  8213. /* Error while parsing headers */
  8214. return -1;
  8215. }
  8216. return response_length + init_skip;
  8217. }
  8218. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8219. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8220. * buffer (which marks the end of HTTP request). Buffer buf may already
  8221. * have some data. The length of the data is stored in nread.
  8222. * Upon every read operation, increase nread by the number of bytes read. */
  8223. static int
  8224. read_message(FILE *fp,
  8225. struct mg_connection *conn,
  8226. char *buf,
  8227. int bufsiz,
  8228. int *nread)
  8229. {
  8230. int request_len, n = 0;
  8231. struct timespec last_action_time;
  8232. double request_timeout;
  8233. if (!conn) {
  8234. return 0;
  8235. }
  8236. memset(&last_action_time, 0, sizeof(last_action_time));
  8237. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  8238. /* value of request_timeout is in seconds, config in milliseconds */
  8239. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8240. } else {
  8241. request_timeout = -1.0;
  8242. }
  8243. if (conn->handled_requests > 0) {
  8244. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8245. request_timeout =
  8246. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8247. }
  8248. }
  8249. request_len = get_http_header_len(buf, *nread);
  8250. /* first time reading from this connection */
  8251. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8252. while (request_len == 0) {
  8253. /* Full request not yet received */
  8254. if (conn->ctx->stop_flag != 0) {
  8255. /* Server is to be stopped. */
  8256. return -1;
  8257. }
  8258. if (*nread >= bufsiz) {
  8259. /* Request too long */
  8260. return -2;
  8261. }
  8262. n = pull_inner(
  8263. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8264. if (n == -2) {
  8265. /* Receive error */
  8266. return -1;
  8267. }
  8268. if (n > 0) {
  8269. *nread += n;
  8270. request_len = get_http_header_len(buf, *nread);
  8271. } else {
  8272. request_len = 0;
  8273. }
  8274. if ((request_len == 0) && (request_timeout >= 0)) {
  8275. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8276. > request_timeout) {
  8277. /* Timeout */
  8278. return -1;
  8279. }
  8280. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8281. }
  8282. }
  8283. return request_len;
  8284. }
  8285. #if !defined(NO_CACHING)
  8286. /* Return True if we should reply 304 Not Modified. */
  8287. static int
  8288. is_not_modified(const struct mg_connection *conn,
  8289. const struct mg_file_stat *filestat)
  8290. {
  8291. char etag[64];
  8292. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8293. const char *inm = mg_get_header(conn, "If-None-Match");
  8294. construct_etag(etag, sizeof(etag), filestat);
  8295. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8296. || ((ims != NULL)
  8297. && (filestat->last_modified <= parse_date_string(ims)));
  8298. }
  8299. #endif /* !NO_CACHING */
  8300. #if !defined(NO_CGI) || !defined(NO_FILES)
  8301. static int
  8302. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8303. {
  8304. const char *expect, *body;
  8305. char buf[MG_BUF_LEN];
  8306. int to_read, nread, success = 0;
  8307. int64_t buffered_len;
  8308. double timeout = -1.0;
  8309. if (!conn) {
  8310. return 0;
  8311. }
  8312. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  8313. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8314. }
  8315. expect = mg_get_header(conn, "Expect");
  8316. /* assert(fp != NULL); */
  8317. if (!fp) {
  8318. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8319. return 0;
  8320. }
  8321. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8322. /* Content length is not specified by the client. */
  8323. mg_send_http_error(conn,
  8324. 411,
  8325. "%s",
  8326. "Error: Client did not specify content length");
  8327. } else if ((expect != NULL)
  8328. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8329. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8330. */
  8331. mg_send_http_error(conn,
  8332. 417,
  8333. "Error: Can not fulfill expectation %s",
  8334. expect);
  8335. } else {
  8336. if (expect != NULL) {
  8337. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8338. conn->status_code = 100;
  8339. } else {
  8340. conn->status_code = 200;
  8341. }
  8342. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8343. - conn->consumed_content;
  8344. /* assert(buffered_len >= 0); */
  8345. /* assert(conn->consumed_content == 0); */
  8346. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8347. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8348. return 0;
  8349. }
  8350. if (buffered_len > 0) {
  8351. if ((int64_t)buffered_len > conn->content_len) {
  8352. buffered_len = (int)conn->content_len;
  8353. }
  8354. body = conn->buf + conn->request_len + conn->consumed_content;
  8355. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8356. conn->consumed_content += buffered_len;
  8357. }
  8358. nread = 0;
  8359. while (conn->consumed_content < conn->content_len) {
  8360. to_read = sizeof(buf);
  8361. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8362. to_read = (int)(conn->content_len - conn->consumed_content);
  8363. }
  8364. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8365. if (nread == -2) {
  8366. /* error */
  8367. break;
  8368. }
  8369. if (nread > 0) {
  8370. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  8371. break;
  8372. }
  8373. }
  8374. conn->consumed_content += nread;
  8375. }
  8376. if (conn->consumed_content == conn->content_len) {
  8377. success = (nread >= 0);
  8378. }
  8379. /* Each error code path in this function must send an error */
  8380. if (!success) {
  8381. /* NOTE: Maybe some data has already been sent. */
  8382. /* TODO (low): If some data has been sent, a correct error
  8383. * reply can no longer be sent, so just close the connection */
  8384. mg_send_http_error(conn, 500, "%s", "");
  8385. }
  8386. }
  8387. return success;
  8388. }
  8389. #endif
  8390. #if !defined(NO_CGI)
  8391. /* This structure helps to create an environment for the spawned CGI
  8392. * program.
  8393. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8394. * last element must be NULL.
  8395. * However, on Windows there is a requirement that all these
  8396. * VARIABLE=VALUE\0
  8397. * strings must reside in a contiguous buffer. The end of the buffer is
  8398. * marked by two '\0' characters.
  8399. * We satisfy both worlds: we create an envp array (which is vars), all
  8400. * entries are actually pointers inside buf. */
  8401. struct cgi_environment {
  8402. struct mg_connection *conn;
  8403. /* Data block */
  8404. char *buf; /* Environment buffer */
  8405. size_t buflen; /* Space available in buf */
  8406. size_t bufused; /* Space taken in buf */
  8407. /* Index block */
  8408. char **var; /* char **envp */
  8409. size_t varlen; /* Number of variables available in var */
  8410. size_t varused; /* Number of variables stored in var */
  8411. };
  8412. static void addenv(struct cgi_environment *env,
  8413. PRINTF_FORMAT_STRING(const char *fmt),
  8414. ...) PRINTF_ARGS(2, 3);
  8415. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8416. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8417. static void
  8418. addenv(struct cgi_environment *env, const char *fmt, ...)
  8419. {
  8420. size_t n, space;
  8421. int truncated = 0;
  8422. char *added;
  8423. va_list ap;
  8424. /* Calculate how much space is left in the buffer */
  8425. space = (env->buflen - env->bufused);
  8426. /* Calculate an estimate for the required space */
  8427. n = strlen(fmt) + 2 + 128;
  8428. do {
  8429. if (space <= n) {
  8430. /* Allocate new buffer */
  8431. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8432. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  8433. if (!added) {
  8434. /* Out of memory */
  8435. mg_cry(env->conn,
  8436. "%s: Cannot allocate memory for CGI variable [%s]",
  8437. __func__,
  8438. fmt);
  8439. return;
  8440. }
  8441. env->buf = added;
  8442. env->buflen = n;
  8443. space = (env->buflen - env->bufused);
  8444. }
  8445. /* Make a pointer to the free space int the buffer */
  8446. added = env->buf + env->bufused;
  8447. /* Copy VARIABLE=VALUE\0 string into the free space */
  8448. va_start(ap, fmt);
  8449. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8450. va_end(ap);
  8451. /* Do not add truncated strings to the environment */
  8452. if (truncated) {
  8453. /* Reallocate the buffer */
  8454. space = 0;
  8455. n = 1;
  8456. }
  8457. } while (truncated);
  8458. /* Calculate number of bytes added to the environment */
  8459. n = strlen(added) + 1;
  8460. env->bufused += n;
  8461. /* Now update the variable index */
  8462. space = (env->varlen - env->varused);
  8463. if (space < 2) {
  8464. mg_cry(env->conn,
  8465. "%s: Cannot register CGI variable [%s]",
  8466. __func__,
  8467. fmt);
  8468. return;
  8469. }
  8470. /* Append a pointer to the added string into the envp array */
  8471. env->var[env->varused] = added;
  8472. env->varused++;
  8473. }
  8474. /* Return 0 on success, non-zero if an error occurs. */
  8475. static int
  8476. prepare_cgi_environment(struct mg_connection *conn,
  8477. const char *prog,
  8478. struct cgi_environment *env)
  8479. {
  8480. const char *s;
  8481. struct vec var_vec;
  8482. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8483. int i, truncated, uri_len;
  8484. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8485. return -1;
  8486. }
  8487. env->conn = conn;
  8488. env->buflen = CGI_ENVIRONMENT_SIZE;
  8489. env->bufused = 0;
  8490. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  8491. if (env->buf == NULL) {
  8492. mg_cry(conn,
  8493. "%s: Not enough memory for environmental buffer",
  8494. __func__);
  8495. return -1;
  8496. }
  8497. env->varlen = MAX_CGI_ENVIR_VARS;
  8498. env->varused = 0;
  8499. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  8500. if (env->var == NULL) {
  8501. mg_cry(conn,
  8502. "%s: Not enough memory for environmental variables",
  8503. __func__);
  8504. mg_free(env->buf);
  8505. return -1;
  8506. }
  8507. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  8508. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8509. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8510. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8511. /* Prepare the environment block */
  8512. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8513. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8514. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8515. #if defined(USE_IPV6)
  8516. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8517. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8518. } else
  8519. #endif
  8520. {
  8521. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8522. }
  8523. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8524. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8525. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8526. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8527. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8528. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8529. /* SCRIPT_NAME */
  8530. uri_len = (int)strlen(conn->request_info.local_uri);
  8531. if (conn->path_info == NULL) {
  8532. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8533. /* URI: /path_to_script/script.cgi */
  8534. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8535. } else {
  8536. /* URI: /path_to_script/ ... using index.cgi */
  8537. const char *index_file = strrchr(prog, '/');
  8538. if (index_file) {
  8539. addenv(env,
  8540. "SCRIPT_NAME=%s%s",
  8541. conn->request_info.local_uri,
  8542. index_file + 1);
  8543. }
  8544. }
  8545. } else {
  8546. /* URI: /path_to_script/script.cgi/path_info */
  8547. addenv(env,
  8548. "SCRIPT_NAME=%.*s",
  8549. uri_len - (int)strlen(conn->path_info),
  8550. conn->request_info.local_uri);
  8551. }
  8552. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8553. if (conn->path_info == NULL) {
  8554. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8555. } else {
  8556. addenv(env,
  8557. "PATH_TRANSLATED=%s%s",
  8558. conn->ctx->config[DOCUMENT_ROOT],
  8559. conn->path_info);
  8560. }
  8561. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8562. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8563. addenv(env, "CONTENT_TYPE=%s", s);
  8564. }
  8565. if (conn->request_info.query_string != NULL) {
  8566. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8567. }
  8568. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8569. addenv(env, "CONTENT_LENGTH=%s", s);
  8570. }
  8571. if ((s = getenv("PATH")) != NULL) {
  8572. addenv(env, "PATH=%s", s);
  8573. }
  8574. if (conn->path_info != NULL) {
  8575. addenv(env, "PATH_INFO=%s", conn->path_info);
  8576. }
  8577. if (conn->status_code > 0) {
  8578. /* CGI error handler should show the status code */
  8579. addenv(env, "STATUS=%d", conn->status_code);
  8580. }
  8581. #if defined(_WIN32)
  8582. if ((s = getenv("COMSPEC")) != NULL) {
  8583. addenv(env, "COMSPEC=%s", s);
  8584. }
  8585. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8586. addenv(env, "SYSTEMROOT=%s", s);
  8587. }
  8588. if ((s = getenv("SystemDrive")) != NULL) {
  8589. addenv(env, "SystemDrive=%s", s);
  8590. }
  8591. if ((s = getenv("ProgramFiles")) != NULL) {
  8592. addenv(env, "ProgramFiles=%s", s);
  8593. }
  8594. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8595. addenv(env, "ProgramFiles(x86)=%s", s);
  8596. }
  8597. #else
  8598. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8599. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8600. }
  8601. #endif /* _WIN32 */
  8602. if ((s = getenv("PERLLIB")) != NULL) {
  8603. addenv(env, "PERLLIB=%s", s);
  8604. }
  8605. if (conn->request_info.remote_user != NULL) {
  8606. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8607. addenv(env, "%s", "AUTH_TYPE=Digest");
  8608. }
  8609. /* Add all headers as HTTP_* variables */
  8610. for (i = 0; i < conn->request_info.num_headers; i++) {
  8611. (void)mg_snprintf(conn,
  8612. &truncated,
  8613. http_var_name,
  8614. sizeof(http_var_name),
  8615. "HTTP_%s",
  8616. conn->request_info.http_headers[i].name);
  8617. if (truncated) {
  8618. mg_cry(conn,
  8619. "%s: HTTP header variable too long [%s]",
  8620. __func__,
  8621. conn->request_info.http_headers[i].name);
  8622. continue;
  8623. }
  8624. /* Convert variable name into uppercase, and change - to _ */
  8625. for (p = http_var_name; *p != '\0'; p++) {
  8626. if (*p == '-') {
  8627. *p = '_';
  8628. }
  8629. *p = (char)toupper(*(unsigned char *)p);
  8630. }
  8631. addenv(env,
  8632. "%s=%s",
  8633. http_var_name,
  8634. conn->request_info.http_headers[i].value);
  8635. }
  8636. /* Add user-specified variables */
  8637. s = conn->ctx->config[CGI_ENVIRONMENT];
  8638. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8639. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8640. }
  8641. env->var[env->varused] = NULL;
  8642. env->buf[env->bufused] = '\0';
  8643. return 0;
  8644. }
  8645. static void
  8646. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8647. {
  8648. char *buf;
  8649. size_t buflen;
  8650. int headers_len, data_len, i, truncated;
  8651. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8652. const char *status, *status_text, *connection_state;
  8653. char *pbuf, dir[PATH_MAX], *p;
  8654. struct mg_request_info ri;
  8655. struct cgi_environment blk;
  8656. FILE *in = NULL, *out = NULL, *err = NULL;
  8657. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8658. pid_t pid = (pid_t)-1;
  8659. if (conn == NULL) {
  8660. return;
  8661. }
  8662. buf = NULL;
  8663. buflen = 16384;
  8664. i = prepare_cgi_environment(conn, prog, &blk);
  8665. if (i != 0) {
  8666. blk.buf = NULL;
  8667. blk.var = NULL;
  8668. goto done;
  8669. }
  8670. /* CGI must be executed in its own directory. 'dir' must point to the
  8671. * directory containing executable program, 'p' must point to the
  8672. * executable program name relative to 'dir'. */
  8673. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8674. if (truncated) {
  8675. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  8676. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8677. goto done;
  8678. }
  8679. if ((p = strrchr(dir, '/')) != NULL) {
  8680. *p++ = '\0';
  8681. } else {
  8682. dir[0] = '.';
  8683. dir[1] = '\0';
  8684. p = (char *)prog;
  8685. }
  8686. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8687. status = strerror(ERRNO);
  8688. mg_cry(conn,
  8689. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8690. prog,
  8691. status);
  8692. mg_send_http_error(conn,
  8693. 500,
  8694. "Error: Cannot create CGI pipe: %s",
  8695. status);
  8696. goto done;
  8697. }
  8698. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  8699. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8700. if (pid == (pid_t)-1) {
  8701. status = strerror(ERRNO);
  8702. mg_cry(conn,
  8703. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8704. prog,
  8705. status);
  8706. mg_send_http_error(conn,
  8707. 500,
  8708. "Error: Cannot spawn CGI process [%s]: %s",
  8709. prog,
  8710. status);
  8711. goto done;
  8712. }
  8713. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  8714. */
  8715. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8716. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8717. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8718. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8719. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8720. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8721. /* Parent closes only one side of the pipes.
  8722. * If we don't mark them as closed, close() attempt before
  8723. * return from this function throws an exception on Windows.
  8724. * Windows does not like when closed descriptor is closed again. */
  8725. (void)close(fdin[0]);
  8726. (void)close(fdout[1]);
  8727. (void)close(fderr[1]);
  8728. fdin[0] = fdout[1] = fderr[1] = -1;
  8729. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8730. status = strerror(ERRNO);
  8731. mg_cry(conn,
  8732. "Error: CGI program \"%s\": Can not open stdin: %s",
  8733. prog,
  8734. status);
  8735. mg_send_http_error(conn,
  8736. 500,
  8737. "Error: CGI can not open fdin\nfopen: %s",
  8738. status);
  8739. goto done;
  8740. }
  8741. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8742. status = strerror(ERRNO);
  8743. mg_cry(conn,
  8744. "Error: CGI program \"%s\": Can not open stdout: %s",
  8745. prog,
  8746. status);
  8747. mg_send_http_error(conn,
  8748. 500,
  8749. "Error: CGI can not open fdout\nfopen: %s",
  8750. status);
  8751. goto done;
  8752. }
  8753. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8754. status = strerror(ERRNO);
  8755. mg_cry(conn,
  8756. "Error: CGI program \"%s\": Can not open stderr: %s",
  8757. prog,
  8758. status);
  8759. mg_send_http_error(conn,
  8760. 500,
  8761. "Error: CGI can not open fdout\nfopen: %s",
  8762. status);
  8763. goto done;
  8764. }
  8765. setbuf(in, NULL);
  8766. setbuf(out, NULL);
  8767. setbuf(err, NULL);
  8768. fout.access.fp = out;
  8769. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  8770. DEBUG_TRACE("CGI: send body data (%lli)\n",
  8771. (signed long long)conn->request_info.content_length);
  8772. /* This is a POST/PUT request, or another request with body data. */
  8773. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8774. /* Error sending the body data */
  8775. mg_cry(conn,
  8776. "Error: CGI program \"%s\": Forward body data failed",
  8777. prog);
  8778. goto done;
  8779. }
  8780. }
  8781. /* Close so child gets an EOF. */
  8782. fclose(in);
  8783. in = NULL;
  8784. fdin[1] = -1;
  8785. /* Now read CGI reply into a buffer. We need to set correct
  8786. * status code, thus we need to see all HTTP headers first.
  8787. * Do not send anything back to client, until we buffer in all
  8788. * HTTP headers. */
  8789. data_len = 0;
  8790. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  8791. if (buf == NULL) {
  8792. mg_send_http_error(conn,
  8793. 500,
  8794. "Error: Not enough memory for CGI buffer (%u bytes)",
  8795. (unsigned int)buflen);
  8796. mg_cry(conn,
  8797. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  8798. "bytes)",
  8799. prog,
  8800. (unsigned int)buflen);
  8801. goto done;
  8802. }
  8803. DEBUG_TRACE("CGI: %s", "wait for response");
  8804. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  8805. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  8806. if (headers_len <= 0) {
  8807. /* Could not parse the CGI response. Check if some error message on
  8808. * stderr. */
  8809. i = pull_all(err, conn, buf, (int)buflen);
  8810. if (i > 0) {
  8811. mg_cry(conn,
  8812. "Error: CGI program \"%s\" sent error "
  8813. "message: [%.*s]",
  8814. prog,
  8815. i,
  8816. buf);
  8817. mg_send_http_error(conn,
  8818. 500,
  8819. "Error: CGI program \"%s\" sent error "
  8820. "message: [%.*s]",
  8821. prog,
  8822. i,
  8823. buf);
  8824. } else {
  8825. mg_cry(conn,
  8826. "Error: CGI program sent malformed or too big "
  8827. "(>%u bytes) HTTP headers: [%.*s]",
  8828. (unsigned)buflen,
  8829. data_len,
  8830. buf);
  8831. mg_send_http_error(conn,
  8832. 500,
  8833. "Error: CGI program sent malformed or too big "
  8834. "(>%u bytes) HTTP headers: [%.*s]",
  8835. (unsigned)buflen,
  8836. data_len,
  8837. buf);
  8838. }
  8839. goto done;
  8840. }
  8841. pbuf = buf;
  8842. buf[headers_len - 1] = '\0';
  8843. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  8844. /* Make up and send the status line */
  8845. status_text = "OK";
  8846. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  8847. != NULL) {
  8848. conn->status_code = atoi(status);
  8849. status_text = status;
  8850. while (isdigit(*(const unsigned char *)status_text)
  8851. || *status_text == ' ') {
  8852. status_text++;
  8853. }
  8854. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  8855. != NULL) {
  8856. conn->status_code = 302;
  8857. } else {
  8858. conn->status_code = 200;
  8859. }
  8860. connection_state =
  8861. get_header(ri.http_headers, ri.num_headers, "Connection");
  8862. if (!header_has_option(connection_state, "keep-alive")) {
  8863. conn->must_close = 1;
  8864. }
  8865. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  8866. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  8867. /* Send headers */
  8868. for (i = 0; i < ri.num_headers; i++) {
  8869. mg_printf(conn,
  8870. "%s: %s\r\n",
  8871. ri.http_headers[i].name,
  8872. ri.http_headers[i].value);
  8873. }
  8874. mg_write(conn, "\r\n", 2);
  8875. /* Send chunk of data that may have been read after the headers */
  8876. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  8877. /* Read the rest of CGI output and send to the client */
  8878. send_file_data(conn, &fout, 0, INT64_MAX);
  8879. DEBUG_TRACE("CGI: %s", "all data sent");
  8880. done:
  8881. mg_free(blk.var);
  8882. mg_free(blk.buf);
  8883. if (pid != (pid_t)-1) {
  8884. kill(pid, SIGKILL);
  8885. #if !defined(_WIN32)
  8886. {
  8887. int st;
  8888. while (waitpid(pid, &st, 0) != -1)
  8889. ; /* clean zombies */
  8890. }
  8891. #endif
  8892. }
  8893. if (fdin[0] != -1) {
  8894. close(fdin[0]);
  8895. }
  8896. if (fdout[1] != -1) {
  8897. close(fdout[1]);
  8898. }
  8899. if (in != NULL) {
  8900. fclose(in);
  8901. } else if (fdin[1] != -1) {
  8902. close(fdin[1]);
  8903. }
  8904. if (out != NULL) {
  8905. fclose(out);
  8906. } else if (fdout[0] != -1) {
  8907. close(fdout[0]);
  8908. }
  8909. if (err != NULL) {
  8910. fclose(err);
  8911. } else if (fderr[0] != -1) {
  8912. close(fderr[0]);
  8913. }
  8914. if (buf != NULL) {
  8915. mg_free(buf);
  8916. }
  8917. }
  8918. #endif /* !NO_CGI */
  8919. #if !defined(NO_FILES)
  8920. static void
  8921. mkcol(struct mg_connection *conn, const char *path)
  8922. {
  8923. int rc, body_len;
  8924. struct de de;
  8925. char date[64];
  8926. time_t curtime = time(NULL);
  8927. if (conn == NULL) {
  8928. return;
  8929. }
  8930. /* TODO (mid): Check the mg_send_http_error situations in this function
  8931. */
  8932. memset(&de.file, 0, sizeof(de.file));
  8933. if (!mg_stat(conn, path, &de.file)) {
  8934. mg_cry(conn,
  8935. "%s: mg_stat(%s) failed: %s",
  8936. __func__,
  8937. path,
  8938. strerror(ERRNO));
  8939. }
  8940. if (de.file.last_modified) {
  8941. /* TODO (mid): This check does not seem to make any sense ! */
  8942. /* TODO (mid): Add a webdav unit test first, before changing
  8943. * anything here. */
  8944. mg_send_http_error(
  8945. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8946. return;
  8947. }
  8948. body_len = conn->data_len - conn->request_len;
  8949. if (body_len > 0) {
  8950. mg_send_http_error(
  8951. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8952. return;
  8953. }
  8954. rc = mg_mkdir(conn, path, 0755);
  8955. if (rc == 0) {
  8956. conn->status_code = 201;
  8957. gmt_time_string(date, sizeof(date), &curtime);
  8958. mg_printf(conn,
  8959. "HTTP/1.1 %d Created\r\n"
  8960. "Date: %s\r\n",
  8961. conn->status_code,
  8962. date);
  8963. send_static_cache_header(conn);
  8964. send_additional_header(conn);
  8965. mg_printf(conn,
  8966. "Content-Length: 0\r\n"
  8967. "Connection: %s\r\n\r\n",
  8968. suggest_connection_header(conn));
  8969. } else if (rc == -1) {
  8970. if (errno == EEXIST) {
  8971. mg_send_http_error(
  8972. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8973. } else if (errno == EACCES) {
  8974. mg_send_http_error(
  8975. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8976. } else if (errno == ENOENT) {
  8977. mg_send_http_error(
  8978. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8979. } else {
  8980. mg_send_http_error(
  8981. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8982. }
  8983. }
  8984. }
  8985. static void
  8986. put_file(struct mg_connection *conn, const char *path)
  8987. {
  8988. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8989. const char *range;
  8990. int64_t r1, r2;
  8991. int rc;
  8992. char date[64];
  8993. time_t curtime = time(NULL);
  8994. if (conn == NULL) {
  8995. return;
  8996. }
  8997. if (mg_stat(conn, path, &file.stat)) {
  8998. /* File already exists */
  8999. conn->status_code = 200;
  9000. if (file.stat.is_directory) {
  9001. /* This is an already existing directory,
  9002. * so there is nothing to do for the server. */
  9003. rc = 0;
  9004. } else {
  9005. /* File exists and is not a directory. */
  9006. /* Can it be replaced? */
  9007. if (file.access.membuf != NULL) {
  9008. /* This is an "in-memory" file, that can not be replaced */
  9009. mg_send_http_error(conn,
  9010. 405,
  9011. "Error: Put not possible\nReplacing %s "
  9012. "is not supported",
  9013. path);
  9014. return;
  9015. }
  9016. /* Check if the server may write this file */
  9017. if (access(path, W_OK) == 0) {
  9018. /* Access granted */
  9019. conn->status_code = 200;
  9020. rc = 1;
  9021. } else {
  9022. mg_send_http_error(
  9023. conn,
  9024. 403,
  9025. "Error: Put not possible\nReplacing %s is not allowed",
  9026. path);
  9027. return;
  9028. }
  9029. }
  9030. } else {
  9031. /* File should be created */
  9032. conn->status_code = 201;
  9033. rc = put_dir(conn, path);
  9034. }
  9035. if (rc == 0) {
  9036. /* put_dir returns 0 if path is a directory */
  9037. gmt_time_string(date, sizeof(date), &curtime);
  9038. mg_printf(conn,
  9039. "HTTP/1.1 %d %s\r\n",
  9040. conn->status_code,
  9041. mg_get_response_code_text(NULL, conn->status_code));
  9042. send_no_cache_header(conn);
  9043. send_additional_header(conn);
  9044. mg_printf(conn,
  9045. "Date: %s\r\n"
  9046. "Content-Length: 0\r\n"
  9047. "Connection: %s\r\n\r\n",
  9048. date,
  9049. suggest_connection_header(conn));
  9050. /* Request to create a directory has been fulfilled successfully.
  9051. * No need to put a file. */
  9052. return;
  9053. }
  9054. if (rc == -1) {
  9055. /* put_dir returns -1 if the path is too long */
  9056. mg_send_http_error(conn,
  9057. 414,
  9058. "Error: Path too long\nput_dir(%s): %s",
  9059. path,
  9060. strerror(ERRNO));
  9061. return;
  9062. }
  9063. if (rc == -2) {
  9064. /* put_dir returns -2 if the directory can not be created */
  9065. mg_send_http_error(conn,
  9066. 500,
  9067. "Error: Can not create directory\nput_dir(%s): %s",
  9068. path,
  9069. strerror(ERRNO));
  9070. return;
  9071. }
  9072. /* A file should be created or overwritten. */
  9073. /* Currently CivetWeb does not nead read+write access. */
  9074. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9075. || file.access.fp == NULL) {
  9076. (void)mg_fclose(&file.access);
  9077. mg_send_http_error(conn,
  9078. 500,
  9079. "Error: Can not create file\nfopen(%s): %s",
  9080. path,
  9081. strerror(ERRNO));
  9082. return;
  9083. }
  9084. fclose_on_exec(&file.access, conn);
  9085. range = mg_get_header(conn, "Content-Range");
  9086. r1 = r2 = 0;
  9087. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9088. conn->status_code = 206; /* Partial content */
  9089. fseeko(file.access.fp, r1, SEEK_SET);
  9090. }
  9091. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9092. /* forward_body_data failed.
  9093. * The error code has already been sent to the client,
  9094. * and conn->status_code is already set. */
  9095. (void)mg_fclose(&file.access);
  9096. return;
  9097. }
  9098. if (mg_fclose(&file.access) != 0) {
  9099. /* fclose failed. This might have different reasons, but a likely
  9100. * one is "no space on disk", http 507. */
  9101. conn->status_code = 507;
  9102. }
  9103. gmt_time_string(date, sizeof(date), &curtime);
  9104. mg_printf(conn,
  9105. "HTTP/1.1 %d %s\r\n",
  9106. conn->status_code,
  9107. mg_get_response_code_text(NULL, conn->status_code));
  9108. send_no_cache_header(conn);
  9109. send_additional_header(conn);
  9110. mg_printf(conn,
  9111. "Date: %s\r\n"
  9112. "Content-Length: 0\r\n"
  9113. "Connection: %s\r\n\r\n",
  9114. date,
  9115. suggest_connection_header(conn));
  9116. }
  9117. static void
  9118. delete_file(struct mg_connection *conn, const char *path)
  9119. {
  9120. struct de de;
  9121. memset(&de.file, 0, sizeof(de.file));
  9122. if (!mg_stat(conn, path, &de.file)) {
  9123. /* mg_stat returns 0 if the file does not exist */
  9124. mg_send_http_error(conn,
  9125. 404,
  9126. "Error: Cannot delete file\nFile %s not found",
  9127. path);
  9128. return;
  9129. }
  9130. #if 0 /* Ignore if a file in memory is inside a folder */
  9131. if (de.access.membuf != NULL) {
  9132. /* the file is cached in memory */
  9133. mg_send_http_error(
  9134. conn,
  9135. 405,
  9136. "Error: Delete not possible\nDeleting %s is not supported",
  9137. path);
  9138. return;
  9139. }
  9140. #endif
  9141. if (de.file.is_directory) {
  9142. if (remove_directory(conn, path)) {
  9143. /* Delete is successful: Return 204 without content. */
  9144. mg_send_http_error(conn, 204, "%s", "");
  9145. } else {
  9146. /* Delete is not successful: Return 500 (Server error). */
  9147. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9148. }
  9149. return;
  9150. }
  9151. /* This is an existing file (not a directory).
  9152. * Check if write permission is granted. */
  9153. if (access(path, W_OK) != 0) {
  9154. /* File is read only */
  9155. mg_send_http_error(
  9156. conn,
  9157. 403,
  9158. "Error: Delete not possible\nDeleting %s is not allowed",
  9159. path);
  9160. return;
  9161. }
  9162. /* Try to delete it. */
  9163. if (mg_remove(conn, path) == 0) {
  9164. /* Delete was successful: Return 204 without content. */
  9165. mg_send_http_error(conn, 204, "%s", "");
  9166. } else {
  9167. /* Delete not successful (file locked). */
  9168. mg_send_http_error(conn,
  9169. 423,
  9170. "Error: Cannot delete file\nremove(%s): %s",
  9171. path,
  9172. strerror(ERRNO));
  9173. }
  9174. }
  9175. #endif /* !NO_FILES */
  9176. static void
  9177. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9178. static void
  9179. do_ssi_include(struct mg_connection *conn,
  9180. const char *ssi,
  9181. char *tag,
  9182. int include_level)
  9183. {
  9184. char file_name[MG_BUF_LEN], path[512], *p;
  9185. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9186. size_t len;
  9187. int truncated = 0;
  9188. if (conn == NULL) {
  9189. return;
  9190. }
  9191. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9192. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9193. * always < MG_BUF_LEN. */
  9194. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9195. /* File name is relative to the webserver root */
  9196. file_name[511] = 0;
  9197. (void)mg_snprintf(conn,
  9198. &truncated,
  9199. path,
  9200. sizeof(path),
  9201. "%s/%s",
  9202. conn->ctx->config[DOCUMENT_ROOT],
  9203. file_name);
  9204. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9205. /* File name is relative to the webserver working directory
  9206. * or it is absolute system path */
  9207. file_name[511] = 0;
  9208. (void)
  9209. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9210. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9211. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9212. /* File name is relative to the currect document */
  9213. file_name[511] = 0;
  9214. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9215. if (!truncated) {
  9216. if ((p = strrchr(path, '/')) != NULL) {
  9217. p[1] = '\0';
  9218. }
  9219. len = strlen(path);
  9220. (void)mg_snprintf(conn,
  9221. &truncated,
  9222. path + len,
  9223. sizeof(path) - len,
  9224. "%s",
  9225. file_name);
  9226. }
  9227. } else {
  9228. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  9229. return;
  9230. }
  9231. if (truncated) {
  9232. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  9233. return;
  9234. }
  9235. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9236. mg_cry(conn,
  9237. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9238. tag,
  9239. path,
  9240. strerror(ERRNO));
  9241. } else {
  9242. fclose_on_exec(&file.access, conn);
  9243. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9244. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9245. path) > 0) {
  9246. send_ssi_file(conn, path, &file, include_level + 1);
  9247. } else {
  9248. send_file_data(conn, &file, 0, INT64_MAX);
  9249. }
  9250. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9251. }
  9252. }
  9253. #if !defined(NO_POPEN)
  9254. static void
  9255. do_ssi_exec(struct mg_connection *conn, char *tag)
  9256. {
  9257. char cmd[1024] = "";
  9258. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9259. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9260. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  9261. } else {
  9262. cmd[1023] = 0;
  9263. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9264. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  9265. } else {
  9266. send_file_data(conn, &file, 0, INT64_MAX);
  9267. pclose(file.access.fp);
  9268. }
  9269. }
  9270. }
  9271. #endif /* !NO_POPEN */
  9272. static int
  9273. mg_fgetc(struct mg_file *filep, int offset)
  9274. {
  9275. if (filep == NULL) {
  9276. return EOF;
  9277. }
  9278. if ((filep->access.membuf != NULL) && (offset >= 0)
  9279. && (((unsigned int)(offset)) < filep->stat.size)) {
  9280. return ((const unsigned char *)filep->access.membuf)[offset];
  9281. } else if (filep->access.fp != NULL) {
  9282. return fgetc(filep->access.fp);
  9283. } else {
  9284. return EOF;
  9285. }
  9286. }
  9287. static void
  9288. send_ssi_file(struct mg_connection *conn,
  9289. const char *path,
  9290. struct mg_file *filep,
  9291. int include_level)
  9292. {
  9293. char buf[MG_BUF_LEN];
  9294. int ch, offset, len, in_tag, in_ssi_tag;
  9295. if (include_level > 10) {
  9296. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  9297. return;
  9298. }
  9299. in_tag = in_ssi_tag = len = offset = 0;
  9300. /* Read file, byte by byte, and look for SSI include tags */
  9301. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9302. if (in_tag) {
  9303. /* We are in a tag, either SSI tag or html tag */
  9304. if (ch == '>') {
  9305. /* Tag is closing */
  9306. buf[len++] = '>';
  9307. if (in_ssi_tag) {
  9308. /* Handle SSI tag */
  9309. buf[len] = 0;
  9310. if (!memcmp(buf + 5, "include", 7)) {
  9311. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9312. #if !defined(NO_POPEN)
  9313. } else if (!memcmp(buf + 5, "exec", 4)) {
  9314. do_ssi_exec(conn, buf + 9);
  9315. #endif /* !NO_POPEN */
  9316. } else {
  9317. mg_cry(conn,
  9318. "%s: unknown SSI "
  9319. "command: \"%s\"",
  9320. path,
  9321. buf);
  9322. }
  9323. len = 0;
  9324. in_ssi_tag = in_tag = 0;
  9325. } else {
  9326. /* Not an SSI tag */
  9327. /* Flush buffer */
  9328. (void)mg_write(conn, buf, (size_t)len);
  9329. len = 0;
  9330. in_tag = 0;
  9331. }
  9332. } else {
  9333. /* Tag is still open */
  9334. buf[len++] = (char)(ch & 0xff);
  9335. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9336. /* All SSI tags start with <!--# */
  9337. in_ssi_tag = 1;
  9338. }
  9339. if ((len + 2) > (int)sizeof(buf)) {
  9340. /* Tag to long for buffer */
  9341. mg_cry(conn, "%s: tag is too large", path);
  9342. return;
  9343. }
  9344. }
  9345. } else {
  9346. /* We are not in a tag yet. */
  9347. if (ch == '<') {
  9348. /* Tag is opening */
  9349. in_tag = 1;
  9350. /* Flush current buffer */
  9351. (void)mg_write(conn, buf, (size_t)len);
  9352. /* Store the < */
  9353. len = 1;
  9354. buf[0] = '<';
  9355. } else {
  9356. /* No Tag */
  9357. /* Add data to buffer */
  9358. buf[len++] = (char)(ch & 0xff);
  9359. /* Flush if buffer is full */
  9360. if (len == (int)sizeof(buf)) {
  9361. mg_write(conn, buf, (size_t)len);
  9362. len = 0;
  9363. }
  9364. }
  9365. }
  9366. }
  9367. /* Send the rest of buffered data */
  9368. if (len > 0) {
  9369. mg_write(conn, buf, (size_t)len);
  9370. }
  9371. }
  9372. static void
  9373. handle_ssi_file_request(struct mg_connection *conn,
  9374. const char *path,
  9375. struct mg_file *filep)
  9376. {
  9377. char date[64];
  9378. time_t curtime = time(NULL);
  9379. const char *cors1, *cors2, *cors3;
  9380. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9381. return;
  9382. }
  9383. if (mg_get_header(conn, "Origin")) {
  9384. /* Cross-origin resource sharing (CORS). */
  9385. cors1 = "Access-Control-Allow-Origin: ";
  9386. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9387. cors3 = "\r\n";
  9388. } else {
  9389. cors1 = cors2 = cors3 = "";
  9390. }
  9391. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9392. /* File exists (precondition for calling this function),
  9393. * but can not be opened by the server. */
  9394. mg_send_http_error(conn,
  9395. 500,
  9396. "Error: Cannot read file\nfopen(%s): %s",
  9397. path,
  9398. strerror(ERRNO));
  9399. } else {
  9400. conn->must_close = 1;
  9401. gmt_time_string(date, sizeof(date), &curtime);
  9402. fclose_on_exec(&filep->access, conn);
  9403. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9404. send_no_cache_header(conn);
  9405. send_additional_header(conn);
  9406. mg_printf(conn,
  9407. "%s%s%s"
  9408. "Date: %s\r\n"
  9409. "Content-Type: text/html\r\n"
  9410. "Connection: %s\r\n\r\n",
  9411. cors1,
  9412. cors2,
  9413. cors3,
  9414. date,
  9415. suggest_connection_header(conn));
  9416. send_ssi_file(conn, path, filep, 0);
  9417. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9418. }
  9419. }
  9420. #if !defined(NO_FILES)
  9421. static void
  9422. send_options(struct mg_connection *conn)
  9423. {
  9424. char date[64];
  9425. time_t curtime = time(NULL);
  9426. if (!conn) {
  9427. return;
  9428. }
  9429. conn->status_code = 200;
  9430. conn->must_close = 1;
  9431. gmt_time_string(date, sizeof(date), &curtime);
  9432. /* We do not set a "Cache-Control" header here, but leave the default.
  9433. * Since browsers do not send an OPTIONS request, we can not test the
  9434. * effect anyway. */
  9435. mg_printf(conn,
  9436. "HTTP/1.1 200 OK\r\n"
  9437. "Date: %s\r\n"
  9438. "Connection: %s\r\n"
  9439. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9440. "PROPFIND, MKCOL\r\n"
  9441. "DAV: 1\r\n",
  9442. date,
  9443. suggest_connection_header(conn));
  9444. send_additional_header(conn);
  9445. mg_printf(conn, "\r\n");
  9446. }
  9447. /* Writes PROPFIND properties for a collection element */
  9448. static void
  9449. print_props(struct mg_connection *conn,
  9450. const char *uri,
  9451. struct mg_file_stat *filep)
  9452. {
  9453. char mtime[64];
  9454. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9455. return;
  9456. }
  9457. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9458. mg_printf(conn,
  9459. "<d:response>"
  9460. "<d:href>%s</d:href>"
  9461. "<d:propstat>"
  9462. "<d:prop>"
  9463. "<d:resourcetype>%s</d:resourcetype>"
  9464. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9465. "<d:getlastmodified>%s</d:getlastmodified>"
  9466. "</d:prop>"
  9467. "<d:status>HTTP/1.1 200 OK</d:status>"
  9468. "</d:propstat>"
  9469. "</d:response>\n",
  9470. uri,
  9471. filep->is_directory ? "<d:collection/>" : "",
  9472. filep->size,
  9473. mtime);
  9474. }
  9475. static int
  9476. print_dav_dir_entry(struct de *de, void *data)
  9477. {
  9478. char href[PATH_MAX];
  9479. int truncated;
  9480. struct mg_connection *conn = (struct mg_connection *)data;
  9481. if (!de || !conn) {
  9482. return -1;
  9483. }
  9484. mg_snprintf(conn,
  9485. &truncated,
  9486. href,
  9487. sizeof(href),
  9488. "%s%s",
  9489. conn->request_info.local_uri,
  9490. de->file_name);
  9491. if (!truncated) {
  9492. size_t href_encoded_size;
  9493. char *href_encoded;
  9494. href_encoded_size = PATH_MAX * 3; /* worst case */
  9495. href_encoded = (char *)mg_malloc(href_encoded_size);
  9496. if (href_encoded == NULL) {
  9497. return -1;
  9498. }
  9499. mg_url_encode(href, href_encoded, href_encoded_size);
  9500. print_props(conn, href_encoded, &de->file);
  9501. mg_free(href_encoded);
  9502. }
  9503. return 0;
  9504. }
  9505. static void
  9506. handle_propfind(struct mg_connection *conn,
  9507. const char *path,
  9508. struct mg_file_stat *filep)
  9509. {
  9510. const char *depth = mg_get_header(conn, "Depth");
  9511. char date[64];
  9512. time_t curtime = time(NULL);
  9513. gmt_time_string(date, sizeof(date), &curtime);
  9514. if (!conn || !path || !filep || !conn->ctx) {
  9515. return;
  9516. }
  9517. conn->must_close = 1;
  9518. conn->status_code = 207;
  9519. mg_printf(conn,
  9520. "HTTP/1.1 207 Multi-Status\r\n"
  9521. "Date: %s\r\n",
  9522. date);
  9523. send_static_cache_header(conn);
  9524. send_additional_header(conn);
  9525. mg_printf(conn,
  9526. "Connection: %s\r\n"
  9527. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9528. suggest_connection_header(conn));
  9529. mg_printf(conn,
  9530. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9531. "<d:multistatus xmlns:d='DAV:'>\n");
  9532. /* Print properties for the requested resource itself */
  9533. print_props(conn, conn->request_info.local_uri, filep);
  9534. /* If it is a directory, print directory entries too if Depth is not 0
  9535. */
  9536. if (filep && filep->is_directory
  9537. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  9538. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9539. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9540. }
  9541. mg_printf(conn, "%s\n", "</d:multistatus>");
  9542. }
  9543. #endif
  9544. void
  9545. mg_lock_connection(struct mg_connection *conn)
  9546. {
  9547. if (conn) {
  9548. (void)pthread_mutex_lock(&conn->mutex);
  9549. }
  9550. }
  9551. void
  9552. mg_unlock_connection(struct mg_connection *conn)
  9553. {
  9554. if (conn) {
  9555. (void)pthread_mutex_unlock(&conn->mutex);
  9556. }
  9557. }
  9558. void
  9559. mg_lock_context(struct mg_context *ctx)
  9560. {
  9561. if (ctx) {
  9562. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9563. }
  9564. }
  9565. void
  9566. mg_unlock_context(struct mg_context *ctx)
  9567. {
  9568. if (ctx) {
  9569. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9570. }
  9571. }
  9572. #if defined(USE_TIMERS)
  9573. #define TIMER_API static
  9574. #include "timer.inl"
  9575. #endif /* USE_TIMERS */
  9576. #ifdef USE_LUA
  9577. #include "mod_lua.inl"
  9578. #endif /* USE_LUA */
  9579. #ifdef USE_DUKTAPE
  9580. #include "mod_duktape.inl"
  9581. #endif /* USE_DUKTAPE */
  9582. #if defined(USE_WEBSOCKET)
  9583. #if !defined(NO_SSL_DL)
  9584. #define SHA_API static
  9585. #include "sha1.inl"
  9586. #endif
  9587. static int
  9588. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9589. {
  9590. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9591. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9592. SHA_CTX sha_ctx;
  9593. int truncated;
  9594. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9595. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9596. if (truncated) {
  9597. conn->must_close = 1;
  9598. return 0;
  9599. }
  9600. SHA1_Init(&sha_ctx);
  9601. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9602. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9603. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9604. mg_printf(conn,
  9605. "HTTP/1.1 101 Switching Protocols\r\n"
  9606. "Upgrade: websocket\r\n"
  9607. "Connection: Upgrade\r\n"
  9608. "Sec-WebSocket-Accept: %s\r\n",
  9609. b64_sha);
  9610. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9611. mg_printf(conn,
  9612. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9613. conn->request_info.acceptedWebSocketSubprotocol);
  9614. } else {
  9615. mg_printf(conn, "%s", "\r\n");
  9616. }
  9617. return 1;
  9618. }
  9619. static void
  9620. read_websocket(struct mg_connection *conn,
  9621. mg_websocket_data_handler ws_data_handler,
  9622. void *callback_data)
  9623. {
  9624. /* Pointer to the beginning of the portion of the incoming websocket
  9625. * message queue.
  9626. * The original websocket upgrade request is never removed, so the queue
  9627. * begins after it. */
  9628. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9629. int n, error, exit_by_callback;
  9630. /* body_len is the length of the entire queue in bytes
  9631. * len is the length of the current message
  9632. * data_len is the length of the current message's data payload
  9633. * header_len is the length of the current message's header */
  9634. size_t i, len, mask_len = 0, header_len, body_len;
  9635. uint64_t data_len = 0;
  9636. /* "The masking key is a 32-bit value chosen at random by the client."
  9637. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9638. */
  9639. unsigned char mask[4];
  9640. /* data points to the place where the message is stored when passed to
  9641. * the
  9642. * websocket_data callback. This is either mem on the stack, or a
  9643. * dynamically allocated buffer if it is too large. */
  9644. unsigned char mem[4096];
  9645. unsigned char mop; /* mask flag and opcode */
  9646. double timeout = -1.0;
  9647. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  9648. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9649. }
  9650. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  9651. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9652. }
  9653. conn->in_websocket_handling = 1;
  9654. mg_set_thread_name("wsock");
  9655. /* Loop continuously, reading messages from the socket, invoking the
  9656. * callback, and waiting repeatedly until an error occurs. */
  9657. while (!conn->ctx->stop_flag && !conn->must_close) {
  9658. header_len = 0;
  9659. assert(conn->data_len >= conn->request_len);
  9660. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9661. len = buf[1] & 127;
  9662. mask_len = (buf[1] & 128) ? 4 : 0;
  9663. if ((len < 126) && (body_len >= mask_len)) {
  9664. /* inline 7-bit length field */
  9665. data_len = len;
  9666. header_len = 2 + mask_len;
  9667. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9668. /* 16-bit length field */
  9669. header_len = 4 + mask_len;
  9670. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9671. } else if (body_len >= (10 + mask_len)) {
  9672. /* 64-bit length field */
  9673. uint32_t l1, l2;
  9674. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9675. memcpy(&l2, &buf[6], 4);
  9676. header_len = 10 + mask_len;
  9677. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9678. if (data_len > (uint64_t)0x7FFF0000ul) {
  9679. /* no can do */
  9680. mg_cry(conn, "websocket out of memory; closing connection");
  9681. break;
  9682. }
  9683. }
  9684. }
  9685. if ((header_len > 0) && (body_len >= header_len)) {
  9686. /* Allocate space to hold websocket payload */
  9687. unsigned char *data = mem;
  9688. if ((size_t)data_len > (size_t)sizeof(mem)) {
  9689. data =
  9690. (unsigned char *)mg_malloc_ctx((size_t)data_len, conn->ctx);
  9691. if (data == NULL) {
  9692. /* Allocation failed, exit the loop and then close the
  9693. * connection */
  9694. mg_cry(conn, "websocket out of memory; closing connection");
  9695. break;
  9696. }
  9697. }
  9698. /* Copy the mask before we shift the queue and destroy it */
  9699. if (mask_len > 0) {
  9700. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9701. } else {
  9702. memset(mask, 0, sizeof(mask));
  9703. }
  9704. /* Read frame payload from the first message in the queue into
  9705. * data and advance the queue by moving the memory in place. */
  9706. assert(body_len >= header_len);
  9707. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  9708. mop = buf[0]; /* current mask and opcode */
  9709. /* Overflow case */
  9710. len = body_len - header_len;
  9711. memcpy(data, buf + header_len, len);
  9712. error = 0;
  9713. while ((uint64_t)len < data_len) {
  9714. n = pull_inner(NULL,
  9715. conn,
  9716. (char *)(data + len),
  9717. (int)(data_len - len),
  9718. timeout);
  9719. if (n <= -2) {
  9720. error = 1;
  9721. break;
  9722. } else if (n > 0) {
  9723. len += (size_t)n;
  9724. } else {
  9725. /* Timeout: should retry */
  9726. /* TODO: retry condition */
  9727. }
  9728. }
  9729. if (error) {
  9730. mg_cry(conn, "Websocket pull failed; closing connection");
  9731. if (data != mem) {
  9732. mg_free(data);
  9733. }
  9734. break;
  9735. }
  9736. conn->data_len = conn->request_len;
  9737. } else {
  9738. mop = buf[0]; /* current mask and opcode, overwritten by
  9739. * memmove() */
  9740. /* Length of the message being read at the front of the
  9741. * queue. Cast to 31 bit is OK, since we limited
  9742. * data_len before. */
  9743. len = (size_t)data_len + header_len;
  9744. /* Copy the data payload into the data pointer for the
  9745. * callback. Cast to 31 bit is OK, since we
  9746. * limited data_len */
  9747. memcpy(data, buf + header_len, (size_t)data_len);
  9748. /* Move the queue forward len bytes */
  9749. memmove(buf, buf + len, body_len - len);
  9750. /* Mark the queue as advanced */
  9751. conn->data_len -= (int)len;
  9752. }
  9753. /* Apply mask if necessary */
  9754. if (mask_len > 0) {
  9755. for (i = 0; i < (size_t)data_len; i++) {
  9756. data[i] ^= mask[i & 3];
  9757. }
  9758. }
  9759. /* Exit the loop if callback signals to exit (server side),
  9760. * or "connection close" opcode received (client side). */
  9761. exit_by_callback = 0;
  9762. if ((ws_data_handler != NULL)
  9763. && !ws_data_handler(conn,
  9764. mop,
  9765. (char *)data,
  9766. (size_t)data_len,
  9767. callback_data)) {
  9768. exit_by_callback = 1;
  9769. }
  9770. if (data != mem) {
  9771. mg_free(data);
  9772. }
  9773. if (exit_by_callback
  9774. || ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9775. /* Opcode == 8, connection close */
  9776. break;
  9777. }
  9778. /* Not breaking the loop, process next websocket frame. */
  9779. } else {
  9780. /* Read from the socket into the next available location in the
  9781. * message queue. */
  9782. n = pull_inner(NULL,
  9783. conn,
  9784. conn->buf + conn->data_len,
  9785. conn->buf_size - conn->data_len,
  9786. timeout);
  9787. if (n <= -2) {
  9788. /* Error, no bytes read */
  9789. break;
  9790. }
  9791. if (n > 0) {
  9792. conn->data_len += n;
  9793. } else {
  9794. /* Timeout: should retry */
  9795. /* TODO: get timeout def */
  9796. }
  9797. }
  9798. }
  9799. mg_set_thread_name("worker");
  9800. conn->in_websocket_handling = 0;
  9801. }
  9802. static int
  9803. mg_websocket_write_exec(struct mg_connection *conn,
  9804. int opcode,
  9805. const char *data,
  9806. size_t dataLen,
  9807. uint32_t masking_key)
  9808. {
  9809. unsigned char header[14];
  9810. size_t headerLen = 1;
  9811. int retval = -1;
  9812. #if defined(__GNUC__) || defined(__MINGW32__)
  9813. /* Disable spurious conversion warning for GCC */
  9814. #pragma GCC diagnostic push
  9815. #pragma GCC diagnostic ignored "-Wconversion"
  9816. #endif
  9817. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  9818. #if defined(__GNUC__) || defined(__MINGW32__)
  9819. #pragma GCC diagnostic pop
  9820. #endif
  9821. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  9822. if (dataLen < 126) {
  9823. /* inline 7-bit length field */
  9824. header[1] = (unsigned char)dataLen;
  9825. headerLen = 2;
  9826. } else if (dataLen <= 0xFFFF) {
  9827. /* 16-bit length field */
  9828. uint16_t len = htons((uint16_t)dataLen);
  9829. header[1] = 126;
  9830. memcpy(header + 2, &len, 2);
  9831. headerLen = 4;
  9832. } else {
  9833. /* 64-bit length field */
  9834. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  9835. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  9836. header[1] = 127;
  9837. memcpy(header + 2, &len1, 4);
  9838. memcpy(header + 6, &len2, 4);
  9839. headerLen = 10;
  9840. }
  9841. if (masking_key) {
  9842. /* add mask */
  9843. header[1] |= 0x80;
  9844. memcpy(header + headerLen, &masking_key, 4);
  9845. headerLen += 4;
  9846. }
  9847. /* Note that POSIX/Winsock's send() is threadsafe
  9848. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  9849. * but mongoose's mg_printf/mg_write is not (because of the loop in
  9850. * push(), although that is only a problem if the packet is large or
  9851. * outgoing buffer is full). */
  9852. /* TODO: Check if this lock should be moved to user land.
  9853. * Currently the server sets this lock for websockets, but
  9854. * not for any other connection. It must be set for every
  9855. * conn read/written by more than one thread, no matter if
  9856. * it is a websocket or regular connection. */
  9857. (void)mg_lock_connection(conn);
  9858. retval = mg_write(conn, header, headerLen);
  9859. if (dataLen > 0) {
  9860. retval = mg_write(conn, data, dataLen);
  9861. }
  9862. /* TODO: Remove this unlock as well, when lock is moved. */
  9863. mg_unlock_connection(conn);
  9864. return retval;
  9865. }
  9866. int
  9867. mg_websocket_write(struct mg_connection *conn,
  9868. int opcode,
  9869. const char *data,
  9870. size_t dataLen)
  9871. {
  9872. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  9873. }
  9874. static void
  9875. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  9876. {
  9877. size_t i = 0;
  9878. i = 0;
  9879. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  9880. /* Convert in 32 bit words, if data is 4 byte aligned */
  9881. while (i < (in_len - 3)) {
  9882. *(uint32_t *)(void *)(out + i) =
  9883. *(uint32_t *)(void *)(in + i) ^ masking_key;
  9884. i += 4;
  9885. }
  9886. }
  9887. if (i != in_len) {
  9888. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  9889. while (i < in_len) {
  9890. *(uint8_t *)(void *)(out + i) =
  9891. *(uint8_t *)(void *)(in + i)
  9892. ^ *(((uint8_t *)&masking_key) + (i % 4));
  9893. i++;
  9894. }
  9895. }
  9896. }
  9897. int
  9898. mg_websocket_client_write(struct mg_connection *conn,
  9899. int opcode,
  9900. const char *data,
  9901. size_t dataLen)
  9902. {
  9903. int retval = -1;
  9904. char *masked_data =
  9905. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  9906. uint32_t masking_key = (uint32_t)get_random();
  9907. if (masked_data == NULL) {
  9908. /* Return -1 in an error case */
  9909. mg_cry(conn,
  9910. "Cannot allocate buffer for masked websocket response: "
  9911. "Out of memory");
  9912. return -1;
  9913. }
  9914. mask_data(data, dataLen, masking_key, masked_data);
  9915. retval = mg_websocket_write_exec(
  9916. conn, opcode, masked_data, dataLen, masking_key);
  9917. mg_free(masked_data);
  9918. return retval;
  9919. }
  9920. static void
  9921. handle_websocket_request(struct mg_connection *conn,
  9922. const char *path,
  9923. int is_callback_resource,
  9924. struct mg_websocket_subprotocols *subprotocols,
  9925. mg_websocket_connect_handler ws_connect_handler,
  9926. mg_websocket_ready_handler ws_ready_handler,
  9927. mg_websocket_data_handler ws_data_handler,
  9928. mg_websocket_close_handler ws_close_handler,
  9929. void *cbData)
  9930. {
  9931. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  9932. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  9933. int lua_websock = 0;
  9934. #if !defined(USE_LUA)
  9935. (void)path;
  9936. #endif
  9937. /* Step 1: Check websocket protocol version. */
  9938. /* Step 1.1: Check Sec-WebSocket-Key. */
  9939. if (!websock_key) {
  9940. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  9941. * requires a Sec-WebSocket-Key header.
  9942. */
  9943. /* It could be the hixie draft version
  9944. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  9945. */
  9946. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  9947. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  9948. char key3[8];
  9949. if ((key1 != NULL) && (key2 != NULL)) {
  9950. /* This version uses 8 byte body data in a GET request */
  9951. conn->content_len = 8;
  9952. if (8 == mg_read(conn, key3, 8)) {
  9953. /* This is the hixie version */
  9954. mg_send_http_error(conn,
  9955. 426,
  9956. "%s",
  9957. "Protocol upgrade to RFC 6455 required");
  9958. return;
  9959. }
  9960. }
  9961. /* This is an unknown version */
  9962. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  9963. return;
  9964. }
  9965. /* Step 1.2: Check websocket protocol version. */
  9966. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  9967. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  9968. /* Reject wrong versions */
  9969. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  9970. return;
  9971. }
  9972. /* Step 1.3: Could check for "Host", but we do not really nead this
  9973. * value for anything, so just ignore it. */
  9974. /* Step 2: If a callback is responsible, call it. */
  9975. if (is_callback_resource) {
  9976. /* Step 2.1 check and select subprotocol */
  9977. const char *protocols[64]; // max 64 headers
  9978. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  9979. "Sec-WebSocket-Protocol",
  9980. protocols,
  9981. 64);
  9982. if ((nbSubprotocolHeader > 0) && subprotocols) {
  9983. int cnt = 0;
  9984. int idx;
  9985. unsigned long len;
  9986. const char *sep, *curSubProtocol,
  9987. *acceptedWebSocketSubprotocol = NULL;
  9988. /* look for matching subprotocol */
  9989. do {
  9990. const char *protocol = protocols[cnt];
  9991. do {
  9992. sep = strchr(protocol, ',');
  9993. curSubProtocol = protocol;
  9994. len = sep ? (unsigned long)(sep - protocol)
  9995. : (unsigned long)strlen(protocol);
  9996. while (sep && isspace(*++sep))
  9997. ; // ignore leading whitespaces
  9998. protocol = sep;
  9999. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10000. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10001. && (strncmp(curSubProtocol,
  10002. subprotocols->subprotocols[idx],
  10003. len) == 0)) {
  10004. acceptedWebSocketSubprotocol =
  10005. subprotocols->subprotocols[idx];
  10006. break;
  10007. }
  10008. }
  10009. } while (sep && !acceptedWebSocketSubprotocol);
  10010. } while (++cnt < nbSubprotocolHeader
  10011. && !acceptedWebSocketSubprotocol);
  10012. conn->request_info.acceptedWebSocketSubprotocol =
  10013. acceptedWebSocketSubprotocol;
  10014. } else if (nbSubprotocolHeader > 0) {
  10015. /* keep legacy behavior */
  10016. const char *protocol = protocols[0];
  10017. /* The protocol is a comma separated list of names. */
  10018. /* The server must only return one value from this list. */
  10019. /* First check if it is a list or just a single value. */
  10020. const char *sep = strrchr(protocol, ',');
  10021. if (sep == NULL) {
  10022. /* Just a single protocol -> accept it. */
  10023. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10024. } else {
  10025. /* Multiple protocols -> accept the last one. */
  10026. /* This is just a quick fix if the client offers multiple
  10027. * protocols. The handler should have a list of accepted
  10028. * protocols on his own
  10029. * and use it to select one protocol among those the client
  10030. * has
  10031. * offered.
  10032. */
  10033. while (isspace(*++sep)) {
  10034. ; /* ignore leading whitespaces */
  10035. }
  10036. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10037. }
  10038. }
  10039. if ((ws_connect_handler != NULL)
  10040. && (ws_connect_handler(conn, cbData) != 0)) {
  10041. /* C callback has returned non-zero, do not proceed with
  10042. * handshake.
  10043. */
  10044. /* Note that C callbacks are no longer called when Lua is
  10045. * responsible, so C can no longer filter callbacks for Lua. */
  10046. return;
  10047. }
  10048. }
  10049. #if defined(USE_LUA)
  10050. /* Step 3: No callback. Check if Lua is responsible. */
  10051. else {
  10052. /* Step 3.1: Check if Lua is responsible. */
  10053. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10054. lua_websock =
  10055. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10056. strlen(
  10057. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10058. path);
  10059. }
  10060. if (lua_websock) {
  10061. /* Step 3.2: Lua is responsible: call it. */
  10062. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10063. if (!conn->lua_websocket_state) {
  10064. /* Lua rejected the new client */
  10065. return;
  10066. }
  10067. }
  10068. }
  10069. #endif
  10070. /* Step 4: Check if there is a responsible websocket handler. */
  10071. if (!is_callback_resource && !lua_websock) {
  10072. /* There is no callback, and Lua is not responsible either. */
  10073. /* Reply with a 404 Not Found. We are still at a standard
  10074. * HTTP request here, before the websocket handshake, so
  10075. * we can still send standard HTTP error replies. */
  10076. mg_send_http_error(conn, 404, "%s", "Not found");
  10077. return;
  10078. }
  10079. /* Step 5: The websocket connection has been accepted */
  10080. if (!send_websocket_handshake(conn, websock_key)) {
  10081. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10082. return;
  10083. }
  10084. /* Step 6: Call the ready handler */
  10085. if (is_callback_resource) {
  10086. if (ws_ready_handler != NULL) {
  10087. ws_ready_handler(conn, cbData);
  10088. }
  10089. #if defined(USE_LUA)
  10090. } else if (lua_websock) {
  10091. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10092. /* the ready handler returned false */
  10093. return;
  10094. }
  10095. #endif
  10096. }
  10097. /* Step 7: Enter the read loop */
  10098. if (is_callback_resource) {
  10099. read_websocket(conn, ws_data_handler, cbData);
  10100. #if defined(USE_LUA)
  10101. } else if (lua_websock) {
  10102. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10103. #endif
  10104. }
  10105. /* Step 8: Call the close handler */
  10106. if (ws_close_handler) {
  10107. ws_close_handler(conn, cbData);
  10108. }
  10109. }
  10110. static int
  10111. is_websocket_protocol(const struct mg_connection *conn)
  10112. {
  10113. const char *upgrade, *connection;
  10114. /* A websocket protocoll has the following HTTP headers:
  10115. *
  10116. * Connection: Upgrade
  10117. * Upgrade: Websocket
  10118. */
  10119. upgrade = mg_get_header(conn, "Upgrade");
  10120. if (upgrade == NULL) {
  10121. return 0; /* fail early, don't waste time checking other header
  10122. * fields
  10123. */
  10124. }
  10125. if (!mg_strcasestr(upgrade, "websocket")) {
  10126. return 0;
  10127. }
  10128. connection = mg_get_header(conn, "Connection");
  10129. if (connection == NULL) {
  10130. return 0;
  10131. }
  10132. if (!mg_strcasestr(connection, "upgrade")) {
  10133. return 0;
  10134. }
  10135. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10136. * "Sec-WebSocket-Version" are also required.
  10137. * Don't check them here, since even an unsupported websocket protocol
  10138. * request still IS a websocket request (in contrast to a standard HTTP
  10139. * request). It will fail later in handle_websocket_request.
  10140. */
  10141. return 1;
  10142. }
  10143. #endif /* !USE_WEBSOCKET */
  10144. static int
  10145. isbyte(int n)
  10146. {
  10147. return (n >= 0) && (n <= 255);
  10148. }
  10149. static int
  10150. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10151. {
  10152. int n, a, b, c, d, slash = 32, len = 0;
  10153. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10154. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10155. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10156. && (slash < 33)) {
  10157. len = n;
  10158. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10159. | (uint32_t)d;
  10160. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10161. }
  10162. return len;
  10163. }
  10164. static int
  10165. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10166. {
  10167. int throttle = 0;
  10168. struct vec vec, val;
  10169. uint32_t net, mask;
  10170. char mult;
  10171. double v;
  10172. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10173. mult = ',';
  10174. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10175. || (v < 0) || ((lowercase(&mult) != 'k')
  10176. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10177. continue;
  10178. }
  10179. v *= (lowercase(&mult) == 'k')
  10180. ? 1024
  10181. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10182. if (vec.len == 1 && vec.ptr[0] == '*') {
  10183. throttle = (int)v;
  10184. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10185. if ((remote_ip & mask) == net) {
  10186. throttle = (int)v;
  10187. }
  10188. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10189. throttle = (int)v;
  10190. }
  10191. }
  10192. return throttle;
  10193. }
  10194. static uint32_t
  10195. get_remote_ip(const struct mg_connection *conn)
  10196. {
  10197. if (!conn) {
  10198. return 0;
  10199. }
  10200. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10201. }
  10202. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10203. #include "handle_form.inl"
  10204. #if defined(MG_LEGACY_INTERFACE)
  10205. /* Implement the deprecated mg_upload function by calling the new
  10206. * mg_handle_form_request function. While mg_upload could only handle
  10207. * HTML forms sent as POST request in multipart/form-data format
  10208. * containing only file input elements, mg_handle_form_request can
  10209. * handle all form input elements and all standard request methods. */
  10210. struct mg_upload_user_data {
  10211. struct mg_connection *conn;
  10212. const char *destination_dir;
  10213. int num_uploaded_files;
  10214. };
  10215. /* Helper function for deprecated mg_upload. */
  10216. static int
  10217. mg_upload_field_found(const char *key,
  10218. const char *filename,
  10219. char *path,
  10220. size_t pathlen,
  10221. void *user_data)
  10222. {
  10223. int truncated = 0;
  10224. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10225. (void)key;
  10226. if (!filename) {
  10227. mg_cry(fud->conn, "%s: No filename set", __func__);
  10228. return FORM_FIELD_STORAGE_ABORT;
  10229. }
  10230. mg_snprintf(fud->conn,
  10231. &truncated,
  10232. path,
  10233. pathlen - 1,
  10234. "%s/%s",
  10235. fud->destination_dir,
  10236. filename);
  10237. if (!truncated) {
  10238. mg_cry(fud->conn, "%s: File path too long", __func__);
  10239. return FORM_FIELD_STORAGE_ABORT;
  10240. }
  10241. return FORM_FIELD_STORAGE_STORE;
  10242. }
  10243. /* Helper function for deprecated mg_upload. */
  10244. static int
  10245. mg_upload_field_get(const char *key,
  10246. const char *value,
  10247. size_t value_size,
  10248. void *user_data)
  10249. {
  10250. /* Function should never be called */
  10251. (void)key;
  10252. (void)value;
  10253. (void)value_size;
  10254. (void)user_data;
  10255. return 0;
  10256. }
  10257. /* Helper function for deprecated mg_upload. */
  10258. static int
  10259. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10260. {
  10261. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10262. (void)file_size;
  10263. fud->num_uploaded_files++;
  10264. fud->conn->ctx->callbacks.upload(fud->conn, path);
  10265. return 0;
  10266. }
  10267. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10268. int
  10269. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10270. {
  10271. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10272. struct mg_form_data_handler fdh = {mg_upload_field_found,
  10273. mg_upload_field_get,
  10274. mg_upload_field_stored,
  10275. 0};
  10276. int ret;
  10277. fdh.user_data = (void *)&fud;
  10278. ret = mg_handle_form_request(conn, &fdh);
  10279. if (ret < 0) {
  10280. mg_cry(conn, "%s: Error while parsing the request", __func__);
  10281. }
  10282. return fud.num_uploaded_files;
  10283. }
  10284. #endif
  10285. static int
  10286. get_first_ssl_listener_index(const struct mg_context *ctx)
  10287. {
  10288. unsigned int i;
  10289. int idx = -1;
  10290. if (ctx) {
  10291. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  10292. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  10293. }
  10294. }
  10295. return idx;
  10296. }
  10297. static void
  10298. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  10299. {
  10300. char host[1025];
  10301. const char *host_header;
  10302. size_t hostlen;
  10303. host_header = mg_get_header(conn, "Host");
  10304. hostlen = sizeof(host);
  10305. if (host_header != NULL) {
  10306. char *pos;
  10307. mg_strlcpy(host, host_header, hostlen);
  10308. host[hostlen - 1] = '\0';
  10309. pos = strchr(host, ':');
  10310. if (pos != NULL) {
  10311. *pos = '\0';
  10312. }
  10313. } else {
  10314. /* Cannot get host from the Host: header.
  10315. * Fallback to our IP address. */
  10316. if (conn) {
  10317. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  10318. }
  10319. }
  10320. /* Send host, port, uri and (if it exists) ?query_string */
  10321. if (conn) {
  10322. mg_printf(conn,
  10323. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  10324. host,
  10325. #if defined(USE_IPV6)
  10326. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  10327. == AF_INET6)
  10328. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  10329. .lsa.sin6.sin6_port)
  10330. :
  10331. #endif
  10332. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  10333. .lsa.sin.sin_port),
  10334. conn->request_info.local_uri,
  10335. (conn->request_info.query_string == NULL) ? "" : "?",
  10336. (conn->request_info.query_string == NULL)
  10337. ? ""
  10338. : conn->request_info.query_string);
  10339. }
  10340. }
  10341. static void
  10342. mg_set_handler_type(struct mg_context *ctx,
  10343. const char *uri,
  10344. int handler_type,
  10345. int is_delete_request,
  10346. mg_request_handler handler,
  10347. struct mg_websocket_subprotocols *subprotocols,
  10348. mg_websocket_connect_handler connect_handler,
  10349. mg_websocket_ready_handler ready_handler,
  10350. mg_websocket_data_handler data_handler,
  10351. mg_websocket_close_handler close_handler,
  10352. mg_authorization_handler auth_handler,
  10353. void *cbdata)
  10354. {
  10355. struct mg_handler_info *tmp_rh, **lastref;
  10356. size_t urilen = strlen(uri);
  10357. if (handler_type == WEBSOCKET_HANDLER) {
  10358. /* assert(handler == NULL); */
  10359. /* assert(is_delete_request || connect_handler!=NULL ||
  10360. * ready_handler!=NULL || data_handler!=NULL ||
  10361. * close_handler!=NULL);
  10362. */
  10363. /* assert(auth_handler == NULL); */
  10364. if (handler != NULL) {
  10365. return;
  10366. }
  10367. if (!is_delete_request && (connect_handler == NULL)
  10368. && (ready_handler == NULL) && (data_handler == NULL)
  10369. && (close_handler == NULL)) {
  10370. return;
  10371. }
  10372. if (auth_handler != NULL) {
  10373. return;
  10374. }
  10375. } else if (handler_type == REQUEST_HANDLER) {
  10376. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10377. * data_handler==NULL && close_handler==NULL); */
  10378. /* assert(is_delete_request || (handler!=NULL));
  10379. */
  10380. /* assert(auth_handler == NULL); */
  10381. if ((connect_handler != NULL) || (ready_handler != NULL)
  10382. || (data_handler != NULL) || (close_handler != NULL)) {
  10383. return;
  10384. }
  10385. if (!is_delete_request && (handler == NULL)) {
  10386. return;
  10387. }
  10388. if (auth_handler != NULL) {
  10389. return;
  10390. }
  10391. } else { /* AUTH_HANDLER */
  10392. /* assert(handler == NULL); */
  10393. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10394. * data_handler==NULL && close_handler==NULL); */
  10395. /* assert(auth_handler != NULL); */
  10396. if (handler != NULL) {
  10397. return;
  10398. }
  10399. if ((connect_handler != NULL) || (ready_handler != NULL)
  10400. || (data_handler != NULL) || (close_handler != NULL)) {
  10401. return;
  10402. }
  10403. if (!is_delete_request && (auth_handler == NULL)) {
  10404. return;
  10405. }
  10406. }
  10407. if (!ctx) {
  10408. return;
  10409. }
  10410. mg_lock_context(ctx);
  10411. /* first try to find an existing handler */
  10412. lastref = &(ctx->handlers);
  10413. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10414. if (tmp_rh->handler_type == handler_type) {
  10415. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10416. if (!is_delete_request) {
  10417. /* update existing handler */
  10418. if (handler_type == REQUEST_HANDLER) {
  10419. tmp_rh->handler = handler;
  10420. } else if (handler_type == WEBSOCKET_HANDLER) {
  10421. tmp_rh->subprotocols = subprotocols;
  10422. tmp_rh->connect_handler = connect_handler;
  10423. tmp_rh->ready_handler = ready_handler;
  10424. tmp_rh->data_handler = data_handler;
  10425. tmp_rh->close_handler = close_handler;
  10426. } else { /* AUTH_HANDLER */
  10427. tmp_rh->auth_handler = auth_handler;
  10428. }
  10429. tmp_rh->cbdata = cbdata;
  10430. } else {
  10431. /* remove existing handler */
  10432. *lastref = tmp_rh->next;
  10433. mg_free(tmp_rh->uri);
  10434. mg_free(tmp_rh);
  10435. }
  10436. mg_unlock_context(ctx);
  10437. return;
  10438. }
  10439. }
  10440. lastref = &(tmp_rh->next);
  10441. }
  10442. if (is_delete_request) {
  10443. /* no handler to set, this was a remove request to a non-existing
  10444. * handler */
  10445. mg_unlock_context(ctx);
  10446. return;
  10447. }
  10448. tmp_rh =
  10449. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  10450. 1,
  10451. ctx);
  10452. if (tmp_rh == NULL) {
  10453. mg_unlock_context(ctx);
  10454. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  10455. return;
  10456. }
  10457. tmp_rh->uri = mg_strdup(uri);
  10458. if (!tmp_rh->uri) {
  10459. mg_unlock_context(ctx);
  10460. mg_free(tmp_rh);
  10461. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  10462. return;
  10463. }
  10464. tmp_rh->uri_len = urilen;
  10465. if (handler_type == REQUEST_HANDLER) {
  10466. tmp_rh->handler = handler;
  10467. } else if (handler_type == WEBSOCKET_HANDLER) {
  10468. tmp_rh->subprotocols = subprotocols;
  10469. tmp_rh->connect_handler = connect_handler;
  10470. tmp_rh->ready_handler = ready_handler;
  10471. tmp_rh->data_handler = data_handler;
  10472. tmp_rh->close_handler = close_handler;
  10473. } else { /* AUTH_HANDLER */
  10474. tmp_rh->auth_handler = auth_handler;
  10475. }
  10476. tmp_rh->cbdata = cbdata;
  10477. tmp_rh->handler_type = handler_type;
  10478. tmp_rh->next = NULL;
  10479. *lastref = tmp_rh;
  10480. mg_unlock_context(ctx);
  10481. }
  10482. void
  10483. mg_set_request_handler(struct mg_context *ctx,
  10484. const char *uri,
  10485. mg_request_handler handler,
  10486. void *cbdata)
  10487. {
  10488. mg_set_handler_type(ctx,
  10489. uri,
  10490. REQUEST_HANDLER,
  10491. handler == NULL,
  10492. handler,
  10493. NULL,
  10494. NULL,
  10495. NULL,
  10496. NULL,
  10497. NULL,
  10498. NULL,
  10499. cbdata);
  10500. }
  10501. void
  10502. mg_set_websocket_handler(struct mg_context *ctx,
  10503. const char *uri,
  10504. mg_websocket_connect_handler connect_handler,
  10505. mg_websocket_ready_handler ready_handler,
  10506. mg_websocket_data_handler data_handler,
  10507. mg_websocket_close_handler close_handler,
  10508. void *cbdata)
  10509. {
  10510. mg_set_websocket_handler_with_subprotocols(ctx,
  10511. uri,
  10512. NULL,
  10513. connect_handler,
  10514. ready_handler,
  10515. data_handler,
  10516. close_handler,
  10517. cbdata);
  10518. }
  10519. void
  10520. mg_set_websocket_handler_with_subprotocols(
  10521. struct mg_context *ctx,
  10522. const char *uri,
  10523. struct mg_websocket_subprotocols *subprotocols,
  10524. mg_websocket_connect_handler connect_handler,
  10525. mg_websocket_ready_handler ready_handler,
  10526. mg_websocket_data_handler data_handler,
  10527. mg_websocket_close_handler close_handler,
  10528. void *cbdata)
  10529. {
  10530. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  10531. && (data_handler == NULL)
  10532. && (close_handler == NULL);
  10533. mg_set_handler_type(ctx,
  10534. uri,
  10535. WEBSOCKET_HANDLER,
  10536. is_delete_request,
  10537. NULL,
  10538. subprotocols,
  10539. connect_handler,
  10540. ready_handler,
  10541. data_handler,
  10542. close_handler,
  10543. NULL,
  10544. cbdata);
  10545. }
  10546. void
  10547. mg_set_auth_handler(struct mg_context *ctx,
  10548. const char *uri,
  10549. mg_request_handler handler,
  10550. void *cbdata)
  10551. {
  10552. mg_set_handler_type(ctx,
  10553. uri,
  10554. AUTH_HANDLER,
  10555. handler == NULL,
  10556. NULL,
  10557. NULL,
  10558. NULL,
  10559. NULL,
  10560. NULL,
  10561. NULL,
  10562. handler,
  10563. cbdata);
  10564. }
  10565. static int
  10566. get_request_handler(struct mg_connection *conn,
  10567. int handler_type,
  10568. mg_request_handler *handler,
  10569. struct mg_websocket_subprotocols **subprotocols,
  10570. mg_websocket_connect_handler *connect_handler,
  10571. mg_websocket_ready_handler *ready_handler,
  10572. mg_websocket_data_handler *data_handler,
  10573. mg_websocket_close_handler *close_handler,
  10574. mg_authorization_handler *auth_handler,
  10575. void **cbdata)
  10576. {
  10577. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10578. if (request_info) {
  10579. const char *uri = request_info->local_uri;
  10580. size_t urilen = strlen(uri);
  10581. struct mg_handler_info *tmp_rh;
  10582. if (!conn || !conn->ctx) {
  10583. return 0;
  10584. }
  10585. mg_lock_context(conn->ctx);
  10586. /* first try for an exact match */
  10587. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10588. tmp_rh = tmp_rh->next) {
  10589. if (tmp_rh->handler_type == handler_type) {
  10590. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10591. if (handler_type == WEBSOCKET_HANDLER) {
  10592. *subprotocols = tmp_rh->subprotocols;
  10593. *connect_handler = tmp_rh->connect_handler;
  10594. *ready_handler = tmp_rh->ready_handler;
  10595. *data_handler = tmp_rh->data_handler;
  10596. *close_handler = tmp_rh->close_handler;
  10597. } else if (handler_type == REQUEST_HANDLER) {
  10598. *handler = tmp_rh->handler;
  10599. } else { /* AUTH_HANDLER */
  10600. *auth_handler = tmp_rh->auth_handler;
  10601. }
  10602. *cbdata = tmp_rh->cbdata;
  10603. mg_unlock_context(conn->ctx);
  10604. return 1;
  10605. }
  10606. }
  10607. }
  10608. /* next try for a partial match, we will accept uri/something */
  10609. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10610. tmp_rh = tmp_rh->next) {
  10611. if (tmp_rh->handler_type == handler_type) {
  10612. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10613. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  10614. if (handler_type == WEBSOCKET_HANDLER) {
  10615. *subprotocols = tmp_rh->subprotocols;
  10616. *connect_handler = tmp_rh->connect_handler;
  10617. *ready_handler = tmp_rh->ready_handler;
  10618. *data_handler = tmp_rh->data_handler;
  10619. *close_handler = tmp_rh->close_handler;
  10620. } else if (handler_type == REQUEST_HANDLER) {
  10621. *handler = tmp_rh->handler;
  10622. } else { /* AUTH_HANDLER */
  10623. *auth_handler = tmp_rh->auth_handler;
  10624. }
  10625. *cbdata = tmp_rh->cbdata;
  10626. mg_unlock_context(conn->ctx);
  10627. return 1;
  10628. }
  10629. }
  10630. }
  10631. /* finally try for pattern match */
  10632. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10633. tmp_rh = tmp_rh->next) {
  10634. if (tmp_rh->handler_type == handler_type) {
  10635. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10636. if (handler_type == WEBSOCKET_HANDLER) {
  10637. *subprotocols = tmp_rh->subprotocols;
  10638. *connect_handler = tmp_rh->connect_handler;
  10639. *ready_handler = tmp_rh->ready_handler;
  10640. *data_handler = tmp_rh->data_handler;
  10641. *close_handler = tmp_rh->close_handler;
  10642. } else if (handler_type == REQUEST_HANDLER) {
  10643. *handler = tmp_rh->handler;
  10644. } else { /* AUTH_HANDLER */
  10645. *auth_handler = tmp_rh->auth_handler;
  10646. }
  10647. *cbdata = tmp_rh->cbdata;
  10648. mg_unlock_context(conn->ctx);
  10649. return 1;
  10650. }
  10651. }
  10652. }
  10653. mg_unlock_context(conn->ctx);
  10654. }
  10655. return 0; /* none found */
  10656. }
  10657. /* Check if the script file is in a path, allowed for script files.
  10658. * This can be used if uploading files is possible not only for the server
  10659. * admin, and the upload mechanism does not check the file extension.
  10660. */
  10661. static int
  10662. is_in_script_path(const struct mg_connection *conn, const char *path)
  10663. {
  10664. /* TODO (Feature): Add config value for allowed script path.
  10665. * Default: All allowed. */
  10666. (void)conn;
  10667. (void)path;
  10668. return 1;
  10669. }
  10670. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10671. static int
  10672. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10673. void *cbdata)
  10674. {
  10675. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10676. if (pcallbacks->websocket_connect) {
  10677. return pcallbacks->websocket_connect(conn);
  10678. }
  10679. /* No handler set - assume "OK" */
  10680. return 0;
  10681. }
  10682. static void
  10683. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10684. {
  10685. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10686. if (pcallbacks->websocket_ready) {
  10687. pcallbacks->websocket_ready(conn);
  10688. }
  10689. }
  10690. static int
  10691. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10692. int bits,
  10693. char *data,
  10694. size_t len,
  10695. void *cbdata)
  10696. {
  10697. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10698. if (pcallbacks->websocket_data) {
  10699. return pcallbacks->websocket_data(conn, bits, data, len);
  10700. }
  10701. /* No handler set - assume "OK" */
  10702. return 1;
  10703. }
  10704. #endif
  10705. /* This is the heart of the Civetweb's logic.
  10706. * This function is called when the request is read, parsed and validated,
  10707. * and Civetweb must decide what action to take: serve a file, or
  10708. * a directory, or call embedded function, etcetera. */
  10709. static void
  10710. handle_request(struct mg_connection *conn)
  10711. {
  10712. struct mg_request_info *ri = &conn->request_info;
  10713. char path[PATH_MAX];
  10714. int uri_len, ssl_index;
  10715. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  10716. is_put_or_delete_request = 0, is_callback_resource = 0;
  10717. int i;
  10718. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10719. mg_request_handler callback_handler = NULL;
  10720. struct mg_websocket_subprotocols *subprotocols;
  10721. mg_websocket_connect_handler ws_connect_handler = NULL;
  10722. mg_websocket_ready_handler ws_ready_handler = NULL;
  10723. mg_websocket_data_handler ws_data_handler = NULL;
  10724. mg_websocket_close_handler ws_close_handler = NULL;
  10725. void *callback_data = NULL;
  10726. mg_authorization_handler auth_handler = NULL;
  10727. void *auth_callback_data = NULL;
  10728. int handler_type;
  10729. time_t curtime = time(NULL);
  10730. char date[64];
  10731. path[0] = 0;
  10732. /* 1. get the request url */
  10733. /* 1.1. split into url and query string */
  10734. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  10735. != NULL) {
  10736. *((char *)conn->request_info.query_string++) = '\0';
  10737. }
  10738. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  10739. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  10740. ssl_index = get_first_ssl_listener_index(conn->ctx);
  10741. if (ssl_index >= 0) {
  10742. redirect_to_https_port(conn, ssl_index);
  10743. } else {
  10744. /* A http to https forward port has been specified,
  10745. * but no https port to forward to. */
  10746. mg_send_http_error(conn,
  10747. 503,
  10748. "%s",
  10749. "Error: SSL forward not configured properly");
  10750. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  10751. }
  10752. return;
  10753. }
  10754. uri_len = (int)strlen(ri->local_uri);
  10755. /* 1.3. decode url (if config says so) */
  10756. if (should_decode_url(conn)) {
  10757. mg_url_decode(
  10758. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  10759. }
  10760. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  10761. * not possible */
  10762. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  10763. /* step 1. completed, the url is known now */
  10764. uri_len = (int)strlen(ri->local_uri);
  10765. DEBUG_TRACE("URL: %s", ri->local_uri);
  10766. /* 2. if this ip has limited speed, set it for this connection */
  10767. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  10768. get_remote_ip(conn),
  10769. ri->local_uri);
  10770. /* 3. call a "handle everything" callback, if registered */
  10771. if (conn->ctx->callbacks.begin_request != NULL) {
  10772. /* Note that since V1.7 the "begin_request" function is called
  10773. * before an authorization check. If an authorization check is
  10774. * required, use a request_handler instead. */
  10775. i = conn->ctx->callbacks.begin_request(conn);
  10776. if (i > 0) {
  10777. /* callback already processed the request. Store the
  10778. return value as a status code for the access log. */
  10779. conn->status_code = i;
  10780. discard_unread_request_data(conn);
  10781. return;
  10782. } else if (i == 0) {
  10783. /* civetweb should process the request */
  10784. } else {
  10785. /* unspecified - may change with the next version */
  10786. return;
  10787. }
  10788. }
  10789. /* request not yet handled by a handler or redirect, so the request
  10790. * is processed here */
  10791. /* 4. Check for CORS preflight requests and handle them (if configured).
  10792. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  10793. */
  10794. if (!strcmp(ri->request_method, "OPTIONS")) {
  10795. /* Send a response to CORS preflights only if
  10796. * access_control_allow_methods is not NULL and not an empty string.
  10797. * In this case, scripts can still handle CORS. */
  10798. const char *cors_meth_cfg =
  10799. conn->ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  10800. const char *cors_orig_cfg =
  10801. conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10802. const char *cors_origin =
  10803. get_header(ri->http_headers, ri->num_headers, "Origin");
  10804. const char *cors_acrm = get_header(ri->http_headers,
  10805. ri->num_headers,
  10806. "Access-Control-Request-Method");
  10807. /* Todo: check if cors_origin is in cors_orig_cfg.
  10808. * Or, let the client check this. */
  10809. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  10810. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  10811. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  10812. /* This is a valid CORS preflight, and the server is configured
  10813. * to
  10814. * handle it automatically. */
  10815. const char *cors_acrh =
  10816. get_header(ri->http_headers,
  10817. ri->num_headers,
  10818. "Access-Control-Request-Headers");
  10819. gmt_time_string(date, sizeof(date), &curtime);
  10820. mg_printf(conn,
  10821. "HTTP/1.1 200 OK\r\n"
  10822. "Date: %s\r\n"
  10823. "Access-Control-Allow-Origin: %s\r\n"
  10824. "Access-Control-Allow-Methods: %s\r\n"
  10825. "Content-Length: 0\r\n"
  10826. "Connection: %s\r\n",
  10827. date,
  10828. cors_orig_cfg,
  10829. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  10830. suggest_connection_header(conn));
  10831. if (cors_acrh != NULL) {
  10832. /* CORS request is asking for additional headers */
  10833. const char *cors_hdr_cfg =
  10834. conn->ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  10835. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  10836. /* Allow only if access_control_allow_headers is
  10837. * not NULL and not an empty string. If this
  10838. * configuration is set to *, allow everything.
  10839. * Otherwise this configuration must be a list
  10840. * of allowed HTTP header names. */
  10841. mg_printf(conn,
  10842. "Access-Control-Allow-Headers: %s\r\n",
  10843. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  10844. : cors_hdr_cfg));
  10845. }
  10846. }
  10847. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  10848. mg_printf(conn, "\r\n");
  10849. return;
  10850. }
  10851. }
  10852. /* 5. interpret the url to find out how the request must be handled
  10853. */
  10854. /* 5.1. first test, if the request targets the regular http(s)://
  10855. * protocol namespace or the websocket ws(s):// protocol namespace.
  10856. */
  10857. is_websocket_request = is_websocket_protocol(conn);
  10858. #if defined(USE_WEBSOCKET)
  10859. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  10860. #else
  10861. handler_type = REQUEST_HANDLER;
  10862. #endif /* defined(USE_WEBSOCKET) */
  10863. /* 5.2. check if the request will be handled by a callback */
  10864. if (get_request_handler(conn,
  10865. handler_type,
  10866. &callback_handler,
  10867. &subprotocols,
  10868. &ws_connect_handler,
  10869. &ws_ready_handler,
  10870. &ws_data_handler,
  10871. &ws_close_handler,
  10872. NULL,
  10873. &callback_data)) {
  10874. /* 5.2.1. A callback will handle this request. All requests
  10875. * handled
  10876. * by a callback have to be considered as requests to a script
  10877. * resource. */
  10878. is_callback_resource = 1;
  10879. is_script_resource = 1;
  10880. is_put_or_delete_request = is_put_or_delete_method(conn);
  10881. } else {
  10882. no_callback_resource:
  10883. /* 5.2.2. No callback is responsible for this request. The URI
  10884. * addresses a file based resource (static content or Lua/cgi
  10885. * scripts in the file system). */
  10886. is_callback_resource = 0;
  10887. interpret_uri(conn,
  10888. path,
  10889. sizeof(path),
  10890. &file.stat,
  10891. &is_found,
  10892. &is_script_resource,
  10893. &is_websocket_request,
  10894. &is_put_or_delete_request);
  10895. }
  10896. /* 6. authorization check */
  10897. /* 6.1. a custom authorization handler is installed */
  10898. if (get_request_handler(conn,
  10899. AUTH_HANDLER,
  10900. NULL,
  10901. NULL,
  10902. NULL,
  10903. NULL,
  10904. NULL,
  10905. NULL,
  10906. &auth_handler,
  10907. &auth_callback_data)) {
  10908. if (!auth_handler(conn, auth_callback_data)) {
  10909. return;
  10910. }
  10911. } else if (is_put_or_delete_request && !is_script_resource
  10912. && !is_callback_resource) {
  10913. /* 6.2. this request is a PUT/DELETE to a real file */
  10914. /* 6.2.1. thus, the server must have real files */
  10915. #if defined(NO_FILES)
  10916. if (1) {
  10917. #else
  10918. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10919. #endif
  10920. /* This server does not have any real files, thus the
  10921. * PUT/DELETE methods are not valid. */
  10922. mg_send_http_error(conn,
  10923. 405,
  10924. "%s method not allowed",
  10925. conn->request_info.request_method);
  10926. return;
  10927. }
  10928. #if !defined(NO_FILES)
  10929. /* 6.2.2. Check if put authorization for static files is
  10930. * available.
  10931. */
  10932. if (!is_authorized_for_put(conn)) {
  10933. send_authorization_request(conn, NULL);
  10934. return;
  10935. }
  10936. #endif
  10937. } else {
  10938. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  10939. * or it is a PUT or DELETE request to a resource that does not
  10940. * correspond to a file. Check authorization. */
  10941. if (!check_authorization(conn, path)) {
  10942. send_authorization_request(conn, NULL);
  10943. return;
  10944. }
  10945. }
  10946. /* request is authorized or does not need authorization */
  10947. /* 7. check if there are request handlers for this uri */
  10948. if (is_callback_resource) {
  10949. if (!is_websocket_request) {
  10950. i = callback_handler(conn, callback_data);
  10951. if (i > 0) {
  10952. /* Do nothing, callback has served the request. Store
  10953. * then return value as status code for the log and discard
  10954. * all data from the client not used by the callback. */
  10955. conn->status_code = i;
  10956. discard_unread_request_data(conn);
  10957. } else {
  10958. /* The handler did NOT handle the request. */
  10959. /* Some proper reactions would be:
  10960. * a) close the connections without sending anything
  10961. * b) send a 404 not found
  10962. * c) try if there is a file matching the URI
  10963. * It would be possible to do a, b or c in the callback
  10964. * implementation, and return 1 - we cannot do anything
  10965. * here, that is not possible in the callback.
  10966. *
  10967. * TODO: What would be the best reaction here?
  10968. * (Note: The reaction may change, if there is a better
  10969. *idea.)
  10970. */
  10971. /* For the moment, use option c: We look for a proper file,
  10972. * but since a file request is not always a script resource,
  10973. * the authorization check might be different. */
  10974. interpret_uri(conn,
  10975. path,
  10976. sizeof(path),
  10977. &file.stat,
  10978. &is_found,
  10979. &is_script_resource,
  10980. &is_websocket_request,
  10981. &is_put_or_delete_request);
  10982. callback_handler = NULL;
  10983. /* Here we are at a dead end:
  10984. * According to URI matching, a callback should be
  10985. * responsible for handling the request,
  10986. * we called it, but the callback declared itself
  10987. * not responsible.
  10988. * We use a goto here, to get out of this dead end,
  10989. * and continue with the default handling.
  10990. * A goto here is simpler and better to understand
  10991. * than some curious loop. */
  10992. goto no_callback_resource;
  10993. }
  10994. } else {
  10995. #if defined(USE_WEBSOCKET)
  10996. handle_websocket_request(conn,
  10997. path,
  10998. is_callback_resource,
  10999. subprotocols,
  11000. ws_connect_handler,
  11001. ws_ready_handler,
  11002. ws_data_handler,
  11003. ws_close_handler,
  11004. callback_data);
  11005. #endif
  11006. }
  11007. return;
  11008. }
  11009. /* 8. handle websocket requests */
  11010. #if defined(USE_WEBSOCKET)
  11011. if (is_websocket_request) {
  11012. if (is_script_resource) {
  11013. if (is_in_script_path(conn, path)) {
  11014. /* Websocket Lua script */
  11015. handle_websocket_request(conn,
  11016. path,
  11017. 0 /* Lua Script */,
  11018. NULL,
  11019. NULL,
  11020. NULL,
  11021. NULL,
  11022. NULL,
  11023. &conn->ctx->callbacks);
  11024. } else {
  11025. /* Script was in an illegal path */
  11026. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11027. }
  11028. } else {
  11029. #if defined(MG_LEGACY_INTERFACE)
  11030. handle_websocket_request(
  11031. conn,
  11032. path,
  11033. !is_script_resource /* could be deprecated global callback */,
  11034. NULL,
  11035. deprecated_websocket_connect_wrapper,
  11036. deprecated_websocket_ready_wrapper,
  11037. deprecated_websocket_data_wrapper,
  11038. NULL,
  11039. &conn->ctx->callbacks);
  11040. #else
  11041. mg_send_http_error(conn, 404, "%s", "Not found");
  11042. #endif
  11043. }
  11044. return;
  11045. } else
  11046. #endif
  11047. #if defined(NO_FILES)
  11048. /* 9a. In case the server uses only callbacks, this uri is
  11049. * unknown.
  11050. * Then, all request handling ends here. */
  11051. mg_send_http_error(conn, 404, "%s", "Not Found");
  11052. #else
  11053. /* 9b. This request is either for a static file or resource handled
  11054. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11055. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  11056. mg_send_http_error(conn, 404, "%s", "Not Found");
  11057. return;
  11058. }
  11059. /* 10. Request is handled by a script */
  11060. if (is_script_resource) {
  11061. handle_file_based_request(conn, path, &file);
  11062. return;
  11063. }
  11064. /* 11. Handle put/delete/mkcol requests */
  11065. if (is_put_or_delete_request) {
  11066. /* 11.1. PUT method */
  11067. if (!strcmp(ri->request_method, "PUT")) {
  11068. put_file(conn, path);
  11069. return;
  11070. }
  11071. /* 11.2. DELETE method */
  11072. if (!strcmp(ri->request_method, "DELETE")) {
  11073. delete_file(conn, path);
  11074. return;
  11075. }
  11076. /* 11.3. MKCOL method */
  11077. if (!strcmp(ri->request_method, "MKCOL")) {
  11078. mkcol(conn, path);
  11079. return;
  11080. }
  11081. /* 11.4. PATCH method
  11082. * This method is not supported for static resources,
  11083. * only for scripts (Lua, CGI) and callbacks. */
  11084. mg_send_http_error(conn,
  11085. 405,
  11086. "%s method not allowed",
  11087. conn->request_info.request_method);
  11088. return;
  11089. }
  11090. /* 11. File does not exist, or it was configured that it should be
  11091. * hidden */
  11092. if (!is_found || (must_hide_file(conn, path))) {
  11093. mg_send_http_error(conn, 404, "%s", "Not found");
  11094. return;
  11095. }
  11096. /* 12. Directory uris should end with a slash */
  11097. if (file.stat.is_directory && (uri_len > 0)
  11098. && (ri->local_uri[uri_len - 1] != '/')) {
  11099. gmt_time_string(date, sizeof(date), &curtime);
  11100. mg_printf(conn,
  11101. "HTTP/1.1 301 Moved Permanently\r\n"
  11102. "Location: %s/\r\n"
  11103. "Date: %s\r\n"
  11104. /* "Cache-Control: private\r\n" (= default) */
  11105. "Content-Length: 0\r\n"
  11106. "Connection: %s\r\n",
  11107. ri->request_uri,
  11108. date,
  11109. suggest_connection_header(conn));
  11110. send_additional_header(conn);
  11111. mg_printf(conn, "\r\n");
  11112. return;
  11113. }
  11114. /* 13. Handle other methods than GET/HEAD */
  11115. /* 13.1. Handle PROPFIND */
  11116. if (!strcmp(ri->request_method, "PROPFIND")) {
  11117. handle_propfind(conn, path, &file.stat);
  11118. return;
  11119. }
  11120. /* 13.2. Handle OPTIONS for files */
  11121. if (!strcmp(ri->request_method, "OPTIONS")) {
  11122. /* This standard handler is only used for real files.
  11123. * Scripts should support the OPTIONS method themselves, to allow a
  11124. * maximum flexibility.
  11125. * Lua and CGI scripts may fully support CORS this way (including
  11126. * preflights). */
  11127. send_options(conn);
  11128. return;
  11129. }
  11130. /* 13.3. everything but GET and HEAD (e.g. POST) */
  11131. if ((0 != strcmp(ri->request_method, "GET"))
  11132. && (0 != strcmp(ri->request_method, "HEAD"))) {
  11133. mg_send_http_error(conn,
  11134. 405,
  11135. "%s method not allowed",
  11136. conn->request_info.request_method);
  11137. return;
  11138. }
  11139. /* 14. directories */
  11140. if (file.stat.is_directory) {
  11141. /* Substitute files have already been handled above. */
  11142. /* Here we can either generate and send a directory listing,
  11143. * or send an "access denied" error. */
  11144. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  11145. "yes")) {
  11146. handle_directory_request(conn, path);
  11147. } else {
  11148. mg_send_http_error(conn,
  11149. 403,
  11150. "%s",
  11151. "Error: Directory listing denied");
  11152. }
  11153. return;
  11154. }
  11155. handle_file_based_request(conn, path, &file);
  11156. #endif /* !defined(NO_FILES) */
  11157. #if 0
  11158. /* Perform redirect and auth checks before calling begin_request()
  11159. * handler.
  11160. * Otherwise, begin_request() would need to perform auth checks and
  11161. * redirects. */
  11162. #endif
  11163. }
  11164. static void
  11165. handle_file_based_request(struct mg_connection *conn,
  11166. const char *path,
  11167. struct mg_file *file)
  11168. {
  11169. if (!conn || !conn->ctx) {
  11170. return;
  11171. }
  11172. if (0) {
  11173. #ifdef USE_LUA
  11174. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  11175. strlen(
  11176. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  11177. path) > 0) {
  11178. if (is_in_script_path(conn, path)) {
  11179. /* Lua server page: an SSI like page containing mostly plain
  11180. * html
  11181. * code
  11182. * plus some tags with server generated contents. */
  11183. handle_lsp_request(conn, path, file, NULL);
  11184. } else {
  11185. /* Script was in an illegal path */
  11186. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11187. }
  11188. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  11189. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  11190. path) > 0) {
  11191. if (is_in_script_path(conn, path)) {
  11192. /* Lua in-server module script: a CGI like script used to
  11193. * generate
  11194. * the
  11195. * entire reply. */
  11196. mg_exec_lua_script(conn, path, NULL);
  11197. } else {
  11198. /* Script was in an illegal path */
  11199. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11200. }
  11201. #endif
  11202. #if defined(USE_DUKTAPE)
  11203. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  11204. strlen(
  11205. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  11206. path) > 0) {
  11207. if (is_in_script_path(conn, path)) {
  11208. /* Call duktape to generate the page */
  11209. mg_exec_duktape_script(conn, path);
  11210. } else {
  11211. /* Script was in an illegal path */
  11212. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11213. }
  11214. #endif
  11215. #if !defined(NO_CGI)
  11216. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  11217. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  11218. path) > 0) {
  11219. if (is_in_script_path(conn, path)) {
  11220. /* CGI scripts may support all HTTP methods */
  11221. handle_cgi_request(conn, path);
  11222. } else {
  11223. /* Script was in an illegal path */
  11224. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11225. }
  11226. #endif /* !NO_CGI */
  11227. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  11228. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  11229. path) > 0) {
  11230. if (is_in_script_path(conn, path)) {
  11231. handle_ssi_file_request(conn, path, file);
  11232. } else {
  11233. /* Script was in an illegal path */
  11234. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11235. }
  11236. #if !defined(NO_CACHING)
  11237. } else if ((!conn->in_error_handler)
  11238. && is_not_modified(conn, &file->stat)) {
  11239. /* Send 304 "Not Modified" - this must not send any body data */
  11240. handle_not_modified_static_file_request(conn, file);
  11241. #endif /* !NO_CACHING */
  11242. } else {
  11243. handle_static_file_request(conn, path, file, NULL, NULL);
  11244. }
  11245. }
  11246. static void
  11247. close_all_listening_sockets(struct mg_context *ctx)
  11248. {
  11249. unsigned int i;
  11250. if (!ctx) {
  11251. return;
  11252. }
  11253. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11254. closesocket(ctx->listening_sockets[i].sock);
  11255. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  11256. }
  11257. mg_free(ctx->listening_sockets);
  11258. ctx->listening_sockets = NULL;
  11259. mg_free(ctx->listening_socket_fds);
  11260. ctx->listening_socket_fds = NULL;
  11261. }
  11262. /* Valid listening port specification is: [ip_address:]port[s]
  11263. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  11264. * Examples for IPv6: [::]:80, [::1]:80,
  11265. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  11266. * see https://tools.ietf.org/html/rfc3513#section-2.2
  11267. * In order to bind to both, IPv4 and IPv6, you can either add
  11268. * both ports using 8080,[::]:8080, or the short form +8080.
  11269. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  11270. * one only accepting IPv4 the other only IPv6. +8080 creates
  11271. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  11272. * environment, they might work differently, or might not work
  11273. * at all - it must be tested what options work best in the
  11274. * relevant network environment.
  11275. */
  11276. static int
  11277. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  11278. {
  11279. unsigned int a, b, c, d, port;
  11280. int ch, len;
  11281. const char *cb;
  11282. #if defined(USE_IPV6)
  11283. char buf[100] = {0};
  11284. #endif
  11285. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  11286. * Also, all-zeroes in the socket address means binding to all addresses
  11287. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  11288. memset(so, 0, sizeof(*so));
  11289. so->lsa.sin.sin_family = AF_INET;
  11290. *ip_version = 0;
  11291. /* Initialize port and len as invalid. */
  11292. port = 0;
  11293. len = 0;
  11294. /* Test for different ways to format this string */
  11295. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  11296. == 5) {
  11297. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  11298. so->lsa.sin.sin_addr.s_addr =
  11299. htonl((a << 24) | (b << 16) | (c << 8) | d);
  11300. so->lsa.sin.sin_port = htons((uint16_t)port);
  11301. *ip_version = 4;
  11302. #if defined(USE_IPV6)
  11303. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  11304. && mg_inet_pton(
  11305. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  11306. /* IPv6 address, examples: see above */
  11307. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  11308. */
  11309. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11310. *ip_version = 6;
  11311. #endif
  11312. } else if ((vec->ptr[0] == '+')
  11313. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  11314. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  11315. /* Add 1 to len for the + character we skipped before */
  11316. len++;
  11317. #if defined(USE_IPV6)
  11318. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  11319. so->lsa.sin6.sin6_family = AF_INET6;
  11320. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11321. *ip_version = 4 + 6;
  11322. #else
  11323. /* Bind to IPv4 only, since IPv6 is not built in. */
  11324. so->lsa.sin.sin_port = htons((uint16_t)port);
  11325. *ip_version = 4;
  11326. #endif
  11327. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  11328. /* If only port is specified, bind to IPv4, INADDR_ANY */
  11329. so->lsa.sin.sin_port = htons((uint16_t)port);
  11330. *ip_version = 4;
  11331. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  11332. /* Could be a hostname */
  11333. /* Will only work for RFC 952 compliant hostnames,
  11334. * starting with a letter, containing only letters,
  11335. * digits and hyphen ('-'). Newer specs may allow
  11336. * more, but this is not guaranteed here, since it
  11337. * may interfere with rules for port option lists. */
  11338. *(char *)cb = 0; /* Use a const cast here and modify the string.
  11339. * We are going to restore the string later. */
  11340. if (mg_inet_pton(
  11341. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  11342. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11343. *ip_version = 4;
  11344. so->lsa.sin.sin_family = AF_INET;
  11345. so->lsa.sin.sin_port = htons((uint16_t)port);
  11346. len += (int)(cb - vec->ptr) + 1;
  11347. } else {
  11348. port = 0;
  11349. len = 0;
  11350. }
  11351. #if defined(USE_IPV6)
  11352. } else if (mg_inet_pton(AF_INET6,
  11353. vec->ptr,
  11354. &so->lsa.sin6,
  11355. sizeof(so->lsa.sin6))) {
  11356. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11357. *ip_version = 6;
  11358. so->lsa.sin6.sin6_family = AF_INET6;
  11359. so->lsa.sin.sin_port = htons((uint16_t)port);
  11360. len += (int)(cb - vec->ptr) + 1;
  11361. } else {
  11362. port = 0;
  11363. len = 0;
  11364. }
  11365. #endif
  11366. }
  11367. *(char *)cb = ':'; /* restore the string */
  11368. } else {
  11369. /* Parsing failure. */
  11370. }
  11371. /* sscanf and the option splitting code ensure the following condition
  11372. */
  11373. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11374. *ip_version = 0;
  11375. return 0;
  11376. }
  11377. ch = vec->ptr[len]; /* Next character after the port number */
  11378. so->is_ssl = (ch == 's');
  11379. so->ssl_redir = (ch == 'r');
  11380. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11381. if (is_valid_port(port)
  11382. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  11383. return 1;
  11384. }
  11385. /* Reset ip_version to 0 of there is an error */
  11386. *ip_version = 0;
  11387. return 0;
  11388. }
  11389. /* Is there any SSL port in use? */
  11390. static int
  11391. is_ssl_port_used(const char *ports)
  11392. {
  11393. if (ports) {
  11394. if (strchr(ports, 's')) {
  11395. return 1;
  11396. }
  11397. if (strchr(ports, 'r')) {
  11398. return 1;
  11399. }
  11400. }
  11401. return 0;
  11402. }
  11403. static int
  11404. set_ports_option(struct mg_context *ctx)
  11405. {
  11406. const char *list;
  11407. int on = 1;
  11408. #if defined(USE_IPV6)
  11409. int off = 0;
  11410. #endif
  11411. struct vec vec;
  11412. struct socket so, *ptr;
  11413. struct pollfd *pfd;
  11414. union usa usa;
  11415. socklen_t len;
  11416. int ip_version;
  11417. int portsTotal = 0;
  11418. int portsOk = 0;
  11419. if (!ctx) {
  11420. return 0;
  11421. }
  11422. memset(&so, 0, sizeof(so));
  11423. memset(&usa, 0, sizeof(usa));
  11424. len = sizeof(usa);
  11425. list = ctx->config[LISTENING_PORTS];
  11426. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11427. portsTotal++;
  11428. if (!parse_port_string(&vec, &so, &ip_version)) {
  11429. mg_cry(fc(ctx),
  11430. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  11431. (int)vec.len,
  11432. vec.ptr,
  11433. portsTotal,
  11434. "[IP_ADDRESS:]PORT[s|r]");
  11435. continue;
  11436. }
  11437. #if !defined(NO_SSL)
  11438. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  11439. mg_cry(fc(ctx), "Cannot add SSL socket (entry %i)", portsTotal);
  11440. continue;
  11441. }
  11442. #endif
  11443. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  11444. == INVALID_SOCKET) {
  11445. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  11446. continue;
  11447. }
  11448. #ifdef _WIN32
  11449. /* Windows SO_REUSEADDR lets many procs binds to a
  11450. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  11451. * if someone already has the socket -- DTL */
  11452. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  11453. * Windows might need a few seconds before
  11454. * the same port can be used again in the
  11455. * same process, so a short Sleep may be
  11456. * required between mg_stop and mg_start.
  11457. */
  11458. if (setsockopt(so.sock,
  11459. SOL_SOCKET,
  11460. SO_EXCLUSIVEADDRUSE,
  11461. (SOCK_OPT_TYPE)&on,
  11462. sizeof(on)) != 0) {
  11463. /* Set reuse option, but don't abort on errors. */
  11464. mg_cry(fc(ctx),
  11465. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  11466. portsTotal);
  11467. }
  11468. #else
  11469. if (setsockopt(so.sock,
  11470. SOL_SOCKET,
  11471. SO_REUSEADDR,
  11472. (SOCK_OPT_TYPE)&on,
  11473. sizeof(on)) != 0) {
  11474. /* Set reuse option, but don't abort on errors. */
  11475. mg_cry(fc(ctx),
  11476. "cannot set socket option SO_REUSEADDR (entry %i)",
  11477. portsTotal);
  11478. }
  11479. #endif
  11480. if (ip_version > 4) {
  11481. #if defined(USE_IPV6)
  11482. if (ip_version == 6) {
  11483. if (so.lsa.sa.sa_family == AF_INET6
  11484. && setsockopt(so.sock,
  11485. IPPROTO_IPV6,
  11486. IPV6_V6ONLY,
  11487. (void *)&off,
  11488. sizeof(off)) != 0) {
  11489. /* Set IPv6 only option, but don't abort on errors. */
  11490. mg_cry(fc(ctx),
  11491. "cannot set socket option IPV6_V6ONLY (entry %i)",
  11492. portsTotal);
  11493. }
  11494. }
  11495. #else
  11496. mg_cry(fc(ctx), "IPv6 not available");
  11497. closesocket(so.sock);
  11498. so.sock = INVALID_SOCKET;
  11499. continue;
  11500. #endif
  11501. }
  11502. if (so.lsa.sa.sa_family == AF_INET) {
  11503. len = sizeof(so.lsa.sin);
  11504. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11505. mg_cry(fc(ctx),
  11506. "cannot bind to %.*s: %d (%s)",
  11507. (int)vec.len,
  11508. vec.ptr,
  11509. (int)ERRNO,
  11510. strerror(errno));
  11511. closesocket(so.sock);
  11512. so.sock = INVALID_SOCKET;
  11513. continue;
  11514. }
  11515. }
  11516. #if defined(USE_IPV6)
  11517. else if (so.lsa.sa.sa_family == AF_INET6) {
  11518. len = sizeof(so.lsa.sin6);
  11519. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11520. mg_cry(fc(ctx),
  11521. "cannot bind to IPv6 %.*s: %d (%s)",
  11522. (int)vec.len,
  11523. vec.ptr,
  11524. (int)ERRNO,
  11525. strerror(errno));
  11526. closesocket(so.sock);
  11527. so.sock = INVALID_SOCKET;
  11528. continue;
  11529. }
  11530. }
  11531. #endif
  11532. else {
  11533. mg_cry(fc(ctx),
  11534. "cannot bind: address family not supported (entry %i)",
  11535. portsTotal);
  11536. closesocket(so.sock);
  11537. so.sock = INVALID_SOCKET;
  11538. continue;
  11539. }
  11540. if (listen(so.sock, SOMAXCONN) != 0) {
  11541. mg_cry(fc(ctx),
  11542. "cannot listen to %.*s: %d (%s)",
  11543. (int)vec.len,
  11544. vec.ptr,
  11545. (int)ERRNO,
  11546. strerror(errno));
  11547. closesocket(so.sock);
  11548. so.sock = INVALID_SOCKET;
  11549. continue;
  11550. }
  11551. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  11552. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  11553. int err = (int)ERRNO;
  11554. mg_cry(fc(ctx),
  11555. "call to getsockname failed %.*s: %d (%s)",
  11556. (int)vec.len,
  11557. vec.ptr,
  11558. err,
  11559. strerror(errno));
  11560. closesocket(so.sock);
  11561. so.sock = INVALID_SOCKET;
  11562. continue;
  11563. }
  11564. /* Update lsa port in case of random free ports */
  11565. #if defined(USE_IPV6)
  11566. if (so.lsa.sa.sa_family == AF_INET6) {
  11567. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  11568. } else
  11569. #endif
  11570. {
  11571. so.lsa.sin.sin_port = usa.sin.sin_port;
  11572. }
  11573. if ((ptr = (struct socket *)
  11574. mg_realloc_ctx(ctx->listening_sockets,
  11575. (ctx->num_listening_sockets + 1)
  11576. * sizeof(ctx->listening_sockets[0]),
  11577. ctx)) == NULL) {
  11578. mg_cry(fc(ctx), "%s", "Out of memory");
  11579. closesocket(so.sock);
  11580. so.sock = INVALID_SOCKET;
  11581. continue;
  11582. }
  11583. if ((pfd = (struct pollfd *)
  11584. mg_realloc_ctx(ctx->listening_socket_fds,
  11585. (ctx->num_listening_sockets + 1)
  11586. * sizeof(ctx->listening_socket_fds[0]),
  11587. ctx)) == NULL) {
  11588. mg_cry(fc(ctx), "%s", "Out of memory");
  11589. closesocket(so.sock);
  11590. so.sock = INVALID_SOCKET;
  11591. mg_free(ptr);
  11592. continue;
  11593. }
  11594. set_close_on_exec(so.sock, fc(ctx));
  11595. ctx->listening_sockets = ptr;
  11596. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  11597. ctx->listening_socket_fds = pfd;
  11598. ctx->num_listening_sockets++;
  11599. portsOk++;
  11600. }
  11601. if (portsOk != portsTotal) {
  11602. close_all_listening_sockets(ctx);
  11603. portsOk = 0;
  11604. }
  11605. return portsOk;
  11606. }
  11607. static const char *
  11608. header_val(const struct mg_connection *conn, const char *header)
  11609. {
  11610. const char *header_value;
  11611. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11612. return "-";
  11613. } else {
  11614. return header_value;
  11615. }
  11616. }
  11617. static void
  11618. log_access(const struct mg_connection *conn)
  11619. {
  11620. const struct mg_request_info *ri;
  11621. struct mg_file fi;
  11622. char date[64], src_addr[IP_ADDR_STR_LEN];
  11623. struct tm *tm;
  11624. const char *referer;
  11625. const char *user_agent;
  11626. char buf[4096];
  11627. if (!conn || !conn->ctx) {
  11628. return;
  11629. }
  11630. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  11631. if (mg_fopen(conn,
  11632. conn->ctx->config[ACCESS_LOG_FILE],
  11633. MG_FOPEN_MODE_APPEND,
  11634. &fi) == 0) {
  11635. fi.access.fp = NULL;
  11636. }
  11637. } else {
  11638. fi.access.fp = NULL;
  11639. }
  11640. /* Log is written to a file and/or a callback. If both are not set,
  11641. * executing the rest of the function is pointless. */
  11642. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  11643. return;
  11644. }
  11645. tm = localtime(&conn->conn_birth_time);
  11646. if (tm != NULL) {
  11647. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11648. } else {
  11649. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11650. date[sizeof(date) - 1] = '\0';
  11651. }
  11652. ri = &conn->request_info;
  11653. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11654. referer = header_val(conn, "Referer");
  11655. user_agent = header_val(conn, "User-Agent");
  11656. mg_snprintf(conn,
  11657. NULL, /* Ignore truncation in access log */
  11658. buf,
  11659. sizeof(buf),
  11660. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11661. src_addr,
  11662. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11663. date,
  11664. ri->request_method ? ri->request_method : "-",
  11665. ri->request_uri ? ri->request_uri : "-",
  11666. ri->query_string ? "?" : "",
  11667. ri->query_string ? ri->query_string : "",
  11668. ri->http_version,
  11669. conn->status_code,
  11670. conn->num_bytes_sent,
  11671. referer,
  11672. user_agent);
  11673. if (conn->ctx->callbacks.log_access) {
  11674. conn->ctx->callbacks.log_access(conn, buf);
  11675. }
  11676. if (fi.access.fp) {
  11677. int ok = 1;
  11678. flockfile(fi.access.fp);
  11679. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11680. ok = 0;
  11681. }
  11682. if (fflush(fi.access.fp) != 0) {
  11683. ok = 0;
  11684. }
  11685. funlockfile(fi.access.fp);
  11686. if (mg_fclose(&fi.access) != 0) {
  11687. ok = 0;
  11688. }
  11689. if (!ok) {
  11690. mg_cry(conn,
  11691. "Error writing log file %s",
  11692. conn->ctx->config[ACCESS_LOG_FILE]);
  11693. }
  11694. }
  11695. }
  11696. /* Verify given socket address against the ACL.
  11697. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  11698. */
  11699. static int
  11700. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  11701. {
  11702. int allowed, flag;
  11703. uint32_t net, mask;
  11704. struct vec vec;
  11705. if (ctx) {
  11706. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  11707. /* If any ACL is set, deny by default */
  11708. allowed = (list == NULL) ? '+' : '-';
  11709. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11710. flag = vec.ptr[0];
  11711. if ((flag != '+' && flag != '-')
  11712. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  11713. mg_cry(fc(ctx),
  11714. "%s: subnet must be [+|-]x.x.x.x[/x]",
  11715. __func__);
  11716. return -1;
  11717. }
  11718. if (net == (remote_ip & mask)) {
  11719. allowed = flag;
  11720. }
  11721. }
  11722. return allowed == '+';
  11723. }
  11724. return -1;
  11725. }
  11726. #if !defined(_WIN32)
  11727. static int
  11728. set_uid_option(struct mg_context *ctx)
  11729. {
  11730. int success = 0;
  11731. if (ctx) {
  11732. /* We are currently running as curr_uid. */
  11733. const uid_t curr_uid = getuid();
  11734. /* If set, we want to run as run_as_user. */
  11735. const char *run_as_user = ctx->config[RUN_AS_USER];
  11736. const struct passwd *to_pw = NULL;
  11737. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  11738. /* run_as_user does not exist on the system. We can't proceed
  11739. * further. */
  11740. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, run_as_user);
  11741. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  11742. /* There was either no request to change user, or we're already
  11743. * running as run_as_user. Nothing else to do.
  11744. */
  11745. success = 1;
  11746. } else {
  11747. /* Valid change request. */
  11748. if (setgid(to_pw->pw_gid) == -1) {
  11749. mg_cry(fc(ctx),
  11750. "%s: setgid(%s): %s",
  11751. __func__,
  11752. run_as_user,
  11753. strerror(errno));
  11754. } else if (setgroups(0, NULL) == -1) {
  11755. mg_cry(fc(ctx),
  11756. "%s: setgroups(): %s",
  11757. __func__,
  11758. strerror(errno));
  11759. } else if (setuid(to_pw->pw_uid) == -1) {
  11760. mg_cry(fc(ctx),
  11761. "%s: setuid(%s): %s",
  11762. __func__,
  11763. run_as_user,
  11764. strerror(errno));
  11765. } else {
  11766. success = 1;
  11767. }
  11768. }
  11769. }
  11770. return success;
  11771. }
  11772. #endif /* !_WIN32 */
  11773. static void
  11774. tls_dtor(void *key)
  11775. {
  11776. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  11777. /* key == pthread_getspecific(sTlsKey); */
  11778. if (tls) {
  11779. if (tls->is_master == 2) {
  11780. tls->is_master = -3; /* Mark memory as dead */
  11781. mg_free(tls);
  11782. }
  11783. }
  11784. pthread_setspecific(sTlsKey, NULL);
  11785. }
  11786. #if !defined(NO_SSL)
  11787. static int
  11788. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  11789. static const char *ssl_error(void);
  11790. static int
  11791. refresh_trust(struct mg_connection *conn)
  11792. {
  11793. static int reload_lock = 0;
  11794. static long int data_check = 0;
  11795. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  11796. struct stat cert_buf;
  11797. long int t;
  11798. const char *pem;
  11799. const char *chain;
  11800. int should_verify_peer;
  11801. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  11802. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  11803. * refresh_trust still can not work. */
  11804. return 0;
  11805. }
  11806. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  11807. if (chain == NULL) {
  11808. /* pem is not NULL here */
  11809. chain = pem;
  11810. }
  11811. if (*chain == 0) {
  11812. chain = NULL;
  11813. }
  11814. t = data_check;
  11815. if (stat(pem, &cert_buf) != -1) {
  11816. t = (long int)cert_buf.st_mtime;
  11817. }
  11818. if (data_check != t) {
  11819. data_check = t;
  11820. should_verify_peer = 0;
  11821. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11822. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  11823. == 0) {
  11824. should_verify_peer = 1;
  11825. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  11826. "optional") == 0) {
  11827. should_verify_peer = 1;
  11828. }
  11829. }
  11830. if (should_verify_peer) {
  11831. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  11832. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  11833. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  11834. ca_file,
  11835. ca_path) != 1) {
  11836. mg_cry(fc(conn->ctx),
  11837. "SSL_CTX_load_verify_locations error: %s "
  11838. "ssl_verify_peer requires setting "
  11839. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11840. "present in "
  11841. "the .conf file?",
  11842. ssl_error());
  11843. return 0;
  11844. }
  11845. }
  11846. if (1 == mg_atomic_inc(p_reload_lock)) {
  11847. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  11848. return 0;
  11849. }
  11850. *p_reload_lock = 0;
  11851. }
  11852. }
  11853. /* lock while cert is reloading */
  11854. while (*p_reload_lock) {
  11855. sleep(1);
  11856. }
  11857. return 1;
  11858. }
  11859. #ifdef OPENSSL_API_1_1
  11860. #else
  11861. static pthread_mutex_t *ssl_mutexes;
  11862. #endif /* OPENSSL_API_1_1 */
  11863. static int
  11864. sslize(struct mg_connection *conn,
  11865. SSL_CTX *s,
  11866. int (*func)(SSL *),
  11867. volatile int *stop_server)
  11868. {
  11869. int ret, err;
  11870. int short_trust;
  11871. unsigned i;
  11872. if (!conn) {
  11873. return 0;
  11874. }
  11875. short_trust =
  11876. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  11877. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  11878. if (short_trust) {
  11879. int trust_ret = refresh_trust(conn);
  11880. if (!trust_ret) {
  11881. return trust_ret;
  11882. }
  11883. }
  11884. conn->ssl = SSL_new(s);
  11885. if (conn->ssl == NULL) {
  11886. return 0;
  11887. }
  11888. SSL_set_app_data(conn->ssl, (char *)conn);
  11889. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  11890. if (ret != 1) {
  11891. err = SSL_get_error(conn->ssl, ret);
  11892. (void)err; /* TODO: set some error message */
  11893. SSL_free(conn->ssl);
  11894. conn->ssl = NULL;
  11895. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11896. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11897. #ifndef OPENSSL_API_1_1
  11898. ERR_remove_state(0);
  11899. #endif
  11900. return 0;
  11901. }
  11902. /* SSL functions may fail and require to be called again:
  11903. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  11904. * Here "func" could be SSL_connect or SSL_accept. */
  11905. for (i = 16; i <= 1024; i *= 2) {
  11906. ret = func(conn->ssl);
  11907. if (ret != 1) {
  11908. err = SSL_get_error(conn->ssl, ret);
  11909. if ((err == SSL_ERROR_WANT_CONNECT)
  11910. || (err == SSL_ERROR_WANT_ACCEPT)
  11911. || (err == SSL_ERROR_WANT_READ)
  11912. || (err == SSL_ERROR_WANT_WRITE)) {
  11913. /* Need to retry the function call "later".
  11914. * See https://linux.die.net/man/3/ssl_get_error
  11915. * This is typical for non-blocking sockets. */
  11916. if (*stop_server) {
  11917. /* Don't wait if the server is going to be stopped. */
  11918. break;
  11919. }
  11920. mg_sleep(i);
  11921. } else if (err == SSL_ERROR_SYSCALL) {
  11922. /* This is an IO error. Look at errno. */
  11923. err = errno;
  11924. /* TODO: set some error message */
  11925. (void)err;
  11926. break;
  11927. } else {
  11928. /* This is an SSL specific error */
  11929. /* TODO: set some error message */
  11930. break;
  11931. }
  11932. } else {
  11933. /* success */
  11934. break;
  11935. }
  11936. }
  11937. if (ret != 1) {
  11938. SSL_free(conn->ssl);
  11939. conn->ssl = NULL;
  11940. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11941. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11942. #ifndef OPENSSL_API_1_1
  11943. ERR_remove_state(0);
  11944. #endif
  11945. return 0;
  11946. }
  11947. return 1;
  11948. }
  11949. /* Return OpenSSL error message (from CRYPTO lib) */
  11950. static const char *
  11951. ssl_error(void)
  11952. {
  11953. unsigned long err;
  11954. err = ERR_get_error();
  11955. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  11956. }
  11957. static int
  11958. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  11959. {
  11960. int i;
  11961. const char hexdigit[] = "0123456789abcdef";
  11962. if ((memlen <= 0) || (buflen <= 0)) {
  11963. return 0;
  11964. }
  11965. if (buflen < (3 * memlen)) {
  11966. return 0;
  11967. }
  11968. for (i = 0; i < memlen; i++) {
  11969. if (i > 0) {
  11970. buf[3 * i - 1] = ' ';
  11971. }
  11972. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  11973. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  11974. }
  11975. buf[3 * memlen - 1] = 0;
  11976. return 1;
  11977. }
  11978. static void
  11979. ssl_get_client_cert_info(struct mg_connection *conn)
  11980. {
  11981. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  11982. if (cert) {
  11983. char str_subject[1024];
  11984. char str_issuer[1024];
  11985. char str_finger[1024];
  11986. unsigned char buf[256];
  11987. char *str_serial = NULL;
  11988. unsigned int ulen;
  11989. int ilen;
  11990. unsigned char *tmp_buf;
  11991. unsigned char *tmp_p;
  11992. /* Handle to algorithm used for fingerprint */
  11993. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  11994. /* Get Subject and issuer */
  11995. X509_NAME *subj = X509_get_subject_name(cert);
  11996. X509_NAME *iss = X509_get_issuer_name(cert);
  11997. /* Get serial number */
  11998. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  11999. /* Translate serial number to a hex string */
  12000. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12001. str_serial = BN_bn2hex(serial_bn);
  12002. BN_free(serial_bn);
  12003. /* Translate subject and issuer to a string */
  12004. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12005. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12006. /* Calculate SHA1 fingerprint and store as a hex string */
  12007. ulen = 0;
  12008. /* ASN1_digest is deprecated. Do the calculation manually,
  12009. * using EVP_Digest. */
  12010. ilen = i2d_X509(cert, NULL);
  12011. tmp_buf =
  12012. (ilen > 0)
  12013. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  12014. : NULL;
  12015. if (tmp_buf) {
  12016. tmp_p = tmp_buf;
  12017. (void)i2d_X509(cert, &tmp_p);
  12018. if (!EVP_Digest(
  12019. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12020. ulen = 0;
  12021. }
  12022. mg_free(tmp_buf);
  12023. }
  12024. if (!hexdump2string(
  12025. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12026. *str_finger = 0;
  12027. }
  12028. conn->request_info.client_cert = (struct mg_client_cert *)
  12029. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->ctx);
  12030. if (conn->request_info.client_cert) {
  12031. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  12032. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  12033. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  12034. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  12035. } else {
  12036. mg_cry(conn,
  12037. "Out of memory: Cannot allocate memory for client "
  12038. "certificate");
  12039. }
  12040. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  12041. * see https://linux.die.net/man/3/bn_bn2hex */
  12042. OPENSSL_free(str_serial);
  12043. /* Free certificate memory */
  12044. X509_free(cert);
  12045. }
  12046. }
  12047. #ifdef OPENSSL_API_1_1
  12048. #else
  12049. static void
  12050. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  12051. {
  12052. (void)line;
  12053. (void)file;
  12054. if (mode & 1) {
  12055. /* 1 is CRYPTO_LOCK */
  12056. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  12057. } else {
  12058. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  12059. }
  12060. }
  12061. #endif /* OPENSSL_API_1_1 */
  12062. #if !defined(NO_SSL_DL)
  12063. static void *
  12064. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  12065. {
  12066. union {
  12067. void *p;
  12068. void (*fp)(void);
  12069. } u;
  12070. void *dll_handle;
  12071. struct ssl_func *fp;
  12072. int ok;
  12073. int truncated = 0;
  12074. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  12075. mg_snprintf(NULL,
  12076. NULL, /* No truncation check for ebuf */
  12077. ebuf,
  12078. ebuf_len,
  12079. "%s: cannot load %s",
  12080. __func__,
  12081. dll_name);
  12082. return NULL;
  12083. }
  12084. ok = 1;
  12085. for (fp = sw; fp->name != NULL; fp++) {
  12086. #ifdef _WIN32
  12087. /* GetProcAddress() returns pointer to function */
  12088. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  12089. #else
  12090. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  12091. * pointers to function pointers. We need to use a union to make a
  12092. * cast. */
  12093. u.p = dlsym(dll_handle, fp->name);
  12094. #endif /* _WIN32 */
  12095. if (u.fp == NULL) {
  12096. if (ok) {
  12097. mg_snprintf(NULL,
  12098. &truncated,
  12099. ebuf,
  12100. ebuf_len,
  12101. "%s: %s: cannot find %s",
  12102. __func__,
  12103. dll_name,
  12104. fp->name);
  12105. ok = 0;
  12106. } else {
  12107. size_t cur_len = strlen(ebuf);
  12108. if (!truncated) {
  12109. mg_snprintf(NULL,
  12110. &truncated,
  12111. ebuf + cur_len,
  12112. ebuf_len - cur_len - 3,
  12113. ", %s",
  12114. fp->name);
  12115. if (truncated) {
  12116. /* If truncated, add "..." */
  12117. strcat(ebuf, "...");
  12118. }
  12119. }
  12120. }
  12121. /* Debug:
  12122. * printf("Missing function: %s\n", fp->name); */
  12123. } else {
  12124. fp->ptr = u.fp;
  12125. }
  12126. }
  12127. if (!ok) {
  12128. (void)dlclose(dll_handle);
  12129. return NULL;
  12130. }
  12131. return dll_handle;
  12132. }
  12133. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  12134. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  12135. #endif /* NO_SSL_DL */
  12136. #if defined(SSL_ALREADY_INITIALIZED)
  12137. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  12138. #else
  12139. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  12140. #endif
  12141. static int
  12142. initialize_ssl(char *ebuf, size_t ebuf_len)
  12143. {
  12144. #ifdef OPENSSL_API_1_1
  12145. if (ebuf_len > 0) {
  12146. ebuf[0] = 0;
  12147. }
  12148. #if !defined(NO_SSL_DL)
  12149. if (!cryptolib_dll_handle) {
  12150. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12151. if (!cryptolib_dll_handle) {
  12152. mg_snprintf(NULL,
  12153. NULL, /* No truncation check for ebuf */
  12154. ebuf,
  12155. ebuf_len,
  12156. "%s: error loading library %s",
  12157. __func__,
  12158. CRYPTO_LIB);
  12159. DEBUG_TRACE("%s", ebuf);
  12160. return 0;
  12161. }
  12162. }
  12163. #endif /* NO_SSL_DL */
  12164. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12165. return 1;
  12166. }
  12167. #else /* not OPENSSL_API_1_1 */
  12168. int i;
  12169. size_t size;
  12170. if (ebuf_len > 0) {
  12171. ebuf[0] = 0;
  12172. }
  12173. #if !defined(NO_SSL_DL)
  12174. if (!cryptolib_dll_handle) {
  12175. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12176. if (!cryptolib_dll_handle) {
  12177. mg_snprintf(NULL,
  12178. NULL, /* No truncation check for ebuf */
  12179. ebuf,
  12180. ebuf_len,
  12181. "%s: error loading library %s",
  12182. __func__,
  12183. CRYPTO_LIB);
  12184. DEBUG_TRACE("%s", ebuf);
  12185. return 0;
  12186. }
  12187. }
  12188. #endif /* NO_SSL_DL */
  12189. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12190. return 1;
  12191. }
  12192. /* Initialize locking callbacks, needed for thread safety.
  12193. * http://www.openssl.org/support/faq.html#PROG1
  12194. */
  12195. i = CRYPTO_num_locks();
  12196. if (i < 0) {
  12197. i = 0;
  12198. }
  12199. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  12200. if (size == 0) {
  12201. ssl_mutexes = NULL;
  12202. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  12203. mg_snprintf(NULL,
  12204. NULL, /* No truncation check for ebuf */
  12205. ebuf,
  12206. ebuf_len,
  12207. "%s: cannot allocate mutexes: %s",
  12208. __func__,
  12209. ssl_error());
  12210. DEBUG_TRACE("%s", ebuf);
  12211. return 0;
  12212. }
  12213. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12214. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  12215. }
  12216. CRYPTO_set_locking_callback(&ssl_locking_callback);
  12217. CRYPTO_set_id_callback(&mg_current_thread_id);
  12218. #endif /* OPENSSL_API_1_1 */
  12219. #if !defined(NO_SSL_DL)
  12220. if (!ssllib_dll_handle) {
  12221. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  12222. if (!ssllib_dll_handle) {
  12223. DEBUG_TRACE("%s", ebuf);
  12224. return 0;
  12225. }
  12226. }
  12227. #endif /* NO_SSL_DL */
  12228. #ifdef OPENSSL_API_1_1
  12229. /* Initialize SSL library */
  12230. OPENSSL_init_ssl(0, NULL);
  12231. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  12232. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  12233. NULL);
  12234. #else
  12235. /* Initialize SSL library */
  12236. SSL_library_init();
  12237. SSL_load_error_strings();
  12238. #endif
  12239. return 1;
  12240. }
  12241. static int
  12242. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  12243. {
  12244. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  12245. mg_cry(fc(ctx),
  12246. "%s: cannot open certificate file %s: %s",
  12247. __func__,
  12248. pem,
  12249. ssl_error());
  12250. return 0;
  12251. }
  12252. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  12253. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  12254. mg_cry(fc(ctx),
  12255. "%s: cannot open private key file %s: %s",
  12256. __func__,
  12257. pem,
  12258. ssl_error());
  12259. return 0;
  12260. }
  12261. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  12262. mg_cry(fc(ctx),
  12263. "%s: certificate and private key do not match: %s",
  12264. __func__,
  12265. pem);
  12266. return 0;
  12267. }
  12268. /* In contrast to OpenSSL, wolfSSL does not support certificate
  12269. * chain files that contain private keys and certificates in
  12270. * SSL_CTX_use_certificate_chain_file.
  12271. * The CivetWeb-Server used pem-Files that contained both information.
  12272. * In order to make wolfSSL work, it is split in two files.
  12273. * One file that contains key and certificate used by the server and
  12274. * an optional chain file for the ssl stack.
  12275. */
  12276. if (chain) {
  12277. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  12278. mg_cry(fc(ctx),
  12279. "%s: cannot use certificate chain file %s: %s",
  12280. __func__,
  12281. pem,
  12282. ssl_error());
  12283. return 0;
  12284. }
  12285. }
  12286. return 1;
  12287. }
  12288. #ifdef OPENSSL_API_1_1
  12289. static unsigned long
  12290. ssl_get_protocol(int version_id)
  12291. {
  12292. long unsigned ret = SSL_OP_ALL;
  12293. if (version_id > 0)
  12294. ret |= SSL_OP_NO_SSLv2;
  12295. if (version_id > 1)
  12296. ret |= SSL_OP_NO_SSLv3;
  12297. if (version_id > 2)
  12298. ret |= SSL_OP_NO_TLSv1;
  12299. if (version_id > 3)
  12300. ret |= SSL_OP_NO_TLSv1_1;
  12301. return ret;
  12302. }
  12303. #else
  12304. static long
  12305. ssl_get_protocol(int version_id)
  12306. {
  12307. long ret = SSL_OP_ALL;
  12308. if (version_id > 0)
  12309. ret |= SSL_OP_NO_SSLv2;
  12310. if (version_id > 1)
  12311. ret |= SSL_OP_NO_SSLv3;
  12312. if (version_id > 2)
  12313. ret |= SSL_OP_NO_TLSv1;
  12314. if (version_id > 3)
  12315. ret |= SSL_OP_NO_TLSv1_1;
  12316. return ret;
  12317. }
  12318. #endif /* OPENSSL_API_1_1 */
  12319. /* SSL callback documentation:
  12320. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  12321. * https://linux.die.net/man/3/ssl_set_info_callback */
  12322. static void
  12323. ssl_info_callback(SSL *ssl, int what, int ret)
  12324. {
  12325. (void)ret;
  12326. if (what & SSL_CB_HANDSHAKE_START) {
  12327. SSL_get_app_data(ssl);
  12328. }
  12329. if (what & SSL_CB_HANDSHAKE_DONE) {
  12330. /* TODO: check for openSSL 1.1 */
  12331. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  12332. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  12333. }
  12334. }
  12335. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  12336. static int
  12337. set_ssl_option(struct mg_context *ctx)
  12338. {
  12339. const char *pem;
  12340. const char *chain;
  12341. int callback_ret;
  12342. int should_verify_peer;
  12343. int peer_certificate_optional;
  12344. const char *ca_path;
  12345. const char *ca_file;
  12346. int use_default_verify_paths;
  12347. int verify_depth;
  12348. time_t now_rt = time(NULL);
  12349. struct timespec now_mt;
  12350. md5_byte_t ssl_context_id[16];
  12351. md5_state_t md5state;
  12352. int protocol_ver;
  12353. char ebuf[128];
  12354. if (!ctx) {
  12355. return 0;
  12356. }
  12357. if (!is_ssl_port_used(ctx->config[LISTENING_PORTS])) {
  12358. /* No SSL port is set. No need to setup SSL. */
  12359. return 1;
  12360. }
  12361. /* Check for external SSL_CTX */
  12362. SSL_CTX* ssl_ctx = 0;
  12363. callback_ret =
  12364. (ctx->callbacks.get_external_ssl_ctx == NULL)
  12365. ? 0
  12366. : (ctx->callbacks.get_external_ssl_ctx(&ssl_ctx, ctx->user_data));
  12367. if (callback_ret < 0) {
  12368. mg_cry(fc(ctx), "get_external_ssl_ctx callback returned error: %i", callback_ret);
  12369. return 0;
  12370. }
  12371. else if (callback_ret > 0) {
  12372. ctx->ssl_ctx = ssl_ctx;
  12373. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12374. mg_cry(fc(ctx), "%s", ebuf);
  12375. return 0;
  12376. }
  12377. #if !defined(NO_SSL_DL)
  12378. if (!ssllib_dll_handle) {
  12379. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  12380. if (!ssllib_dll_handle) {
  12381. mg_cry(fc(ctx), "%s", ebuf);
  12382. return 0;
  12383. }
  12384. }
  12385. #endif /* NO_SSL_DL */
  12386. return 1;
  12387. }
  12388. /* else continue */
  12389. /* If PEM file is not specified and the init_ssl callback
  12390. * is not specified, setup will fail. */
  12391. if (((pem = ctx->config[SSL_CERTIFICATE]) == NULL)
  12392. && (ctx->callbacks.init_ssl == NULL)) {
  12393. /* No certificate and no callback:
  12394. * Essential data to set up TLS is missing.
  12395. */
  12396. mg_cry(fc(ctx),
  12397. "Initializing SSL failed: -%s is not set",
  12398. config_options[SSL_CERTIFICATE].name);
  12399. return 0;
  12400. }
  12401. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  12402. if (chain == NULL) {
  12403. chain = pem;
  12404. }
  12405. if ((chain != NULL) && (*chain == 0)) {
  12406. chain = NULL;
  12407. }
  12408. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12409. mg_cry(fc(ctx), "%s", ebuf);
  12410. return 0;
  12411. }
  12412. #ifdef OPENSSL_API_1_1
  12413. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  12414. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  12415. return 0;
  12416. }
  12417. #else
  12418. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  12419. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  12420. return 0;
  12421. }
  12422. #endif /* OPENSSL_API_1_1 */
  12423. SSL_CTX_clear_options(ctx->ssl_ctx,
  12424. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  12425. | SSL_OP_NO_TLSv1_1);
  12426. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  12427. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  12428. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  12429. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  12430. SSL_CTX_set_options(ctx->ssl_ctx,
  12431. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12432. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  12433. #if !defined(NO_SSL_DL)
  12434. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  12435. #endif /* NO_SSL_DL */
  12436. #ifdef __clang__
  12437. #pragma clang diagnostic push
  12438. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  12439. #endif
  12440. /* Depending on the OpenSSL version, the callback may be
  12441. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  12442. * yielding in an "incompatible-pointer-type" warning for the other
  12443. * version. It seems to be "unclear" what is correct:
  12444. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  12445. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  12446. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  12447. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  12448. * Disable this warning here.
  12449. * Alternative would be a version dependent ssl_info_callback and
  12450. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  12451. */
  12452. SSL_CTX_set_info_callback(ctx->ssl_ctx, ssl_info_callback);
  12453. #ifdef __clang__
  12454. #pragma clang diagnostic pop
  12455. #endif
  12456. /* If a callback has been specified, call it. */
  12457. callback_ret =
  12458. (ctx->callbacks.init_ssl == NULL)
  12459. ? 0
  12460. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  12461. /* If callback returns 0, civetweb sets up the SSL certificate.
  12462. * If it returns 1, civetweb assumes the calback already did this.
  12463. * If it returns -1, initializing ssl fails. */
  12464. if (callback_ret < 0) {
  12465. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  12466. return 0;
  12467. }
  12468. if (callback_ret > 0) {
  12469. /* Callback did everything. */
  12470. return 1;
  12471. }
  12472. /* Use some UID as session context ID. */
  12473. md5_init(&md5state);
  12474. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  12475. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  12476. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  12477. md5_append(&md5state,
  12478. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  12479. strlen(ctx->config[LISTENING_PORTS]));
  12480. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  12481. md5_finish(&md5state, ssl_context_id);
  12482. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  12483. (const unsigned char *)&ssl_context_id,
  12484. sizeof(ssl_context_id));
  12485. if (pem != NULL) {
  12486. if (!ssl_use_pem_file(ctx, pem, chain)) {
  12487. return 0;
  12488. }
  12489. }
  12490. /* Should we support client certificates? */
  12491. /* Default is "no". */
  12492. should_verify_peer = 0;
  12493. peer_certificate_optional = 0;
  12494. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12495. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  12496. /* Yes, they are mandatory */
  12497. should_verify_peer = 1;
  12498. peer_certificate_optional = 0;
  12499. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  12500. == 0) {
  12501. /* Yes, they are optional */
  12502. should_verify_peer = 1;
  12503. peer_certificate_optional = 1;
  12504. }
  12505. }
  12506. use_default_verify_paths =
  12507. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  12508. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  12509. if (should_verify_peer) {
  12510. ca_path = ctx->config[SSL_CA_PATH];
  12511. ca_file = ctx->config[SSL_CA_FILE];
  12512. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  12513. != 1) {
  12514. mg_cry(fc(ctx),
  12515. "SSL_CTX_load_verify_locations error: %s "
  12516. "ssl_verify_peer requires setting "
  12517. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12518. "present in "
  12519. "the .conf file?",
  12520. ssl_error());
  12521. return 0;
  12522. }
  12523. if (peer_certificate_optional) {
  12524. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  12525. } else {
  12526. SSL_CTX_set_verify(ctx->ssl_ctx,
  12527. SSL_VERIFY_PEER
  12528. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  12529. NULL);
  12530. }
  12531. if (use_default_verify_paths
  12532. && (SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1)) {
  12533. mg_cry(fc(ctx),
  12534. "SSL_CTX_set_default_verify_paths error: %s",
  12535. ssl_error());
  12536. return 0;
  12537. }
  12538. if (ctx->config[SSL_VERIFY_DEPTH]) {
  12539. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  12540. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  12541. }
  12542. }
  12543. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  12544. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  12545. != 1) {
  12546. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  12547. }
  12548. }
  12549. return 1;
  12550. }
  12551. static void
  12552. uninitialize_ssl(void)
  12553. {
  12554. #ifdef OPENSSL_API_1_1
  12555. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12556. /* Shutdown according to
  12557. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12558. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12559. */
  12560. CONF_modules_unload(1);
  12561. #else
  12562. int i;
  12563. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12564. /* Shutdown according to
  12565. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12566. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12567. */
  12568. CRYPTO_set_locking_callback(NULL);
  12569. CRYPTO_set_id_callback(NULL);
  12570. ENGINE_cleanup();
  12571. CONF_modules_unload(1);
  12572. ERR_free_strings();
  12573. EVP_cleanup();
  12574. CRYPTO_cleanup_all_ex_data();
  12575. ERR_remove_state(0);
  12576. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12577. pthread_mutex_destroy(&ssl_mutexes[i]);
  12578. }
  12579. mg_free(ssl_mutexes);
  12580. ssl_mutexes = NULL;
  12581. #endif /* OPENSSL_API_1_1 */
  12582. }
  12583. }
  12584. #endif /* !NO_SSL */
  12585. static int
  12586. set_gpass_option(struct mg_context *ctx)
  12587. {
  12588. if (ctx) {
  12589. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12590. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  12591. if ((path != NULL) && !mg_stat(fc(ctx), path, &file.stat)) {
  12592. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  12593. return 0;
  12594. }
  12595. return 1;
  12596. }
  12597. return 0;
  12598. }
  12599. static int
  12600. set_acl_option(struct mg_context *ctx)
  12601. {
  12602. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  12603. }
  12604. static void
  12605. reset_per_request_attributes(struct mg_connection *conn)
  12606. {
  12607. if (!conn) {
  12608. return;
  12609. }
  12610. conn->connection_type =
  12611. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  12612. conn->num_bytes_sent = conn->consumed_content = 0;
  12613. conn->path_info = NULL;
  12614. conn->status_code = -1;
  12615. conn->content_len = -1;
  12616. conn->is_chunked = 0;
  12617. conn->must_close = 0;
  12618. conn->request_len = 0;
  12619. conn->throttle = 0;
  12620. conn->data_len = 0;
  12621. conn->chunk_remainder = 0;
  12622. conn->accept_gzip = 0;
  12623. conn->response_info.content_length = conn->request_info.content_length = -1;
  12624. conn->response_info.http_version = conn->request_info.http_version = NULL;
  12625. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  12626. conn->response_info.status_text = NULL;
  12627. conn->response_info.status_code = 0;
  12628. conn->request_info.remote_user = NULL;
  12629. conn->request_info.request_method = NULL;
  12630. conn->request_info.request_uri = NULL;
  12631. conn->request_info.local_uri = NULL;
  12632. #if defined(MG_LEGACY_INTERFACE)
  12633. /* Legacy before split into local_uri and request_uri */
  12634. conn->request_info.uri = NULL;
  12635. #endif
  12636. }
  12637. #if 0
  12638. /* Note: set_sock_timeout is not required for non-blocking sockets.
  12639. * Leave this function here (commented out) for reference until
  12640. * CivetWeb 1.9 is tested, and the tests confirme this function is
  12641. * no longer required.
  12642. */
  12643. static int
  12644. set_sock_timeout(SOCKET sock, int milliseconds)
  12645. {
  12646. int r0 = 0, r1, r2;
  12647. #ifdef _WIN32
  12648. /* Windows specific */
  12649. DWORD tv = (DWORD)milliseconds;
  12650. #else
  12651. /* Linux, ... (not Windows) */
  12652. struct timeval tv;
  12653. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  12654. * max. time waiting for the acknowledged of TCP data before the connection
  12655. * will be forcefully closed and ETIMEDOUT is returned to the application.
  12656. * If this option is not set, the default timeout of 20-30 minutes is used.
  12657. */
  12658. /* #define TCP_USER_TIMEOUT (18) */
  12659. #if defined(TCP_USER_TIMEOUT)
  12660. unsigned int uto = (unsigned int)milliseconds;
  12661. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  12662. #endif
  12663. memset(&tv, 0, sizeof(tv));
  12664. tv.tv_sec = milliseconds / 1000;
  12665. tv.tv_usec = (milliseconds * 1000) % 1000000;
  12666. #endif /* _WIN32 */
  12667. r1 = setsockopt(
  12668. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12669. r2 = setsockopt(
  12670. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12671. return r0 || r1 || r2;
  12672. }
  12673. #endif
  12674. static int
  12675. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  12676. {
  12677. if (setsockopt(sock,
  12678. IPPROTO_TCP,
  12679. TCP_NODELAY,
  12680. (SOCK_OPT_TYPE)&nodelay_on,
  12681. sizeof(nodelay_on)) != 0) {
  12682. /* Error */
  12683. return 1;
  12684. }
  12685. /* OK */
  12686. return 0;
  12687. }
  12688. static void
  12689. close_socket_gracefully(struct mg_connection *conn)
  12690. {
  12691. #if defined(_WIN32)
  12692. char buf[MG_BUF_LEN];
  12693. int n;
  12694. #endif
  12695. struct linger linger;
  12696. int error_code = 0;
  12697. int linger_timeout = -2;
  12698. socklen_t opt_len = sizeof(error_code);
  12699. if (!conn) {
  12700. return;
  12701. }
  12702. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  12703. * "Note that enabling a nonzero timeout on a nonblocking socket
  12704. * is not recommended.", so set it to blocking now */
  12705. set_blocking_mode(conn->client.sock);
  12706. /* Send FIN to the client */
  12707. shutdown(conn->client.sock, SHUTDOWN_WR);
  12708. #if defined(_WIN32)
  12709. /* Read and discard pending incoming data. If we do not do that and
  12710. * close
  12711. * the socket, the data in the send buffer may be discarded. This
  12712. * behaviour is seen on Windows, when client keeps sending data
  12713. * when server decides to close the connection; then when client
  12714. * does recv() it gets no data back. */
  12715. do {
  12716. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  12717. } while (n > 0);
  12718. #endif
  12719. if (conn->ctx->config[LINGER_TIMEOUT]) {
  12720. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  12721. }
  12722. /* Set linger option according to configuration */
  12723. if (linger_timeout >= 0) {
  12724. /* Set linger option to avoid socket hanging out after close. This
  12725. * prevent ephemeral port exhaust problem under high QPS. */
  12726. linger.l_onoff = 1;
  12727. #if defined(_MSC_VER)
  12728. #pragma warning(push)
  12729. #pragma warning(disable : 4244)
  12730. #endif
  12731. #if defined(__GNUC__) || defined(__MINGW32__)
  12732. #pragma GCC diagnostic push
  12733. #pragma GCC diagnostic ignored "-Wconversion"
  12734. #endif
  12735. /* Data type of linger structure elements may differ,
  12736. * so we don't know what cast we need here.
  12737. * Disable type conversion warnings. */
  12738. linger.l_linger = (linger_timeout + 999) / 1000;
  12739. #if defined(__GNUC__) || defined(__MINGW32__)
  12740. #pragma GCC diagnostic pop
  12741. #endif
  12742. #if defined(_MSC_VER)
  12743. #pragma warning(pop)
  12744. #endif
  12745. } else {
  12746. linger.l_onoff = 0;
  12747. linger.l_linger = 0;
  12748. }
  12749. if (linger_timeout < -1) {
  12750. /* Default: don't configure any linger */
  12751. } else if (getsockopt(conn->client.sock,
  12752. SOL_SOCKET,
  12753. SO_ERROR,
  12754. (char *)&error_code,
  12755. &opt_len) != 0) {
  12756. /* Cannot determine if socket is already closed. This should
  12757. * not occur and never did in a test. Log an error message
  12758. * and continue. */
  12759. mg_cry(conn,
  12760. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  12761. __func__,
  12762. strerror(ERRNO));
  12763. } else if (error_code == ECONNRESET) {
  12764. /* Socket already closed by client/peer, close socket without linger
  12765. */
  12766. } else {
  12767. /* Set linger timeout */
  12768. if (setsockopt(conn->client.sock,
  12769. SOL_SOCKET,
  12770. SO_LINGER,
  12771. (char *)&linger,
  12772. sizeof(linger)) != 0) {
  12773. mg_cry(conn,
  12774. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  12775. __func__,
  12776. linger.l_onoff,
  12777. linger.l_linger,
  12778. strerror(ERRNO));
  12779. }
  12780. }
  12781. /* Now we know that our FIN is ACK-ed, safe to close */
  12782. closesocket(conn->client.sock);
  12783. conn->client.sock = INVALID_SOCKET;
  12784. }
  12785. static void
  12786. close_connection(struct mg_connection *conn)
  12787. {
  12788. #if defined(USE_SERVER_STATS)
  12789. conn->conn_state = 6; /* to close */
  12790. #endif
  12791. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12792. if (conn->lua_websocket_state) {
  12793. lua_websocket_close(conn, conn->lua_websocket_state);
  12794. conn->lua_websocket_state = NULL;
  12795. }
  12796. #endif
  12797. mg_lock_connection(conn);
  12798. /* Set close flag, so keep-alive loops will stop */
  12799. conn->must_close = 1;
  12800. /* call the connection_close callback if assigned */
  12801. if (conn->ctx->callbacks.connection_close != NULL) {
  12802. if (conn->ctx->context_type == CONTEXT_SERVER) {
  12803. conn->ctx->callbacks.connection_close(conn);
  12804. }
  12805. }
  12806. /* Reset user data, after close callback is called.
  12807. * Do not reuse it. If the user needs a destructor,
  12808. * it must be done in the connection_close callback. */
  12809. mg_set_user_connection_data(conn, NULL);
  12810. #if defined(USE_SERVER_STATS)
  12811. conn->conn_state = 7; /* closing */
  12812. #endif
  12813. #ifndef NO_SSL
  12814. if (conn->ssl != NULL) {
  12815. /* Run SSL_shutdown twice to ensure completly close SSL connection
  12816. */
  12817. SSL_shutdown(conn->ssl);
  12818. SSL_free(conn->ssl);
  12819. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12820. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12821. #ifndef OPENSSL_API_1_1
  12822. ERR_remove_state(0);
  12823. #endif
  12824. conn->ssl = NULL;
  12825. }
  12826. #endif
  12827. if (conn->client.sock != INVALID_SOCKET) {
  12828. close_socket_gracefully(conn);
  12829. conn->client.sock = INVALID_SOCKET;
  12830. }
  12831. mg_unlock_connection(conn);
  12832. #if defined(USE_SERVER_STATS)
  12833. conn->conn_state = 8; /* closed */
  12834. #endif
  12835. }
  12836. void
  12837. mg_close_connection(struct mg_connection *conn)
  12838. {
  12839. #if defined(USE_WEBSOCKET)
  12840. struct mg_context *client_ctx = NULL;
  12841. #endif /* defined(USE_WEBSOCKET) */
  12842. if ((conn == NULL) || (conn->ctx == NULL)) {
  12843. return;
  12844. }
  12845. #if defined(USE_WEBSOCKET)
  12846. if (conn->ctx->context_type == CONTEXT_SERVER) {
  12847. if (conn->in_websocket_handling) {
  12848. /* Set close flag, so the server thread can exit. */
  12849. conn->must_close = 1;
  12850. return;
  12851. }
  12852. }
  12853. if (conn->ctx->context_type == CONTEXT_WS_CLIENT) {
  12854. unsigned int i;
  12855. /* ws/wss client */
  12856. client_ctx = conn->ctx;
  12857. /* client context: loops must end */
  12858. conn->ctx->stop_flag = 1;
  12859. conn->must_close = 1;
  12860. /* We need to get the client thread out of the select/recv call
  12861. * here. */
  12862. /* Since we use a sleep quantum of some seconds to check for recv
  12863. * timeouts, we will just wait a few seconds in mg_join_thread. */
  12864. /* join worker thread */
  12865. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  12866. if (client_ctx->worker_threadids[i] != 0) {
  12867. mg_join_thread(client_ctx->worker_threadids[i]);
  12868. }
  12869. }
  12870. }
  12871. #endif /* defined(USE_WEBSOCKET) */
  12872. close_connection(conn);
  12873. #ifndef NO_SSL
  12874. if (conn->client_ssl_ctx != NULL) {
  12875. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  12876. }
  12877. #endif
  12878. #if defined(USE_WEBSOCKET)
  12879. if (client_ctx != NULL) {
  12880. /* free context */
  12881. mg_free(client_ctx->worker_threadids);
  12882. mg_free(client_ctx);
  12883. (void)pthread_mutex_destroy(&conn->mutex);
  12884. mg_free(conn);
  12885. } else if (conn->ctx->context_type == CONTEXT_HTTP_CLIENT) {
  12886. mg_free(conn);
  12887. }
  12888. #else
  12889. if (conn->ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  12890. mg_free(conn);
  12891. }
  12892. #endif /* defined(USE_WEBSOCKET) */
  12893. }
  12894. /* Only for memory statistics */
  12895. static struct mg_context common_client_context;
  12896. static struct mg_connection *
  12897. mg_connect_client_impl(const struct mg_client_options *client_options,
  12898. int use_ssl,
  12899. char *ebuf,
  12900. size_t ebuf_len)
  12901. {
  12902. struct mg_connection *conn = NULL;
  12903. SOCKET sock;
  12904. union usa sa;
  12905. struct sockaddr *psa;
  12906. socklen_t len;
  12907. unsigned max_req_size =
  12908. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  12909. /* Size of structures, aligned to 8 bytes */
  12910. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  12911. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  12912. conn = (struct mg_connection *)mg_calloc_ctx(1,
  12913. conn_size + ctx_size
  12914. + max_req_size,
  12915. &common_client_context);
  12916. if (conn == NULL) {
  12917. mg_snprintf(NULL,
  12918. NULL, /* No truncation check for ebuf */
  12919. ebuf,
  12920. ebuf_len,
  12921. "calloc(): %s",
  12922. strerror(ERRNO));
  12923. return NULL;
  12924. }
  12925. conn->ctx = (struct mg_context *)(((char *)conn) + conn_size);
  12926. conn->buf = (((char *)conn) + conn_size + ctx_size);
  12927. conn->buf_size = (int)max_req_size;
  12928. conn->ctx->context_type = CONTEXT_HTTP_CLIENT;
  12929. if (!connect_socket(&common_client_context,
  12930. client_options->host,
  12931. client_options->port,
  12932. use_ssl,
  12933. ebuf,
  12934. ebuf_len,
  12935. &sock,
  12936. &sa)) {
  12937. /* ebuf is set by connect_socket,
  12938. * free all memory and return NULL; */
  12939. mg_free(conn);
  12940. return NULL;
  12941. }
  12942. #ifndef NO_SSL
  12943. #ifdef OPENSSL_API_1_1
  12944. if (use_ssl
  12945. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  12946. mg_snprintf(NULL,
  12947. NULL, /* No truncation check for ebuf */
  12948. ebuf,
  12949. ebuf_len,
  12950. "SSL_CTX_new error");
  12951. closesocket(sock);
  12952. mg_free(conn);
  12953. return NULL;
  12954. }
  12955. #else
  12956. if (use_ssl
  12957. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  12958. == NULL) {
  12959. mg_snprintf(NULL,
  12960. NULL, /* No truncation check for ebuf */
  12961. ebuf,
  12962. ebuf_len,
  12963. "SSL_CTX_new error");
  12964. closesocket(sock);
  12965. mg_free(conn);
  12966. return NULL;
  12967. }
  12968. #endif /* OPENSSL_API_1_1 */
  12969. #endif /* NO_SSL */
  12970. #ifdef USE_IPV6
  12971. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  12972. : sizeof(conn->client.rsa.sin6);
  12973. psa = (sa.sa.sa_family == AF_INET)
  12974. ? (struct sockaddr *)&(conn->client.rsa.sin)
  12975. : (struct sockaddr *)&(conn->client.rsa.sin6);
  12976. #else
  12977. len = sizeof(conn->client.rsa.sin);
  12978. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  12979. #endif
  12980. conn->client.sock = sock;
  12981. conn->client.lsa = sa;
  12982. if (getsockname(sock, psa, &len) != 0) {
  12983. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  12984. }
  12985. conn->client.is_ssl = use_ssl ? 1 : 0;
  12986. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12987. #ifndef NO_SSL
  12988. if (use_ssl) {
  12989. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  12990. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  12991. * SSL_CTX_set_verify call is needed to switch off server
  12992. * certificate checking, which is off by default in OpenSSL and
  12993. * on in yaSSL. */
  12994. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  12995. * SSL_VERIFY_PEER, verify_ssl_server); */
  12996. if (client_options->client_cert) {
  12997. if (!ssl_use_pem_file(&common_client_context,
  12998. client_options->client_cert,
  12999. NULL)) {
  13000. mg_snprintf(NULL,
  13001. NULL, /* No truncation check for ebuf */
  13002. ebuf,
  13003. ebuf_len,
  13004. "Can not use SSL client certificate");
  13005. SSL_CTX_free(conn->client_ssl_ctx);
  13006. closesocket(sock);
  13007. mg_free(conn);
  13008. return NULL;
  13009. }
  13010. }
  13011. if (client_options->server_cert) {
  13012. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  13013. client_options->server_cert,
  13014. NULL);
  13015. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  13016. } else {
  13017. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  13018. }
  13019. if (!sslize(conn,
  13020. conn->client_ssl_ctx,
  13021. SSL_connect,
  13022. &(conn->ctx->stop_flag))) {
  13023. mg_snprintf(NULL,
  13024. NULL, /* No truncation check for ebuf */
  13025. ebuf,
  13026. ebuf_len,
  13027. "SSL connection error");
  13028. SSL_CTX_free(conn->client_ssl_ctx);
  13029. closesocket(sock);
  13030. mg_free(conn);
  13031. return NULL;
  13032. }
  13033. }
  13034. #endif
  13035. if (0 != set_non_blocking_mode(sock)) {
  13036. /* TODO: handle error */
  13037. ;
  13038. }
  13039. return conn;
  13040. }
  13041. CIVETWEB_API struct mg_connection *
  13042. mg_connect_client_secure(const struct mg_client_options *client_options,
  13043. char *error_buffer,
  13044. size_t error_buffer_size)
  13045. {
  13046. return mg_connect_client_impl(client_options,
  13047. 1,
  13048. error_buffer,
  13049. error_buffer_size);
  13050. }
  13051. struct mg_connection *
  13052. mg_connect_client(const char *host,
  13053. int port,
  13054. int use_ssl,
  13055. char *error_buffer,
  13056. size_t error_buffer_size)
  13057. {
  13058. struct mg_client_options opts;
  13059. memset(&opts, 0, sizeof(opts));
  13060. opts.host = host;
  13061. opts.port = port;
  13062. return mg_connect_client_impl(&opts,
  13063. use_ssl,
  13064. error_buffer,
  13065. error_buffer_size);
  13066. }
  13067. static const struct {
  13068. const char *proto;
  13069. size_t proto_len;
  13070. unsigned default_port;
  13071. } abs_uri_protocols[] = {{"http://", 7, 80},
  13072. {"https://", 8, 443},
  13073. {"ws://", 5, 80},
  13074. {"wss://", 6, 443},
  13075. {NULL, 0, 0}};
  13076. /* Check if the uri is valid.
  13077. * return 0 for invalid uri,
  13078. * return 1 for *,
  13079. * return 2 for relative uri,
  13080. * return 3 for absolute uri without port,
  13081. * return 4 for absolute uri with port */
  13082. static int
  13083. get_uri_type(const char *uri)
  13084. {
  13085. int i;
  13086. const char *hostend, *portbegin;
  13087. char *portend;
  13088. unsigned long port;
  13089. /* According to the HTTP standard
  13090. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  13091. * URI can be an asterisk (*) or should start with slash (relative uri),
  13092. * or it should start with the protocol (absolute uri). */
  13093. if ((uri[0] == '*') && (uri[1] == '\0')) {
  13094. /* asterisk */
  13095. return 1;
  13096. }
  13097. /* Valid URIs according to RFC 3986
  13098. * (https://www.ietf.org/rfc/rfc3986.txt)
  13099. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  13100. * and unreserved characters A-Z a-z 0-9 and -._~
  13101. * and % encoded symbols.
  13102. */
  13103. for (i = 0; uri[i] != 0; i++) {
  13104. if (uri[i] < 33) {
  13105. /* control characters and spaces are invalid */
  13106. return 0;
  13107. }
  13108. if (uri[i] > 126) {
  13109. /* non-ascii characters must be % encoded */
  13110. return 0;
  13111. } else {
  13112. switch (uri[i]) {
  13113. case '"': /* 34 */
  13114. case '<': /* 60 */
  13115. case '>': /* 62 */
  13116. case '\\': /* 92 */
  13117. case '^': /* 94 */
  13118. case '`': /* 96 */
  13119. case '{': /* 123 */
  13120. case '|': /* 124 */
  13121. case '}': /* 125 */
  13122. return 0;
  13123. default:
  13124. /* character is ok */
  13125. break;
  13126. }
  13127. }
  13128. }
  13129. /* A relative uri starts with a / character */
  13130. if (uri[0] == '/') {
  13131. /* relative uri */
  13132. return 2;
  13133. }
  13134. /* It could be an absolute uri: */
  13135. /* This function only checks if the uri is valid, not if it is
  13136. * addressing the current server. So civetweb can also be used
  13137. * as a proxy server. */
  13138. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13139. if (mg_strncasecmp(uri,
  13140. abs_uri_protocols[i].proto,
  13141. abs_uri_protocols[i].proto_len) == 0) {
  13142. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  13143. if (!hostend) {
  13144. return 0;
  13145. }
  13146. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  13147. if (!portbegin) {
  13148. return 3;
  13149. }
  13150. port = strtoul(portbegin + 1, &portend, 10);
  13151. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  13152. return 0;
  13153. }
  13154. return 4;
  13155. }
  13156. }
  13157. return 0;
  13158. }
  13159. /* Return NULL or the relative uri at the current server */
  13160. static const char *
  13161. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  13162. {
  13163. const char *server_domain;
  13164. size_t server_domain_len;
  13165. size_t request_domain_len = 0;
  13166. unsigned long port = 0;
  13167. int i, auth_domain_check_enabled;
  13168. const char *hostbegin = NULL;
  13169. const char *hostend = NULL;
  13170. const char *portbegin;
  13171. char *portend;
  13172. auth_domain_check_enabled =
  13173. !mg_strcasecmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  13174. if (!auth_domain_check_enabled) {
  13175. return 0;
  13176. }
  13177. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  13178. if (!server_domain) {
  13179. return 0;
  13180. }
  13181. server_domain_len = strlen(server_domain);
  13182. if (!server_domain_len) {
  13183. return 0;
  13184. }
  13185. /* DNS is case insensitive, so use case insensitive string compare here
  13186. */
  13187. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13188. if (mg_strncasecmp(uri,
  13189. abs_uri_protocols[i].proto,
  13190. abs_uri_protocols[i].proto_len) == 0) {
  13191. hostbegin = uri + abs_uri_protocols[i].proto_len;
  13192. hostend = strchr(hostbegin, '/');
  13193. if (!hostend) {
  13194. return 0;
  13195. }
  13196. portbegin = strchr(hostbegin, ':');
  13197. if ((!portbegin) || (portbegin > hostend)) {
  13198. port = abs_uri_protocols[i].default_port;
  13199. request_domain_len = (size_t)(hostend - hostbegin);
  13200. } else {
  13201. port = strtoul(portbegin + 1, &portend, 10);
  13202. if ((portend != hostend) || (port <= 0)
  13203. || !is_valid_port(port)) {
  13204. return 0;
  13205. }
  13206. request_domain_len = (size_t)(portbegin - hostbegin);
  13207. }
  13208. /* protocol found, port set */
  13209. break;
  13210. }
  13211. }
  13212. if (!port) {
  13213. /* port remains 0 if the protocol is not found */
  13214. return 0;
  13215. }
  13216. /* Check if the request is directed to a different server. */
  13217. /* First check if the port is the same (IPv4 and IPv6). */
  13218. #if defined(USE_IPV6)
  13219. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  13220. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  13221. /* Request is directed to a different port */
  13222. return 0;
  13223. }
  13224. } else
  13225. #endif
  13226. {
  13227. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  13228. /* Request is directed to a different port */
  13229. return 0;
  13230. }
  13231. }
  13232. /* Finally check if the server corresponds to the authentication
  13233. * domain of the server (the server domain).
  13234. * Allow full matches (like http://mydomain.com/path/file.ext), and
  13235. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  13236. * but do not allow substrings (like
  13237. * http://notmydomain.com/path/file.ext
  13238. * or http://mydomain.com.fake/path/file.ext).
  13239. */
  13240. if (auth_domain_check_enabled) {
  13241. if ((request_domain_len == server_domain_len)
  13242. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  13243. /* Request is directed to this server - full name match. */
  13244. } else {
  13245. if (request_domain_len < (server_domain_len + 2)) {
  13246. /* Request is directed to another server: The server name is
  13247. * longer
  13248. * than
  13249. * the request name. Drop this case here to avoid overflows
  13250. * in
  13251. * the
  13252. * following checks. */
  13253. return 0;
  13254. }
  13255. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  13256. /* Request is directed to another server: It could be a
  13257. * substring
  13258. * like notmyserver.com */
  13259. return 0;
  13260. }
  13261. if (0 != memcmp(server_domain,
  13262. hostbegin + request_domain_len - server_domain_len,
  13263. server_domain_len)) {
  13264. /* Request is directed to another server:
  13265. * The server name is different. */
  13266. return 0;
  13267. }
  13268. }
  13269. }
  13270. return hostend;
  13271. }
  13272. static int
  13273. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13274. {
  13275. if (ebuf_len > 0) {
  13276. ebuf[0] = '\0';
  13277. }
  13278. *err = 0;
  13279. reset_per_request_attributes(conn);
  13280. if (!conn) {
  13281. mg_snprintf(conn,
  13282. NULL, /* No truncation check for ebuf */
  13283. ebuf,
  13284. ebuf_len,
  13285. "%s",
  13286. "Internal error");
  13287. *err = 500;
  13288. return 0;
  13289. }
  13290. /* Set the time the request was received. This value should be used for
  13291. * timeouts. */
  13292. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  13293. conn->request_len =
  13294. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  13295. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  13296. */
  13297. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  13298. mg_snprintf(conn,
  13299. NULL, /* No truncation check for ebuf */
  13300. ebuf,
  13301. ebuf_len,
  13302. "%s",
  13303. "Invalid message size");
  13304. *err = 500;
  13305. return 0;
  13306. }
  13307. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  13308. mg_snprintf(conn,
  13309. NULL, /* No truncation check for ebuf */
  13310. ebuf,
  13311. ebuf_len,
  13312. "%s",
  13313. "Message too large");
  13314. *err = 413;
  13315. return 0;
  13316. }
  13317. if (conn->request_len <= 0) {
  13318. if (conn->data_len > 0) {
  13319. mg_snprintf(conn,
  13320. NULL, /* No truncation check for ebuf */
  13321. ebuf,
  13322. ebuf_len,
  13323. "%s",
  13324. "Malformed message");
  13325. *err = 400;
  13326. } else {
  13327. /* Server did not recv anything -> just close the connection */
  13328. conn->must_close = 1;
  13329. mg_snprintf(conn,
  13330. NULL, /* No truncation check for ebuf */
  13331. ebuf,
  13332. ebuf_len,
  13333. "%s",
  13334. "No data received");
  13335. *err = 0;
  13336. }
  13337. return 0;
  13338. }
  13339. return 1;
  13340. }
  13341. static int
  13342. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13343. {
  13344. const char *cl;
  13345. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13346. return 0;
  13347. }
  13348. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  13349. <= 0) {
  13350. mg_snprintf(conn,
  13351. NULL, /* No truncation check for ebuf */
  13352. ebuf,
  13353. ebuf_len,
  13354. "%s",
  13355. "Bad request");
  13356. *err = 400;
  13357. return 0;
  13358. }
  13359. /* Message is a valid request */
  13360. if ((cl = get_header(conn->request_info.http_headers,
  13361. conn->request_info.num_headers,
  13362. "Content-Length")) != NULL) {
  13363. /* Request/response has content length set */
  13364. char *endptr = NULL;
  13365. conn->content_len = strtoll(cl, &endptr, 10);
  13366. if (endptr == cl) {
  13367. mg_snprintf(conn,
  13368. NULL, /* No truncation check for ebuf */
  13369. ebuf,
  13370. ebuf_len,
  13371. "%s",
  13372. "Bad request");
  13373. *err = 411;
  13374. return 0;
  13375. }
  13376. /* Publish the content length back to the request info. */
  13377. conn->request_info.content_length = conn->content_len;
  13378. } else if ((cl = get_header(conn->request_info.http_headers,
  13379. conn->request_info.num_headers,
  13380. "Transfer-Encoding")) != NULL
  13381. && !mg_strcasecmp(cl, "chunked")) {
  13382. conn->is_chunked = 1;
  13383. conn->content_len = -1; /* unknown content length */
  13384. } else if (get_http_method_info(conn->request_info.request_method)
  13385. ->request_has_body) {
  13386. /* POST or PUT request without content length set */
  13387. conn->content_len = -1; /* unknown content length */
  13388. } else {
  13389. /* Other request */
  13390. conn->content_len = 0; /* No content */
  13391. }
  13392. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  13393. return 1;
  13394. }
  13395. /* conn is assumed to be valid in this internal function */
  13396. static int
  13397. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13398. {
  13399. const char *cl;
  13400. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13401. return 0;
  13402. }
  13403. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  13404. <= 0) {
  13405. mg_snprintf(conn,
  13406. NULL, /* No truncation check for ebuf */
  13407. ebuf,
  13408. ebuf_len,
  13409. "%s",
  13410. "Bad response");
  13411. *err = 400;
  13412. return 0;
  13413. }
  13414. /* Message is a valid response */
  13415. if ((cl = get_header(conn->response_info.http_headers,
  13416. conn->response_info.num_headers,
  13417. "Content-Length")) != NULL) {
  13418. /* Request/response has content length set */
  13419. char *endptr = NULL;
  13420. conn->content_len = strtoll(cl, &endptr, 10);
  13421. if (endptr == cl) {
  13422. mg_snprintf(conn,
  13423. NULL, /* No truncation check for ebuf */
  13424. ebuf,
  13425. ebuf_len,
  13426. "%s",
  13427. "Bad request");
  13428. *err = 411;
  13429. return 0;
  13430. }
  13431. /* Publish the content length back to the response info. */
  13432. conn->response_info.content_length = conn->content_len;
  13433. /* TODO: check if it is still used in response_info */
  13434. conn->request_info.content_length = conn->content_len;
  13435. } else if ((cl = get_header(conn->response_info.http_headers,
  13436. conn->response_info.num_headers,
  13437. "Transfer-Encoding")) != NULL
  13438. && !mg_strcasecmp(cl, "chunked")) {
  13439. conn->is_chunked = 1;
  13440. conn->content_len = -1; /* unknown content length */
  13441. } else {
  13442. conn->content_len = -1; /* unknown content length */
  13443. }
  13444. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  13445. return 1;
  13446. }
  13447. int
  13448. mg_get_response(struct mg_connection *conn,
  13449. char *ebuf,
  13450. size_t ebuf_len,
  13451. int timeout)
  13452. {
  13453. int err, ret;
  13454. char txt[32]; /* will not overflow */
  13455. struct mg_context *octx;
  13456. struct mg_context rctx;
  13457. if (ebuf_len > 0) {
  13458. ebuf[0] = '\0';
  13459. }
  13460. if (!conn) {
  13461. mg_snprintf(conn,
  13462. NULL, /* No truncation check for ebuf */
  13463. ebuf,
  13464. ebuf_len,
  13465. "%s",
  13466. "Parameter error");
  13467. return -1;
  13468. }
  13469. /* Implementation of API function for HTTP clients */
  13470. octx = conn->ctx;
  13471. rctx = *(conn->ctx);
  13472. if (timeout >= 0) {
  13473. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  13474. rctx.config[REQUEST_TIMEOUT] = txt;
  13475. /* Not required for non-blocking sockets.
  13476. set_sock_timeout(conn->client.sock, timeout);
  13477. */
  13478. } else {
  13479. rctx.config[REQUEST_TIMEOUT] = NULL;
  13480. }
  13481. conn->ctx = &rctx;
  13482. ret = get_response(conn, ebuf, ebuf_len, &err);
  13483. conn->ctx = octx;
  13484. #if defined(MG_LEGACY_INTERFACE)
  13485. /* TODO: 1) uri is deprecated;
  13486. * 2) here, ri.uri is the http response code */
  13487. conn->request_info.uri = conn->request_info.request_uri;
  13488. #endif
  13489. conn->request_info.local_uri = conn->request_info.request_uri;
  13490. /* TODO (mid): Define proper return values - maybe return length?
  13491. * For the first test use <0 for error and >0 for OK */
  13492. return (ret == 0) ? -1 : +1;
  13493. }
  13494. struct mg_connection *
  13495. mg_download(const char *host,
  13496. int port,
  13497. int use_ssl,
  13498. char *ebuf,
  13499. size_t ebuf_len,
  13500. const char *fmt,
  13501. ...)
  13502. {
  13503. struct mg_connection *conn;
  13504. va_list ap;
  13505. int i;
  13506. int reqerr;
  13507. if (ebuf_len > 0) {
  13508. ebuf[0] = '\0';
  13509. }
  13510. va_start(ap, fmt);
  13511. /* open a connection */
  13512. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  13513. if (conn != NULL) {
  13514. i = mg_vprintf(conn, fmt, ap);
  13515. if (i <= 0) {
  13516. mg_snprintf(conn,
  13517. NULL, /* No truncation check for ebuf */
  13518. ebuf,
  13519. ebuf_len,
  13520. "%s",
  13521. "Error sending request");
  13522. } else {
  13523. get_response(conn, ebuf, ebuf_len, &reqerr);
  13524. #if defined(MG_LEGACY_INTERFACE)
  13525. /* TODO: 1) uri is deprecated;
  13526. * 2) here, ri.uri is the http response code */
  13527. conn->request_info.uri = conn->request_info.request_uri;
  13528. #endif
  13529. conn->request_info.local_uri = conn->request_info.request_uri;
  13530. }
  13531. }
  13532. /* if an error occured, close the connection */
  13533. if ((ebuf[0] != '\0') && (conn != NULL)) {
  13534. mg_close_connection(conn);
  13535. conn = NULL;
  13536. }
  13537. va_end(ap);
  13538. return conn;
  13539. }
  13540. struct websocket_client_thread_data {
  13541. struct mg_connection *conn;
  13542. mg_websocket_data_handler data_handler;
  13543. mg_websocket_close_handler close_handler;
  13544. void *callback_data;
  13545. };
  13546. #if defined(USE_WEBSOCKET)
  13547. #ifdef _WIN32
  13548. static unsigned __stdcall websocket_client_thread(void *data)
  13549. #else
  13550. static void *
  13551. websocket_client_thread(void *data)
  13552. #endif
  13553. {
  13554. struct websocket_client_thread_data *cdata =
  13555. (struct websocket_client_thread_data *)data;
  13556. mg_set_thread_name("ws-clnt");
  13557. if (cdata->conn->ctx) {
  13558. if (cdata->conn->ctx->callbacks.init_thread) {
  13559. /* 3 indicates a websocket client thread */
  13560. /* TODO: check if conn->ctx can be set */
  13561. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  13562. }
  13563. }
  13564. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  13565. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  13566. if (cdata->close_handler != NULL) {
  13567. cdata->close_handler(cdata->conn, cdata->callback_data);
  13568. }
  13569. /* The websocket_client context has only this thread. If it runs out,
  13570. set the stop_flag to 2 (= "stopped"). */
  13571. cdata->conn->ctx->stop_flag = 2;
  13572. mg_free((void *)cdata);
  13573. #ifdef _WIN32
  13574. return 0;
  13575. #else
  13576. return NULL;
  13577. #endif
  13578. }
  13579. #endif
  13580. struct mg_connection *
  13581. mg_connect_websocket_client(const char *host,
  13582. int port,
  13583. int use_ssl,
  13584. char *error_buffer,
  13585. size_t error_buffer_size,
  13586. const char *path,
  13587. const char *origin,
  13588. mg_websocket_data_handler data_func,
  13589. mg_websocket_close_handler close_func,
  13590. void *user_data)
  13591. {
  13592. struct mg_connection *conn = NULL;
  13593. #if defined(USE_WEBSOCKET)
  13594. struct mg_context *newctx = NULL;
  13595. struct websocket_client_thread_data *thread_data;
  13596. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  13597. static const char *handshake_req;
  13598. if (origin != NULL) {
  13599. handshake_req = "GET %s HTTP/1.1\r\n"
  13600. "Host: %s\r\n"
  13601. "Upgrade: websocket\r\n"
  13602. "Connection: Upgrade\r\n"
  13603. "Sec-WebSocket-Key: %s\r\n"
  13604. "Sec-WebSocket-Version: 13\r\n"
  13605. "Origin: %s\r\n"
  13606. "\r\n";
  13607. } else {
  13608. handshake_req = "GET %s HTTP/1.1\r\n"
  13609. "Host: %s\r\n"
  13610. "Upgrade: websocket\r\n"
  13611. "Connection: Upgrade\r\n"
  13612. "Sec-WebSocket-Key: %s\r\n"
  13613. "Sec-WebSocket-Version: 13\r\n"
  13614. "\r\n";
  13615. }
  13616. /* Establish the client connection and request upgrade */
  13617. conn = mg_download(host,
  13618. port,
  13619. use_ssl,
  13620. error_buffer,
  13621. error_buffer_size,
  13622. handshake_req,
  13623. path,
  13624. host,
  13625. magic,
  13626. origin);
  13627. /* Connection object will be null if something goes wrong */
  13628. if (conn == NULL) {
  13629. if (!*error_buffer) {
  13630. /* There should be already an error message */
  13631. mg_snprintf(conn,
  13632. NULL, /* No truncation check for ebuf */
  13633. error_buffer,
  13634. error_buffer_size,
  13635. "Unexpected error");
  13636. }
  13637. return NULL;
  13638. }
  13639. if (conn->response_info.status_code != 101) {
  13640. /* We sent an "upgrade" request. For a correct websocket
  13641. * protocol handshake, we expect a "101 Continue" response.
  13642. * Otherwise it is a protocol violation. Maybe the HTTP
  13643. * Server does not know websockets. */
  13644. if (!*error_buffer) {
  13645. /* set an error, if not yet set */
  13646. mg_snprintf(conn,
  13647. NULL, /* No truncation check for ebuf */
  13648. error_buffer,
  13649. error_buffer_size,
  13650. "Unexpected server reply");
  13651. }
  13652. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  13653. mg_free(conn);
  13654. return NULL;
  13655. }
  13656. /* For client connections, mg_context is fake. Since we need to set a
  13657. * callback function, we need to create a copy and modify it. */
  13658. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  13659. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  13660. newctx->user_data = user_data;
  13661. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  13662. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  13663. newctx->worker_threadids =
  13664. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  13665. sizeof(pthread_t),
  13666. newctx);
  13667. conn->ctx = newctx;
  13668. thread_data = (struct websocket_client_thread_data *)
  13669. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  13670. thread_data->conn = conn;
  13671. thread_data->data_handler = data_func;
  13672. thread_data->close_handler = close_func;
  13673. thread_data->callback_data = user_data;
  13674. /* Start a thread to read the websocket client connection
  13675. * This thread will automatically stop when mg_disconnect is
  13676. * called on the client connection */
  13677. if (mg_start_thread_with_id(websocket_client_thread,
  13678. (void *)thread_data,
  13679. newctx->worker_threadids) != 0) {
  13680. mg_free((void *)thread_data);
  13681. mg_free((void *)newctx->worker_threadids);
  13682. mg_free((void *)newctx);
  13683. mg_free((void *)conn);
  13684. conn = NULL;
  13685. DEBUG_TRACE("%s",
  13686. "Websocket client connect thread could not be started\r\n");
  13687. }
  13688. #else
  13689. /* Appease "unused parameter" warnings */
  13690. (void)host;
  13691. (void)port;
  13692. (void)use_ssl;
  13693. (void)error_buffer;
  13694. (void)error_buffer_size;
  13695. (void)path;
  13696. (void)origin;
  13697. (void)user_data;
  13698. (void)data_func;
  13699. (void)close_func;
  13700. #endif
  13701. return conn;
  13702. }
  13703. /* Prepare connection data structure */
  13704. static void
  13705. init_connection(struct mg_connection *conn)
  13706. {
  13707. /* Is keep alive allowed by the server */
  13708. int keep_alive_enabled =
  13709. !mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  13710. if (!keep_alive_enabled) {
  13711. conn->must_close = 1;
  13712. }
  13713. /* Important: on new connection, reset the receiving buffer. Credit
  13714. * goes to crule42. */
  13715. conn->data_len = 0;
  13716. conn->handled_requests = 0;
  13717. mg_set_user_connection_data(conn, NULL);
  13718. #if defined(USE_SERVER_STATS)
  13719. conn->conn_state = 2; /* init */
  13720. #endif
  13721. /* call the init_connection callback if assigned */
  13722. if (conn->ctx->callbacks.init_connection != NULL) {
  13723. if (conn->ctx->context_type == CONTEXT_SERVER) {
  13724. void *conn_data = NULL;
  13725. conn->ctx->callbacks.init_connection(conn, &conn_data);
  13726. mg_set_user_connection_data(conn, conn_data);
  13727. }
  13728. }
  13729. }
  13730. /* Process a connection - may handle multiple requests
  13731. * using the same connection.
  13732. * Must be called with a valid connection (conn and
  13733. * conn->ctx must be valid).
  13734. */
  13735. static void
  13736. process_new_connection(struct mg_connection *conn)
  13737. {
  13738. struct mg_request_info *ri = &conn->request_info;
  13739. int keep_alive, discard_len;
  13740. char ebuf[100];
  13741. const char *hostend;
  13742. int reqerr, uri_type;
  13743. #if defined(USE_SERVER_STATS)
  13744. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  13745. mg_atomic_add(&(conn->ctx->total_connections), 1);
  13746. if (mcon > (conn->ctx->max_connections)) {
  13747. /* could use atomic compare exchange, but this
  13748. * seems overkill for statistics data */
  13749. conn->ctx->max_connections = mcon;
  13750. }
  13751. #endif
  13752. init_connection(conn);
  13753. DEBUG_TRACE("Start processing connection from %s",
  13754. conn->request_info.remote_addr);
  13755. /* Loop over multiple requests sent using the same connection
  13756. * (while "keep alive"). */
  13757. do {
  13758. DEBUG_TRACE("calling get_request (%i times for this connection)",
  13759. conn->handled_requests + 1);
  13760. #if defined(USE_SERVER_STATS)
  13761. conn->conn_state = 3; /* ready */
  13762. #endif
  13763. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  13764. /* The request sent by the client could not be understood by
  13765. * the server, or it was incomplete or a timeout. Send an
  13766. * error message and close the connection. */
  13767. if (reqerr > 0) {
  13768. /*assert(ebuf[0] != '\0');*/
  13769. mg_send_http_error(conn, reqerr, "%s", ebuf);
  13770. }
  13771. } else if (strcmp(ri->http_version, "1.0")
  13772. && strcmp(ri->http_version, "1.1")) {
  13773. mg_snprintf(conn,
  13774. NULL, /* No truncation check for ebuf */
  13775. ebuf,
  13776. sizeof(ebuf),
  13777. "Bad HTTP version: [%s]",
  13778. ri->http_version);
  13779. mg_send_http_error(conn, 505, "%s", ebuf);
  13780. }
  13781. if (ebuf[0] == '\0') {
  13782. uri_type = get_uri_type(conn->request_info.request_uri);
  13783. switch (uri_type) {
  13784. case 1:
  13785. /* Asterisk */
  13786. conn->request_info.local_uri = NULL;
  13787. break;
  13788. case 2:
  13789. /* relative uri */
  13790. conn->request_info.local_uri = conn->request_info.request_uri;
  13791. break;
  13792. case 3:
  13793. case 4:
  13794. /* absolute uri (with/without port) */
  13795. hostend = get_rel_url_at_current_server(
  13796. conn->request_info.request_uri, conn);
  13797. if (hostend) {
  13798. conn->request_info.local_uri = hostend;
  13799. } else {
  13800. conn->request_info.local_uri = NULL;
  13801. }
  13802. break;
  13803. default:
  13804. mg_snprintf(conn,
  13805. NULL, /* No truncation check for ebuf */
  13806. ebuf,
  13807. sizeof(ebuf),
  13808. "Invalid URI");
  13809. mg_send_http_error(conn, 400, "%s", ebuf);
  13810. conn->request_info.local_uri = NULL;
  13811. break;
  13812. }
  13813. #if defined(MG_LEGACY_INTERFACE)
  13814. /* Legacy before split into local_uri and request_uri */
  13815. conn->request_info.uri = conn->request_info.local_uri;
  13816. #endif
  13817. }
  13818. DEBUG_TRACE("http: %s, error: %s",
  13819. (ri->http_version ? ri->http_version : "none"),
  13820. (ebuf[0] ? ebuf : "none"));
  13821. if (ebuf[0] == '\0') {
  13822. if (conn->request_info.local_uri) {
  13823. /* handle request to local server */
  13824. #if defined(USE_SERVER_STATS)
  13825. conn->conn_state = 4; /* processing */
  13826. #endif
  13827. handle_request(conn);
  13828. #if defined(USE_SERVER_STATS)
  13829. conn->conn_state = 5; /* processed */
  13830. mg_atomic_add(&(conn->ctx->total_data_read),
  13831. conn->consumed_content);
  13832. mg_atomic_add(&(conn->ctx->total_data_written),
  13833. conn->num_bytes_sent);
  13834. #endif
  13835. DEBUG_TRACE("%s", "handle_request done");
  13836. if (conn->ctx->callbacks.end_request != NULL) {
  13837. conn->ctx->callbacks.end_request(conn, conn->status_code);
  13838. DEBUG_TRACE("%s", "end_request callback done");
  13839. }
  13840. log_access(conn);
  13841. } else {
  13842. /* TODO: handle non-local request (PROXY) */
  13843. conn->must_close = 1;
  13844. }
  13845. } else {
  13846. conn->must_close = 1;
  13847. }
  13848. if (ri->remote_user != NULL) {
  13849. mg_free((void *)ri->remote_user);
  13850. /* Important! When having connections with and without auth
  13851. * would cause double free and then crash */
  13852. ri->remote_user = NULL;
  13853. }
  13854. /* NOTE(lsm): order is important here. should_keep_alive() call
  13855. * is using parsed request, which will be invalid after
  13856. * memmove's below.
  13857. * Therefore, memorize should_keep_alive() result now for later
  13858. * use in loop exit condition. */
  13859. keep_alive = (conn->ctx->stop_flag == 0) && should_keep_alive(conn)
  13860. && (conn->content_len >= 0);
  13861. /* Discard all buffered data for this request */
  13862. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  13863. && ((conn->request_len + conn->content_len)
  13864. < (int64_t)conn->data_len))
  13865. ? (int)(conn->request_len + conn->content_len)
  13866. : conn->data_len;
  13867. /*assert(discard_len >= 0);*/
  13868. if (discard_len < 0) {
  13869. DEBUG_TRACE("internal error: discard_len = %li",
  13870. (long int)discard_len);
  13871. break;
  13872. }
  13873. conn->data_len -= discard_len;
  13874. if (conn->data_len > 0) {
  13875. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  13876. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  13877. }
  13878. /* assert(conn->data_len >= 0); */
  13879. /* assert(conn->data_len <= conn->buf_size); */
  13880. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  13881. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  13882. (long int)conn->data_len,
  13883. (long int)conn->buf_size);
  13884. break;
  13885. }
  13886. conn->handled_requests++;
  13887. } while (keep_alive);
  13888. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  13889. conn->request_info.remote_addr,
  13890. difftime(time(NULL), conn->conn_birth_time));
  13891. close_connection(conn);
  13892. #if defined(USE_SERVER_STATS)
  13893. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  13894. mg_atomic_dec(&(conn->ctx->active_connections));
  13895. #endif
  13896. }
  13897. #if defined(ALTERNATIVE_QUEUE)
  13898. static void
  13899. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13900. {
  13901. unsigned int i;
  13902. for (;;) {
  13903. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13904. /* find a free worker slot and signal it */
  13905. if (ctx->client_socks[i].in_use == 0) {
  13906. ctx->client_socks[i] = *sp;
  13907. ctx->client_socks[i].in_use = 1;
  13908. event_signal(ctx->client_wait_events[i]);
  13909. return;
  13910. }
  13911. }
  13912. /* queue is full */
  13913. mg_sleep(1);
  13914. }
  13915. }
  13916. static int
  13917. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13918. {
  13919. DEBUG_TRACE("%s", "going idle");
  13920. ctx->client_socks[thread_index].in_use = 0;
  13921. event_wait(ctx->client_wait_events[thread_index]);
  13922. *sp = ctx->client_socks[thread_index];
  13923. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13924. return !ctx->stop_flag;
  13925. }
  13926. #else /* ALTERNATIVE_QUEUE */
  13927. /* Worker threads take accepted socket from the queue */
  13928. static int
  13929. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13930. {
  13931. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13932. (void)thread_index;
  13933. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13934. DEBUG_TRACE("%s", "going idle");
  13935. /* If the queue is empty, wait. We're idle at this point. */
  13936. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  13937. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  13938. }
  13939. /* If we're stopping, sq_head may be equal to sq_tail. */
  13940. if (ctx->sq_head > ctx->sq_tail) {
  13941. /* Copy socket from the queue and increment tail */
  13942. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  13943. ctx->sq_tail++;
  13944. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13945. /* Wrap pointers if needed */
  13946. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  13947. ctx->sq_tail -= QUEUE_SIZE(ctx);
  13948. ctx->sq_head -= QUEUE_SIZE(ctx);
  13949. }
  13950. }
  13951. (void)pthread_cond_signal(&ctx->sq_empty);
  13952. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13953. return !ctx->stop_flag;
  13954. #undef QUEUE_SIZE
  13955. }
  13956. /* Master thread adds accepted socket to a queue */
  13957. static void
  13958. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13959. {
  13960. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13961. if (!ctx) {
  13962. return;
  13963. }
  13964. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13965. /* If the queue is full, wait */
  13966. while ((ctx->stop_flag == 0)
  13967. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  13968. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  13969. }
  13970. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  13971. /* Copy socket to the queue and increment head */
  13972. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  13973. ctx->sq_head++;
  13974. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  13975. }
  13976. (void)pthread_cond_signal(&ctx->sq_full);
  13977. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13978. #undef QUEUE_SIZE
  13979. }
  13980. #endif /* ALTERNATIVE_QUEUE */
  13981. struct worker_thread_args {
  13982. struct mg_context *ctx;
  13983. int index;
  13984. };
  13985. static void *
  13986. worker_thread_run(struct worker_thread_args *thread_args)
  13987. {
  13988. struct mg_context *ctx = thread_args->ctx;
  13989. struct mg_connection *conn;
  13990. struct mg_workerTLS tls;
  13991. #if defined(MG_LEGACY_INTERFACE)
  13992. uint32_t addr;
  13993. #endif
  13994. mg_set_thread_name("worker");
  13995. tls.is_master = 0;
  13996. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13997. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13998. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13999. #endif
  14000. /* Initialize thread local storage before calling any callback */
  14001. pthread_setspecific(sTlsKey, &tls);
  14002. if (ctx->callbacks.init_thread) {
  14003. /* call init_thread for a worker thread (type 1) */
  14004. ctx->callbacks.init_thread(ctx, 1);
  14005. }
  14006. /* Connection structure has been pre-allocated */
  14007. if (((int)thread_args->index < 0)
  14008. || ((unsigned)thread_args->index
  14009. >= (unsigned)ctx->cfg_worker_threads)) {
  14010. mg_cry(fc(ctx),
  14011. "Internal error: Invalid worker index %i",
  14012. (int)thread_args->index);
  14013. return NULL;
  14014. }
  14015. conn = ctx->worker_connections + thread_args->index;
  14016. /* Request buffers are not pre-allocated. They are private to the
  14017. * request and do not contain any state information that might be
  14018. * of interest to anyone observing a server status. */
  14019. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->ctx);
  14020. if (conn->buf == NULL) {
  14021. mg_cry(fc(ctx),
  14022. "Out of memory: Cannot allocate buffer for worker %i",
  14023. (int)thread_args->index);
  14024. return NULL;
  14025. }
  14026. conn->buf_size = (int)ctx->max_request_size;
  14027. conn->ctx = ctx;
  14028. conn->thread_index = thread_args->index;
  14029. conn->request_info.user_data = ctx->user_data;
  14030. /* Allocate a mutex for this connection to allow communication both
  14031. * within the request handler and from elsewhere in the application
  14032. */
  14033. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  14034. #if defined(USE_SERVER_STATS)
  14035. conn->conn_state = 1; /* not consumed */
  14036. #endif
  14037. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  14038. * signal sq_empty condvar to wake up the master waiting in
  14039. * produce_socket() */
  14040. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  14041. conn->conn_birth_time = time(NULL);
  14042. /* Fill in IP, port info early so even if SSL setup below fails,
  14043. * error handler would have the corresponding info.
  14044. * Thanks to Johannes Winkelmann for the patch.
  14045. */
  14046. #if defined(USE_IPV6)
  14047. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  14048. conn->request_info.remote_port =
  14049. ntohs(conn->client.rsa.sin6.sin6_port);
  14050. } else
  14051. #endif
  14052. {
  14053. conn->request_info.remote_port =
  14054. ntohs(conn->client.rsa.sin.sin_port);
  14055. }
  14056. sockaddr_to_string(conn->request_info.remote_addr,
  14057. sizeof(conn->request_info.remote_addr),
  14058. &conn->client.rsa);
  14059. DEBUG_TRACE("Start processing connection from %s",
  14060. conn->request_info.remote_addr);
  14061. #if defined(MG_LEGACY_INTERFACE)
  14062. /* This legacy interface only works for the IPv4 case */
  14063. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  14064. memcpy(&conn->request_info.remote_ip, &addr, 4);
  14065. #endif
  14066. conn->request_info.is_ssl = conn->client.is_ssl;
  14067. if (conn->client.is_ssl) {
  14068. #ifndef NO_SSL
  14069. /* HTTPS connection */
  14070. if (sslize(conn,
  14071. conn->ctx->ssl_ctx,
  14072. SSL_accept,
  14073. &(conn->ctx->stop_flag))) {
  14074. /* Get SSL client certificate information (if set) */
  14075. ssl_get_client_cert_info(conn);
  14076. /* process HTTPS connection */
  14077. process_new_connection(conn);
  14078. /* Free client certificate info */
  14079. if (conn->request_info.client_cert) {
  14080. mg_free((void *)(conn->request_info.client_cert->subject));
  14081. mg_free((void *)(conn->request_info.client_cert->issuer));
  14082. mg_free((void *)(conn->request_info.client_cert->serial));
  14083. mg_free((void *)(conn->request_info.client_cert->finger));
  14084. conn->request_info.client_cert->subject = 0;
  14085. conn->request_info.client_cert->issuer = 0;
  14086. conn->request_info.client_cert->serial = 0;
  14087. conn->request_info.client_cert->finger = 0;
  14088. mg_free(conn->request_info.client_cert);
  14089. conn->request_info.client_cert = 0;
  14090. }
  14091. }
  14092. #endif
  14093. } else {
  14094. /* process HTTP connection */
  14095. process_new_connection(conn);
  14096. }
  14097. DEBUG_TRACE("%s", "Connection closed");
  14098. }
  14099. pthread_setspecific(sTlsKey, NULL);
  14100. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14101. CloseHandle(tls.pthread_cond_helper_mutex);
  14102. #endif
  14103. pthread_mutex_destroy(&conn->mutex);
  14104. /* Free the request buffer. */
  14105. conn->buf_size = 0;
  14106. mg_free(conn->buf);
  14107. conn->buf = NULL;
  14108. #if defined(USE_SERVER_STATS)
  14109. conn->conn_state = 9; /* done */
  14110. #endif
  14111. DEBUG_TRACE("%s", "exiting");
  14112. return NULL;
  14113. }
  14114. /* Threads have different return types on Windows and Unix. */
  14115. #ifdef _WIN32
  14116. static unsigned __stdcall worker_thread(void *thread_func_param)
  14117. {
  14118. struct worker_thread_args *pwta =
  14119. (struct worker_thread_args *)thread_func_param;
  14120. worker_thread_run(pwta);
  14121. mg_free(thread_func_param);
  14122. return 0;
  14123. }
  14124. #else
  14125. static void *
  14126. worker_thread(void *thread_func_param)
  14127. {
  14128. struct worker_thread_args *pwta =
  14129. (struct worker_thread_args *)thread_func_param;
  14130. worker_thread_run(pwta);
  14131. mg_free(thread_func_param);
  14132. return NULL;
  14133. }
  14134. #endif /* _WIN32 */
  14135. static void
  14136. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  14137. {
  14138. struct socket so;
  14139. char src_addr[IP_ADDR_STR_LEN];
  14140. socklen_t len = sizeof(so.rsa);
  14141. int on = 1;
  14142. if (!listener) {
  14143. return;
  14144. }
  14145. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  14146. == INVALID_SOCKET) {
  14147. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  14148. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  14149. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  14150. closesocket(so.sock);
  14151. } else {
  14152. /* Put so socket structure into the queue */
  14153. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  14154. set_close_on_exec(so.sock, fc(ctx));
  14155. so.is_ssl = listener->is_ssl;
  14156. so.ssl_redir = listener->ssl_redir;
  14157. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  14158. mg_cry(fc(ctx),
  14159. "%s: getsockname() failed: %s",
  14160. __func__,
  14161. strerror(ERRNO));
  14162. }
  14163. /* Set TCP keep-alive. This is needed because if HTTP-level
  14164. * keep-alive
  14165. * is enabled, and client resets the connection, server won't get
  14166. * TCP FIN or RST and will keep the connection open forever. With
  14167. * TCP keep-alive, next keep-alive handshake will figure out that
  14168. * the client is down and will close the server end.
  14169. * Thanks to Igor Klopov who suggested the patch. */
  14170. if (setsockopt(so.sock,
  14171. SOL_SOCKET,
  14172. SO_KEEPALIVE,
  14173. (SOCK_OPT_TYPE)&on,
  14174. sizeof(on)) != 0) {
  14175. mg_cry(fc(ctx),
  14176. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  14177. __func__,
  14178. strerror(ERRNO));
  14179. }
  14180. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  14181. * to effectively fill up the underlying IP packet payload and
  14182. * reduce the overhead of sending lots of small buffers. However
  14183. * this hurts the server's throughput (ie. operations per second)
  14184. * when HTTP 1.1 persistent connections are used and the responses
  14185. * are relatively small (eg. less than 1400 bytes).
  14186. */
  14187. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  14188. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  14189. if (set_tcp_nodelay(so.sock, 1) != 0) {
  14190. mg_cry(fc(ctx),
  14191. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  14192. __func__,
  14193. strerror(ERRNO));
  14194. }
  14195. }
  14196. /* We are using non-blocking sockets. Thus, the
  14197. * set_sock_timeout(so.sock, timeout);
  14198. * call is no longer required. */
  14199. /* The "non blocking" property should already be
  14200. * inherited from the parent socket. Set it for
  14201. * non-compliant socket implementations. */
  14202. set_non_blocking_mode(so.sock);
  14203. so.in_use = 0;
  14204. produce_socket(ctx, &so);
  14205. }
  14206. }
  14207. static void
  14208. master_thread_run(void *thread_func_param)
  14209. {
  14210. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  14211. struct mg_workerTLS tls;
  14212. struct pollfd *pfd;
  14213. unsigned int i;
  14214. unsigned int workerthreadcount;
  14215. if (!ctx) {
  14216. return;
  14217. }
  14218. mg_set_thread_name("master");
  14219. /* Increase priority of the master thread */
  14220. #if defined(_WIN32)
  14221. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  14222. #elif defined(USE_MASTER_THREAD_PRIORITY)
  14223. int min_prio = sched_get_priority_min(SCHED_RR);
  14224. int max_prio = sched_get_priority_max(SCHED_RR);
  14225. if ((min_prio >= 0) && (max_prio >= 0)
  14226. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  14227. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  14228. struct sched_param sched_param = {0};
  14229. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  14230. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  14231. }
  14232. #endif
  14233. /* Initialize thread local storage */
  14234. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14235. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14236. #endif
  14237. tls.is_master = 1;
  14238. pthread_setspecific(sTlsKey, &tls);
  14239. if (ctx->callbacks.init_thread) {
  14240. /* Callback for the master thread (type 0) */
  14241. ctx->callbacks.init_thread(ctx, 0);
  14242. }
  14243. /* Server starts *now* */
  14244. ctx->start_time = time(NULL);
  14245. /* Start the server */
  14246. pfd = ctx->listening_socket_fds;
  14247. while (ctx->stop_flag == 0) {
  14248. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14249. pfd[i].fd = ctx->listening_sockets[i].sock;
  14250. pfd[i].events = POLLIN;
  14251. }
  14252. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  14253. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14254. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  14255. * successful poll, and POLLIN is defined as
  14256. * (POLLRDNORM | POLLRDBAND)
  14257. * Therefore, we're checking pfd[i].revents & POLLIN, not
  14258. * pfd[i].revents == POLLIN. */
  14259. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  14260. accept_new_connection(&ctx->listening_sockets[i], ctx);
  14261. }
  14262. }
  14263. }
  14264. }
  14265. /* Here stop_flag is 1 - Initiate shutdown. */
  14266. DEBUG_TRACE("%s", "stopping workers");
  14267. /* Stop signal received: somebody called mg_stop. Quit. */
  14268. close_all_listening_sockets(ctx);
  14269. /* Wakeup workers that are waiting for connections to handle. */
  14270. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14271. #if defined(ALTERNATIVE_QUEUE)
  14272. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14273. event_signal(ctx->client_wait_events[i]);
  14274. /* Since we know all sockets, we can shutdown the connections. */
  14275. if (ctx->client_socks[i].in_use) {
  14276. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  14277. }
  14278. }
  14279. #else
  14280. pthread_cond_broadcast(&ctx->sq_full);
  14281. #endif
  14282. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14283. /* Join all worker threads to avoid leaking threads. */
  14284. workerthreadcount = ctx->cfg_worker_threads;
  14285. for (i = 0; i < workerthreadcount; i++) {
  14286. if (ctx->worker_threadids[i] != 0) {
  14287. mg_join_thread(ctx->worker_threadids[i]);
  14288. }
  14289. }
  14290. #if defined(USE_LUA)
  14291. /* Free Lua state of lua background task */
  14292. if (ctx->lua_background_state) {
  14293. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14294. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  14295. if (lua_istable(lstate, -1)) {
  14296. reg_boolean(lstate, "shutdown", 1);
  14297. lua_pop(lstate, 1);
  14298. mg_sleep(2);
  14299. }
  14300. lua_close(lstate);
  14301. ctx->lua_background_state = 0;
  14302. }
  14303. #endif
  14304. DEBUG_TRACE("%s", "exiting");
  14305. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14306. CloseHandle(tls.pthread_cond_helper_mutex);
  14307. #endif
  14308. pthread_setspecific(sTlsKey, NULL);
  14309. /* Signal mg_stop() that we're done.
  14310. * WARNING: This must be the very last thing this
  14311. * thread does, as ctx becomes invalid after this line. */
  14312. ctx->stop_flag = 2;
  14313. }
  14314. /* Threads have different return types on Windows and Unix. */
  14315. #ifdef _WIN32
  14316. static unsigned __stdcall master_thread(void *thread_func_param)
  14317. {
  14318. master_thread_run(thread_func_param);
  14319. return 0;
  14320. }
  14321. #else
  14322. static void *
  14323. master_thread(void *thread_func_param)
  14324. {
  14325. master_thread_run(thread_func_param);
  14326. return NULL;
  14327. }
  14328. #endif /* _WIN32 */
  14329. static void
  14330. free_context(struct mg_context *ctx)
  14331. {
  14332. int i;
  14333. struct mg_handler_info *tmp_rh;
  14334. if (ctx == NULL) {
  14335. return;
  14336. }
  14337. if (ctx->callbacks.exit_context) {
  14338. ctx->callbacks.exit_context(ctx);
  14339. }
  14340. /* All threads exited, no sync is needed. Destroy thread mutex and
  14341. * condvars
  14342. */
  14343. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  14344. #if defined(ALTERNATIVE_QUEUE)
  14345. mg_free(ctx->client_socks);
  14346. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14347. event_destroy(ctx->client_wait_events[i]);
  14348. }
  14349. mg_free(ctx->client_wait_events);
  14350. #else
  14351. (void)pthread_cond_destroy(&ctx->sq_empty);
  14352. (void)pthread_cond_destroy(&ctx->sq_full);
  14353. #endif
  14354. /* Destroy other context global data structures mutex */
  14355. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  14356. #if defined(USE_TIMERS)
  14357. timers_exit(ctx);
  14358. #endif
  14359. /* Deallocate config parameters */
  14360. for (i = 0; i < NUM_OPTIONS; i++) {
  14361. if (ctx->config[i] != NULL) {
  14362. #if defined(_MSC_VER)
  14363. #pragma warning(suppress : 6001)
  14364. #endif
  14365. mg_free(ctx->config[i]);
  14366. }
  14367. }
  14368. /* Deallocate request handlers */
  14369. while (ctx->handlers) {
  14370. tmp_rh = ctx->handlers;
  14371. ctx->handlers = tmp_rh->next;
  14372. mg_free(tmp_rh->uri);
  14373. mg_free(tmp_rh);
  14374. }
  14375. #ifndef NO_SSL
  14376. /* Deallocate SSL context */
  14377. if (ctx->ssl_ctx != NULL) {
  14378. SSL_CTX* ssl_ctx = 0;
  14379. int callback_ret =
  14380. (ctx->callbacks.get_external_ssl_ctx == NULL)
  14381. ? 0
  14382. : (ctx->callbacks.get_external_ssl_ctx(&ssl_ctx, ctx->user_data));
  14383. if (callback_ret == 0) {
  14384. SSL_CTX_free(ctx->ssl_ctx);
  14385. }
  14386. // else ignore error and ommit SSL_CTX_free in case callback_ret is 1
  14387. }
  14388. #endif /* !NO_SSL */
  14389. /* Deallocate worker thread ID array */
  14390. if (ctx->worker_threadids != NULL) {
  14391. mg_free(ctx->worker_threadids);
  14392. }
  14393. /* Deallocate worker thread ID array */
  14394. if (ctx->worker_connections != NULL) {
  14395. mg_free(ctx->worker_connections);
  14396. }
  14397. /* deallocate system name string */
  14398. mg_free(ctx->systemName);
  14399. /* Deallocate context itself */
  14400. mg_free(ctx);
  14401. }
  14402. void
  14403. mg_stop(struct mg_context *ctx)
  14404. {
  14405. pthread_t mt;
  14406. if (!ctx) {
  14407. return;
  14408. }
  14409. /* We don't use a lock here. Calling mg_stop with the same ctx from
  14410. * two threads is not allowed. */
  14411. mt = ctx->masterthreadid;
  14412. if (mt == 0) {
  14413. return;
  14414. }
  14415. ctx->masterthreadid = 0;
  14416. /* Set stop flag, so all threads know they have to exit. */
  14417. ctx->stop_flag = 1;
  14418. /* Wait until everything has stopped. */
  14419. while (ctx->stop_flag != 2) {
  14420. (void)mg_sleep(10);
  14421. }
  14422. mg_join_thread(mt);
  14423. free_context(ctx);
  14424. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14425. (void)WSACleanup();
  14426. #endif /* _WIN32 && !__SYMBIAN32__ */
  14427. }
  14428. static void
  14429. get_system_name(char **sysName)
  14430. {
  14431. #if defined(_WIN32)
  14432. #if !defined(__SYMBIAN32__)
  14433. #if defined(_WIN32_WCE)
  14434. *sysName = mg_strdup("WinCE");
  14435. #else
  14436. char name[128];
  14437. DWORD dwVersion = 0;
  14438. DWORD dwMajorVersion = 0;
  14439. DWORD dwMinorVersion = 0;
  14440. DWORD dwBuild = 0;
  14441. BOOL wowRet, isWoW = FALSE;
  14442. #ifdef _MSC_VER
  14443. #pragma warning(push)
  14444. /* GetVersion was declared deprecated */
  14445. #pragma warning(disable : 4996)
  14446. #endif
  14447. dwVersion = GetVersion();
  14448. #ifdef _MSC_VER
  14449. #pragma warning(pop)
  14450. #endif
  14451. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14452. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14453. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  14454. (void)dwBuild;
  14455. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  14456. sprintf(name,
  14457. "Windows %u.%u%s",
  14458. (unsigned)dwMajorVersion,
  14459. (unsigned)dwMinorVersion,
  14460. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  14461. *sysName = mg_strdup(name);
  14462. #endif
  14463. #else
  14464. *sysName = mg_strdup("Symbian");
  14465. #endif
  14466. #else
  14467. struct utsname name;
  14468. memset(&name, 0, sizeof(name));
  14469. uname(&name);
  14470. *sysName = mg_strdup(name.sysname);
  14471. #endif
  14472. }
  14473. struct mg_context *
  14474. mg_start(const struct mg_callbacks *callbacks,
  14475. void *user_data,
  14476. const char **options)
  14477. {
  14478. struct mg_context *ctx;
  14479. const char *name, *value, *default_value;
  14480. int idx, ok, workerthreadcount;
  14481. unsigned int i;
  14482. int itmp;
  14483. void (*exit_callback)(const struct mg_context *ctx) = 0;
  14484. struct mg_workerTLS tls;
  14485. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14486. WSADATA data;
  14487. WSAStartup(MAKEWORD(2, 2), &data);
  14488. #endif /* _WIN32 && !__SYMBIAN32__ */
  14489. /* Allocate context and initialize reasonable general case defaults. */
  14490. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  14491. return NULL;
  14492. }
  14493. /* Random number generator will initialize at the first call */
  14494. ctx->auth_nonce_mask =
  14495. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  14496. if (mg_init_library_called == 0) {
  14497. /* Legacy INIT, if mg_start is called without mg_init_library.
  14498. * Note: This may cause a memory leak */
  14499. const char *ports_option =
  14500. config_options[LISTENING_PORTS].default_value;
  14501. if (options) {
  14502. const char **run_options = options;
  14503. const char *optname = config_options[LISTENING_PORTS].name;
  14504. /* Try to find the "listening_ports" option */
  14505. while (*run_options) {
  14506. if (!strcmp(*run_options, optname)) {
  14507. ports_option = run_options[1];
  14508. }
  14509. run_options += 2;
  14510. }
  14511. }
  14512. if (is_ssl_port_used(ports_option)) {
  14513. /* Initialize with SSL support */
  14514. mg_init_library(MG_FEATURES_TLS);
  14515. } else {
  14516. /* Initialize without SSL support */
  14517. mg_init_library(MG_FEATURES_DEFAULT);
  14518. }
  14519. }
  14520. tls.is_master = -1;
  14521. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14522. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14523. tls.pthread_cond_helper_mutex = NULL;
  14524. #endif
  14525. pthread_setspecific(sTlsKey, &tls);
  14526. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  14527. #if !defined(ALTERNATIVE_QUEUE)
  14528. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  14529. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  14530. #endif
  14531. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  14532. if (!ok) {
  14533. /* Fatal error - abort start. However, this situation should never
  14534. * occur in practice. */
  14535. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  14536. mg_free(ctx);
  14537. pthread_setspecific(sTlsKey, NULL);
  14538. return NULL;
  14539. }
  14540. if (callbacks) {
  14541. ctx->callbacks = *callbacks;
  14542. exit_callback = callbacks->exit_context;
  14543. ctx->callbacks.exit_context = 0;
  14544. }
  14545. ctx->user_data = user_data;
  14546. ctx->handlers = NULL;
  14547. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14548. ctx->shared_lua_websockets = 0;
  14549. #endif
  14550. while (options && (name = *options++) != NULL) {
  14551. if ((idx = get_option_index(name)) == -1) {
  14552. mg_cry(fc(ctx), "Invalid option: %s", name);
  14553. free_context(ctx);
  14554. pthread_setspecific(sTlsKey, NULL);
  14555. return NULL;
  14556. } else if ((value = *options++) == NULL) {
  14557. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  14558. free_context(ctx);
  14559. pthread_setspecific(sTlsKey, NULL);
  14560. return NULL;
  14561. }
  14562. if (ctx->config[idx] != NULL) {
  14563. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  14564. mg_free(ctx->config[idx]);
  14565. }
  14566. ctx->config[idx] = mg_strdup(value);
  14567. DEBUG_TRACE("[%s] -> [%s]", name, value);
  14568. }
  14569. /* Set default value if needed */
  14570. for (i = 0; config_options[i].name != NULL; i++) {
  14571. default_value = config_options[i].default_value;
  14572. if ((ctx->config[i] == NULL) && (default_value != NULL)) {
  14573. ctx->config[i] = mg_strdup(default_value);
  14574. }
  14575. }
  14576. itmp = atoi(ctx->config[MAX_REQUEST_SIZE]);
  14577. if (itmp < 1024) {
  14578. mg_cry(fc(ctx), "max_request_size too small");
  14579. free_context(ctx);
  14580. pthread_setspecific(sTlsKey, NULL);
  14581. return NULL;
  14582. }
  14583. ctx->max_request_size = (unsigned)itmp;
  14584. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  14585. if (workerthreadcount > MAX_WORKER_THREADS) {
  14586. mg_cry(fc(ctx), "Too many worker threads");
  14587. free_context(ctx);
  14588. pthread_setspecific(sTlsKey, NULL);
  14589. return NULL;
  14590. }
  14591. if (workerthreadcount <= 0) {
  14592. mg_cry(fc(ctx), "Invalid number of worker threads");
  14593. free_context(ctx);
  14594. pthread_setspecific(sTlsKey, NULL);
  14595. return NULL;
  14596. }
  14597. #if defined(NO_FILES)
  14598. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  14599. mg_cry(fc(ctx), "%s", "Document root must not be set");
  14600. free_context(ctx);
  14601. pthread_setspecific(sTlsKey, NULL);
  14602. return NULL;
  14603. }
  14604. #endif
  14605. get_system_name(&ctx->systemName);
  14606. #if defined(USE_LUA)
  14607. /* If a Lua background script has been configured, start it. */
  14608. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  14609. char ebuf[256];
  14610. lua_State *state = (void *)mg_prepare_lua_context_script(
  14611. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  14612. if (!state) {
  14613. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  14614. free_context(ctx);
  14615. pthread_setspecific(sTlsKey, NULL);
  14616. return NULL;
  14617. }
  14618. ctx->lua_background_state = (void *)state;
  14619. lua_newtable(state);
  14620. reg_boolean(state, "shutdown", 0);
  14621. struct vec opt_vec;
  14622. struct vec eq_vec;
  14623. const char *sparams = ctx->config[LUA_BACKGROUND_SCRIPT_PARAMS];
  14624. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  14625. reg_llstring(
  14626. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  14627. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  14628. break;
  14629. }
  14630. lua_setglobal(state, LUABACKGROUNDPARAMS);
  14631. } else {
  14632. ctx->lua_background_state = 0;
  14633. }
  14634. #endif
  14635. /* NOTE(lsm): order is important here. SSL certificates must
  14636. * be initialized before listening ports. UID must be set last. */
  14637. if (!set_gpass_option(ctx) ||
  14638. #if !defined(NO_SSL)
  14639. !set_ssl_option(ctx) ||
  14640. #endif
  14641. !set_ports_option(ctx) ||
  14642. #if !defined(_WIN32)
  14643. !set_uid_option(ctx) ||
  14644. #endif
  14645. !set_acl_option(ctx)) {
  14646. free_context(ctx);
  14647. pthread_setspecific(sTlsKey, NULL);
  14648. return NULL;
  14649. }
  14650. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  14651. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  14652. * won't kill the whole process. */
  14653. (void)signal(SIGPIPE, SIG_IGN);
  14654. #endif /* !_WIN32 && !__SYMBIAN32__ */
  14655. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  14656. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14657. sizeof(pthread_t),
  14658. ctx);
  14659. if (ctx->worker_threadids == NULL) {
  14660. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  14661. free_context(ctx);
  14662. pthread_setspecific(sTlsKey, NULL);
  14663. return NULL;
  14664. }
  14665. ctx->worker_connections =
  14666. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14667. sizeof(struct mg_connection),
  14668. ctx);
  14669. if (ctx->worker_connections == NULL) {
  14670. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  14671. free_context(ctx);
  14672. pthread_setspecific(sTlsKey, NULL);
  14673. return NULL;
  14674. }
  14675. #if defined(ALTERNATIVE_QUEUE)
  14676. ctx->client_wait_events =
  14677. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  14678. ctx->cfg_worker_threads,
  14679. ctx);
  14680. if (ctx->client_wait_events == NULL) {
  14681. mg_cry(fc(ctx), "Not enough memory for worker event array");
  14682. mg_free(ctx->worker_threadids);
  14683. free_context(ctx);
  14684. pthread_setspecific(sTlsKey, NULL);
  14685. return NULL;
  14686. }
  14687. ctx->client_socks =
  14688. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  14689. ctx->cfg_worker_threads,
  14690. ctx);
  14691. if (ctx->client_wait_events == NULL) {
  14692. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  14693. mg_free(ctx->client_socks);
  14694. mg_free(ctx->worker_threadids);
  14695. free_context(ctx);
  14696. pthread_setspecific(sTlsKey, NULL);
  14697. return NULL;
  14698. }
  14699. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14700. ctx->client_wait_events[i] = event_create();
  14701. if (ctx->client_wait_events[i] == 0) {
  14702. mg_cry(fc(ctx), "Error creating worker event %i", i);
  14703. while (i > 0) {
  14704. i--;
  14705. event_destroy(ctx->client_wait_events[i]);
  14706. }
  14707. mg_free(ctx->client_socks);
  14708. mg_free(ctx->worker_threadids);
  14709. free_context(ctx);
  14710. pthread_setspecific(sTlsKey, NULL);
  14711. return NULL;
  14712. }
  14713. }
  14714. #endif
  14715. #if defined(USE_TIMERS)
  14716. if (timers_init(ctx) != 0) {
  14717. mg_cry(fc(ctx), "Error creating timers");
  14718. free_context(ctx);
  14719. pthread_setspecific(sTlsKey, NULL);
  14720. return NULL;
  14721. }
  14722. #endif
  14723. /* Context has been created - init user libraries */
  14724. if (ctx->callbacks.init_context) {
  14725. ctx->callbacks.init_context(ctx);
  14726. }
  14727. ctx->callbacks.exit_context = exit_callback;
  14728. ctx->context_type = CONTEXT_SERVER; /* server context */
  14729. /* Start master (listening) thread */
  14730. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  14731. /* Start worker threads */
  14732. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14733. struct worker_thread_args *wta = (struct worker_thread_args *)
  14734. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  14735. if (wta) {
  14736. wta->ctx = ctx;
  14737. wta->index = (int)i;
  14738. }
  14739. if ((wta == NULL)
  14740. || (mg_start_thread_with_id(worker_thread,
  14741. wta,
  14742. &ctx->worker_threadids[i]) != 0)) {
  14743. /* thread was not created */
  14744. if (wta != NULL) {
  14745. mg_free(wta);
  14746. }
  14747. if (i > 0) {
  14748. mg_cry(fc(ctx),
  14749. "Cannot start worker thread %i: error %ld",
  14750. i + 1,
  14751. (long)ERRNO);
  14752. } else {
  14753. mg_cry(fc(ctx),
  14754. "Cannot create threads: error %ld",
  14755. (long)ERRNO);
  14756. free_context(ctx);
  14757. pthread_setspecific(sTlsKey, NULL);
  14758. return NULL;
  14759. }
  14760. break;
  14761. }
  14762. }
  14763. pthread_setspecific(sTlsKey, NULL);
  14764. return ctx;
  14765. }
  14766. /* Feature check API function */
  14767. unsigned
  14768. mg_check_feature(unsigned feature)
  14769. {
  14770. static const unsigned feature_set = 0
  14771. /* Set bits for available features according to API documentation.
  14772. * This bit mask is created at compile time, according to the active
  14773. * preprocessor defines. It is a single const value at runtime. */
  14774. #if !defined(NO_FILES)
  14775. | 0x0001u
  14776. #endif
  14777. #if !defined(NO_SSL)
  14778. | 0x0002u
  14779. #endif
  14780. #if !defined(NO_CGI)
  14781. | 0x0004u
  14782. #endif
  14783. #if defined(USE_IPV6)
  14784. | 0x0008u
  14785. #endif
  14786. #if defined(USE_WEBSOCKET)
  14787. | 0x0010u
  14788. #endif
  14789. #if defined(USE_LUA)
  14790. | 0x0020u
  14791. #endif
  14792. #if defined(USE_DUKTAPE)
  14793. | 0x0040u
  14794. #endif
  14795. #if !defined(NO_CACHING)
  14796. | 0x0080u
  14797. #endif
  14798. #if defined(USE_SERVER_STATS)
  14799. | 0x0100u
  14800. #endif
  14801. /* Set some extra bits not defined in the API documentation.
  14802. * These bits may change without further notice. */
  14803. #if defined(MG_LEGACY_INTERFACE)
  14804. | 0x8000u
  14805. #endif
  14806. #if defined(MEMORY_DEBUGGING)
  14807. | 0x0100u
  14808. #endif
  14809. #if defined(USE_TIMERS)
  14810. | 0x0200u
  14811. #endif
  14812. #if !defined(NO_NONCE_CHECK)
  14813. | 0x0400u
  14814. #endif
  14815. #if !defined(NO_POPEN)
  14816. | 0x0800u
  14817. #endif
  14818. ;
  14819. return (feature & feature_set);
  14820. }
  14821. /* strcat with additional NULL check to avoid clang scan-build warning. */
  14822. #define strcat0(a, b) \
  14823. { \
  14824. if ((a != NULL) && (b != NULL)) { \
  14825. strcat(a, b); \
  14826. } \
  14827. }
  14828. /* Get system information. It can be printed or stored by the caller.
  14829. * Return the size of available information. */
  14830. static int
  14831. mg_get_system_info_impl(char *buffer, int buflen)
  14832. {
  14833. char block[256];
  14834. int system_info_length = 0;
  14835. #if defined(_WIN32)
  14836. const char *eol = "\r\n";
  14837. #else
  14838. const char *eol = "\n";
  14839. #endif
  14840. const char *eoobj = "}";
  14841. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  14842. if ((buffer == NULL) || (buflen < 1)) {
  14843. buflen = 0;
  14844. } else {
  14845. *buffer = 0;
  14846. }
  14847. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  14848. system_info_length += (int)strlen(block);
  14849. if (system_info_length < buflen) {
  14850. strcat0(buffer, block);
  14851. }
  14852. /* Server version */
  14853. {
  14854. const char *version = mg_version();
  14855. mg_snprintf(NULL,
  14856. NULL,
  14857. block,
  14858. sizeof(block),
  14859. "\"version\" : \"%s\",%s",
  14860. version,
  14861. eol);
  14862. system_info_length += (int)strlen(block);
  14863. if (system_info_length < buflen) {
  14864. strcat0(buffer, block);
  14865. }
  14866. }
  14867. /* System info */
  14868. {
  14869. #if defined(_WIN32)
  14870. #if !defined(__SYMBIAN32__)
  14871. DWORD dwVersion = 0;
  14872. DWORD dwMajorVersion = 0;
  14873. DWORD dwMinorVersion = 0;
  14874. SYSTEM_INFO si;
  14875. GetSystemInfo(&si);
  14876. #ifdef _MSC_VER
  14877. #pragma warning(push)
  14878. /* GetVersion was declared deprecated */
  14879. #pragma warning(disable : 4996)
  14880. #endif
  14881. dwVersion = GetVersion();
  14882. #ifdef _MSC_VER
  14883. #pragma warning(pop)
  14884. #endif
  14885. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14886. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14887. mg_snprintf(NULL,
  14888. NULL,
  14889. block,
  14890. sizeof(block),
  14891. "\"os\" : \"Windows %u.%u\",%s",
  14892. (unsigned)dwMajorVersion,
  14893. (unsigned)dwMinorVersion,
  14894. eol);
  14895. system_info_length += (int)strlen(block);
  14896. if (system_info_length < buflen) {
  14897. strcat0(buffer, block);
  14898. }
  14899. mg_snprintf(NULL,
  14900. NULL,
  14901. block,
  14902. sizeof(block),
  14903. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  14904. (unsigned)si.wProcessorArchitecture,
  14905. (unsigned)si.dwNumberOfProcessors,
  14906. (unsigned)si.dwActiveProcessorMask,
  14907. eol);
  14908. system_info_length += (int)strlen(block);
  14909. if (system_info_length < buflen) {
  14910. strcat0(buffer, block);
  14911. }
  14912. #else
  14913. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  14914. system_info_length += (int)strlen(block);
  14915. if (system_info_length < buflen) {
  14916. strcat0(buffer, block);
  14917. }
  14918. #endif
  14919. #else
  14920. struct utsname name;
  14921. memset(&name, 0, sizeof(name));
  14922. uname(&name);
  14923. mg_snprintf(NULL,
  14924. NULL,
  14925. block,
  14926. sizeof(block),
  14927. "\"os\" : \"%s %s (%s) - %s\",%s",
  14928. name.sysname,
  14929. name.version,
  14930. name.release,
  14931. name.machine,
  14932. eol);
  14933. system_info_length += (int)strlen(block);
  14934. if (system_info_length < buflen) {
  14935. strcat0(buffer, block);
  14936. }
  14937. #endif
  14938. }
  14939. /* Features */
  14940. {
  14941. mg_snprintf(NULL,
  14942. NULL,
  14943. block,
  14944. sizeof(block),
  14945. "\"features\" : %lu,%s"
  14946. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  14947. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  14948. eol,
  14949. mg_check_feature(1) ? " Files" : "",
  14950. mg_check_feature(2) ? " HTTPS" : "",
  14951. mg_check_feature(4) ? " CGI" : "",
  14952. mg_check_feature(8) ? " IPv6" : "",
  14953. mg_check_feature(16) ? " WebSockets" : "",
  14954. mg_check_feature(32) ? " Lua" : "",
  14955. mg_check_feature(64) ? " JavaScript" : "",
  14956. mg_check_feature(128) ? " Cache" : "",
  14957. mg_check_feature(256) ? " Stats" : "",
  14958. eol);
  14959. system_info_length += (int)strlen(block);
  14960. if (system_info_length < buflen) {
  14961. strcat0(buffer, block);
  14962. }
  14963. #ifdef USE_LUA
  14964. mg_snprintf(NULL,
  14965. NULL,
  14966. block,
  14967. sizeof(block),
  14968. "\"lua_version\" : \"%u (%s)\",%s",
  14969. (unsigned)LUA_VERSION_NUM,
  14970. LUA_RELEASE,
  14971. eol);
  14972. system_info_length += (int)strlen(block);
  14973. if (system_info_length < buflen) {
  14974. strcat0(buffer, block);
  14975. }
  14976. #endif
  14977. #if defined(USE_DUKTAPE)
  14978. mg_snprintf(NULL,
  14979. NULL,
  14980. block,
  14981. sizeof(block),
  14982. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  14983. (unsigned)DUK_VERSION / 10000,
  14984. ((unsigned)DUK_VERSION / 100) % 100,
  14985. (unsigned)DUK_VERSION % 100,
  14986. eol);
  14987. system_info_length += (int)strlen(block);
  14988. if (system_info_length < buflen) {
  14989. strcat0(buffer, block);
  14990. }
  14991. #endif
  14992. }
  14993. /* Build date */
  14994. {
  14995. #if defined(__GNUC__)
  14996. #pragma GCC diagnostic push
  14997. /* Disable bogus compiler warning -Wdate-time */
  14998. #pragma GCC diagnostic ignored "-Wall"
  14999. #pragma GCC diagnostic ignored "-Werror"
  15000. #endif
  15001. mg_snprintf(NULL,
  15002. NULL,
  15003. block,
  15004. sizeof(block),
  15005. "\"build\" : \"%s\",%s",
  15006. __DATE__,
  15007. eol);
  15008. #if defined(__GNUC__)
  15009. #pragma GCC diagnostic pop
  15010. #endif
  15011. system_info_length += (int)strlen(block);
  15012. if (system_info_length < buflen) {
  15013. strcat0(buffer, block);
  15014. }
  15015. }
  15016. /* Compiler information */
  15017. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  15018. {
  15019. #if defined(_MSC_VER)
  15020. mg_snprintf(NULL,
  15021. NULL,
  15022. block,
  15023. sizeof(block),
  15024. "\"compiler\" : \"MSC: %u (%u)\",%s",
  15025. (unsigned)_MSC_VER,
  15026. (unsigned)_MSC_FULL_VER,
  15027. eol);
  15028. system_info_length += (int)strlen(block);
  15029. if (system_info_length < buflen) {
  15030. strcat0(buffer, block);
  15031. }
  15032. #elif defined(__MINGW64__)
  15033. mg_snprintf(NULL,
  15034. NULL,
  15035. block,
  15036. sizeof(block),
  15037. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  15038. (unsigned)__MINGW64_VERSION_MAJOR,
  15039. (unsigned)__MINGW64_VERSION_MINOR,
  15040. eol);
  15041. system_info_length += (int)strlen(block);
  15042. if (system_info_length < buflen) {
  15043. strcat0(buffer, block);
  15044. }
  15045. mg_snprintf(NULL,
  15046. NULL,
  15047. block,
  15048. sizeof(block),
  15049. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15050. (unsigned)__MINGW32_MAJOR_VERSION,
  15051. (unsigned)__MINGW32_MINOR_VERSION,
  15052. eol);
  15053. system_info_length += (int)strlen(block);
  15054. if (system_info_length < buflen) {
  15055. strcat0(buffer, block);
  15056. }
  15057. #elif defined(__MINGW32__)
  15058. mg_snprintf(NULL,
  15059. NULL,
  15060. block,
  15061. sizeof(block),
  15062. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15063. (unsigned)__MINGW32_MAJOR_VERSION,
  15064. (unsigned)__MINGW32_MINOR_VERSION,
  15065. eol);
  15066. system_info_length += (int)strlen(block);
  15067. if (system_info_length < buflen) {
  15068. strcat0(buffer, block);
  15069. }
  15070. #elif defined(__clang__)
  15071. mg_snprintf(NULL,
  15072. NULL,
  15073. block,
  15074. sizeof(block),
  15075. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  15076. __clang_major__,
  15077. __clang_minor__,
  15078. __clang_patchlevel__,
  15079. __clang_version__,
  15080. eol);
  15081. system_info_length += (int)strlen(block);
  15082. if (system_info_length < buflen) {
  15083. strcat0(buffer, block);
  15084. }
  15085. #elif defined(__GNUC__)
  15086. mg_snprintf(NULL,
  15087. NULL,
  15088. block,
  15089. sizeof(block),
  15090. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  15091. (unsigned)__GNUC__,
  15092. (unsigned)__GNUC_MINOR__,
  15093. (unsigned)__GNUC_PATCHLEVEL__,
  15094. eol);
  15095. system_info_length += (int)strlen(block);
  15096. if (system_info_length < buflen) {
  15097. strcat0(buffer, block);
  15098. }
  15099. #elif defined(__INTEL_COMPILER)
  15100. mg_snprintf(NULL,
  15101. NULL,
  15102. block,
  15103. sizeof(block),
  15104. "\"compiler\" : \"Intel C/C++: %u\",%s",
  15105. (unsigned)__INTEL_COMPILER,
  15106. eol);
  15107. system_info_length += (int)strlen(block);
  15108. if (system_info_length < buflen) {
  15109. strcat0(buffer, block);
  15110. }
  15111. #elif defined(__BORLANDC__)
  15112. mg_snprintf(NULL,
  15113. NULL,
  15114. block,
  15115. sizeof(block),
  15116. "\"compiler\" : \"Borland C: 0x%x\",%s",
  15117. (unsigned)__BORLANDC__,
  15118. eol);
  15119. system_info_length += (int)strlen(block);
  15120. if (system_info_length < buflen) {
  15121. strcat0(buffer, block);
  15122. }
  15123. #elif defined(__SUNPRO_C)
  15124. mg_snprintf(NULL,
  15125. NULL,
  15126. block,
  15127. sizeof(block),
  15128. "\"compiler\" : \"Solaris: 0x%x\",%s",
  15129. (unsigned)__SUNPRO_C,
  15130. eol);
  15131. system_info_length += (int)strlen(block);
  15132. if (system_info_length < buflen) {
  15133. strcat0(buffer, block);
  15134. }
  15135. #else
  15136. mg_snprintf(NULL,
  15137. NULL,
  15138. block,
  15139. sizeof(block),
  15140. "\"compiler\" : \"other\",%s",
  15141. eol);
  15142. system_info_length += (int)strlen(block);
  15143. if (system_info_length < buflen) {
  15144. strcat0(buffer, block);
  15145. }
  15146. #endif
  15147. }
  15148. /* Determine 32/64 bit data mode.
  15149. * see https://en.wikipedia.org/wiki/64-bit_computing */
  15150. {
  15151. mg_snprintf(
  15152. NULL,
  15153. NULL,
  15154. block,
  15155. sizeof(block),
  15156. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  15157. "ptr:%u, size:%u, time:%u\"%s",
  15158. (unsigned)sizeof(short),
  15159. (unsigned)sizeof(int),
  15160. (unsigned)sizeof(long),
  15161. (unsigned)sizeof(long long),
  15162. (unsigned)sizeof(float),
  15163. (unsigned)sizeof(double),
  15164. (unsigned)sizeof(long double),
  15165. (unsigned)sizeof(char),
  15166. (unsigned)sizeof(wchar_t),
  15167. (unsigned)sizeof(void *),
  15168. (unsigned)sizeof(size_t),
  15169. (unsigned)sizeof(time_t),
  15170. eol);
  15171. system_info_length += (int)strlen(block);
  15172. if (system_info_length < buflen) {
  15173. strcat0(buffer, block);
  15174. }
  15175. }
  15176. /* Terminate string */
  15177. if ((buflen > 0) && buffer && buffer[0]) {
  15178. if (system_info_length < buflen) {
  15179. strcat0(buffer, eoobj);
  15180. strcat0(buffer, eol);
  15181. }
  15182. }
  15183. system_info_length += reserved_len;
  15184. return system_info_length;
  15185. }
  15186. #if defined(USE_SERVER_STATS)
  15187. /* Get context information. It can be printed or stored by the caller.
  15188. * Return the size of available information. */
  15189. static int
  15190. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  15191. {
  15192. char block[256];
  15193. int context_info_length = 0;
  15194. #if defined(_WIN32)
  15195. const char *eol = "\r\n";
  15196. #else
  15197. const char *eol = "\n";
  15198. #endif
  15199. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  15200. const char *eoobj = "}";
  15201. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15202. if ((buffer == NULL) || (buflen < 1)) {
  15203. buflen = 0;
  15204. } else {
  15205. *buffer = 0;
  15206. }
  15207. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15208. context_info_length += (int)strlen(block);
  15209. if (context_info_length < buflen) {
  15210. strcat0(buffer, block);
  15211. }
  15212. /* Memory information */
  15213. if (ms) {
  15214. mg_snprintf(NULL,
  15215. NULL,
  15216. block,
  15217. sizeof(block),
  15218. "\"memory\" : {%s"
  15219. "\"blocks\" : %i,%s"
  15220. "\"used\" : %" INT64_FMT ",%s"
  15221. "\"maxUsed\" : %" INT64_FMT "%s"
  15222. "}%s%s",
  15223. eol,
  15224. ms->blockCount,
  15225. eol,
  15226. ms->totalMemUsed,
  15227. eol,
  15228. ms->maxMemUsed,
  15229. eol,
  15230. (ctx ? "," : ""),
  15231. eol);
  15232. context_info_length += (int)strlen(block);
  15233. if (context_info_length + reserved_len < buflen) {
  15234. strcat0(buffer, block);
  15235. }
  15236. }
  15237. /* Connections information */
  15238. if (ctx) {
  15239. mg_snprintf(NULL,
  15240. NULL,
  15241. block,
  15242. sizeof(block),
  15243. "\"connections\" : {%s"
  15244. "\"active\" : %i,%s"
  15245. "\"maxActive\" : %i,%s"
  15246. "\"total\" : %" INT64_FMT "%s"
  15247. "},%s",
  15248. eol,
  15249. ctx->active_connections,
  15250. eol,
  15251. ctx->max_connections,
  15252. eol,
  15253. ctx->total_connections,
  15254. eol,
  15255. eol);
  15256. context_info_length += (int)strlen(block);
  15257. if (context_info_length + reserved_len < buflen) {
  15258. strcat0(buffer, block);
  15259. }
  15260. }
  15261. /* Requests information */
  15262. if (ctx) {
  15263. mg_snprintf(NULL,
  15264. NULL,
  15265. block,
  15266. sizeof(block),
  15267. "\"requests\" : {%s"
  15268. "\"total\" : %" INT64_FMT "%s"
  15269. "},%s",
  15270. eol,
  15271. ctx->total_requests,
  15272. eol,
  15273. eol);
  15274. context_info_length += (int)strlen(block);
  15275. if (context_info_length + reserved_len < buflen) {
  15276. strcat0(buffer, block);
  15277. }
  15278. }
  15279. /* Data information */
  15280. if (ctx) {
  15281. mg_snprintf(NULL,
  15282. NULL,
  15283. block,
  15284. sizeof(block),
  15285. "\"data\" : {%s"
  15286. "\"read\" : %" INT64_FMT "%s,"
  15287. "\"written\" : %" INT64_FMT "%s"
  15288. "},%s",
  15289. eol,
  15290. ctx->total_data_read,
  15291. eol,
  15292. ctx->total_data_written,
  15293. eol,
  15294. eol);
  15295. context_info_length += (int)strlen(block);
  15296. if (context_info_length + reserved_len < buflen) {
  15297. strcat0(buffer, block);
  15298. }
  15299. }
  15300. /* Execution time information */
  15301. if (ctx) {
  15302. char start_time_str[64] = {0};
  15303. char now_str[64] = {0};
  15304. time_t start_time = ctx->start_time;
  15305. time_t now = time(NULL);
  15306. gmt_time_string(start_time_str,
  15307. sizeof(start_time_str) - 1,
  15308. &start_time);
  15309. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15310. mg_snprintf(NULL,
  15311. NULL,
  15312. block,
  15313. sizeof(block),
  15314. "\"time\" : {%s"
  15315. "\"uptime\" : %.0f,%s"
  15316. "\"start\" : \"%s\",%s"
  15317. "\"now\" : \"%s\"%s"
  15318. "}%s",
  15319. eol,
  15320. difftime(now, start_time),
  15321. eol,
  15322. start_time_str,
  15323. eol,
  15324. now_str,
  15325. eol,
  15326. eol);
  15327. context_info_length += (int)strlen(block);
  15328. if (context_info_length + reserved_len < buflen) {
  15329. strcat0(buffer, block);
  15330. }
  15331. }
  15332. /* Terminate string */
  15333. if ((buflen > 0) && buffer && buffer[0]) {
  15334. if (context_info_length < buflen) {
  15335. strcat0(buffer, eoobj);
  15336. strcat0(buffer, eol);
  15337. }
  15338. }
  15339. context_info_length += reserved_len;
  15340. return context_info_length;
  15341. }
  15342. #endif
  15343. #ifdef MG_EXPERIMENTAL_INTERFACES
  15344. /* Get connection information. It can be printed or stored by the caller.
  15345. * Return the size of available information. */
  15346. static int
  15347. mg_get_connection_info_impl(const struct mg_context *ctx,
  15348. int idx,
  15349. char *buffer,
  15350. int buflen)
  15351. {
  15352. const struct mg_connection *conn;
  15353. const struct mg_request_info *ri;
  15354. char block[256];
  15355. int connection_info_length = 0;
  15356. int state = 0;
  15357. const char *state_str = "unknown";
  15358. #if defined(_WIN32)
  15359. const char *eol = "\r\n";
  15360. #else
  15361. const char *eol = "\n";
  15362. #endif
  15363. const char *eoobj = "}";
  15364. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15365. if ((buffer == NULL) || (buflen < 1)) {
  15366. buflen = 0;
  15367. } else {
  15368. *buffer = 0;
  15369. }
  15370. if ((ctx == NULL) || (idx < 0)) {
  15371. /* Parameter error */
  15372. return 0;
  15373. }
  15374. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  15375. /* Out of range */
  15376. return 0;
  15377. }
  15378. /* Take connection [idx]. This connection is not locked in
  15379. * any way, so some other thread might use it. */
  15380. conn = (ctx->worker_connections) + idx;
  15381. /* Initialize output string */
  15382. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15383. connection_info_length += (int)strlen(block);
  15384. if (connection_info_length < buflen) {
  15385. strcat0(buffer, block);
  15386. }
  15387. /* Init variables */
  15388. ri = &(conn->request_info);
  15389. #if defined(USE_SERVER_STATS)
  15390. state = conn->conn_state;
  15391. /* State as string */
  15392. switch (state) {
  15393. case 0:
  15394. state_str = "undefined";
  15395. break;
  15396. case 1:
  15397. state_str = "not used";
  15398. break;
  15399. case 2:
  15400. state_str = "init";
  15401. break;
  15402. case 3:
  15403. state_str = "ready";
  15404. break;
  15405. case 4:
  15406. state_str = "processing";
  15407. break;
  15408. case 5:
  15409. state_str = "processed";
  15410. break;
  15411. case 6:
  15412. state_str = "to close";
  15413. break;
  15414. case 7:
  15415. state_str = "closing";
  15416. break;
  15417. case 8:
  15418. state_str = "closed";
  15419. break;
  15420. case 9:
  15421. state_str = "done";
  15422. break;
  15423. }
  15424. #endif
  15425. /* Connection info */
  15426. if ((state >= 3) && (state < 9)) {
  15427. mg_snprintf(NULL,
  15428. NULL,
  15429. block,
  15430. sizeof(block),
  15431. "\"connection\" : {%s"
  15432. "\"remote\" : {%s"
  15433. "\"protocol\" : \"%s\",%s"
  15434. "\"addr\" : \"%s\",%s"
  15435. "\"port\" : %u%s"
  15436. "},%s"
  15437. "\"handled_requests\" : %u%s"
  15438. "},%s",
  15439. eol,
  15440. eol,
  15441. get_proto_name(conn),
  15442. eol,
  15443. ri->remote_addr,
  15444. eol,
  15445. ri->remote_port,
  15446. eol,
  15447. eol,
  15448. conn->handled_requests,
  15449. eol,
  15450. eol);
  15451. connection_info_length += (int)strlen(block);
  15452. if (connection_info_length + reserved_len < buflen) {
  15453. strcat0(buffer, block);
  15454. }
  15455. }
  15456. /* Request info */
  15457. if ((state >= 4) && (state < 6)) {
  15458. mg_snprintf(NULL,
  15459. NULL,
  15460. block,
  15461. sizeof(block),
  15462. "\"request_info\" : {%s"
  15463. "\"method\" : \"%s\",%s"
  15464. "\"uri\" : \"%s\",%s"
  15465. "\"query\" : %s%s%s%s"
  15466. "},%s",
  15467. eol,
  15468. ri->request_method,
  15469. eol,
  15470. ri->request_uri,
  15471. eol,
  15472. ri->query_string ? "\"" : "",
  15473. ri->query_string ? ri->query_string : "null",
  15474. ri->query_string ? "\"" : "",
  15475. eol,
  15476. eol);
  15477. connection_info_length += (int)strlen(block);
  15478. if (connection_info_length + reserved_len < buflen) {
  15479. strcat0(buffer, block);
  15480. }
  15481. }
  15482. /* Execution time information */
  15483. if ((state >= 2) && (state < 9)) {
  15484. char start_time_str[64] = {0};
  15485. char now_str[64] = {0};
  15486. time_t start_time = conn->conn_birth_time;
  15487. time_t now = time(NULL);
  15488. gmt_time_string(start_time_str,
  15489. sizeof(start_time_str) - 1,
  15490. &start_time);
  15491. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15492. mg_snprintf(NULL,
  15493. NULL,
  15494. block,
  15495. sizeof(block),
  15496. "\"time\" : {%s"
  15497. "\"uptime\" : %.0f,%s"
  15498. "\"start\" : \"%s\",%s"
  15499. "\"now\" : \"%s\"%s"
  15500. "},%s",
  15501. eol,
  15502. difftime(now, start_time),
  15503. eol,
  15504. start_time_str,
  15505. eol,
  15506. now_str,
  15507. eol,
  15508. eol);
  15509. connection_info_length += (int)strlen(block);
  15510. if (connection_info_length + reserved_len < buflen) {
  15511. strcat0(buffer, block);
  15512. }
  15513. }
  15514. /* Remote user name */
  15515. if ((ri->remote_user) && (state < 9)) {
  15516. mg_snprintf(NULL,
  15517. NULL,
  15518. block,
  15519. sizeof(block),
  15520. "\"user\" : {%s"
  15521. "\"name\" : \"%s\",%s"
  15522. "},%s",
  15523. eol,
  15524. ri->remote_user,
  15525. eol,
  15526. eol);
  15527. connection_info_length += (int)strlen(block);
  15528. if (connection_info_length + reserved_len < buflen) {
  15529. strcat0(buffer, block);
  15530. }
  15531. }
  15532. /* Data block */
  15533. if (state >= 3) {
  15534. mg_snprintf(NULL,
  15535. NULL,
  15536. block,
  15537. sizeof(block),
  15538. "\"data\" : {%s"
  15539. "\"read\" : %" INT64_FMT ",%s"
  15540. "\"written\" : %" INT64_FMT "%s"
  15541. "},%s",
  15542. eol,
  15543. conn->consumed_content,
  15544. eol,
  15545. conn->num_bytes_sent,
  15546. eol,
  15547. eol);
  15548. connection_info_length += (int)strlen(block);
  15549. if (connection_info_length + reserved_len < buflen) {
  15550. strcat0(buffer, block);
  15551. }
  15552. }
  15553. /* State */
  15554. mg_snprintf(NULL,
  15555. NULL,
  15556. block,
  15557. sizeof(block),
  15558. "\"state\" : \"%s\"%s",
  15559. state_str,
  15560. eol);
  15561. connection_info_length += (int)strlen(block);
  15562. if (connection_info_length + reserved_len < buflen) {
  15563. strcat0(buffer, block);
  15564. }
  15565. /* Terminate string */
  15566. if ((buflen > 0) && buffer && buffer[0]) {
  15567. if (connection_info_length < buflen) {
  15568. strcat0(buffer, eoobj);
  15569. strcat0(buffer, eol);
  15570. }
  15571. }
  15572. connection_info_length += reserved_len;
  15573. return connection_info_length;
  15574. }
  15575. #endif
  15576. /* Get system information. It can be printed or stored by the caller.
  15577. * Return the size of available information. */
  15578. int
  15579. mg_get_system_info(char *buffer, int buflen)
  15580. {
  15581. if ((buffer == NULL) || (buflen < 1)) {
  15582. return mg_get_system_info_impl(NULL, 0);
  15583. } else {
  15584. /* Reset buffer, so we can always use strcat. */
  15585. buffer[0] = 0;
  15586. return mg_get_system_info_impl(buffer, buflen);
  15587. }
  15588. }
  15589. /* Get context information. It can be printed or stored by the caller.
  15590. * Return the size of available information. */
  15591. int
  15592. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  15593. {
  15594. #if defined(USE_SERVER_STATS)
  15595. if ((buffer == NULL) || (buflen < 1)) {
  15596. return mg_get_context_info_impl(ctx, NULL, 0);
  15597. } else {
  15598. /* Reset buffer, so we can always use strcat. */
  15599. buffer[0] = 0;
  15600. return mg_get_context_info_impl(ctx, buffer, buflen);
  15601. }
  15602. #else
  15603. (void)ctx;
  15604. if ((buffer != NULL) && (buflen > 0)) {
  15605. buffer[0] = 0;
  15606. }
  15607. return 0;
  15608. #endif
  15609. }
  15610. #ifdef MG_EXPERIMENTAL_INTERFACES
  15611. int
  15612. mg_get_connection_info(const struct mg_context *ctx,
  15613. int idx,
  15614. char *buffer,
  15615. int buflen)
  15616. {
  15617. if ((buffer == NULL) || (buflen < 1)) {
  15618. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  15619. } else {
  15620. /* Reset buffer, so we can always use strcat. */
  15621. buffer[0] = 0;
  15622. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  15623. }
  15624. }
  15625. #endif
  15626. /* Initialize this library. This function does not need to be thread safe.
  15627. */
  15628. unsigned
  15629. mg_init_library(unsigned features)
  15630. {
  15631. #if !defined(NO_SSL)
  15632. char ebuf[128];
  15633. #endif
  15634. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  15635. unsigned features_inited = features_to_init;
  15636. if (mg_init_library_called <= 0) {
  15637. /* Not initialized yet */
  15638. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  15639. return 0;
  15640. }
  15641. }
  15642. mg_global_lock();
  15643. if (mg_init_library_called <= 0) {
  15644. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  15645. /* Fatal error - abort start. However, this situation should
  15646. * never occur in practice. */
  15647. return 0;
  15648. }
  15649. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15650. InitializeCriticalSection(&global_log_file_lock);
  15651. #endif /* _WIN32 && !__SYMBIAN32__ */
  15652. #if !defined(_WIN32)
  15653. pthread_mutexattr_init(&pthread_mutex_attr);
  15654. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  15655. #endif
  15656. #if defined(USE_LUA)
  15657. lua_init_optional_libraries();
  15658. #endif
  15659. }
  15660. #if !defined(NO_SSL)
  15661. if (features_to_init & 2) {
  15662. if (!mg_ssl_initialized) {
  15663. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  15664. mg_ssl_initialized = 1;
  15665. } else {
  15666. (void)ebuf;
  15667. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  15668. features_inited &= ~(2u);
  15669. }
  15670. } else {
  15671. /* ssl already initialized */
  15672. }
  15673. }
  15674. #endif
  15675. /* Start WinSock for Windows */
  15676. if (mg_init_library_called <= 0) {
  15677. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15678. WSADATA data;
  15679. WSAStartup(MAKEWORD(2, 2), &data);
  15680. #endif /* _WIN32 && !__SYMBIAN32__ */
  15681. mg_init_library_called = 1;
  15682. } else {
  15683. mg_init_library_called++;
  15684. }
  15685. mg_global_unlock();
  15686. return features_inited;
  15687. }
  15688. /* Un-initialize this library. */
  15689. unsigned
  15690. mg_exit_library(void)
  15691. {
  15692. if (mg_init_library_called <= 0) {
  15693. return 0;
  15694. }
  15695. mg_global_lock();
  15696. mg_init_library_called--;
  15697. if (mg_init_library_called == 0) {
  15698. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15699. (void)WSACleanup();
  15700. #endif /* _WIN32 && !__SYMBIAN32__ */
  15701. #if !defined(NO_SSL)
  15702. if (mg_ssl_initialized) {
  15703. uninitialize_ssl();
  15704. mg_ssl_initialized = 0;
  15705. }
  15706. #endif
  15707. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15708. (void)DeleteCriticalSection(&global_log_file_lock);
  15709. #endif /* _WIN32 && !__SYMBIAN32__ */
  15710. #if !defined(_WIN32)
  15711. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  15712. #endif
  15713. (void)pthread_key_delete(sTlsKey);
  15714. #if defined(USE_LUA)
  15715. lua_exit_optional_libraries();
  15716. #endif
  15717. mg_global_unlock();
  15718. (void)pthread_mutex_destroy(&global_lock_mutex);
  15719. return 1;
  15720. }
  15721. mg_global_unlock();
  15722. return 1;
  15723. }
  15724. /* End of civetweb.c */