civetweb.c 477 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166
  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. socklen_t len = (socklen_t)sizeof(sockerr);
  7017. FD_ZERO(&fdset);
  7018. FD_SET(*sock, &fdset);
  7019. timeout.tv_sec = 10; /* 10 second timeout */
  7020. timeout.tv_usec = 0;
  7021. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7022. /* Not connected */
  7023. mg_snprintf(NULL,
  7024. NULL, /* No truncation check for ebuf */
  7025. ebuf,
  7026. ebuf_len,
  7027. "connect(%s:%d): timeout",
  7028. host,
  7029. port);
  7030. closesocket(*sock);
  7031. *sock = INVALID_SOCKET;
  7032. return 0;
  7033. }
  7034. getsockopt(*sock, SOL_SOCKET, SO_ERROR, &sockerr, &len);
  7035. if (sockerr != 0) {
  7036. /* Not connected */
  7037. mg_snprintf(NULL,
  7038. NULL, /* No truncation check for ebuf */
  7039. ebuf,
  7040. ebuf_len,
  7041. "connect(%s:%d): error %s",
  7042. host,
  7043. port,
  7044. strerror(sockerr));
  7045. closesocket(*sock);
  7046. *sock = INVALID_SOCKET;
  7047. return 0;
  7048. }
  7049. }
  7050. return 1;
  7051. }
  7052. int
  7053. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7054. {
  7055. static const char *dont_escape = "._-$,;~()";
  7056. static const char *hex = "0123456789abcdef";
  7057. char *pos = dst;
  7058. const char *end = dst + dst_len - 1;
  7059. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7060. if (isalnum(*(const unsigned char *)src)
  7061. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7062. *pos = *src;
  7063. } else if (pos + 2 < end) {
  7064. pos[0] = '%';
  7065. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7066. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7067. pos += 2;
  7068. } else {
  7069. break;
  7070. }
  7071. }
  7072. *pos = '\0';
  7073. return (*src == '\0') ? (int)(pos - dst) : -1;
  7074. }
  7075. /* Return 0 on success, non-zero if an error occurs. */
  7076. static int
  7077. print_dir_entry(struct de *de)
  7078. {
  7079. size_t hrefsize;
  7080. char *href;
  7081. char size[64], mod[64];
  7082. struct tm *tm;
  7083. hrefsize = PATH_MAX * 3; /* worst case */
  7084. href = (char *)mg_malloc(hrefsize);
  7085. if (href == NULL) {
  7086. return -1;
  7087. }
  7088. if (de->file.is_directory) {
  7089. mg_snprintf(de->conn,
  7090. NULL, /* Buffer is big enough */
  7091. size,
  7092. sizeof(size),
  7093. "%s",
  7094. "[DIRECTORY]");
  7095. } else {
  7096. /* We use (signed) cast below because MSVC 6 compiler cannot
  7097. * convert unsigned __int64 to double. Sigh. */
  7098. if (de->file.size < 1024) {
  7099. mg_snprintf(de->conn,
  7100. NULL, /* Buffer is big enough */
  7101. size,
  7102. sizeof(size),
  7103. "%d",
  7104. (int)de->file.size);
  7105. } else if (de->file.size < 0x100000) {
  7106. mg_snprintf(de->conn,
  7107. NULL, /* Buffer is big enough */
  7108. size,
  7109. sizeof(size),
  7110. "%.1fk",
  7111. (double)de->file.size / 1024.0);
  7112. } else if (de->file.size < 0x40000000) {
  7113. mg_snprintf(de->conn,
  7114. NULL, /* Buffer is big enough */
  7115. size,
  7116. sizeof(size),
  7117. "%.1fM",
  7118. (double)de->file.size / 1048576);
  7119. } else {
  7120. mg_snprintf(de->conn,
  7121. NULL, /* Buffer is big enough */
  7122. size,
  7123. sizeof(size),
  7124. "%.1fG",
  7125. (double)de->file.size / 1073741824);
  7126. }
  7127. }
  7128. /* Note: mg_snprintf will not cause a buffer overflow above.
  7129. * So, string truncation checks are not required here. */
  7130. tm = localtime(&de->file.last_modified);
  7131. if (tm != NULL) {
  7132. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7133. } else {
  7134. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7135. mod[sizeof(mod) - 1] = '\0';
  7136. }
  7137. mg_url_encode(de->file_name, href, hrefsize);
  7138. mg_printf(de->conn,
  7139. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7140. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7141. de->conn->request_info.local_uri,
  7142. href,
  7143. de->file.is_directory ? "/" : "",
  7144. de->file_name,
  7145. de->file.is_directory ? "/" : "",
  7146. mod,
  7147. size);
  7148. mg_free(href);
  7149. return 0;
  7150. }
  7151. /* This function is called from send_directory() and used for
  7152. * sorting directory entries by size, or name, or modification time.
  7153. * On windows, __cdecl specification is needed in case if project is built
  7154. * with __stdcall convention. qsort always requires __cdels callback. */
  7155. static int WINCDECL
  7156. compare_dir_entries(const void *p1, const void *p2)
  7157. {
  7158. if (p1 && p2) {
  7159. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7160. const char *query_string = a->conn->request_info.query_string;
  7161. int cmp_result = 0;
  7162. if (query_string == NULL) {
  7163. query_string = "na";
  7164. }
  7165. if (a->file.is_directory && !b->file.is_directory) {
  7166. return -1; /* Always put directories on top */
  7167. } else if (!a->file.is_directory && b->file.is_directory) {
  7168. return 1; /* Always put directories on top */
  7169. } else if (*query_string == 'n') {
  7170. cmp_result = strcmp(a->file_name, b->file_name);
  7171. } else if (*query_string == 's') {
  7172. cmp_result = (a->file.size == b->file.size)
  7173. ? 0
  7174. : ((a->file.size > b->file.size) ? 1 : -1);
  7175. } else if (*query_string == 'd') {
  7176. cmp_result =
  7177. (a->file.last_modified == b->file.last_modified)
  7178. ? 0
  7179. : ((a->file.last_modified > b->file.last_modified) ? 1
  7180. : -1);
  7181. }
  7182. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7183. }
  7184. return 0;
  7185. }
  7186. static int
  7187. must_hide_file(struct mg_connection *conn, const char *path)
  7188. {
  7189. if (conn && conn->ctx) {
  7190. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7191. const char *pattern = conn->ctx->config[HIDE_FILES];
  7192. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7193. || ((pattern != NULL)
  7194. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7195. }
  7196. return 0;
  7197. }
  7198. static int
  7199. scan_directory(struct mg_connection *conn,
  7200. const char *dir,
  7201. void *data,
  7202. int (*cb)(struct de *, void *))
  7203. {
  7204. char path[PATH_MAX];
  7205. struct dirent *dp;
  7206. DIR *dirp;
  7207. struct de de;
  7208. int truncated;
  7209. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7210. return 0;
  7211. } else {
  7212. de.conn = conn;
  7213. while ((dp = mg_readdir(dirp)) != NULL) {
  7214. /* Do not show current dir and hidden files */
  7215. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7216. || must_hide_file(conn, dp->d_name)) {
  7217. continue;
  7218. }
  7219. mg_snprintf(
  7220. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7221. /* If we don't memset stat structure to zero, mtime will have
  7222. * garbage and strftime() will segfault later on in
  7223. * print_dir_entry(). memset is required only if mg_stat()
  7224. * fails. For more details, see
  7225. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7226. memset(&de.file, 0, sizeof(de.file));
  7227. if (truncated) {
  7228. /* If the path is not complete, skip processing. */
  7229. continue;
  7230. }
  7231. if (!mg_stat(conn, path, &de.file)) {
  7232. mg_cry(conn,
  7233. "%s: mg_stat(%s) failed: %s",
  7234. __func__,
  7235. path,
  7236. strerror(ERRNO));
  7237. }
  7238. de.file_name = dp->d_name;
  7239. cb(&de, data);
  7240. }
  7241. (void)mg_closedir(dirp);
  7242. }
  7243. return 1;
  7244. }
  7245. #if !defined(NO_FILES)
  7246. static int
  7247. remove_directory(struct mg_connection *conn, const char *dir)
  7248. {
  7249. char path[PATH_MAX];
  7250. struct dirent *dp;
  7251. DIR *dirp;
  7252. struct de de;
  7253. int truncated;
  7254. int ok = 1;
  7255. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7256. return 0;
  7257. } else {
  7258. de.conn = conn;
  7259. while ((dp = mg_readdir(dirp)) != NULL) {
  7260. /* Do not show current dir (but show hidden files as they will
  7261. * also be removed) */
  7262. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7263. continue;
  7264. }
  7265. mg_snprintf(
  7266. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7267. /* If we don't memset stat structure to zero, mtime will have
  7268. * garbage and strftime() will segfault later on in
  7269. * print_dir_entry(). memset is required only if mg_stat()
  7270. * fails. For more details, see
  7271. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7272. memset(&de.file, 0, sizeof(de.file));
  7273. if (truncated) {
  7274. /* Do not delete anything shorter */
  7275. ok = 0;
  7276. continue;
  7277. }
  7278. if (!mg_stat(conn, path, &de.file)) {
  7279. mg_cry(conn,
  7280. "%s: mg_stat(%s) failed: %s",
  7281. __func__,
  7282. path,
  7283. strerror(ERRNO));
  7284. ok = 0;
  7285. }
  7286. if (de.file.is_directory) {
  7287. if (remove_directory(conn, path) == 0) {
  7288. ok = 0;
  7289. }
  7290. } else {
  7291. /* This will fail file is the file is in memory */
  7292. if (mg_remove(conn, path) == 0) {
  7293. ok = 0;
  7294. }
  7295. }
  7296. }
  7297. (void)mg_closedir(dirp);
  7298. IGNORE_UNUSED_RESULT(rmdir(dir));
  7299. }
  7300. return ok;
  7301. }
  7302. #endif
  7303. struct dir_scan_data {
  7304. struct de *entries;
  7305. unsigned int num_entries;
  7306. unsigned int arr_size;
  7307. };
  7308. /* Behaves like realloc(), but frees original pointer on failure */
  7309. static void *
  7310. realloc2(void *ptr, size_t size)
  7311. {
  7312. void *new_ptr = mg_realloc(ptr, size);
  7313. if (new_ptr == NULL) {
  7314. mg_free(ptr);
  7315. }
  7316. return new_ptr;
  7317. }
  7318. static int
  7319. dir_scan_callback(struct de *de, void *data)
  7320. {
  7321. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7322. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7323. dsd->arr_size *= 2;
  7324. dsd->entries =
  7325. (struct de *)realloc2(dsd->entries,
  7326. dsd->arr_size * sizeof(dsd->entries[0]));
  7327. }
  7328. if (dsd->entries == NULL) {
  7329. /* TODO(lsm, low): propagate an error to the caller */
  7330. dsd->num_entries = 0;
  7331. } else {
  7332. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7333. dsd->entries[dsd->num_entries].file = de->file;
  7334. dsd->entries[dsd->num_entries].conn = de->conn;
  7335. dsd->num_entries++;
  7336. }
  7337. return 0;
  7338. }
  7339. static void
  7340. handle_directory_request(struct mg_connection *conn, const char *dir)
  7341. {
  7342. unsigned int i;
  7343. int sort_direction;
  7344. struct dir_scan_data data = {NULL, 0, 128};
  7345. char date[64];
  7346. time_t curtime = time(NULL);
  7347. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7348. mg_send_http_error(conn,
  7349. 500,
  7350. "Error: Cannot open directory\nopendir(%s): %s",
  7351. dir,
  7352. strerror(ERRNO));
  7353. return;
  7354. }
  7355. gmt_time_string(date, sizeof(date), &curtime);
  7356. if (!conn) {
  7357. return;
  7358. }
  7359. sort_direction = ((conn->request_info.query_string != NULL)
  7360. && (conn->request_info.query_string[1] == 'd'))
  7361. ? 'a'
  7362. : 'd';
  7363. conn->must_close = 1;
  7364. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7365. send_static_cache_header(conn);
  7366. send_additional_header(conn);
  7367. mg_printf(conn,
  7368. "Date: %s\r\n"
  7369. "Connection: close\r\n"
  7370. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7371. date);
  7372. mg_printf(conn,
  7373. "<html><head><title>Index of %s</title>"
  7374. "<style>th {text-align: left;}</style></head>"
  7375. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7376. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7377. "<th><a href=\"?d%c\">Modified</a></th>"
  7378. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7379. "<tr><td colspan=\"3\"><hr></td></tr>",
  7380. conn->request_info.local_uri,
  7381. conn->request_info.local_uri,
  7382. sort_direction,
  7383. sort_direction,
  7384. sort_direction);
  7385. /* Print first entry - link to a parent directory */
  7386. mg_printf(conn,
  7387. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7388. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7389. conn->request_info.local_uri,
  7390. "..",
  7391. "Parent directory",
  7392. "-",
  7393. "-");
  7394. /* Sort and print directory entries */
  7395. if (data.entries != NULL) {
  7396. qsort(data.entries,
  7397. (size_t)data.num_entries,
  7398. sizeof(data.entries[0]),
  7399. compare_dir_entries);
  7400. for (i = 0; i < data.num_entries; i++) {
  7401. print_dir_entry(&data.entries[i]);
  7402. mg_free(data.entries[i].file_name);
  7403. }
  7404. mg_free(data.entries);
  7405. }
  7406. mg_printf(conn, "%s", "</table></body></html>");
  7407. conn->status_code = 200;
  7408. }
  7409. /* Send len bytes from the opened file to the client. */
  7410. static void
  7411. send_file_data(struct mg_connection *conn,
  7412. struct mg_file *filep,
  7413. int64_t offset,
  7414. int64_t len)
  7415. {
  7416. char buf[MG_BUF_LEN];
  7417. int to_read, num_read, num_written;
  7418. int64_t size;
  7419. if (!filep || !conn) {
  7420. return;
  7421. }
  7422. /* Sanity check the offset */
  7423. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7424. : (int64_t)(filep->stat.size);
  7425. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7426. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7427. /* file stored in memory */
  7428. if (len > size - offset) {
  7429. len = size - offset;
  7430. }
  7431. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7432. } else if (len > 0 && filep->access.fp != NULL) {
  7433. /* file stored on disk */
  7434. #if defined(__linux__)
  7435. /* sendfile is only available for Linux */
  7436. if ((conn->ssl == 0) && (conn->throttle == 0)
  7437. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  7438. "yes"))) {
  7439. off_t sf_offs = (off_t)offset;
  7440. ssize_t sf_sent;
  7441. int sf_file = fileno(filep->access.fp);
  7442. int loop_cnt = 0;
  7443. do {
  7444. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7445. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7446. size_t sf_tosend =
  7447. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7448. sf_sent =
  7449. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7450. if (sf_sent > 0) {
  7451. len -= sf_sent;
  7452. offset += sf_sent;
  7453. } else if (loop_cnt == 0) {
  7454. /* This file can not be sent using sendfile.
  7455. * This might be the case for pseudo-files in the
  7456. * /sys/ and /proc/ file system.
  7457. * Use the regular user mode copy code instead. */
  7458. break;
  7459. } else if (sf_sent == 0) {
  7460. /* No error, but 0 bytes sent. May be EOF? */
  7461. return;
  7462. }
  7463. loop_cnt++;
  7464. } while ((len > 0) && (sf_sent >= 0));
  7465. if (sf_sent > 0) {
  7466. return; /* OK */
  7467. }
  7468. /* sf_sent<0 means error, thus fall back to the classic way */
  7469. /* This is always the case, if sf_file is not a "normal" file,
  7470. * e.g., for sending data from the output of a CGI process. */
  7471. offset = (int64_t)sf_offs;
  7472. }
  7473. #endif
  7474. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7475. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  7476. mg_send_http_error(
  7477. conn,
  7478. 500,
  7479. "%s",
  7480. "Error: Unable to access file at requested position.");
  7481. } else {
  7482. while (len > 0) {
  7483. /* Calculate how much to read from the file in the buffer */
  7484. to_read = sizeof(buf);
  7485. if ((int64_t)to_read > len) {
  7486. to_read = (int)len;
  7487. }
  7488. /* Read from file, exit the loop on error */
  7489. if ((num_read =
  7490. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7491. <= 0) {
  7492. break;
  7493. }
  7494. /* Send read bytes to the client, exit the loop on error */
  7495. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7496. != num_read) {
  7497. break;
  7498. }
  7499. /* Both read and were successful, adjust counters */
  7500. len -= num_written;
  7501. }
  7502. }
  7503. }
  7504. }
  7505. static int
  7506. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7507. {
  7508. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7509. }
  7510. static void
  7511. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7512. {
  7513. if ((filestat != NULL) && (buf != NULL)) {
  7514. mg_snprintf(NULL,
  7515. NULL, /* All calls to construct_etag use 64 byte buffer */
  7516. buf,
  7517. buf_len,
  7518. "\"%lx.%" INT64_FMT "\"",
  7519. (unsigned long)filestat->last_modified,
  7520. filestat->size);
  7521. }
  7522. }
  7523. static void
  7524. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7525. {
  7526. if (filep != NULL && filep->fp != NULL) {
  7527. #ifdef _WIN32
  7528. (void)conn; /* Unused. */
  7529. #else
  7530. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7531. mg_cry(conn,
  7532. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7533. __func__,
  7534. strerror(ERRNO));
  7535. }
  7536. #endif
  7537. }
  7538. }
  7539. static void
  7540. handle_static_file_request(struct mg_connection *conn,
  7541. const char *path,
  7542. struct mg_file *filep,
  7543. const char *mime_type,
  7544. const char *additional_headers)
  7545. {
  7546. char date[64], lm[64], etag[64];
  7547. char range[128]; /* large enough, so there will be no overflow */
  7548. const char *msg = "OK", *hdr;
  7549. time_t curtime = time(NULL);
  7550. int64_t cl, r1, r2;
  7551. struct vec mime_vec;
  7552. int n, truncated;
  7553. char gz_path[PATH_MAX];
  7554. const char *encoding = "";
  7555. const char *cors1, *cors2, *cors3;
  7556. int allow_on_the_fly_compression;
  7557. if ((conn == NULL) || (conn->ctx == NULL) || (filep == NULL)) {
  7558. return;
  7559. }
  7560. if (mime_type == NULL) {
  7561. get_mime_type(conn->ctx, path, &mime_vec);
  7562. } else {
  7563. mime_vec.ptr = mime_type;
  7564. mime_vec.len = strlen(mime_type);
  7565. }
  7566. if (filep->stat.size > INT64_MAX) {
  7567. mg_send_http_error(conn,
  7568. 500,
  7569. "Error: File size is too large to send\n%" INT64_FMT,
  7570. filep->stat.size);
  7571. return;
  7572. }
  7573. cl = (int64_t)filep->stat.size;
  7574. conn->status_code = 200;
  7575. range[0] = '\0';
  7576. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7577. * it's important to rewrite the filename after resolving
  7578. * the mime type from it, to preserve the actual file's type */
  7579. allow_on_the_fly_compression = conn->accept_gzip;
  7580. if (filep->stat.is_gzipped) {
  7581. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7582. if (truncated) {
  7583. mg_send_http_error(conn,
  7584. 500,
  7585. "Error: Path of zipped file too long (%s)",
  7586. path);
  7587. return;
  7588. }
  7589. path = gz_path;
  7590. encoding = "Content-Encoding: gzip\r\n";
  7591. /* File is already compressed. No "on the fly" compression. */
  7592. allow_on_the_fly_compression = 0;
  7593. }
  7594. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7595. mg_send_http_error(conn,
  7596. 500,
  7597. "Error: Cannot open file\nfopen(%s): %s",
  7598. path,
  7599. strerror(ERRNO));
  7600. return;
  7601. }
  7602. fclose_on_exec(&filep->access, conn);
  7603. /* If Range: header specified, act accordingly */
  7604. r1 = r2 = 0;
  7605. hdr = mg_get_header(conn, "Range");
  7606. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7607. && (r1 >= 0) && (r2 >= 0)) {
  7608. /* actually, range requests don't play well with a pre-gzipped
  7609. * file (since the range is specified in the uncompressed space) */
  7610. if (filep->stat.is_gzipped) {
  7611. mg_send_http_error(
  7612. conn,
  7613. 416, /* 416 = Range Not Satisfiable */
  7614. "%s",
  7615. "Error: Range requests in gzipped files are not supported");
  7616. (void)mg_fclose(
  7617. &filep->access); /* ignore error on read only file */
  7618. return;
  7619. }
  7620. conn->status_code = 206;
  7621. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7622. mg_snprintf(conn,
  7623. NULL, /* range buffer is big enough */
  7624. range,
  7625. sizeof(range),
  7626. "Content-Range: bytes "
  7627. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7628. r1,
  7629. r1 + cl - 1,
  7630. filep->stat.size);
  7631. msg = "Partial Content";
  7632. /* Do not compress ranges. */
  7633. allow_on_the_fly_compression = 0;
  7634. }
  7635. hdr = mg_get_header(conn, "Origin");
  7636. if (hdr) {
  7637. /* Cross-origin resource sharing (CORS), see
  7638. * http://www.html5rocks.com/en/tutorials/cors/,
  7639. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7640. * -
  7641. * preflight is not supported for files. */
  7642. cors1 = "Access-Control-Allow-Origin: ";
  7643. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7644. cors3 = "\r\n";
  7645. } else {
  7646. cors1 = cors2 = cors3 = "";
  7647. }
  7648. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  7649. * according to
  7650. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7651. gmt_time_string(date, sizeof(date), &curtime);
  7652. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7653. construct_etag(etag, sizeof(etag), &filep->stat);
  7654. /* On the fly compression allowed */
  7655. if (allow_on_the_fly_compression) {
  7656. ;
  7657. /* TODO: add interface to compression module */
  7658. /* e.g., def from https://zlib.net/zlib_how.html */
  7659. /* Check license (zlib has a permissive license, but */
  7660. /* is still not MIT) and use dynamic binding like */
  7661. /* done with OpenSSL */
  7662. /* See #199 (https://github.com/civetweb/civetweb/issues/199) */
  7663. }
  7664. /* Send header */
  7665. (void)mg_printf(conn,
  7666. "HTTP/1.1 %d %s\r\n"
  7667. "%s%s%s"
  7668. "Date: %s\r\n",
  7669. conn->status_code,
  7670. msg,
  7671. cors1,
  7672. cors2,
  7673. cors3,
  7674. date);
  7675. send_static_cache_header(conn);
  7676. send_additional_header(conn);
  7677. (void)mg_printf(conn,
  7678. "Last-Modified: %s\r\n"
  7679. "Etag: %s\r\n"
  7680. "Content-Type: %.*s\r\n"
  7681. "Content-Length: %" INT64_FMT "\r\n"
  7682. "Connection: %s\r\n"
  7683. "Accept-Ranges: bytes\r\n"
  7684. "%s%s",
  7685. lm,
  7686. etag,
  7687. (int)mime_vec.len,
  7688. mime_vec.ptr,
  7689. cl,
  7690. suggest_connection_header(conn),
  7691. range,
  7692. encoding);
  7693. /* The previous code must not add any header starting with X- to make
  7694. * sure no one of the additional_headers is included twice */
  7695. if (additional_headers != NULL) {
  7696. (void)mg_printf(conn,
  7697. "%.*s\r\n\r\n",
  7698. (int)strlen(additional_headers),
  7699. additional_headers);
  7700. } else {
  7701. (void)mg_printf(conn, "\r\n");
  7702. }
  7703. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7704. send_file_data(conn, filep, r1, cl);
  7705. }
  7706. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7707. }
  7708. #if !defined(NO_CACHING)
  7709. static void
  7710. handle_not_modified_static_file_request(struct mg_connection *conn,
  7711. struct mg_file *filep)
  7712. {
  7713. char date[64], lm[64], etag[64];
  7714. time_t curtime = time(NULL);
  7715. if ((conn == NULL) || (filep == NULL)) {
  7716. return;
  7717. }
  7718. conn->status_code = 304;
  7719. gmt_time_string(date, sizeof(date), &curtime);
  7720. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7721. construct_etag(etag, sizeof(etag), &filep->stat);
  7722. (void)mg_printf(conn,
  7723. "HTTP/1.1 %d %s\r\n"
  7724. "Date: %s\r\n",
  7725. conn->status_code,
  7726. mg_get_response_code_text(conn, conn->status_code),
  7727. date);
  7728. send_static_cache_header(conn);
  7729. send_additional_header(conn);
  7730. (void)mg_printf(conn,
  7731. "Last-Modified: %s\r\n"
  7732. "Etag: %s\r\n"
  7733. "Connection: %s\r\n"
  7734. "\r\n",
  7735. lm,
  7736. etag,
  7737. suggest_connection_header(conn));
  7738. }
  7739. #endif
  7740. void
  7741. mg_send_file(struct mg_connection *conn, const char *path)
  7742. {
  7743. mg_send_mime_file(conn, path, NULL);
  7744. }
  7745. void
  7746. mg_send_mime_file(struct mg_connection *conn,
  7747. const char *path,
  7748. const char *mime_type)
  7749. {
  7750. mg_send_mime_file2(conn, path, mime_type, NULL);
  7751. }
  7752. void
  7753. mg_send_mime_file2(struct mg_connection *conn,
  7754. const char *path,
  7755. const char *mime_type,
  7756. const char *additional_headers)
  7757. {
  7758. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7759. if (!conn) {
  7760. /* No conn */
  7761. return;
  7762. }
  7763. if (mg_stat(conn, path, &file.stat)) {
  7764. if (file.stat.is_directory) {
  7765. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7766. "yes")) {
  7767. handle_directory_request(conn, path);
  7768. } else {
  7769. mg_send_http_error(conn,
  7770. 403,
  7771. "%s",
  7772. "Error: Directory listing denied");
  7773. }
  7774. } else {
  7775. handle_static_file_request(
  7776. conn, path, &file, mime_type, additional_headers);
  7777. }
  7778. } else {
  7779. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7780. }
  7781. }
  7782. /* For a given PUT path, create all intermediate subdirectories.
  7783. * Return 0 if the path itself is a directory.
  7784. * Return 1 if the path leads to a file.
  7785. * Return -1 for if the path is too long.
  7786. * Return -2 if path can not be created.
  7787. */
  7788. static int
  7789. put_dir(struct mg_connection *conn, const char *path)
  7790. {
  7791. char buf[PATH_MAX];
  7792. const char *s, *p;
  7793. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7794. size_t len;
  7795. int res = 1;
  7796. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7797. len = (size_t)(p - path);
  7798. if (len >= sizeof(buf)) {
  7799. /* path too long */
  7800. res = -1;
  7801. break;
  7802. }
  7803. memcpy(buf, path, len);
  7804. buf[len] = '\0';
  7805. /* Try to create intermediate directory */
  7806. DEBUG_TRACE("mkdir(%s)", buf);
  7807. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7808. /* path does not exixt and can not be created */
  7809. res = -2;
  7810. break;
  7811. }
  7812. /* Is path itself a directory? */
  7813. if (p[1] == '\0') {
  7814. res = 0;
  7815. }
  7816. }
  7817. return res;
  7818. }
  7819. static void
  7820. remove_bad_file(const struct mg_connection *conn, const char *path)
  7821. {
  7822. int r = mg_remove(conn, path);
  7823. if (r != 0) {
  7824. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7825. }
  7826. }
  7827. long long
  7828. mg_store_body(struct mg_connection *conn, const char *path)
  7829. {
  7830. char buf[MG_BUF_LEN];
  7831. long long len = 0;
  7832. int ret, n;
  7833. struct mg_file fi;
  7834. if (conn->consumed_content != 0) {
  7835. mg_cry(conn, "%s: Contents already consumed", __func__);
  7836. return -11;
  7837. }
  7838. ret = put_dir(conn, path);
  7839. if (ret < 0) {
  7840. /* -1 for path too long,
  7841. * -2 for path can not be created. */
  7842. return ret;
  7843. }
  7844. if (ret != 1) {
  7845. /* Return 0 means, path itself is a directory. */
  7846. return 0;
  7847. }
  7848. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7849. return -12;
  7850. }
  7851. ret = mg_read(conn, buf, sizeof(buf));
  7852. while (ret > 0) {
  7853. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7854. if (n != ret) {
  7855. (void)mg_fclose(
  7856. &fi.access); /* File is bad and will be removed anyway. */
  7857. remove_bad_file(conn, path);
  7858. return -13;
  7859. }
  7860. len += ret;
  7861. ret = mg_read(conn, buf, sizeof(buf));
  7862. }
  7863. /* File is open for writing. If fclose fails, there was probably an
  7864. * error flushing the buffer to disk, so the file on disk might be
  7865. * broken. Delete it and return an error to the caller. */
  7866. if (mg_fclose(&fi.access) != 0) {
  7867. remove_bad_file(conn, path);
  7868. return -14;
  7869. }
  7870. return len;
  7871. }
  7872. /* Parse a buffer:
  7873. * Forward the string pointer till the end of a word, then
  7874. * terminate it and forward till the begin of the next word.
  7875. */
  7876. static int
  7877. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  7878. {
  7879. /* Forward until a space is found - use isgraph here */
  7880. /* See http://www.cplusplus.com/reference/cctype/ */
  7881. while (isgraph(**ppw)) {
  7882. (*ppw)++;
  7883. }
  7884. /* Check end of word */
  7885. if (eol) {
  7886. /* must be a end of line */
  7887. if ((**ppw != '\r') && (**ppw != '\n')) {
  7888. return -1;
  7889. }
  7890. } else {
  7891. /* must be a end of a word, but not a line */
  7892. if (**ppw != ' ') {
  7893. return -1;
  7894. }
  7895. }
  7896. /* Terminate and forward to the next word */
  7897. do {
  7898. **ppw = 0;
  7899. (*ppw)++;
  7900. } while ((**ppw) && isspace(**ppw));
  7901. /* Check after term */
  7902. if (!eol) {
  7903. /* if it's not the end of line, there must be a next word */
  7904. if (!isgraph(**ppw)) {
  7905. return -1;
  7906. }
  7907. }
  7908. /* ok */
  7909. return 1;
  7910. }
  7911. /* Parse HTTP headers from the given buffer, advance buf pointer
  7912. * to the point where parsing stopped.
  7913. * All parameters must be valid pointers (not NULL).
  7914. * Return <0 on error. */
  7915. static int
  7916. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  7917. {
  7918. int i;
  7919. int num_headers = 0;
  7920. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  7921. char *dp = *buf;
  7922. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7923. dp++;
  7924. }
  7925. if (dp == *buf) {
  7926. /* End of headers reached. */
  7927. break;
  7928. }
  7929. if (*dp != ':') {
  7930. /* This is not a valid field. */
  7931. return -1;
  7932. }
  7933. /* End of header key (*dp == ':') */
  7934. /* Truncate here and set the key name */
  7935. *dp = 0;
  7936. hdr[i].name = *buf;
  7937. do {
  7938. dp++;
  7939. } while (*dp == ' ');
  7940. /* The rest of the line is the value */
  7941. hdr[i].value = dp;
  7942. *buf = dp + strcspn(dp, "\r\n");
  7943. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7944. *buf = NULL;
  7945. }
  7946. num_headers = i + 1;
  7947. if (*buf) {
  7948. (*buf)[0] = 0;
  7949. (*buf)[1] = 0;
  7950. *buf += 2;
  7951. } else {
  7952. *buf = dp;
  7953. break;
  7954. }
  7955. if ((*buf)[0] == '\r') {
  7956. /* This is the end of the header */
  7957. break;
  7958. }
  7959. }
  7960. return num_headers;
  7961. }
  7962. struct mg_http_method_info {
  7963. const char *name;
  7964. int request_has_body;
  7965. int response_has_body;
  7966. int is_safe;
  7967. int is_idempotent;
  7968. int is_cacheable;
  7969. };
  7970. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  7971. static struct mg_http_method_info http_methods[] = {
  7972. /* HTTP (RFC 2616) */
  7973. {"GET", 0, 1, 1, 1, 1},
  7974. {"POST", 1, 1, 0, 0, 0},
  7975. {"PUT", 1, 0, 0, 1, 0},
  7976. {"DELETE", 0, 0, 0, 1, 0},
  7977. {"HEAD", 0, 0, 1, 1, 1},
  7978. {"OPTIONS", 0, 0, 1, 1, 0},
  7979. {"CONNECT", 1, 1, 0, 0, 0},
  7980. /* TRACE method (RFC 2616) is not supported for security reasons */
  7981. /* PATCH method (RFC 5789) */
  7982. {"PATCH", 1, 0, 0, 0, 0},
  7983. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7984. /* WEBDAV (RFC 2518) */
  7985. {"PROPFIND", 0, 1, 1, 1, 0},
  7986. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  7987. * Some PROPFIND results MAY be cached, with care,
  7988. * as there is no cache validation mechanism for
  7989. * most properties. This method is both safe and
  7990. * idempotent (see Section 9.1 of [RFC2616]). */
  7991. {"MKCOL", 0, 0, 0, 1, 0},
  7992. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  7993. * When MKCOL is invoked without a request body,
  7994. * the newly created collection SHOULD have no
  7995. * members. A MKCOL request message may contain
  7996. * a message body. The precise behavior of a MKCOL
  7997. * request when the body is present is undefined,
  7998. * ... ==> We do not support MKCOL with body data.
  7999. * This method is idempotent, but not safe (see
  8000. * Section 9.1 of [RFC2616]). Responses to this
  8001. * method MUST NOT be cached. */
  8002. /* Unsupported WEBDAV Methods: */
  8003. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8004. /* + 11 methods from RFC 3253 */
  8005. /* ORDERPATCH (RFC 3648) */
  8006. /* ACL (RFC 3744) */
  8007. /* SEARCH (RFC 5323) */
  8008. /* + MicroSoft extensions
  8009. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8010. /* REPORT method (RFC 3253) */
  8011. {"REPORT", 1, 1, 1, 1, 1},
  8012. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8013. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8014. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8015. * to be useful for REST in case a "GET request with body" is
  8016. * required. */
  8017. {NULL, 0, 0, 0, 0, 0}
  8018. /* end of list */
  8019. };
  8020. static const struct mg_http_method_info *
  8021. get_http_method_info(const char *method)
  8022. {
  8023. /* Check if the method is known to the server. The list of all known
  8024. * HTTP methods can be found here at
  8025. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8026. */
  8027. const struct mg_http_method_info *m = http_methods;
  8028. while (m->name) {
  8029. if (!strcmp(m->name, method)) {
  8030. return m;
  8031. }
  8032. m++;
  8033. }
  8034. return NULL;
  8035. }
  8036. static int
  8037. is_valid_http_method(const char *method)
  8038. {
  8039. return (get_http_method_info(method) != NULL);
  8040. }
  8041. /* Parse HTTP request, fill in mg_request_info structure.
  8042. * This function modifies the buffer by NUL-terminating
  8043. * HTTP request components, header names and header values.
  8044. * Parameters:
  8045. * buf (in/out): pointer to the HTTP header to parse and split
  8046. * len (in): length of HTTP header buffer
  8047. * re (out): parsed header as mg_request_info
  8048. * buf and ri must be valid pointers (not NULL), len>0.
  8049. * Returns <0 on error. */
  8050. static int
  8051. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8052. {
  8053. int request_length;
  8054. int init_skip = 0;
  8055. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  8056. * remote_port */
  8057. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8058. NULL;
  8059. ri->num_headers = 0;
  8060. /* RFC says that all initial whitespaces should be ingored */
  8061. /* This included all leading \r and \n (isspace) */
  8062. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8063. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8064. buf++;
  8065. len--;
  8066. init_skip++;
  8067. }
  8068. if (len == 0) {
  8069. /* Incomplete request */
  8070. return 0;
  8071. }
  8072. /* Control characters are not allowed, including zero */
  8073. if (iscntrl(*(unsigned char *)buf)) {
  8074. return -1;
  8075. }
  8076. /* Find end of HTTP header */
  8077. request_length = get_http_header_len(buf, len);
  8078. if (request_length <= 0) {
  8079. return request_length;
  8080. }
  8081. buf[request_length - 1] = '\0';
  8082. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8083. return -1;
  8084. }
  8085. /* The first word has to be the HTTP method */
  8086. ri->request_method = buf;
  8087. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8088. return -1;
  8089. }
  8090. /* Check for a valid http method */
  8091. if (!is_valid_http_method(ri->request_method)) {
  8092. return -1;
  8093. }
  8094. /* The second word is the URI */
  8095. ri->request_uri = buf;
  8096. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8097. return -1;
  8098. }
  8099. /* Next would be the HTTP version */
  8100. ri->http_version = buf;
  8101. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8102. return -1;
  8103. }
  8104. /* Check for a valid HTTP version key */
  8105. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8106. /* Invalid request */
  8107. return -1;
  8108. }
  8109. ri->http_version += 5;
  8110. /* Parse all HTTP headers */
  8111. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8112. if (ri->num_headers < 0) {
  8113. /* Error while parsing headers */
  8114. return -1;
  8115. }
  8116. return request_length + init_skip;
  8117. }
  8118. static int
  8119. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8120. {
  8121. int response_length;
  8122. int init_skip = 0;
  8123. char *tmp, *tmp2;
  8124. long l;
  8125. /* Initialize elements. */
  8126. ri->http_version = ri->status_text = NULL;
  8127. ri->num_headers = ri->status_code = 0;
  8128. /* RFC says that all initial whitespaces should be ingored */
  8129. /* This included all leading \r and \n (isspace) */
  8130. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8131. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8132. buf++;
  8133. len--;
  8134. init_skip++;
  8135. }
  8136. if (len == 0) {
  8137. /* Incomplete request */
  8138. return 0;
  8139. }
  8140. /* Control characters are not allowed, including zero */
  8141. if (iscntrl(*(unsigned char *)buf)) {
  8142. return -1;
  8143. }
  8144. /* Find end of HTTP header */
  8145. response_length = get_http_header_len(buf, len);
  8146. if (response_length <= 0) {
  8147. return response_length;
  8148. }
  8149. buf[response_length - 1] = '\0';
  8150. /* TODO: Define mg_response_info and implement parsing */
  8151. (void)buf;
  8152. (void)len;
  8153. (void)ri;
  8154. /* RFC says that all initial whitespaces should be ingored */
  8155. while ((*buf != '\0') && isspace(*(unsigned char *)buf)) {
  8156. buf++;
  8157. }
  8158. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8159. return -1;
  8160. }
  8161. /* The first word is the HTTP version */
  8162. /* Check for a valid HTTP version key */
  8163. if (strncmp(buf, "HTTP/", 5) != 0) {
  8164. /* Invalid request */
  8165. return -1;
  8166. }
  8167. buf += 5;
  8168. if (!isgraph(buf[0])) {
  8169. /* Invalid request */
  8170. return -1;
  8171. }
  8172. ri->http_version = buf;
  8173. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8174. return -1;
  8175. }
  8176. /* The second word is the status as a number */
  8177. tmp = buf;
  8178. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8179. return -1;
  8180. }
  8181. l = strtol(tmp, &tmp2, 10);
  8182. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8183. /* Everything else but a 3 digit code is invalid */
  8184. return -1;
  8185. }
  8186. ri->status_code = (int)l;
  8187. /* The rest of the line is the status text */
  8188. ri->status_text = buf;
  8189. /* Find end of status text */
  8190. /* isgraph or isspace = isprint */
  8191. while (isprint(*buf)) {
  8192. buf++;
  8193. }
  8194. if ((*buf != '\r') && (*buf != '\n')) {
  8195. return -1;
  8196. }
  8197. /* Terminate string and forward buf to next line */
  8198. do {
  8199. *buf = 0;
  8200. buf++;
  8201. } while ((*buf) && isspace(*buf));
  8202. /* Parse all HTTP headers */
  8203. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8204. if (ri->num_headers < 0) {
  8205. /* Error while parsing headers */
  8206. return -1;
  8207. }
  8208. return response_length + init_skip;
  8209. }
  8210. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8211. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8212. * buffer (which marks the end of HTTP request). Buffer buf may already
  8213. * have some data. The length of the data is stored in nread.
  8214. * Upon every read operation, increase nread by the number of bytes read. */
  8215. static int
  8216. read_message(FILE *fp,
  8217. struct mg_connection *conn,
  8218. char *buf,
  8219. int bufsiz,
  8220. int *nread)
  8221. {
  8222. int request_len, n = 0;
  8223. struct timespec last_action_time;
  8224. double request_timeout;
  8225. if (!conn) {
  8226. return 0;
  8227. }
  8228. memset(&last_action_time, 0, sizeof(last_action_time));
  8229. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  8230. /* value of request_timeout is in seconds, config in milliseconds */
  8231. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8232. } else {
  8233. request_timeout = -1.0;
  8234. }
  8235. if (conn->handled_requests > 0) {
  8236. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8237. request_timeout =
  8238. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8239. }
  8240. }
  8241. request_len = get_http_header_len(buf, *nread);
  8242. /* first time reading from this connection */
  8243. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8244. while (request_len == 0) {
  8245. /* Full request not yet received */
  8246. if (conn->ctx->stop_flag != 0) {
  8247. /* Server is to be stopped. */
  8248. return -1;
  8249. }
  8250. if (*nread >= bufsiz) {
  8251. /* Request too long */
  8252. return -2;
  8253. }
  8254. n = pull_inner(
  8255. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8256. if (n == -2) {
  8257. /* Receive error */
  8258. return -1;
  8259. }
  8260. if (n > 0) {
  8261. *nread += n;
  8262. request_len = get_http_header_len(buf, *nread);
  8263. } else {
  8264. request_len = 0;
  8265. }
  8266. if ((request_len == 0) && (request_timeout >= 0)) {
  8267. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8268. > request_timeout) {
  8269. /* Timeout */
  8270. return -1;
  8271. }
  8272. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8273. }
  8274. }
  8275. return request_len;
  8276. }
  8277. #if !defined(NO_CACHING)
  8278. /* Return True if we should reply 304 Not Modified. */
  8279. static int
  8280. is_not_modified(const struct mg_connection *conn,
  8281. const struct mg_file_stat *filestat)
  8282. {
  8283. char etag[64];
  8284. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8285. const char *inm = mg_get_header(conn, "If-None-Match");
  8286. construct_etag(etag, sizeof(etag), filestat);
  8287. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8288. || ((ims != NULL)
  8289. && (filestat->last_modified <= parse_date_string(ims)));
  8290. }
  8291. #endif /* !NO_CACHING */
  8292. #if !defined(NO_CGI) || !defined(NO_FILES)
  8293. static int
  8294. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8295. {
  8296. const char *expect, *body;
  8297. char buf[MG_BUF_LEN];
  8298. int to_read, nread, success = 0;
  8299. int64_t buffered_len;
  8300. double timeout = -1.0;
  8301. if (!conn) {
  8302. return 0;
  8303. }
  8304. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  8305. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8306. }
  8307. expect = mg_get_header(conn, "Expect");
  8308. /* assert(fp != NULL); */
  8309. if (!fp) {
  8310. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8311. return 0;
  8312. }
  8313. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8314. /* Content length is not specified by the client. */
  8315. mg_send_http_error(conn,
  8316. 411,
  8317. "%s",
  8318. "Error: Client did not specify content length");
  8319. } else if ((expect != NULL)
  8320. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8321. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8322. */
  8323. mg_send_http_error(conn,
  8324. 417,
  8325. "Error: Can not fulfill expectation %s",
  8326. expect);
  8327. } else {
  8328. if (expect != NULL) {
  8329. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8330. conn->status_code = 100;
  8331. } else {
  8332. conn->status_code = 200;
  8333. }
  8334. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8335. - conn->consumed_content;
  8336. /* assert(buffered_len >= 0); */
  8337. /* assert(conn->consumed_content == 0); */
  8338. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8339. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8340. return 0;
  8341. }
  8342. if (buffered_len > 0) {
  8343. if ((int64_t)buffered_len > conn->content_len) {
  8344. buffered_len = (int)conn->content_len;
  8345. }
  8346. body = conn->buf + conn->request_len + conn->consumed_content;
  8347. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8348. conn->consumed_content += buffered_len;
  8349. }
  8350. nread = 0;
  8351. while (conn->consumed_content < conn->content_len) {
  8352. to_read = sizeof(buf);
  8353. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8354. to_read = (int)(conn->content_len - conn->consumed_content);
  8355. }
  8356. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8357. if (nread == -2) {
  8358. /* error */
  8359. break;
  8360. }
  8361. if (nread > 0) {
  8362. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  8363. break;
  8364. }
  8365. }
  8366. conn->consumed_content += nread;
  8367. }
  8368. if (conn->consumed_content == conn->content_len) {
  8369. success = (nread >= 0);
  8370. }
  8371. /* Each error code path in this function must send an error */
  8372. if (!success) {
  8373. /* NOTE: Maybe some data has already been sent. */
  8374. /* TODO (low): If some data has been sent, a correct error
  8375. * reply can no longer be sent, so just close the connection */
  8376. mg_send_http_error(conn, 500, "%s", "");
  8377. }
  8378. }
  8379. return success;
  8380. }
  8381. #endif
  8382. #if !defined(NO_CGI)
  8383. /* This structure helps to create an environment for the spawned CGI
  8384. * program.
  8385. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8386. * last element must be NULL.
  8387. * However, on Windows there is a requirement that all these
  8388. * VARIABLE=VALUE\0
  8389. * strings must reside in a contiguous buffer. The end of the buffer is
  8390. * marked by two '\0' characters.
  8391. * We satisfy both worlds: we create an envp array (which is vars), all
  8392. * entries are actually pointers inside buf. */
  8393. struct cgi_environment {
  8394. struct mg_connection *conn;
  8395. /* Data block */
  8396. char *buf; /* Environment buffer */
  8397. size_t buflen; /* Space available in buf */
  8398. size_t bufused; /* Space taken in buf */
  8399. /* Index block */
  8400. char **var; /* char **envp */
  8401. size_t varlen; /* Number of variables available in var */
  8402. size_t varused; /* Number of variables stored in var */
  8403. };
  8404. static void addenv(struct cgi_environment *env,
  8405. PRINTF_FORMAT_STRING(const char *fmt),
  8406. ...) PRINTF_ARGS(2, 3);
  8407. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8408. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8409. static void
  8410. addenv(struct cgi_environment *env, const char *fmt, ...)
  8411. {
  8412. size_t n, space;
  8413. int truncated = 0;
  8414. char *added;
  8415. va_list ap;
  8416. /* Calculate how much space is left in the buffer */
  8417. space = (env->buflen - env->bufused);
  8418. /* Calculate an estimate for the required space */
  8419. n = strlen(fmt) + 2 + 128;
  8420. do {
  8421. if (space <= n) {
  8422. /* Allocate new buffer */
  8423. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8424. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  8425. if (!added) {
  8426. /* Out of memory */
  8427. mg_cry(env->conn,
  8428. "%s: Cannot allocate memory for CGI variable [%s]",
  8429. __func__,
  8430. fmt);
  8431. return;
  8432. }
  8433. env->buf = added;
  8434. env->buflen = n;
  8435. space = (env->buflen - env->bufused);
  8436. }
  8437. /* Make a pointer to the free space int the buffer */
  8438. added = env->buf + env->bufused;
  8439. /* Copy VARIABLE=VALUE\0 string into the free space */
  8440. va_start(ap, fmt);
  8441. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8442. va_end(ap);
  8443. /* Do not add truncated strings to the environment */
  8444. if (truncated) {
  8445. /* Reallocate the buffer */
  8446. space = 0;
  8447. n = 1;
  8448. }
  8449. } while (truncated);
  8450. /* Calculate number of bytes added to the environment */
  8451. n = strlen(added) + 1;
  8452. env->bufused += n;
  8453. /* Now update the variable index */
  8454. space = (env->varlen - env->varused);
  8455. if (space < 2) {
  8456. mg_cry(env->conn,
  8457. "%s: Cannot register CGI variable [%s]",
  8458. __func__,
  8459. fmt);
  8460. return;
  8461. }
  8462. /* Append a pointer to the added string into the envp array */
  8463. env->var[env->varused] = added;
  8464. env->varused++;
  8465. }
  8466. /* Return 0 on success, non-zero if an error occurs. */
  8467. static int
  8468. prepare_cgi_environment(struct mg_connection *conn,
  8469. const char *prog,
  8470. struct cgi_environment *env)
  8471. {
  8472. const char *s;
  8473. struct vec var_vec;
  8474. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8475. int i, truncated, uri_len;
  8476. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8477. return -1;
  8478. }
  8479. env->conn = conn;
  8480. env->buflen = CGI_ENVIRONMENT_SIZE;
  8481. env->bufused = 0;
  8482. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  8483. if (env->buf == NULL) {
  8484. mg_cry(conn,
  8485. "%s: Not enough memory for environmental buffer",
  8486. __func__);
  8487. return -1;
  8488. }
  8489. env->varlen = MAX_CGI_ENVIR_VARS;
  8490. env->varused = 0;
  8491. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  8492. if (env->var == NULL) {
  8493. mg_cry(conn,
  8494. "%s: Not enough memory for environmental variables",
  8495. __func__);
  8496. mg_free(env->buf);
  8497. return -1;
  8498. }
  8499. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  8500. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8501. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8502. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8503. /* Prepare the environment block */
  8504. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8505. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8506. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8507. #if defined(USE_IPV6)
  8508. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8509. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8510. } else
  8511. #endif
  8512. {
  8513. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8514. }
  8515. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8516. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8517. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8518. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8519. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8520. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8521. /* SCRIPT_NAME */
  8522. uri_len = (int)strlen(conn->request_info.local_uri);
  8523. if (conn->path_info == NULL) {
  8524. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8525. /* URI: /path_to_script/script.cgi */
  8526. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8527. } else {
  8528. /* URI: /path_to_script/ ... using index.cgi */
  8529. const char *index_file = strrchr(prog, '/');
  8530. if (index_file) {
  8531. addenv(env,
  8532. "SCRIPT_NAME=%s%s",
  8533. conn->request_info.local_uri,
  8534. index_file + 1);
  8535. }
  8536. }
  8537. } else {
  8538. /* URI: /path_to_script/script.cgi/path_info */
  8539. addenv(env,
  8540. "SCRIPT_NAME=%.*s",
  8541. uri_len - (int)strlen(conn->path_info),
  8542. conn->request_info.local_uri);
  8543. }
  8544. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8545. if (conn->path_info == NULL) {
  8546. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8547. } else {
  8548. addenv(env,
  8549. "PATH_TRANSLATED=%s%s",
  8550. conn->ctx->config[DOCUMENT_ROOT],
  8551. conn->path_info);
  8552. }
  8553. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8554. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8555. addenv(env, "CONTENT_TYPE=%s", s);
  8556. }
  8557. if (conn->request_info.query_string != NULL) {
  8558. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8559. }
  8560. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8561. addenv(env, "CONTENT_LENGTH=%s", s);
  8562. }
  8563. if ((s = getenv("PATH")) != NULL) {
  8564. addenv(env, "PATH=%s", s);
  8565. }
  8566. if (conn->path_info != NULL) {
  8567. addenv(env, "PATH_INFO=%s", conn->path_info);
  8568. }
  8569. if (conn->status_code > 0) {
  8570. /* CGI error handler should show the status code */
  8571. addenv(env, "STATUS=%d", conn->status_code);
  8572. }
  8573. #if defined(_WIN32)
  8574. if ((s = getenv("COMSPEC")) != NULL) {
  8575. addenv(env, "COMSPEC=%s", s);
  8576. }
  8577. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8578. addenv(env, "SYSTEMROOT=%s", s);
  8579. }
  8580. if ((s = getenv("SystemDrive")) != NULL) {
  8581. addenv(env, "SystemDrive=%s", s);
  8582. }
  8583. if ((s = getenv("ProgramFiles")) != NULL) {
  8584. addenv(env, "ProgramFiles=%s", s);
  8585. }
  8586. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8587. addenv(env, "ProgramFiles(x86)=%s", s);
  8588. }
  8589. #else
  8590. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8591. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8592. }
  8593. #endif /* _WIN32 */
  8594. if ((s = getenv("PERLLIB")) != NULL) {
  8595. addenv(env, "PERLLIB=%s", s);
  8596. }
  8597. if (conn->request_info.remote_user != NULL) {
  8598. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8599. addenv(env, "%s", "AUTH_TYPE=Digest");
  8600. }
  8601. /* Add all headers as HTTP_* variables */
  8602. for (i = 0; i < conn->request_info.num_headers; i++) {
  8603. (void)mg_snprintf(conn,
  8604. &truncated,
  8605. http_var_name,
  8606. sizeof(http_var_name),
  8607. "HTTP_%s",
  8608. conn->request_info.http_headers[i].name);
  8609. if (truncated) {
  8610. mg_cry(conn,
  8611. "%s: HTTP header variable too long [%s]",
  8612. __func__,
  8613. conn->request_info.http_headers[i].name);
  8614. continue;
  8615. }
  8616. /* Convert variable name into uppercase, and change - to _ */
  8617. for (p = http_var_name; *p != '\0'; p++) {
  8618. if (*p == '-') {
  8619. *p = '_';
  8620. }
  8621. *p = (char)toupper(*(unsigned char *)p);
  8622. }
  8623. addenv(env,
  8624. "%s=%s",
  8625. http_var_name,
  8626. conn->request_info.http_headers[i].value);
  8627. }
  8628. /* Add user-specified variables */
  8629. s = conn->ctx->config[CGI_ENVIRONMENT];
  8630. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8631. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8632. }
  8633. env->var[env->varused] = NULL;
  8634. env->buf[env->bufused] = '\0';
  8635. return 0;
  8636. }
  8637. static void
  8638. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8639. {
  8640. char *buf;
  8641. size_t buflen;
  8642. int headers_len, data_len, i, truncated;
  8643. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8644. const char *status, *status_text, *connection_state;
  8645. char *pbuf, dir[PATH_MAX], *p;
  8646. struct mg_request_info ri;
  8647. struct cgi_environment blk;
  8648. FILE *in = NULL, *out = NULL, *err = NULL;
  8649. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8650. pid_t pid = (pid_t)-1;
  8651. if (conn == NULL) {
  8652. return;
  8653. }
  8654. buf = NULL;
  8655. buflen = 16384;
  8656. i = prepare_cgi_environment(conn, prog, &blk);
  8657. if (i != 0) {
  8658. blk.buf = NULL;
  8659. blk.var = NULL;
  8660. goto done;
  8661. }
  8662. /* CGI must be executed in its own directory. 'dir' must point to the
  8663. * directory containing executable program, 'p' must point to the
  8664. * executable program name relative to 'dir'. */
  8665. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8666. if (truncated) {
  8667. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  8668. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8669. goto done;
  8670. }
  8671. if ((p = strrchr(dir, '/')) != NULL) {
  8672. *p++ = '\0';
  8673. } else {
  8674. dir[0] = '.';
  8675. dir[1] = '\0';
  8676. p = (char *)prog;
  8677. }
  8678. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8679. status = strerror(ERRNO);
  8680. mg_cry(conn,
  8681. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8682. prog,
  8683. status);
  8684. mg_send_http_error(conn,
  8685. 500,
  8686. "Error: Cannot create CGI pipe: %s",
  8687. status);
  8688. goto done;
  8689. }
  8690. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  8691. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8692. if (pid == (pid_t)-1) {
  8693. status = strerror(ERRNO);
  8694. mg_cry(conn,
  8695. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8696. prog,
  8697. status);
  8698. mg_send_http_error(conn,
  8699. 500,
  8700. "Error: Cannot spawn CGI process [%s]: %s",
  8701. prog,
  8702. status);
  8703. goto done;
  8704. }
  8705. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  8706. */
  8707. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8708. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8709. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8710. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8711. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8712. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8713. /* Parent closes only one side of the pipes.
  8714. * If we don't mark them as closed, close() attempt before
  8715. * return from this function throws an exception on Windows.
  8716. * Windows does not like when closed descriptor is closed again. */
  8717. (void)close(fdin[0]);
  8718. (void)close(fdout[1]);
  8719. (void)close(fderr[1]);
  8720. fdin[0] = fdout[1] = fderr[1] = -1;
  8721. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8722. status = strerror(ERRNO);
  8723. mg_cry(conn,
  8724. "Error: CGI program \"%s\": Can not open stdin: %s",
  8725. prog,
  8726. status);
  8727. mg_send_http_error(conn,
  8728. 500,
  8729. "Error: CGI can not open fdin\nfopen: %s",
  8730. status);
  8731. goto done;
  8732. }
  8733. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8734. status = strerror(ERRNO);
  8735. mg_cry(conn,
  8736. "Error: CGI program \"%s\": Can not open stdout: %s",
  8737. prog,
  8738. status);
  8739. mg_send_http_error(conn,
  8740. 500,
  8741. "Error: CGI can not open fdout\nfopen: %s",
  8742. status);
  8743. goto done;
  8744. }
  8745. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8746. status = strerror(ERRNO);
  8747. mg_cry(conn,
  8748. "Error: CGI program \"%s\": Can not open stderr: %s",
  8749. prog,
  8750. status);
  8751. mg_send_http_error(conn,
  8752. 500,
  8753. "Error: CGI can not open fdout\nfopen: %s",
  8754. status);
  8755. goto done;
  8756. }
  8757. setbuf(in, NULL);
  8758. setbuf(out, NULL);
  8759. setbuf(err, NULL);
  8760. fout.access.fp = out;
  8761. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  8762. DEBUG_TRACE("CGI: send body data (%lli)\n",
  8763. (signed long long)conn->request_info.content_length);
  8764. /* This is a POST/PUT request, or another request with body data. */
  8765. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8766. /* Error sending the body data */
  8767. mg_cry(conn,
  8768. "Error: CGI program \"%s\": Forward body data failed",
  8769. prog);
  8770. goto done;
  8771. }
  8772. }
  8773. /* Close so child gets an EOF. */
  8774. fclose(in);
  8775. in = NULL;
  8776. fdin[1] = -1;
  8777. /* Now read CGI reply into a buffer. We need to set correct
  8778. * status code, thus we need to see all HTTP headers first.
  8779. * Do not send anything back to client, until we buffer in all
  8780. * HTTP headers. */
  8781. data_len = 0;
  8782. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  8783. if (buf == NULL) {
  8784. mg_send_http_error(conn,
  8785. 500,
  8786. "Error: Not enough memory for CGI buffer (%u bytes)",
  8787. (unsigned int)buflen);
  8788. mg_cry(conn,
  8789. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  8790. "bytes)",
  8791. prog,
  8792. (unsigned int)buflen);
  8793. goto done;
  8794. }
  8795. DEBUG_TRACE("CGI: %s", "wait for response");
  8796. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  8797. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  8798. if (headers_len <= 0) {
  8799. /* Could not parse the CGI response. Check if some error message on
  8800. * stderr. */
  8801. i = pull_all(err, conn, buf, (int)buflen);
  8802. if (i > 0) {
  8803. mg_cry(conn,
  8804. "Error: CGI program \"%s\" sent error "
  8805. "message: [%.*s]",
  8806. prog,
  8807. i,
  8808. buf);
  8809. mg_send_http_error(conn,
  8810. 500,
  8811. "Error: CGI program \"%s\" sent error "
  8812. "message: [%.*s]",
  8813. prog,
  8814. i,
  8815. buf);
  8816. } else {
  8817. mg_cry(conn,
  8818. "Error: CGI program sent malformed or too big "
  8819. "(>%u bytes) HTTP headers: [%.*s]",
  8820. (unsigned)buflen,
  8821. data_len,
  8822. buf);
  8823. mg_send_http_error(conn,
  8824. 500,
  8825. "Error: CGI program sent malformed or too big "
  8826. "(>%u bytes) HTTP headers: [%.*s]",
  8827. (unsigned)buflen,
  8828. data_len,
  8829. buf);
  8830. }
  8831. goto done;
  8832. }
  8833. pbuf = buf;
  8834. buf[headers_len - 1] = '\0';
  8835. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  8836. /* Make up and send the status line */
  8837. status_text = "OK";
  8838. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  8839. != NULL) {
  8840. conn->status_code = atoi(status);
  8841. status_text = status;
  8842. while (isdigit(*(const unsigned char *)status_text)
  8843. || *status_text == ' ') {
  8844. status_text++;
  8845. }
  8846. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  8847. != NULL) {
  8848. conn->status_code = 302;
  8849. } else {
  8850. conn->status_code = 200;
  8851. }
  8852. connection_state =
  8853. get_header(ri.http_headers, ri.num_headers, "Connection");
  8854. if (!header_has_option(connection_state, "keep-alive")) {
  8855. conn->must_close = 1;
  8856. }
  8857. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  8858. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  8859. /* Send headers */
  8860. for (i = 0; i < ri.num_headers; i++) {
  8861. mg_printf(conn,
  8862. "%s: %s\r\n",
  8863. ri.http_headers[i].name,
  8864. ri.http_headers[i].value);
  8865. }
  8866. mg_write(conn, "\r\n", 2);
  8867. /* Send chunk of data that may have been read after the headers */
  8868. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  8869. /* Read the rest of CGI output and send to the client */
  8870. send_file_data(conn, &fout, 0, INT64_MAX);
  8871. DEBUG_TRACE("CGI: %s", "all data sent");
  8872. done:
  8873. mg_free(blk.var);
  8874. mg_free(blk.buf);
  8875. if (pid != (pid_t)-1) {
  8876. kill(pid, SIGKILL);
  8877. #if !defined(_WIN32)
  8878. {
  8879. int st;
  8880. while (waitpid(pid, &st, 0) != -1)
  8881. ; /* clean zombies */
  8882. }
  8883. #endif
  8884. }
  8885. if (fdin[0] != -1) {
  8886. close(fdin[0]);
  8887. }
  8888. if (fdout[1] != -1) {
  8889. close(fdout[1]);
  8890. }
  8891. if (in != NULL) {
  8892. fclose(in);
  8893. } else if (fdin[1] != -1) {
  8894. close(fdin[1]);
  8895. }
  8896. if (out != NULL) {
  8897. fclose(out);
  8898. } else if (fdout[0] != -1) {
  8899. close(fdout[0]);
  8900. }
  8901. if (err != NULL) {
  8902. fclose(err);
  8903. } else if (fderr[0] != -1) {
  8904. close(fderr[0]);
  8905. }
  8906. if (buf != NULL) {
  8907. mg_free(buf);
  8908. }
  8909. }
  8910. #endif /* !NO_CGI */
  8911. #if !defined(NO_FILES)
  8912. static void
  8913. mkcol(struct mg_connection *conn, const char *path)
  8914. {
  8915. int rc, body_len;
  8916. struct de de;
  8917. char date[64];
  8918. time_t curtime = time(NULL);
  8919. if (conn == NULL) {
  8920. return;
  8921. }
  8922. /* TODO (mid): Check the mg_send_http_error situations in this function
  8923. */
  8924. memset(&de.file, 0, sizeof(de.file));
  8925. if (!mg_stat(conn, path, &de.file)) {
  8926. mg_cry(conn,
  8927. "%s: mg_stat(%s) failed: %s",
  8928. __func__,
  8929. path,
  8930. strerror(ERRNO));
  8931. }
  8932. if (de.file.last_modified) {
  8933. /* TODO (mid): This check does not seem to make any sense ! */
  8934. /* TODO (mid): Add a webdav unit test first, before changing
  8935. * anything here. */
  8936. mg_send_http_error(
  8937. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8938. return;
  8939. }
  8940. body_len = conn->data_len - conn->request_len;
  8941. if (body_len > 0) {
  8942. mg_send_http_error(
  8943. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8944. return;
  8945. }
  8946. rc = mg_mkdir(conn, path, 0755);
  8947. if (rc == 0) {
  8948. conn->status_code = 201;
  8949. gmt_time_string(date, sizeof(date), &curtime);
  8950. mg_printf(conn,
  8951. "HTTP/1.1 %d Created\r\n"
  8952. "Date: %s\r\n",
  8953. conn->status_code,
  8954. date);
  8955. send_static_cache_header(conn);
  8956. send_additional_header(conn);
  8957. mg_printf(conn,
  8958. "Content-Length: 0\r\n"
  8959. "Connection: %s\r\n\r\n",
  8960. suggest_connection_header(conn));
  8961. } else if (rc == -1) {
  8962. if (errno == EEXIST) {
  8963. mg_send_http_error(
  8964. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8965. } else if (errno == EACCES) {
  8966. mg_send_http_error(
  8967. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8968. } else if (errno == ENOENT) {
  8969. mg_send_http_error(
  8970. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8971. } else {
  8972. mg_send_http_error(
  8973. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8974. }
  8975. }
  8976. }
  8977. static void
  8978. put_file(struct mg_connection *conn, const char *path)
  8979. {
  8980. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8981. const char *range;
  8982. int64_t r1, r2;
  8983. int rc;
  8984. char date[64];
  8985. time_t curtime = time(NULL);
  8986. if (conn == NULL) {
  8987. return;
  8988. }
  8989. if (mg_stat(conn, path, &file.stat)) {
  8990. /* File already exists */
  8991. conn->status_code = 200;
  8992. if (file.stat.is_directory) {
  8993. /* This is an already existing directory,
  8994. * so there is nothing to do for the server. */
  8995. rc = 0;
  8996. } else {
  8997. /* File exists and is not a directory. */
  8998. /* Can it be replaced? */
  8999. if (file.access.membuf != NULL) {
  9000. /* This is an "in-memory" file, that can not be replaced */
  9001. mg_send_http_error(conn,
  9002. 405,
  9003. "Error: Put not possible\nReplacing %s "
  9004. "is not supported",
  9005. path);
  9006. return;
  9007. }
  9008. /* Check if the server may write this file */
  9009. if (access(path, W_OK) == 0) {
  9010. /* Access granted */
  9011. conn->status_code = 200;
  9012. rc = 1;
  9013. } else {
  9014. mg_send_http_error(
  9015. conn,
  9016. 403,
  9017. "Error: Put not possible\nReplacing %s is not allowed",
  9018. path);
  9019. return;
  9020. }
  9021. }
  9022. } else {
  9023. /* File should be created */
  9024. conn->status_code = 201;
  9025. rc = put_dir(conn, path);
  9026. }
  9027. if (rc == 0) {
  9028. /* put_dir returns 0 if path is a directory */
  9029. gmt_time_string(date, sizeof(date), &curtime);
  9030. mg_printf(conn,
  9031. "HTTP/1.1 %d %s\r\n",
  9032. conn->status_code,
  9033. mg_get_response_code_text(NULL, conn->status_code));
  9034. send_no_cache_header(conn);
  9035. send_additional_header(conn);
  9036. mg_printf(conn,
  9037. "Date: %s\r\n"
  9038. "Content-Length: 0\r\n"
  9039. "Connection: %s\r\n\r\n",
  9040. date,
  9041. suggest_connection_header(conn));
  9042. /* Request to create a directory has been fulfilled successfully.
  9043. * No need to put a file. */
  9044. return;
  9045. }
  9046. if (rc == -1) {
  9047. /* put_dir returns -1 if the path is too long */
  9048. mg_send_http_error(conn,
  9049. 414,
  9050. "Error: Path too long\nput_dir(%s): %s",
  9051. path,
  9052. strerror(ERRNO));
  9053. return;
  9054. }
  9055. if (rc == -2) {
  9056. /* put_dir returns -2 if the directory can not be created */
  9057. mg_send_http_error(conn,
  9058. 500,
  9059. "Error: Can not create directory\nput_dir(%s): %s",
  9060. path,
  9061. strerror(ERRNO));
  9062. return;
  9063. }
  9064. /* A file should be created or overwritten. */
  9065. /* Currently CivetWeb does not nead read+write access. */
  9066. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9067. || file.access.fp == NULL) {
  9068. (void)mg_fclose(&file.access);
  9069. mg_send_http_error(conn,
  9070. 500,
  9071. "Error: Can not create file\nfopen(%s): %s",
  9072. path,
  9073. strerror(ERRNO));
  9074. return;
  9075. }
  9076. fclose_on_exec(&file.access, conn);
  9077. range = mg_get_header(conn, "Content-Range");
  9078. r1 = r2 = 0;
  9079. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9080. conn->status_code = 206; /* Partial content */
  9081. fseeko(file.access.fp, r1, SEEK_SET);
  9082. }
  9083. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9084. /* forward_body_data failed.
  9085. * The error code has already been sent to the client,
  9086. * and conn->status_code is already set. */
  9087. (void)mg_fclose(&file.access);
  9088. return;
  9089. }
  9090. if (mg_fclose(&file.access) != 0) {
  9091. /* fclose failed. This might have different reasons, but a likely
  9092. * one is "no space on disk", http 507. */
  9093. conn->status_code = 507;
  9094. }
  9095. gmt_time_string(date, sizeof(date), &curtime);
  9096. mg_printf(conn,
  9097. "HTTP/1.1 %d %s\r\n",
  9098. conn->status_code,
  9099. mg_get_response_code_text(NULL, conn->status_code));
  9100. send_no_cache_header(conn);
  9101. send_additional_header(conn);
  9102. mg_printf(conn,
  9103. "Date: %s\r\n"
  9104. "Content-Length: 0\r\n"
  9105. "Connection: %s\r\n\r\n",
  9106. date,
  9107. suggest_connection_header(conn));
  9108. }
  9109. static void
  9110. delete_file(struct mg_connection *conn, const char *path)
  9111. {
  9112. struct de de;
  9113. memset(&de.file, 0, sizeof(de.file));
  9114. if (!mg_stat(conn, path, &de.file)) {
  9115. /* mg_stat returns 0 if the file does not exist */
  9116. mg_send_http_error(conn,
  9117. 404,
  9118. "Error: Cannot delete file\nFile %s not found",
  9119. path);
  9120. return;
  9121. }
  9122. #if 0 /* Ignore if a file in memory is inside a folder */
  9123. if (de.access.membuf != NULL) {
  9124. /* the file is cached in memory */
  9125. mg_send_http_error(
  9126. conn,
  9127. 405,
  9128. "Error: Delete not possible\nDeleting %s is not supported",
  9129. path);
  9130. return;
  9131. }
  9132. #endif
  9133. if (de.file.is_directory) {
  9134. if (remove_directory(conn, path)) {
  9135. /* Delete is successful: Return 204 without content. */
  9136. mg_send_http_error(conn, 204, "%s", "");
  9137. } else {
  9138. /* Delete is not successful: Return 500 (Server error). */
  9139. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9140. }
  9141. return;
  9142. }
  9143. /* This is an existing file (not a directory).
  9144. * Check if write permission is granted. */
  9145. if (access(path, W_OK) != 0) {
  9146. /* File is read only */
  9147. mg_send_http_error(
  9148. conn,
  9149. 403,
  9150. "Error: Delete not possible\nDeleting %s is not allowed",
  9151. path);
  9152. return;
  9153. }
  9154. /* Try to delete it. */
  9155. if (mg_remove(conn, path) == 0) {
  9156. /* Delete was successful: Return 204 without content. */
  9157. mg_send_http_error(conn, 204, "%s", "");
  9158. } else {
  9159. /* Delete not successful (file locked). */
  9160. mg_send_http_error(conn,
  9161. 423,
  9162. "Error: Cannot delete file\nremove(%s): %s",
  9163. path,
  9164. strerror(ERRNO));
  9165. }
  9166. }
  9167. #endif /* !NO_FILES */
  9168. static void
  9169. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9170. static void
  9171. do_ssi_include(struct mg_connection *conn,
  9172. const char *ssi,
  9173. char *tag,
  9174. int include_level)
  9175. {
  9176. char file_name[MG_BUF_LEN], path[512], *p;
  9177. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9178. size_t len;
  9179. int truncated = 0;
  9180. if (conn == NULL) {
  9181. return;
  9182. }
  9183. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9184. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9185. * always < MG_BUF_LEN. */
  9186. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9187. /* File name is relative to the webserver root */
  9188. file_name[511] = 0;
  9189. (void)mg_snprintf(conn,
  9190. &truncated,
  9191. path,
  9192. sizeof(path),
  9193. "%s/%s",
  9194. conn->ctx->config[DOCUMENT_ROOT],
  9195. file_name);
  9196. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9197. /* File name is relative to the webserver working directory
  9198. * or it is absolute system path */
  9199. file_name[511] = 0;
  9200. (void)
  9201. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9202. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9203. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9204. /* File name is relative to the currect document */
  9205. file_name[511] = 0;
  9206. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9207. if (!truncated) {
  9208. if ((p = strrchr(path, '/')) != NULL) {
  9209. p[1] = '\0';
  9210. }
  9211. len = strlen(path);
  9212. (void)mg_snprintf(conn,
  9213. &truncated,
  9214. path + len,
  9215. sizeof(path) - len,
  9216. "%s",
  9217. file_name);
  9218. }
  9219. } else {
  9220. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  9221. return;
  9222. }
  9223. if (truncated) {
  9224. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  9225. return;
  9226. }
  9227. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9228. mg_cry(conn,
  9229. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9230. tag,
  9231. path,
  9232. strerror(ERRNO));
  9233. } else {
  9234. fclose_on_exec(&file.access, conn);
  9235. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9236. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9237. path) > 0) {
  9238. send_ssi_file(conn, path, &file, include_level + 1);
  9239. } else {
  9240. send_file_data(conn, &file, 0, INT64_MAX);
  9241. }
  9242. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9243. }
  9244. }
  9245. #if !defined(NO_POPEN)
  9246. static void
  9247. do_ssi_exec(struct mg_connection *conn, char *tag)
  9248. {
  9249. char cmd[1024] = "";
  9250. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9251. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9252. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  9253. } else {
  9254. cmd[1023] = 0;
  9255. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9256. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  9257. } else {
  9258. send_file_data(conn, &file, 0, INT64_MAX);
  9259. pclose(file.access.fp);
  9260. }
  9261. }
  9262. }
  9263. #endif /* !NO_POPEN */
  9264. static int
  9265. mg_fgetc(struct mg_file *filep, int offset)
  9266. {
  9267. if (filep == NULL) {
  9268. return EOF;
  9269. }
  9270. if ((filep->access.membuf != NULL) && (offset >= 0)
  9271. && (((unsigned int)(offset)) < filep->stat.size)) {
  9272. return ((const unsigned char *)filep->access.membuf)[offset];
  9273. } else if (filep->access.fp != NULL) {
  9274. return fgetc(filep->access.fp);
  9275. } else {
  9276. return EOF;
  9277. }
  9278. }
  9279. static void
  9280. send_ssi_file(struct mg_connection *conn,
  9281. const char *path,
  9282. struct mg_file *filep,
  9283. int include_level)
  9284. {
  9285. char buf[MG_BUF_LEN];
  9286. int ch, offset, len, in_tag, in_ssi_tag;
  9287. if (include_level > 10) {
  9288. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  9289. return;
  9290. }
  9291. in_tag = in_ssi_tag = len = offset = 0;
  9292. /* Read file, byte by byte, and look for SSI include tags */
  9293. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9294. if (in_tag) {
  9295. /* We are in a tag, either SSI tag or html tag */
  9296. if (ch == '>') {
  9297. /* Tag is closing */
  9298. buf[len++] = '>';
  9299. if (in_ssi_tag) {
  9300. /* Handle SSI tag */
  9301. buf[len] = 0;
  9302. if (!memcmp(buf + 5, "include", 7)) {
  9303. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9304. #if !defined(NO_POPEN)
  9305. } else if (!memcmp(buf + 5, "exec", 4)) {
  9306. do_ssi_exec(conn, buf + 9);
  9307. #endif /* !NO_POPEN */
  9308. } else {
  9309. mg_cry(conn,
  9310. "%s: unknown SSI "
  9311. "command: \"%s\"",
  9312. path,
  9313. buf);
  9314. }
  9315. len = 0;
  9316. in_ssi_tag = in_tag = 0;
  9317. } else {
  9318. /* Not an SSI tag */
  9319. /* Flush buffer */
  9320. (void)mg_write(conn, buf, (size_t)len);
  9321. len = 0;
  9322. in_tag = 0;
  9323. }
  9324. } else {
  9325. /* Tag is still open */
  9326. buf[len++] = (char)(ch & 0xff);
  9327. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9328. /* All SSI tags start with <!--# */
  9329. in_ssi_tag = 1;
  9330. }
  9331. if ((len + 2) > (int)sizeof(buf)) {
  9332. /* Tag to long for buffer */
  9333. mg_cry(conn, "%s: tag is too large", path);
  9334. return;
  9335. }
  9336. }
  9337. } else {
  9338. /* We are not in a tag yet. */
  9339. if (ch == '<') {
  9340. /* Tag is opening */
  9341. in_tag = 1;
  9342. /* Flush current buffer */
  9343. (void)mg_write(conn, buf, (size_t)len);
  9344. /* Store the < */
  9345. len = 1;
  9346. buf[0] = '<';
  9347. } else {
  9348. /* No Tag */
  9349. /* Add data to buffer */
  9350. buf[len++] = (char)(ch & 0xff);
  9351. /* Flush if buffer is full */
  9352. if (len == (int)sizeof(buf)) {
  9353. mg_write(conn, buf, (size_t)len);
  9354. len = 0;
  9355. }
  9356. }
  9357. }
  9358. }
  9359. /* Send the rest of buffered data */
  9360. if (len > 0) {
  9361. mg_write(conn, buf, (size_t)len);
  9362. }
  9363. }
  9364. static void
  9365. handle_ssi_file_request(struct mg_connection *conn,
  9366. const char *path,
  9367. struct mg_file *filep)
  9368. {
  9369. char date[64];
  9370. time_t curtime = time(NULL);
  9371. const char *cors1, *cors2, *cors3;
  9372. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9373. return;
  9374. }
  9375. if (mg_get_header(conn, "Origin")) {
  9376. /* Cross-origin resource sharing (CORS). */
  9377. cors1 = "Access-Control-Allow-Origin: ";
  9378. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9379. cors3 = "\r\n";
  9380. } else {
  9381. cors1 = cors2 = cors3 = "";
  9382. }
  9383. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9384. /* File exists (precondition for calling this function),
  9385. * but can not be opened by the server. */
  9386. mg_send_http_error(conn,
  9387. 500,
  9388. "Error: Cannot read file\nfopen(%s): %s",
  9389. path,
  9390. strerror(ERRNO));
  9391. } else {
  9392. conn->must_close = 1;
  9393. gmt_time_string(date, sizeof(date), &curtime);
  9394. fclose_on_exec(&filep->access, conn);
  9395. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9396. send_no_cache_header(conn);
  9397. send_additional_header(conn);
  9398. mg_printf(conn,
  9399. "%s%s%s"
  9400. "Date: %s\r\n"
  9401. "Content-Type: text/html\r\n"
  9402. "Connection: %s\r\n\r\n",
  9403. cors1,
  9404. cors2,
  9405. cors3,
  9406. date,
  9407. suggest_connection_header(conn));
  9408. send_ssi_file(conn, path, filep, 0);
  9409. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9410. }
  9411. }
  9412. #if !defined(NO_FILES)
  9413. static void
  9414. send_options(struct mg_connection *conn)
  9415. {
  9416. char date[64];
  9417. time_t curtime = time(NULL);
  9418. if (!conn) {
  9419. return;
  9420. }
  9421. conn->status_code = 200;
  9422. conn->must_close = 1;
  9423. gmt_time_string(date, sizeof(date), &curtime);
  9424. /* We do not set a "Cache-Control" header here, but leave the default.
  9425. * Since browsers do not send an OPTIONS request, we can not test the
  9426. * effect anyway. */
  9427. mg_printf(conn,
  9428. "HTTP/1.1 200 OK\r\n"
  9429. "Date: %s\r\n"
  9430. "Connection: %s\r\n"
  9431. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9432. "PROPFIND, MKCOL\r\n"
  9433. "DAV: 1\r\n",
  9434. date,
  9435. suggest_connection_header(conn));
  9436. send_additional_header(conn);
  9437. mg_printf(conn, "\r\n");
  9438. }
  9439. /* Writes PROPFIND properties for a collection element */
  9440. static void
  9441. print_props(struct mg_connection *conn,
  9442. const char *uri,
  9443. struct mg_file_stat *filep)
  9444. {
  9445. char mtime[64];
  9446. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9447. return;
  9448. }
  9449. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9450. mg_printf(conn,
  9451. "<d:response>"
  9452. "<d:href>%s</d:href>"
  9453. "<d:propstat>"
  9454. "<d:prop>"
  9455. "<d:resourcetype>%s</d:resourcetype>"
  9456. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9457. "<d:getlastmodified>%s</d:getlastmodified>"
  9458. "</d:prop>"
  9459. "<d:status>HTTP/1.1 200 OK</d:status>"
  9460. "</d:propstat>"
  9461. "</d:response>\n",
  9462. uri,
  9463. filep->is_directory ? "<d:collection/>" : "",
  9464. filep->size,
  9465. mtime);
  9466. }
  9467. static int
  9468. print_dav_dir_entry(struct de *de, void *data)
  9469. {
  9470. char href[PATH_MAX];
  9471. int truncated;
  9472. struct mg_connection *conn = (struct mg_connection *)data;
  9473. if (!de || !conn) {
  9474. return -1;
  9475. }
  9476. mg_snprintf(conn,
  9477. &truncated,
  9478. href,
  9479. sizeof(href),
  9480. "%s%s",
  9481. conn->request_info.local_uri,
  9482. de->file_name);
  9483. if (!truncated) {
  9484. size_t href_encoded_size;
  9485. char *href_encoded;
  9486. href_encoded_size = PATH_MAX * 3; /* worst case */
  9487. href_encoded = (char *)mg_malloc(href_encoded_size);
  9488. if (href_encoded == NULL) {
  9489. return -1;
  9490. }
  9491. mg_url_encode(href, href_encoded, href_encoded_size);
  9492. print_props(conn, href_encoded, &de->file);
  9493. mg_free(href_encoded);
  9494. }
  9495. return 0;
  9496. }
  9497. static void
  9498. handle_propfind(struct mg_connection *conn,
  9499. const char *path,
  9500. struct mg_file_stat *filep)
  9501. {
  9502. const char *depth = mg_get_header(conn, "Depth");
  9503. char date[64];
  9504. time_t curtime = time(NULL);
  9505. gmt_time_string(date, sizeof(date), &curtime);
  9506. if (!conn || !path || !filep || !conn->ctx) {
  9507. return;
  9508. }
  9509. conn->must_close = 1;
  9510. conn->status_code = 207;
  9511. mg_printf(conn,
  9512. "HTTP/1.1 207 Multi-Status\r\n"
  9513. "Date: %s\r\n",
  9514. date);
  9515. send_static_cache_header(conn);
  9516. send_additional_header(conn);
  9517. mg_printf(conn,
  9518. "Connection: %s\r\n"
  9519. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9520. suggest_connection_header(conn));
  9521. mg_printf(conn,
  9522. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9523. "<d:multistatus xmlns:d='DAV:'>\n");
  9524. /* Print properties for the requested resource itself */
  9525. print_props(conn, conn->request_info.local_uri, filep);
  9526. /* If it is a directory, print directory entries too if Depth is not 0
  9527. */
  9528. if (filep && filep->is_directory
  9529. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  9530. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9531. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9532. }
  9533. mg_printf(conn, "%s\n", "</d:multistatus>");
  9534. }
  9535. #endif
  9536. void
  9537. mg_lock_connection(struct mg_connection *conn)
  9538. {
  9539. if (conn) {
  9540. (void)pthread_mutex_lock(&conn->mutex);
  9541. }
  9542. }
  9543. void
  9544. mg_unlock_connection(struct mg_connection *conn)
  9545. {
  9546. if (conn) {
  9547. (void)pthread_mutex_unlock(&conn->mutex);
  9548. }
  9549. }
  9550. void
  9551. mg_lock_context(struct mg_context *ctx)
  9552. {
  9553. if (ctx) {
  9554. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9555. }
  9556. }
  9557. void
  9558. mg_unlock_context(struct mg_context *ctx)
  9559. {
  9560. if (ctx) {
  9561. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9562. }
  9563. }
  9564. #if defined(USE_TIMERS)
  9565. #define TIMER_API static
  9566. #include "timer.inl"
  9567. #endif /* USE_TIMERS */
  9568. #ifdef USE_LUA
  9569. #include "mod_lua.inl"
  9570. #endif /* USE_LUA */
  9571. #ifdef USE_DUKTAPE
  9572. #include "mod_duktape.inl"
  9573. #endif /* USE_DUKTAPE */
  9574. #if defined(USE_WEBSOCKET)
  9575. #if !defined(NO_SSL_DL)
  9576. #define SHA_API static
  9577. #include "sha1.inl"
  9578. #endif
  9579. static int
  9580. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9581. {
  9582. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9583. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9584. SHA_CTX sha_ctx;
  9585. int truncated;
  9586. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9587. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9588. if (truncated) {
  9589. conn->must_close = 1;
  9590. return 0;
  9591. }
  9592. SHA1_Init(&sha_ctx);
  9593. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9594. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9595. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9596. mg_printf(conn,
  9597. "HTTP/1.1 101 Switching Protocols\r\n"
  9598. "Upgrade: websocket\r\n"
  9599. "Connection: Upgrade\r\n"
  9600. "Sec-WebSocket-Accept: %s\r\n",
  9601. b64_sha);
  9602. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9603. mg_printf(conn,
  9604. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9605. conn->request_info.acceptedWebSocketSubprotocol);
  9606. } else {
  9607. mg_printf(conn, "%s", "\r\n");
  9608. }
  9609. return 1;
  9610. }
  9611. static void
  9612. read_websocket(struct mg_connection *conn,
  9613. mg_websocket_data_handler ws_data_handler,
  9614. void *callback_data)
  9615. {
  9616. /* Pointer to the beginning of the portion of the incoming websocket
  9617. * message queue.
  9618. * The original websocket upgrade request is never removed, so the queue
  9619. * begins after it. */
  9620. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9621. int n, error, exit_by_callback;
  9622. /* body_len is the length of the entire queue in bytes
  9623. * len is the length of the current message
  9624. * data_len is the length of the current message's data payload
  9625. * header_len is the length of the current message's header */
  9626. size_t i, len, mask_len = 0, header_len, body_len;
  9627. uint64_t data_len = 0;
  9628. /* "The masking key is a 32-bit value chosen at random by the client."
  9629. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9630. */
  9631. unsigned char mask[4];
  9632. /* data points to the place where the message is stored when passed to
  9633. * the
  9634. * websocket_data callback. This is either mem on the stack, or a
  9635. * dynamically allocated buffer if it is too large. */
  9636. unsigned char mem[4096];
  9637. unsigned char mop; /* mask flag and opcode */
  9638. double timeout = -1.0;
  9639. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  9640. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9641. }
  9642. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  9643. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9644. }
  9645. conn->in_websocket_handling = 1;
  9646. mg_set_thread_name("wsock");
  9647. /* Loop continuously, reading messages from the socket, invoking the
  9648. * callback, and waiting repeatedly until an error occurs. */
  9649. while (!conn->ctx->stop_flag && !conn->must_close) {
  9650. header_len = 0;
  9651. assert(conn->data_len >= conn->request_len);
  9652. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9653. len = buf[1] & 127;
  9654. mask_len = (buf[1] & 128) ? 4 : 0;
  9655. if ((len < 126) && (body_len >= mask_len)) {
  9656. /* inline 7-bit length field */
  9657. data_len = len;
  9658. header_len = 2 + mask_len;
  9659. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9660. /* 16-bit length field */
  9661. header_len = 4 + mask_len;
  9662. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9663. } else if (body_len >= (10 + mask_len)) {
  9664. /* 64-bit length field */
  9665. uint32_t l1, l2;
  9666. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9667. memcpy(&l2, &buf[6], 4);
  9668. header_len = 10 + mask_len;
  9669. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9670. if (data_len > (uint64_t)0x7FFF0000ul) {
  9671. /* no can do */
  9672. mg_cry(conn, "websocket out of memory; closing connection");
  9673. break;
  9674. }
  9675. }
  9676. }
  9677. if ((header_len > 0) && (body_len >= header_len)) {
  9678. /* Allocate space to hold websocket payload */
  9679. unsigned char *data = mem;
  9680. if ((size_t)data_len > (size_t)sizeof(mem)) {
  9681. data =
  9682. (unsigned char *)mg_malloc_ctx((size_t)data_len, conn->ctx);
  9683. if (data == NULL) {
  9684. /* Allocation failed, exit the loop and then close the
  9685. * connection */
  9686. mg_cry(conn, "websocket out of memory; closing connection");
  9687. break;
  9688. }
  9689. }
  9690. /* Copy the mask before we shift the queue and destroy it */
  9691. if (mask_len > 0) {
  9692. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9693. } else {
  9694. memset(mask, 0, sizeof(mask));
  9695. }
  9696. /* Read frame payload from the first message in the queue into
  9697. * data and advance the queue by moving the memory in place. */
  9698. assert(body_len >= header_len);
  9699. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  9700. mop = buf[0]; /* current mask and opcode */
  9701. /* Overflow case */
  9702. len = body_len - header_len;
  9703. memcpy(data, buf + header_len, len);
  9704. error = 0;
  9705. while ((uint64_t)len < data_len) {
  9706. n = pull_inner(NULL,
  9707. conn,
  9708. (char *)(data + len),
  9709. (int)(data_len - len),
  9710. timeout);
  9711. if (n <= -2) {
  9712. error = 1;
  9713. break;
  9714. } else if (n > 0) {
  9715. len += (size_t)n;
  9716. } else {
  9717. /* Timeout: should retry */
  9718. /* TODO: retry condition */
  9719. }
  9720. }
  9721. if (error) {
  9722. mg_cry(conn, "Websocket pull failed; closing connection");
  9723. if (data != mem) {
  9724. mg_free(data);
  9725. }
  9726. break;
  9727. }
  9728. conn->data_len = conn->request_len;
  9729. } else {
  9730. mop = buf[0]; /* current mask and opcode, overwritten by
  9731. * memmove() */
  9732. /* Length of the message being read at the front of the
  9733. * queue. Cast to 31 bit is OK, since we limited
  9734. * data_len before. */
  9735. len = (size_t)data_len + header_len;
  9736. /* Copy the data payload into the data pointer for the
  9737. * callback. Cast to 31 bit is OK, since we
  9738. * limited data_len */
  9739. memcpy(data, buf + header_len, (size_t)data_len);
  9740. /* Move the queue forward len bytes */
  9741. memmove(buf, buf + len, body_len - len);
  9742. /* Mark the queue as advanced */
  9743. conn->data_len -= (int)len;
  9744. }
  9745. /* Apply mask if necessary */
  9746. if (mask_len > 0) {
  9747. for (i = 0; i < (size_t)data_len; i++) {
  9748. data[i] ^= mask[i & 3];
  9749. }
  9750. }
  9751. /* Exit the loop if callback signals to exit (server side),
  9752. * or "connection close" opcode received (client side). */
  9753. exit_by_callback = 0;
  9754. if ((ws_data_handler != NULL)
  9755. && !ws_data_handler(conn,
  9756. mop,
  9757. (char *)data,
  9758. (size_t)data_len,
  9759. callback_data)) {
  9760. exit_by_callback = 1;
  9761. }
  9762. if (data != mem) {
  9763. mg_free(data);
  9764. }
  9765. if (exit_by_callback
  9766. || ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9767. /* Opcode == 8, connection close */
  9768. break;
  9769. }
  9770. /* Not breaking the loop, process next websocket frame. */
  9771. } else {
  9772. /* Read from the socket into the next available location in the
  9773. * message queue. */
  9774. n = pull_inner(NULL,
  9775. conn,
  9776. conn->buf + conn->data_len,
  9777. conn->buf_size - conn->data_len,
  9778. timeout);
  9779. if (n <= -2) {
  9780. /* Error, no bytes read */
  9781. break;
  9782. }
  9783. if (n > 0) {
  9784. conn->data_len += n;
  9785. } else {
  9786. /* Timeout: should retry */
  9787. /* TODO: get timeout def */
  9788. }
  9789. }
  9790. }
  9791. mg_set_thread_name("worker");
  9792. conn->in_websocket_handling = 0;
  9793. }
  9794. static int
  9795. mg_websocket_write_exec(struct mg_connection *conn,
  9796. int opcode,
  9797. const char *data,
  9798. size_t dataLen,
  9799. uint32_t masking_key)
  9800. {
  9801. unsigned char header[14];
  9802. size_t headerLen = 1;
  9803. int retval = -1;
  9804. #if defined(__GNUC__) || defined(__MINGW32__)
  9805. /* Disable spurious conversion warning for GCC */
  9806. #pragma GCC diagnostic push
  9807. #pragma GCC diagnostic ignored "-Wconversion"
  9808. #endif
  9809. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  9810. #if defined(__GNUC__) || defined(__MINGW32__)
  9811. #pragma GCC diagnostic pop
  9812. #endif
  9813. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  9814. if (dataLen < 126) {
  9815. /* inline 7-bit length field */
  9816. header[1] = (unsigned char)dataLen;
  9817. headerLen = 2;
  9818. } else if (dataLen <= 0xFFFF) {
  9819. /* 16-bit length field */
  9820. uint16_t len = htons((uint16_t)dataLen);
  9821. header[1] = 126;
  9822. memcpy(header + 2, &len, 2);
  9823. headerLen = 4;
  9824. } else {
  9825. /* 64-bit length field */
  9826. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  9827. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  9828. header[1] = 127;
  9829. memcpy(header + 2, &len1, 4);
  9830. memcpy(header + 6, &len2, 4);
  9831. headerLen = 10;
  9832. }
  9833. if (masking_key) {
  9834. /* add mask */
  9835. header[1] |= 0x80;
  9836. memcpy(header + headerLen, &masking_key, 4);
  9837. headerLen += 4;
  9838. }
  9839. /* Note that POSIX/Winsock's send() is threadsafe
  9840. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  9841. * but mongoose's mg_printf/mg_write is not (because of the loop in
  9842. * push(), although that is only a problem if the packet is large or
  9843. * outgoing buffer is full). */
  9844. /* TODO: Check if this lock should be moved to user land.
  9845. * Currently the server sets this lock for websockets, but
  9846. * not for any other connection. It must be set for every
  9847. * conn read/written by more than one thread, no matter if
  9848. * it is a websocket or regular connection. */
  9849. (void)mg_lock_connection(conn);
  9850. retval = mg_write(conn, header, headerLen);
  9851. if (dataLen > 0) {
  9852. retval = mg_write(conn, data, dataLen);
  9853. }
  9854. /* TODO: Remove this unlock as well, when lock is moved. */
  9855. mg_unlock_connection(conn);
  9856. return retval;
  9857. }
  9858. int
  9859. mg_websocket_write(struct mg_connection *conn,
  9860. int opcode,
  9861. const char *data,
  9862. size_t dataLen)
  9863. {
  9864. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  9865. }
  9866. static void
  9867. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  9868. {
  9869. size_t i = 0;
  9870. i = 0;
  9871. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  9872. /* Convert in 32 bit words, if data is 4 byte aligned */
  9873. while (i < (in_len - 3)) {
  9874. *(uint32_t *)(void *)(out + i) =
  9875. *(uint32_t *)(void *)(in + i) ^ masking_key;
  9876. i += 4;
  9877. }
  9878. }
  9879. if (i != in_len) {
  9880. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  9881. while (i < in_len) {
  9882. *(uint8_t *)(void *)(out + i) =
  9883. *(uint8_t *)(void *)(in + i)
  9884. ^ *(((uint8_t *)&masking_key) + (i % 4));
  9885. i++;
  9886. }
  9887. }
  9888. }
  9889. int
  9890. mg_websocket_client_write(struct mg_connection *conn,
  9891. int opcode,
  9892. const char *data,
  9893. size_t dataLen)
  9894. {
  9895. int retval = -1;
  9896. char *masked_data =
  9897. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  9898. uint32_t masking_key = (uint32_t)get_random();
  9899. if (masked_data == NULL) {
  9900. /* Return -1 in an error case */
  9901. mg_cry(conn,
  9902. "Cannot allocate buffer for masked websocket response: "
  9903. "Out of memory");
  9904. return -1;
  9905. }
  9906. mask_data(data, dataLen, masking_key, masked_data);
  9907. retval = mg_websocket_write_exec(
  9908. conn, opcode, masked_data, dataLen, masking_key);
  9909. mg_free(masked_data);
  9910. return retval;
  9911. }
  9912. static void
  9913. handle_websocket_request(struct mg_connection *conn,
  9914. const char *path,
  9915. int is_callback_resource,
  9916. struct mg_websocket_subprotocols *subprotocols,
  9917. mg_websocket_connect_handler ws_connect_handler,
  9918. mg_websocket_ready_handler ws_ready_handler,
  9919. mg_websocket_data_handler ws_data_handler,
  9920. mg_websocket_close_handler ws_close_handler,
  9921. void *cbData)
  9922. {
  9923. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  9924. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  9925. int lua_websock = 0;
  9926. #if !defined(USE_LUA)
  9927. (void)path;
  9928. #endif
  9929. /* Step 1: Check websocket protocol version. */
  9930. /* Step 1.1: Check Sec-WebSocket-Key. */
  9931. if (!websock_key) {
  9932. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  9933. * requires a Sec-WebSocket-Key header.
  9934. */
  9935. /* It could be the hixie draft version
  9936. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  9937. */
  9938. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  9939. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  9940. char key3[8];
  9941. if ((key1 != NULL) && (key2 != NULL)) {
  9942. /* This version uses 8 byte body data in a GET request */
  9943. conn->content_len = 8;
  9944. if (8 == mg_read(conn, key3, 8)) {
  9945. /* This is the hixie version */
  9946. mg_send_http_error(conn,
  9947. 426,
  9948. "%s",
  9949. "Protocol upgrade to RFC 6455 required");
  9950. return;
  9951. }
  9952. }
  9953. /* This is an unknown version */
  9954. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  9955. return;
  9956. }
  9957. /* Step 1.2: Check websocket protocol version. */
  9958. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  9959. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  9960. /* Reject wrong versions */
  9961. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  9962. return;
  9963. }
  9964. /* Step 1.3: Could check for "Host", but we do not really nead this
  9965. * value for anything, so just ignore it. */
  9966. /* Step 2: If a callback is responsible, call it. */
  9967. if (is_callback_resource) {
  9968. /* Step 2.1 check and select subprotocol */
  9969. const char *protocols[64]; // max 64 headers
  9970. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  9971. "Sec-WebSocket-Protocol",
  9972. protocols,
  9973. 64);
  9974. if ((nbSubprotocolHeader > 0) && subprotocols) {
  9975. int cnt = 0;
  9976. int idx;
  9977. unsigned long len;
  9978. const char *sep, *curSubProtocol,
  9979. *acceptedWebSocketSubprotocol = NULL;
  9980. /* look for matching subprotocol */
  9981. do {
  9982. const char *protocol = protocols[cnt];
  9983. do {
  9984. sep = strchr(protocol, ',');
  9985. curSubProtocol = protocol;
  9986. len = sep ? (unsigned long)(sep - protocol)
  9987. : (unsigned long)strlen(protocol);
  9988. while (sep && isspace(*++sep))
  9989. ; // ignore leading whitespaces
  9990. protocol = sep;
  9991. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  9992. if ((strlen(subprotocols->subprotocols[idx]) == len)
  9993. && (strncmp(curSubProtocol,
  9994. subprotocols->subprotocols[idx],
  9995. len) == 0)) {
  9996. acceptedWebSocketSubprotocol =
  9997. subprotocols->subprotocols[idx];
  9998. break;
  9999. }
  10000. }
  10001. } while (sep && !acceptedWebSocketSubprotocol);
  10002. } while (++cnt < nbSubprotocolHeader
  10003. && !acceptedWebSocketSubprotocol);
  10004. conn->request_info.acceptedWebSocketSubprotocol =
  10005. acceptedWebSocketSubprotocol;
  10006. } else if (nbSubprotocolHeader > 0) {
  10007. /* keep legacy behavior */
  10008. const char *protocol = protocols[0];
  10009. /* The protocol is a comma separated list of names. */
  10010. /* The server must only return one value from this list. */
  10011. /* First check if it is a list or just a single value. */
  10012. const char *sep = strrchr(protocol, ',');
  10013. if (sep == NULL) {
  10014. /* Just a single protocol -> accept it. */
  10015. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10016. } else {
  10017. /* Multiple protocols -> accept the last one. */
  10018. /* This is just a quick fix if the client offers multiple
  10019. * protocols. The handler should have a list of accepted
  10020. * protocols on his own
  10021. * and use it to select one protocol among those the client
  10022. * has
  10023. * offered.
  10024. */
  10025. while (isspace(*++sep)) {
  10026. ; /* ignore leading whitespaces */
  10027. }
  10028. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10029. }
  10030. }
  10031. if ((ws_connect_handler != NULL)
  10032. && (ws_connect_handler(conn, cbData) != 0)) {
  10033. /* C callback has returned non-zero, do not proceed with
  10034. * handshake.
  10035. */
  10036. /* Note that C callbacks are no longer called when Lua is
  10037. * responsible, so C can no longer filter callbacks for Lua. */
  10038. return;
  10039. }
  10040. }
  10041. #if defined(USE_LUA)
  10042. /* Step 3: No callback. Check if Lua is responsible. */
  10043. else {
  10044. /* Step 3.1: Check if Lua is responsible. */
  10045. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10046. lua_websock =
  10047. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10048. strlen(
  10049. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10050. path);
  10051. }
  10052. if (lua_websock) {
  10053. /* Step 3.2: Lua is responsible: call it. */
  10054. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10055. if (!conn->lua_websocket_state) {
  10056. /* Lua rejected the new client */
  10057. return;
  10058. }
  10059. }
  10060. }
  10061. #endif
  10062. /* Step 4: Check if there is a responsible websocket handler. */
  10063. if (!is_callback_resource && !lua_websock) {
  10064. /* There is no callback, and Lua is not responsible either. */
  10065. /* Reply with a 404 Not Found. We are still at a standard
  10066. * HTTP request here, before the websocket handshake, so
  10067. * we can still send standard HTTP error replies. */
  10068. mg_send_http_error(conn, 404, "%s", "Not found");
  10069. return;
  10070. }
  10071. /* Step 5: The websocket connection has been accepted */
  10072. if (!send_websocket_handshake(conn, websock_key)) {
  10073. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10074. return;
  10075. }
  10076. /* Step 6: Call the ready handler */
  10077. if (is_callback_resource) {
  10078. if (ws_ready_handler != NULL) {
  10079. ws_ready_handler(conn, cbData);
  10080. }
  10081. #if defined(USE_LUA)
  10082. } else if (lua_websock) {
  10083. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10084. /* the ready handler returned false */
  10085. return;
  10086. }
  10087. #endif
  10088. }
  10089. /* Step 7: Enter the read loop */
  10090. if (is_callback_resource) {
  10091. read_websocket(conn, ws_data_handler, cbData);
  10092. #if defined(USE_LUA)
  10093. } else if (lua_websock) {
  10094. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10095. #endif
  10096. }
  10097. /* Step 8: Call the close handler */
  10098. if (ws_close_handler) {
  10099. ws_close_handler(conn, cbData);
  10100. }
  10101. }
  10102. static int
  10103. is_websocket_protocol(const struct mg_connection *conn)
  10104. {
  10105. const char *upgrade, *connection;
  10106. /* A websocket protocoll has the following HTTP headers:
  10107. *
  10108. * Connection: Upgrade
  10109. * Upgrade: Websocket
  10110. */
  10111. upgrade = mg_get_header(conn, "Upgrade");
  10112. if (upgrade == NULL) {
  10113. return 0; /* fail early, don't waste time checking other header
  10114. * fields
  10115. */
  10116. }
  10117. if (!mg_strcasestr(upgrade, "websocket")) {
  10118. return 0;
  10119. }
  10120. connection = mg_get_header(conn, "Connection");
  10121. if (connection == NULL) {
  10122. return 0;
  10123. }
  10124. if (!mg_strcasestr(connection, "upgrade")) {
  10125. return 0;
  10126. }
  10127. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10128. * "Sec-WebSocket-Version" are also required.
  10129. * Don't check them here, since even an unsupported websocket protocol
  10130. * request still IS a websocket request (in contrast to a standard HTTP
  10131. * request). It will fail later in handle_websocket_request.
  10132. */
  10133. return 1;
  10134. }
  10135. #endif /* !USE_WEBSOCKET */
  10136. static int
  10137. isbyte(int n)
  10138. {
  10139. return (n >= 0) && (n <= 255);
  10140. }
  10141. static int
  10142. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10143. {
  10144. int n, a, b, c, d, slash = 32, len = 0;
  10145. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10146. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10147. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10148. && (slash < 33)) {
  10149. len = n;
  10150. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10151. | (uint32_t)d;
  10152. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10153. }
  10154. return len;
  10155. }
  10156. static int
  10157. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10158. {
  10159. int throttle = 0;
  10160. struct vec vec, val;
  10161. uint32_t net, mask;
  10162. char mult;
  10163. double v;
  10164. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10165. mult = ',';
  10166. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10167. || (v < 0) || ((lowercase(&mult) != 'k')
  10168. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10169. continue;
  10170. }
  10171. v *= (lowercase(&mult) == 'k')
  10172. ? 1024
  10173. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10174. if (vec.len == 1 && vec.ptr[0] == '*') {
  10175. throttle = (int)v;
  10176. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10177. if ((remote_ip & mask) == net) {
  10178. throttle = (int)v;
  10179. }
  10180. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10181. throttle = (int)v;
  10182. }
  10183. }
  10184. return throttle;
  10185. }
  10186. static uint32_t
  10187. get_remote_ip(const struct mg_connection *conn)
  10188. {
  10189. if (!conn) {
  10190. return 0;
  10191. }
  10192. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10193. }
  10194. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10195. #include "handle_form.inl"
  10196. #if defined(MG_LEGACY_INTERFACE)
  10197. /* Implement the deprecated mg_upload function by calling the new
  10198. * mg_handle_form_request function. While mg_upload could only handle
  10199. * HTML forms sent as POST request in multipart/form-data format
  10200. * containing only file input elements, mg_handle_form_request can
  10201. * handle all form input elements and all standard request methods. */
  10202. struct mg_upload_user_data {
  10203. struct mg_connection *conn;
  10204. const char *destination_dir;
  10205. int num_uploaded_files;
  10206. };
  10207. /* Helper function for deprecated mg_upload. */
  10208. static int
  10209. mg_upload_field_found(const char *key,
  10210. const char *filename,
  10211. char *path,
  10212. size_t pathlen,
  10213. void *user_data)
  10214. {
  10215. int truncated = 0;
  10216. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10217. (void)key;
  10218. if (!filename) {
  10219. mg_cry(fud->conn, "%s: No filename set", __func__);
  10220. return FORM_FIELD_STORAGE_ABORT;
  10221. }
  10222. mg_snprintf(fud->conn,
  10223. &truncated,
  10224. path,
  10225. pathlen - 1,
  10226. "%s/%s",
  10227. fud->destination_dir,
  10228. filename);
  10229. if (!truncated) {
  10230. mg_cry(fud->conn, "%s: File path too long", __func__);
  10231. return FORM_FIELD_STORAGE_ABORT;
  10232. }
  10233. return FORM_FIELD_STORAGE_STORE;
  10234. }
  10235. /* Helper function for deprecated mg_upload. */
  10236. static int
  10237. mg_upload_field_get(const char *key,
  10238. const char *value,
  10239. size_t value_size,
  10240. void *user_data)
  10241. {
  10242. /* Function should never be called */
  10243. (void)key;
  10244. (void)value;
  10245. (void)value_size;
  10246. (void)user_data;
  10247. return 0;
  10248. }
  10249. /* Helper function for deprecated mg_upload. */
  10250. static int
  10251. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10252. {
  10253. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10254. (void)file_size;
  10255. fud->num_uploaded_files++;
  10256. fud->conn->ctx->callbacks.upload(fud->conn, path);
  10257. return 0;
  10258. }
  10259. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10260. int
  10261. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10262. {
  10263. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10264. struct mg_form_data_handler fdh = {mg_upload_field_found,
  10265. mg_upload_field_get,
  10266. mg_upload_field_stored,
  10267. 0};
  10268. int ret;
  10269. fdh.user_data = (void *)&fud;
  10270. ret = mg_handle_form_request(conn, &fdh);
  10271. if (ret < 0) {
  10272. mg_cry(conn, "%s: Error while parsing the request", __func__);
  10273. }
  10274. return fud.num_uploaded_files;
  10275. }
  10276. #endif
  10277. static int
  10278. get_first_ssl_listener_index(const struct mg_context *ctx)
  10279. {
  10280. unsigned int i;
  10281. int idx = -1;
  10282. if (ctx) {
  10283. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  10284. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  10285. }
  10286. }
  10287. return idx;
  10288. }
  10289. static void
  10290. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  10291. {
  10292. char host[1025];
  10293. const char *host_header;
  10294. size_t hostlen;
  10295. host_header = mg_get_header(conn, "Host");
  10296. hostlen = sizeof(host);
  10297. if (host_header != NULL) {
  10298. char *pos;
  10299. mg_strlcpy(host, host_header, hostlen);
  10300. host[hostlen - 1] = '\0';
  10301. pos = strchr(host, ':');
  10302. if (pos != NULL) {
  10303. *pos = '\0';
  10304. }
  10305. } else {
  10306. /* Cannot get host from the Host: header.
  10307. * Fallback to our IP address. */
  10308. if (conn) {
  10309. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  10310. }
  10311. }
  10312. /* Send host, port, uri and (if it exists) ?query_string */
  10313. if (conn) {
  10314. mg_printf(conn,
  10315. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  10316. host,
  10317. #if defined(USE_IPV6)
  10318. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  10319. == AF_INET6)
  10320. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  10321. .lsa.sin6.sin6_port)
  10322. :
  10323. #endif
  10324. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  10325. .lsa.sin.sin_port),
  10326. conn->request_info.local_uri,
  10327. (conn->request_info.query_string == NULL) ? "" : "?",
  10328. (conn->request_info.query_string == NULL)
  10329. ? ""
  10330. : conn->request_info.query_string);
  10331. }
  10332. }
  10333. static void
  10334. mg_set_handler_type(struct mg_context *ctx,
  10335. const char *uri,
  10336. int handler_type,
  10337. int is_delete_request,
  10338. mg_request_handler handler,
  10339. struct mg_websocket_subprotocols *subprotocols,
  10340. mg_websocket_connect_handler connect_handler,
  10341. mg_websocket_ready_handler ready_handler,
  10342. mg_websocket_data_handler data_handler,
  10343. mg_websocket_close_handler close_handler,
  10344. mg_authorization_handler auth_handler,
  10345. void *cbdata)
  10346. {
  10347. struct mg_handler_info *tmp_rh, **lastref;
  10348. size_t urilen = strlen(uri);
  10349. if (handler_type == WEBSOCKET_HANDLER) {
  10350. /* assert(handler == NULL); */
  10351. /* assert(is_delete_request || connect_handler!=NULL ||
  10352. * ready_handler!=NULL || data_handler!=NULL ||
  10353. * close_handler!=NULL);
  10354. */
  10355. /* assert(auth_handler == NULL); */
  10356. if (handler != NULL) {
  10357. return;
  10358. }
  10359. if (!is_delete_request && (connect_handler == NULL)
  10360. && (ready_handler == NULL) && (data_handler == NULL)
  10361. && (close_handler == NULL)) {
  10362. return;
  10363. }
  10364. if (auth_handler != NULL) {
  10365. return;
  10366. }
  10367. } else if (handler_type == REQUEST_HANDLER) {
  10368. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10369. * data_handler==NULL && close_handler==NULL); */
  10370. /* assert(is_delete_request || (handler!=NULL));
  10371. */
  10372. /* assert(auth_handler == NULL); */
  10373. if ((connect_handler != NULL) || (ready_handler != NULL)
  10374. || (data_handler != NULL) || (close_handler != NULL)) {
  10375. return;
  10376. }
  10377. if (!is_delete_request && (handler == NULL)) {
  10378. return;
  10379. }
  10380. if (auth_handler != NULL) {
  10381. return;
  10382. }
  10383. } else { /* AUTH_HANDLER */
  10384. /* assert(handler == NULL); */
  10385. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10386. * data_handler==NULL && close_handler==NULL); */
  10387. /* assert(auth_handler != NULL); */
  10388. if (handler != NULL) {
  10389. return;
  10390. }
  10391. if ((connect_handler != NULL) || (ready_handler != NULL)
  10392. || (data_handler != NULL) || (close_handler != NULL)) {
  10393. return;
  10394. }
  10395. if (!is_delete_request && (auth_handler == NULL)) {
  10396. return;
  10397. }
  10398. }
  10399. if (!ctx) {
  10400. return;
  10401. }
  10402. mg_lock_context(ctx);
  10403. /* first try to find an existing handler */
  10404. lastref = &(ctx->handlers);
  10405. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10406. if (tmp_rh->handler_type == handler_type) {
  10407. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10408. if (!is_delete_request) {
  10409. /* update existing handler */
  10410. if (handler_type == REQUEST_HANDLER) {
  10411. tmp_rh->handler = handler;
  10412. } else if (handler_type == WEBSOCKET_HANDLER) {
  10413. tmp_rh->subprotocols = subprotocols;
  10414. tmp_rh->connect_handler = connect_handler;
  10415. tmp_rh->ready_handler = ready_handler;
  10416. tmp_rh->data_handler = data_handler;
  10417. tmp_rh->close_handler = close_handler;
  10418. } else { /* AUTH_HANDLER */
  10419. tmp_rh->auth_handler = auth_handler;
  10420. }
  10421. tmp_rh->cbdata = cbdata;
  10422. } else {
  10423. /* remove existing handler */
  10424. *lastref = tmp_rh->next;
  10425. mg_free(tmp_rh->uri);
  10426. mg_free(tmp_rh);
  10427. }
  10428. mg_unlock_context(ctx);
  10429. return;
  10430. }
  10431. }
  10432. lastref = &(tmp_rh->next);
  10433. }
  10434. if (is_delete_request) {
  10435. /* no handler to set, this was a remove request to a non-existing
  10436. * handler */
  10437. mg_unlock_context(ctx);
  10438. return;
  10439. }
  10440. tmp_rh =
  10441. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  10442. 1,
  10443. ctx);
  10444. if (tmp_rh == NULL) {
  10445. mg_unlock_context(ctx);
  10446. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  10447. return;
  10448. }
  10449. tmp_rh->uri = mg_strdup(uri);
  10450. if (!tmp_rh->uri) {
  10451. mg_unlock_context(ctx);
  10452. mg_free(tmp_rh);
  10453. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  10454. return;
  10455. }
  10456. tmp_rh->uri_len = urilen;
  10457. if (handler_type == REQUEST_HANDLER) {
  10458. tmp_rh->handler = handler;
  10459. } else if (handler_type == WEBSOCKET_HANDLER) {
  10460. tmp_rh->subprotocols = subprotocols;
  10461. tmp_rh->connect_handler = connect_handler;
  10462. tmp_rh->ready_handler = ready_handler;
  10463. tmp_rh->data_handler = data_handler;
  10464. tmp_rh->close_handler = close_handler;
  10465. } else { /* AUTH_HANDLER */
  10466. tmp_rh->auth_handler = auth_handler;
  10467. }
  10468. tmp_rh->cbdata = cbdata;
  10469. tmp_rh->handler_type = handler_type;
  10470. tmp_rh->next = NULL;
  10471. *lastref = tmp_rh;
  10472. mg_unlock_context(ctx);
  10473. }
  10474. void
  10475. mg_set_request_handler(struct mg_context *ctx,
  10476. const char *uri,
  10477. mg_request_handler handler,
  10478. void *cbdata)
  10479. {
  10480. mg_set_handler_type(ctx,
  10481. uri,
  10482. REQUEST_HANDLER,
  10483. handler == NULL,
  10484. handler,
  10485. NULL,
  10486. NULL,
  10487. NULL,
  10488. NULL,
  10489. NULL,
  10490. NULL,
  10491. cbdata);
  10492. }
  10493. void
  10494. mg_set_websocket_handler(struct mg_context *ctx,
  10495. const char *uri,
  10496. mg_websocket_connect_handler connect_handler,
  10497. mg_websocket_ready_handler ready_handler,
  10498. mg_websocket_data_handler data_handler,
  10499. mg_websocket_close_handler close_handler,
  10500. void *cbdata)
  10501. {
  10502. mg_set_websocket_handler_with_subprotocols(ctx,
  10503. uri,
  10504. NULL,
  10505. connect_handler,
  10506. ready_handler,
  10507. data_handler,
  10508. close_handler,
  10509. cbdata);
  10510. }
  10511. void
  10512. mg_set_websocket_handler_with_subprotocols(
  10513. struct mg_context *ctx,
  10514. const char *uri,
  10515. struct mg_websocket_subprotocols *subprotocols,
  10516. mg_websocket_connect_handler connect_handler,
  10517. mg_websocket_ready_handler ready_handler,
  10518. mg_websocket_data_handler data_handler,
  10519. mg_websocket_close_handler close_handler,
  10520. void *cbdata)
  10521. {
  10522. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  10523. && (data_handler == NULL)
  10524. && (close_handler == NULL);
  10525. mg_set_handler_type(ctx,
  10526. uri,
  10527. WEBSOCKET_HANDLER,
  10528. is_delete_request,
  10529. NULL,
  10530. subprotocols,
  10531. connect_handler,
  10532. ready_handler,
  10533. data_handler,
  10534. close_handler,
  10535. NULL,
  10536. cbdata);
  10537. }
  10538. void
  10539. mg_set_auth_handler(struct mg_context *ctx,
  10540. const char *uri,
  10541. mg_request_handler handler,
  10542. void *cbdata)
  10543. {
  10544. mg_set_handler_type(ctx,
  10545. uri,
  10546. AUTH_HANDLER,
  10547. handler == NULL,
  10548. NULL,
  10549. NULL,
  10550. NULL,
  10551. NULL,
  10552. NULL,
  10553. NULL,
  10554. handler,
  10555. cbdata);
  10556. }
  10557. static int
  10558. get_request_handler(struct mg_connection *conn,
  10559. int handler_type,
  10560. mg_request_handler *handler,
  10561. struct mg_websocket_subprotocols **subprotocols,
  10562. mg_websocket_connect_handler *connect_handler,
  10563. mg_websocket_ready_handler *ready_handler,
  10564. mg_websocket_data_handler *data_handler,
  10565. mg_websocket_close_handler *close_handler,
  10566. mg_authorization_handler *auth_handler,
  10567. void **cbdata)
  10568. {
  10569. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10570. if (request_info) {
  10571. const char *uri = request_info->local_uri;
  10572. size_t urilen = strlen(uri);
  10573. struct mg_handler_info *tmp_rh;
  10574. if (!conn || !conn->ctx) {
  10575. return 0;
  10576. }
  10577. mg_lock_context(conn->ctx);
  10578. /* first try for an exact match */
  10579. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10580. tmp_rh = tmp_rh->next) {
  10581. if (tmp_rh->handler_type == handler_type) {
  10582. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10583. if (handler_type == WEBSOCKET_HANDLER) {
  10584. *subprotocols = tmp_rh->subprotocols;
  10585. *connect_handler = tmp_rh->connect_handler;
  10586. *ready_handler = tmp_rh->ready_handler;
  10587. *data_handler = tmp_rh->data_handler;
  10588. *close_handler = tmp_rh->close_handler;
  10589. } else if (handler_type == REQUEST_HANDLER) {
  10590. *handler = tmp_rh->handler;
  10591. } else { /* AUTH_HANDLER */
  10592. *auth_handler = tmp_rh->auth_handler;
  10593. }
  10594. *cbdata = tmp_rh->cbdata;
  10595. mg_unlock_context(conn->ctx);
  10596. return 1;
  10597. }
  10598. }
  10599. }
  10600. /* next try for a partial match, we will accept uri/something */
  10601. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10602. tmp_rh = tmp_rh->next) {
  10603. if (tmp_rh->handler_type == handler_type) {
  10604. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10605. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  10606. if (handler_type == WEBSOCKET_HANDLER) {
  10607. *subprotocols = tmp_rh->subprotocols;
  10608. *connect_handler = tmp_rh->connect_handler;
  10609. *ready_handler = tmp_rh->ready_handler;
  10610. *data_handler = tmp_rh->data_handler;
  10611. *close_handler = tmp_rh->close_handler;
  10612. } else if (handler_type == REQUEST_HANDLER) {
  10613. *handler = tmp_rh->handler;
  10614. } else { /* AUTH_HANDLER */
  10615. *auth_handler = tmp_rh->auth_handler;
  10616. }
  10617. *cbdata = tmp_rh->cbdata;
  10618. mg_unlock_context(conn->ctx);
  10619. return 1;
  10620. }
  10621. }
  10622. }
  10623. /* finally try for pattern match */
  10624. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10625. tmp_rh = tmp_rh->next) {
  10626. if (tmp_rh->handler_type == handler_type) {
  10627. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10628. if (handler_type == WEBSOCKET_HANDLER) {
  10629. *subprotocols = tmp_rh->subprotocols;
  10630. *connect_handler = tmp_rh->connect_handler;
  10631. *ready_handler = tmp_rh->ready_handler;
  10632. *data_handler = tmp_rh->data_handler;
  10633. *close_handler = tmp_rh->close_handler;
  10634. } else if (handler_type == REQUEST_HANDLER) {
  10635. *handler = tmp_rh->handler;
  10636. } else { /* AUTH_HANDLER */
  10637. *auth_handler = tmp_rh->auth_handler;
  10638. }
  10639. *cbdata = tmp_rh->cbdata;
  10640. mg_unlock_context(conn->ctx);
  10641. return 1;
  10642. }
  10643. }
  10644. }
  10645. mg_unlock_context(conn->ctx);
  10646. }
  10647. return 0; /* none found */
  10648. }
  10649. /* Check if the script file is in a path, allowed for script files.
  10650. * This can be used if uploading files is possible not only for the server
  10651. * admin, and the upload mechanism does not check the file extension.
  10652. */
  10653. static int
  10654. is_in_script_path(const struct mg_connection *conn, const char *path)
  10655. {
  10656. /* TODO (Feature): Add config value for allowed script path.
  10657. * Default: All allowed. */
  10658. (void)conn;
  10659. (void)path;
  10660. return 1;
  10661. }
  10662. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10663. static int
  10664. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10665. void *cbdata)
  10666. {
  10667. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10668. if (pcallbacks->websocket_connect) {
  10669. return pcallbacks->websocket_connect(conn);
  10670. }
  10671. /* No handler set - assume "OK" */
  10672. return 0;
  10673. }
  10674. static void
  10675. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10676. {
  10677. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10678. if (pcallbacks->websocket_ready) {
  10679. pcallbacks->websocket_ready(conn);
  10680. }
  10681. }
  10682. static int
  10683. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10684. int bits,
  10685. char *data,
  10686. size_t len,
  10687. void *cbdata)
  10688. {
  10689. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10690. if (pcallbacks->websocket_data) {
  10691. return pcallbacks->websocket_data(conn, bits, data, len);
  10692. }
  10693. /* No handler set - assume "OK" */
  10694. return 1;
  10695. }
  10696. #endif
  10697. /* This is the heart of the Civetweb's logic.
  10698. * This function is called when the request is read, parsed and validated,
  10699. * and Civetweb must decide what action to take: serve a file, or
  10700. * a directory, or call embedded function, etcetera. */
  10701. static void
  10702. handle_request(struct mg_connection *conn)
  10703. {
  10704. struct mg_request_info *ri = &conn->request_info;
  10705. char path[PATH_MAX];
  10706. int uri_len, ssl_index;
  10707. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  10708. is_put_or_delete_request = 0, is_callback_resource = 0;
  10709. int i;
  10710. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10711. mg_request_handler callback_handler = NULL;
  10712. struct mg_websocket_subprotocols *subprotocols;
  10713. mg_websocket_connect_handler ws_connect_handler = NULL;
  10714. mg_websocket_ready_handler ws_ready_handler = NULL;
  10715. mg_websocket_data_handler ws_data_handler = NULL;
  10716. mg_websocket_close_handler ws_close_handler = NULL;
  10717. void *callback_data = NULL;
  10718. mg_authorization_handler auth_handler = NULL;
  10719. void *auth_callback_data = NULL;
  10720. int handler_type;
  10721. time_t curtime = time(NULL);
  10722. char date[64];
  10723. path[0] = 0;
  10724. /* 1. get the request url */
  10725. /* 1.1. split into url and query string */
  10726. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  10727. != NULL) {
  10728. *((char *)conn->request_info.query_string++) = '\0';
  10729. }
  10730. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  10731. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  10732. ssl_index = get_first_ssl_listener_index(conn->ctx);
  10733. if (ssl_index >= 0) {
  10734. redirect_to_https_port(conn, ssl_index);
  10735. } else {
  10736. /* A http to https forward port has been specified,
  10737. * but no https port to forward to. */
  10738. mg_send_http_error(conn,
  10739. 503,
  10740. "%s",
  10741. "Error: SSL forward not configured properly");
  10742. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  10743. }
  10744. return;
  10745. }
  10746. uri_len = (int)strlen(ri->local_uri);
  10747. /* 1.3. decode url (if config says so) */
  10748. if (should_decode_url(conn)) {
  10749. mg_url_decode(
  10750. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  10751. }
  10752. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  10753. * not possible */
  10754. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  10755. /* step 1. completed, the url is known now */
  10756. uri_len = (int)strlen(ri->local_uri);
  10757. DEBUG_TRACE("URL: %s", ri->local_uri);
  10758. /* 2. if this ip has limited speed, set it for this connection */
  10759. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  10760. get_remote_ip(conn),
  10761. ri->local_uri);
  10762. /* 3. call a "handle everything" callback, if registered */
  10763. if (conn->ctx->callbacks.begin_request != NULL) {
  10764. /* Note that since V1.7 the "begin_request" function is called
  10765. * before an authorization check. If an authorization check is
  10766. * required, use a request_handler instead. */
  10767. i = conn->ctx->callbacks.begin_request(conn);
  10768. if (i > 0) {
  10769. /* callback already processed the request. Store the
  10770. return value as a status code for the access log. */
  10771. conn->status_code = i;
  10772. discard_unread_request_data(conn);
  10773. return;
  10774. } else if (i == 0) {
  10775. /* civetweb should process the request */
  10776. } else {
  10777. /* unspecified - may change with the next version */
  10778. return;
  10779. }
  10780. }
  10781. /* request not yet handled by a handler or redirect, so the request
  10782. * is processed here */
  10783. /* 4. Check for CORS preflight requests and handle them (if configured).
  10784. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  10785. */
  10786. if (!strcmp(ri->request_method, "OPTIONS")) {
  10787. /* Send a response to CORS preflights only if
  10788. * access_control_allow_methods is not NULL and not an empty string.
  10789. * In this case, scripts can still handle CORS. */
  10790. const char *cors_meth_cfg =
  10791. conn->ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  10792. const char *cors_orig_cfg =
  10793. conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10794. const char *cors_origin =
  10795. get_header(ri->http_headers, ri->num_headers, "Origin");
  10796. const char *cors_acrm = get_header(ri->http_headers,
  10797. ri->num_headers,
  10798. "Access-Control-Request-Method");
  10799. /* Todo: check if cors_origin is in cors_orig_cfg.
  10800. * Or, let the client check this. */
  10801. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  10802. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  10803. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  10804. /* This is a valid CORS preflight, and the server is configured
  10805. * to
  10806. * handle it automatically. */
  10807. const char *cors_acrh =
  10808. get_header(ri->http_headers,
  10809. ri->num_headers,
  10810. "Access-Control-Request-Headers");
  10811. gmt_time_string(date, sizeof(date), &curtime);
  10812. mg_printf(conn,
  10813. "HTTP/1.1 200 OK\r\n"
  10814. "Date: %s\r\n"
  10815. "Access-Control-Allow-Origin: %s\r\n"
  10816. "Access-Control-Allow-Methods: %s\r\n"
  10817. "Content-Length: 0\r\n"
  10818. "Connection: %s\r\n",
  10819. date,
  10820. cors_orig_cfg,
  10821. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  10822. suggest_connection_header(conn));
  10823. if (cors_acrh != NULL) {
  10824. /* CORS request is asking for additional headers */
  10825. const char *cors_hdr_cfg =
  10826. conn->ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  10827. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  10828. /* Allow only if access_control_allow_headers is
  10829. * not NULL and not an empty string. If this
  10830. * configuration is set to *, allow everything.
  10831. * Otherwise this configuration must be a list
  10832. * of allowed HTTP header names. */
  10833. mg_printf(conn,
  10834. "Access-Control-Allow-Headers: %s\r\n",
  10835. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  10836. : cors_hdr_cfg));
  10837. }
  10838. }
  10839. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  10840. mg_printf(conn, "\r\n");
  10841. return;
  10842. }
  10843. }
  10844. /* 5. interpret the url to find out how the request must be handled
  10845. */
  10846. /* 5.1. first test, if the request targets the regular http(s)://
  10847. * protocol namespace or the websocket ws(s):// protocol namespace.
  10848. */
  10849. is_websocket_request = is_websocket_protocol(conn);
  10850. #if defined(USE_WEBSOCKET)
  10851. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  10852. #else
  10853. handler_type = REQUEST_HANDLER;
  10854. #endif /* defined(USE_WEBSOCKET) */
  10855. /* 5.2. check if the request will be handled by a callback */
  10856. if (get_request_handler(conn,
  10857. handler_type,
  10858. &callback_handler,
  10859. &subprotocols,
  10860. &ws_connect_handler,
  10861. &ws_ready_handler,
  10862. &ws_data_handler,
  10863. &ws_close_handler,
  10864. NULL,
  10865. &callback_data)) {
  10866. /* 5.2.1. A callback will handle this request. All requests
  10867. * handled
  10868. * by a callback have to be considered as requests to a script
  10869. * resource. */
  10870. is_callback_resource = 1;
  10871. is_script_resource = 1;
  10872. is_put_or_delete_request = is_put_or_delete_method(conn);
  10873. } else {
  10874. no_callback_resource:
  10875. /* 5.2.2. No callback is responsible for this request. The URI
  10876. * addresses a file based resource (static content or Lua/cgi
  10877. * scripts in the file system). */
  10878. is_callback_resource = 0;
  10879. interpret_uri(conn,
  10880. path,
  10881. sizeof(path),
  10882. &file.stat,
  10883. &is_found,
  10884. &is_script_resource,
  10885. &is_websocket_request,
  10886. &is_put_or_delete_request);
  10887. }
  10888. /* 6. authorization check */
  10889. /* 6.1. a custom authorization handler is installed */
  10890. if (get_request_handler(conn,
  10891. AUTH_HANDLER,
  10892. NULL,
  10893. NULL,
  10894. NULL,
  10895. NULL,
  10896. NULL,
  10897. NULL,
  10898. &auth_handler,
  10899. &auth_callback_data)) {
  10900. if (!auth_handler(conn, auth_callback_data)) {
  10901. return;
  10902. }
  10903. } else if (is_put_or_delete_request && !is_script_resource
  10904. && !is_callback_resource) {
  10905. /* 6.2. this request is a PUT/DELETE to a real file */
  10906. /* 6.2.1. thus, the server must have real files */
  10907. #if defined(NO_FILES)
  10908. if (1) {
  10909. #else
  10910. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10911. #endif
  10912. /* This server does not have any real files, thus the
  10913. * PUT/DELETE methods are not valid. */
  10914. mg_send_http_error(conn,
  10915. 405,
  10916. "%s method not allowed",
  10917. conn->request_info.request_method);
  10918. return;
  10919. }
  10920. #if !defined(NO_FILES)
  10921. /* 6.2.2. Check if put authorization for static files is
  10922. * available.
  10923. */
  10924. if (!is_authorized_for_put(conn)) {
  10925. send_authorization_request(conn, NULL);
  10926. return;
  10927. }
  10928. #endif
  10929. } else {
  10930. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  10931. * or it is a PUT or DELETE request to a resource that does not
  10932. * correspond to a file. Check authorization. */
  10933. if (!check_authorization(conn, path)) {
  10934. send_authorization_request(conn, NULL);
  10935. return;
  10936. }
  10937. }
  10938. /* request is authorized or does not need authorization */
  10939. /* 7. check if there are request handlers for this uri */
  10940. if (is_callback_resource) {
  10941. if (!is_websocket_request) {
  10942. i = callback_handler(conn, callback_data);
  10943. if (i > 0) {
  10944. /* Do nothing, callback has served the request. Store
  10945. * then return value as status code for the log and discard
  10946. * all data from the client not used by the callback. */
  10947. conn->status_code = i;
  10948. discard_unread_request_data(conn);
  10949. } else {
  10950. /* The handler did NOT handle the request. */
  10951. /* Some proper reactions would be:
  10952. * a) close the connections without sending anything
  10953. * b) send a 404 not found
  10954. * c) try if there is a file matching the URI
  10955. * It would be possible to do a, b or c in the callback
  10956. * implementation, and return 1 - we cannot do anything
  10957. * here, that is not possible in the callback.
  10958. *
  10959. * TODO: What would be the best reaction here?
  10960. * (Note: The reaction may change, if there is a better
  10961. *idea.)
  10962. */
  10963. /* For the moment, use option c: We look for a proper file,
  10964. * but since a file request is not always a script resource,
  10965. * the authorization check might be different. */
  10966. interpret_uri(conn,
  10967. path,
  10968. sizeof(path),
  10969. &file.stat,
  10970. &is_found,
  10971. &is_script_resource,
  10972. &is_websocket_request,
  10973. &is_put_or_delete_request);
  10974. callback_handler = NULL;
  10975. /* Here we are at a dead end:
  10976. * According to URI matching, a callback should be
  10977. * responsible for handling the request,
  10978. * we called it, but the callback declared itself
  10979. * not responsible.
  10980. * We use a goto here, to get out of this dead end,
  10981. * and continue with the default handling.
  10982. * A goto here is simpler and better to understand
  10983. * than some curious loop. */
  10984. goto no_callback_resource;
  10985. }
  10986. } else {
  10987. #if defined(USE_WEBSOCKET)
  10988. handle_websocket_request(conn,
  10989. path,
  10990. is_callback_resource,
  10991. subprotocols,
  10992. ws_connect_handler,
  10993. ws_ready_handler,
  10994. ws_data_handler,
  10995. ws_close_handler,
  10996. callback_data);
  10997. #endif
  10998. }
  10999. return;
  11000. }
  11001. /* 8. handle websocket requests */
  11002. #if defined(USE_WEBSOCKET)
  11003. if (is_websocket_request) {
  11004. if (is_script_resource) {
  11005. if (is_in_script_path(conn, path)) {
  11006. /* Websocket Lua script */
  11007. handle_websocket_request(conn,
  11008. path,
  11009. 0 /* Lua Script */,
  11010. NULL,
  11011. NULL,
  11012. NULL,
  11013. NULL,
  11014. NULL,
  11015. &conn->ctx->callbacks);
  11016. } else {
  11017. /* Script was in an illegal path */
  11018. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11019. }
  11020. } else {
  11021. #if defined(MG_LEGACY_INTERFACE)
  11022. handle_websocket_request(
  11023. conn,
  11024. path,
  11025. !is_script_resource /* could be deprecated global callback */,
  11026. NULL,
  11027. deprecated_websocket_connect_wrapper,
  11028. deprecated_websocket_ready_wrapper,
  11029. deprecated_websocket_data_wrapper,
  11030. NULL,
  11031. &conn->ctx->callbacks);
  11032. #else
  11033. mg_send_http_error(conn, 404, "%s", "Not found");
  11034. #endif
  11035. }
  11036. return;
  11037. } else
  11038. #endif
  11039. #if defined(NO_FILES)
  11040. /* 9a. In case the server uses only callbacks, this uri is
  11041. * unknown.
  11042. * Then, all request handling ends here. */
  11043. mg_send_http_error(conn, 404, "%s", "Not Found");
  11044. #else
  11045. /* 9b. This request is either for a static file or resource handled
  11046. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11047. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  11048. mg_send_http_error(conn, 404, "%s", "Not Found");
  11049. return;
  11050. }
  11051. /* 10. Request is handled by a script */
  11052. if (is_script_resource) {
  11053. handle_file_based_request(conn, path, &file);
  11054. return;
  11055. }
  11056. /* 11. Handle put/delete/mkcol requests */
  11057. if (is_put_or_delete_request) {
  11058. /* 11.1. PUT method */
  11059. if (!strcmp(ri->request_method, "PUT")) {
  11060. put_file(conn, path);
  11061. return;
  11062. }
  11063. /* 11.2. DELETE method */
  11064. if (!strcmp(ri->request_method, "DELETE")) {
  11065. delete_file(conn, path);
  11066. return;
  11067. }
  11068. /* 11.3. MKCOL method */
  11069. if (!strcmp(ri->request_method, "MKCOL")) {
  11070. mkcol(conn, path);
  11071. return;
  11072. }
  11073. /* 11.4. PATCH method
  11074. * This method is not supported for static resources,
  11075. * only for scripts (Lua, CGI) and callbacks. */
  11076. mg_send_http_error(conn,
  11077. 405,
  11078. "%s method not allowed",
  11079. conn->request_info.request_method);
  11080. return;
  11081. }
  11082. /* 11. File does not exist, or it was configured that it should be
  11083. * hidden */
  11084. if (!is_found || (must_hide_file(conn, path))) {
  11085. mg_send_http_error(conn, 404, "%s", "Not found");
  11086. return;
  11087. }
  11088. /* 12. Directory uris should end with a slash */
  11089. if (file.stat.is_directory && (uri_len > 0)
  11090. && (ri->local_uri[uri_len - 1] != '/')) {
  11091. gmt_time_string(date, sizeof(date), &curtime);
  11092. mg_printf(conn,
  11093. "HTTP/1.1 301 Moved Permanently\r\n"
  11094. "Location: %s/\r\n"
  11095. "Date: %s\r\n"
  11096. /* "Cache-Control: private\r\n" (= default) */
  11097. "Content-Length: 0\r\n"
  11098. "Connection: %s\r\n",
  11099. ri->request_uri,
  11100. date,
  11101. suggest_connection_header(conn));
  11102. send_additional_header(conn);
  11103. mg_printf(conn, "\r\n");
  11104. return;
  11105. }
  11106. /* 13. Handle other methods than GET/HEAD */
  11107. /* 13.1. Handle PROPFIND */
  11108. if (!strcmp(ri->request_method, "PROPFIND")) {
  11109. handle_propfind(conn, path, &file.stat);
  11110. return;
  11111. }
  11112. /* 13.2. Handle OPTIONS for files */
  11113. if (!strcmp(ri->request_method, "OPTIONS")) {
  11114. /* This standard handler is only used for real files.
  11115. * Scripts should support the OPTIONS method themselves, to allow a
  11116. * maximum flexibility.
  11117. * Lua and CGI scripts may fully support CORS this way (including
  11118. * preflights). */
  11119. send_options(conn);
  11120. return;
  11121. }
  11122. /* 13.3. everything but GET and HEAD (e.g. POST) */
  11123. if ((0 != strcmp(ri->request_method, "GET"))
  11124. && (0 != strcmp(ri->request_method, "HEAD"))) {
  11125. mg_send_http_error(conn,
  11126. 405,
  11127. "%s method not allowed",
  11128. conn->request_info.request_method);
  11129. return;
  11130. }
  11131. /* 14. directories */
  11132. if (file.stat.is_directory) {
  11133. /* Substitute files have already been handled above. */
  11134. /* Here we can either generate and send a directory listing,
  11135. * or send an "access denied" error. */
  11136. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  11137. "yes")) {
  11138. handle_directory_request(conn, path);
  11139. } else {
  11140. mg_send_http_error(conn,
  11141. 403,
  11142. "%s",
  11143. "Error: Directory listing denied");
  11144. }
  11145. return;
  11146. }
  11147. handle_file_based_request(conn, path, &file);
  11148. #endif /* !defined(NO_FILES) */
  11149. #if 0
  11150. /* Perform redirect and auth checks before calling begin_request()
  11151. * handler.
  11152. * Otherwise, begin_request() would need to perform auth checks and
  11153. * redirects. */
  11154. #endif
  11155. }
  11156. static void
  11157. handle_file_based_request(struct mg_connection *conn,
  11158. const char *path,
  11159. struct mg_file *file)
  11160. {
  11161. if (!conn || !conn->ctx) {
  11162. return;
  11163. }
  11164. if (0) {
  11165. #ifdef USE_LUA
  11166. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  11167. strlen(
  11168. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  11169. path) > 0) {
  11170. if (is_in_script_path(conn, path)) {
  11171. /* Lua server page: an SSI like page containing mostly plain
  11172. * html
  11173. * code
  11174. * plus some tags with server generated contents. */
  11175. handle_lsp_request(conn, path, file, NULL);
  11176. } else {
  11177. /* Script was in an illegal path */
  11178. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11179. }
  11180. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  11181. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  11182. path) > 0) {
  11183. if (is_in_script_path(conn, path)) {
  11184. /* Lua in-server module script: a CGI like script used to
  11185. * generate
  11186. * the
  11187. * entire reply. */
  11188. mg_exec_lua_script(conn, path, NULL);
  11189. } else {
  11190. /* Script was in an illegal path */
  11191. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11192. }
  11193. #endif
  11194. #if defined(USE_DUKTAPE)
  11195. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  11196. strlen(
  11197. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  11198. path) > 0) {
  11199. if (is_in_script_path(conn, path)) {
  11200. /* Call duktape to generate the page */
  11201. mg_exec_duktape_script(conn, path);
  11202. } else {
  11203. /* Script was in an illegal path */
  11204. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11205. }
  11206. #endif
  11207. #if !defined(NO_CGI)
  11208. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  11209. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  11210. path) > 0) {
  11211. if (is_in_script_path(conn, path)) {
  11212. /* CGI scripts may support all HTTP methods */
  11213. handle_cgi_request(conn, path);
  11214. } else {
  11215. /* Script was in an illegal path */
  11216. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11217. }
  11218. #endif /* !NO_CGI */
  11219. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  11220. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  11221. path) > 0) {
  11222. if (is_in_script_path(conn, path)) {
  11223. handle_ssi_file_request(conn, path, file);
  11224. } else {
  11225. /* Script was in an illegal path */
  11226. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11227. }
  11228. #if !defined(NO_CACHING)
  11229. } else if ((!conn->in_error_handler)
  11230. && is_not_modified(conn, &file->stat)) {
  11231. /* Send 304 "Not Modified" - this must not send any body data */
  11232. handle_not_modified_static_file_request(conn, file);
  11233. #endif /* !NO_CACHING */
  11234. } else {
  11235. handle_static_file_request(conn, path, file, NULL, NULL);
  11236. }
  11237. }
  11238. static void
  11239. close_all_listening_sockets(struct mg_context *ctx)
  11240. {
  11241. unsigned int i;
  11242. if (!ctx) {
  11243. return;
  11244. }
  11245. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11246. closesocket(ctx->listening_sockets[i].sock);
  11247. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  11248. }
  11249. mg_free(ctx->listening_sockets);
  11250. ctx->listening_sockets = NULL;
  11251. mg_free(ctx->listening_socket_fds);
  11252. ctx->listening_socket_fds = NULL;
  11253. }
  11254. /* Valid listening port specification is: [ip_address:]port[s]
  11255. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  11256. * Examples for IPv6: [::]:80, [::1]:80,
  11257. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  11258. * see https://tools.ietf.org/html/rfc3513#section-2.2
  11259. * In order to bind to both, IPv4 and IPv6, you can either add
  11260. * both ports using 8080,[::]:8080, or the short form +8080.
  11261. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  11262. * one only accepting IPv4 the other only IPv6. +8080 creates
  11263. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  11264. * environment, they might work differently, or might not work
  11265. * at all - it must be tested what options work best in the
  11266. * relevant network environment.
  11267. */
  11268. static int
  11269. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  11270. {
  11271. unsigned int a, b, c, d, port;
  11272. int ch, len;
  11273. const char *cb;
  11274. #if defined(USE_IPV6)
  11275. char buf[100] = {0};
  11276. #endif
  11277. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  11278. * Also, all-zeroes in the socket address means binding to all addresses
  11279. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  11280. memset(so, 0, sizeof(*so));
  11281. so->lsa.sin.sin_family = AF_INET;
  11282. *ip_version = 0;
  11283. /* Initialize port and len as invalid. */
  11284. port = 0;
  11285. len = 0;
  11286. /* Test for different ways to format this string */
  11287. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  11288. == 5) {
  11289. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  11290. so->lsa.sin.sin_addr.s_addr =
  11291. htonl((a << 24) | (b << 16) | (c << 8) | d);
  11292. so->lsa.sin.sin_port = htons((uint16_t)port);
  11293. *ip_version = 4;
  11294. #if defined(USE_IPV6)
  11295. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  11296. && mg_inet_pton(
  11297. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  11298. /* IPv6 address, examples: see above */
  11299. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  11300. */
  11301. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11302. *ip_version = 6;
  11303. #endif
  11304. } else if ((vec->ptr[0] == '+')
  11305. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  11306. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  11307. /* Add 1 to len for the + character we skipped before */
  11308. len++;
  11309. #if defined(USE_IPV6)
  11310. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  11311. so->lsa.sin6.sin6_family = AF_INET6;
  11312. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11313. *ip_version = 4 + 6;
  11314. #else
  11315. /* Bind to IPv4 only, since IPv6 is not built in. */
  11316. so->lsa.sin.sin_port = htons((uint16_t)port);
  11317. *ip_version = 4;
  11318. #endif
  11319. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  11320. /* If only port is specified, bind to IPv4, INADDR_ANY */
  11321. so->lsa.sin.sin_port = htons((uint16_t)port);
  11322. *ip_version = 4;
  11323. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  11324. /* Could be a hostname */
  11325. /* Will only work for RFC 952 compliant hostnames,
  11326. * starting with a letter, containing only letters,
  11327. * digits and hyphen ('-'). Newer specs may allow
  11328. * more, but this is not guaranteed here, since it
  11329. * may interfere with rules for port option lists. */
  11330. *(char *)cb = 0; /* Use a const cast here and modify the string.
  11331. * We are going to restore the string later. */
  11332. if (mg_inet_pton(
  11333. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  11334. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11335. *ip_version = 4;
  11336. so->lsa.sin.sin_family = AF_INET;
  11337. so->lsa.sin.sin_port = htons((uint16_t)port);
  11338. len += (int)(cb - vec->ptr) + 1;
  11339. } else {
  11340. port = 0;
  11341. len = 0;
  11342. }
  11343. #if defined(USE_IPV6)
  11344. } else if (mg_inet_pton(AF_INET6,
  11345. vec->ptr,
  11346. &so->lsa.sin6,
  11347. sizeof(so->lsa.sin6))) {
  11348. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11349. *ip_version = 6;
  11350. so->lsa.sin6.sin6_family = AF_INET6;
  11351. so->lsa.sin.sin_port = htons((uint16_t)port);
  11352. len += (int)(cb - vec->ptr) + 1;
  11353. } else {
  11354. port = 0;
  11355. len = 0;
  11356. }
  11357. #endif
  11358. }
  11359. *(char *)cb = ':'; /* restore the string */
  11360. } else {
  11361. /* Parsing failure. */
  11362. }
  11363. /* sscanf and the option splitting code ensure the following condition
  11364. */
  11365. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11366. *ip_version = 0;
  11367. return 0;
  11368. }
  11369. ch = vec->ptr[len]; /* Next character after the port number */
  11370. so->is_ssl = (ch == 's');
  11371. so->ssl_redir = (ch == 'r');
  11372. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11373. if (is_valid_port(port)
  11374. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  11375. return 1;
  11376. }
  11377. /* Reset ip_version to 0 of there is an error */
  11378. *ip_version = 0;
  11379. return 0;
  11380. }
  11381. /* Is there any SSL port in use? */
  11382. static int
  11383. is_ssl_port_used(const char *ports)
  11384. {
  11385. if (ports) {
  11386. if (strchr(ports, 's')) {
  11387. return 1;
  11388. }
  11389. if (strchr(ports, 'r')) {
  11390. return 1;
  11391. }
  11392. }
  11393. return 0;
  11394. }
  11395. static int
  11396. set_ports_option(struct mg_context *ctx)
  11397. {
  11398. const char *list;
  11399. int on = 1;
  11400. #if defined(USE_IPV6)
  11401. int off = 0;
  11402. #endif
  11403. struct vec vec;
  11404. struct socket so, *ptr;
  11405. struct pollfd *pfd;
  11406. union usa usa;
  11407. socklen_t len;
  11408. int ip_version;
  11409. int portsTotal = 0;
  11410. int portsOk = 0;
  11411. if (!ctx) {
  11412. return 0;
  11413. }
  11414. memset(&so, 0, sizeof(so));
  11415. memset(&usa, 0, sizeof(usa));
  11416. len = sizeof(usa);
  11417. list = ctx->config[LISTENING_PORTS];
  11418. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11419. portsTotal++;
  11420. if (!parse_port_string(&vec, &so, &ip_version)) {
  11421. mg_cry(fc(ctx),
  11422. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  11423. (int)vec.len,
  11424. vec.ptr,
  11425. portsTotal,
  11426. "[IP_ADDRESS:]PORT[s|r]");
  11427. continue;
  11428. }
  11429. #if !defined(NO_SSL)
  11430. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  11431. mg_cry(fc(ctx), "Cannot add SSL socket (entry %i)", portsTotal);
  11432. continue;
  11433. }
  11434. #endif
  11435. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  11436. == INVALID_SOCKET) {
  11437. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  11438. continue;
  11439. }
  11440. #ifdef _WIN32
  11441. /* Windows SO_REUSEADDR lets many procs binds to a
  11442. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  11443. * if someone already has the socket -- DTL */
  11444. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  11445. * Windows might need a few seconds before
  11446. * the same port can be used again in the
  11447. * same process, so a short Sleep may be
  11448. * required between mg_stop and mg_start.
  11449. */
  11450. if (setsockopt(so.sock,
  11451. SOL_SOCKET,
  11452. SO_EXCLUSIVEADDRUSE,
  11453. (SOCK_OPT_TYPE)&on,
  11454. sizeof(on)) != 0) {
  11455. /* Set reuse option, but don't abort on errors. */
  11456. mg_cry(fc(ctx),
  11457. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  11458. portsTotal);
  11459. }
  11460. #else
  11461. if (setsockopt(so.sock,
  11462. SOL_SOCKET,
  11463. SO_REUSEADDR,
  11464. (SOCK_OPT_TYPE)&on,
  11465. sizeof(on)) != 0) {
  11466. /* Set reuse option, but don't abort on errors. */
  11467. mg_cry(fc(ctx),
  11468. "cannot set socket option SO_REUSEADDR (entry %i)",
  11469. portsTotal);
  11470. }
  11471. #endif
  11472. if (ip_version > 4) {
  11473. #if defined(USE_IPV6)
  11474. if (ip_version == 6) {
  11475. if (so.lsa.sa.sa_family == AF_INET6
  11476. && setsockopt(so.sock,
  11477. IPPROTO_IPV6,
  11478. IPV6_V6ONLY,
  11479. (void *)&off,
  11480. sizeof(off)) != 0) {
  11481. /* Set IPv6 only option, but don't abort on errors. */
  11482. mg_cry(fc(ctx),
  11483. "cannot set socket option IPV6_V6ONLY (entry %i)",
  11484. portsTotal);
  11485. }
  11486. }
  11487. #else
  11488. mg_cry(fc(ctx), "IPv6 not available");
  11489. closesocket(so.sock);
  11490. so.sock = INVALID_SOCKET;
  11491. continue;
  11492. #endif
  11493. }
  11494. if (so.lsa.sa.sa_family == AF_INET) {
  11495. len = sizeof(so.lsa.sin);
  11496. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11497. mg_cry(fc(ctx),
  11498. "cannot bind to %.*s: %d (%s)",
  11499. (int)vec.len,
  11500. vec.ptr,
  11501. (int)ERRNO,
  11502. strerror(errno));
  11503. closesocket(so.sock);
  11504. so.sock = INVALID_SOCKET;
  11505. continue;
  11506. }
  11507. }
  11508. #if defined(USE_IPV6)
  11509. else if (so.lsa.sa.sa_family == AF_INET6) {
  11510. len = sizeof(so.lsa.sin6);
  11511. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11512. mg_cry(fc(ctx),
  11513. "cannot bind to IPv6 %.*s: %d (%s)",
  11514. (int)vec.len,
  11515. vec.ptr,
  11516. (int)ERRNO,
  11517. strerror(errno));
  11518. closesocket(so.sock);
  11519. so.sock = INVALID_SOCKET;
  11520. continue;
  11521. }
  11522. }
  11523. #endif
  11524. else {
  11525. mg_cry(fc(ctx),
  11526. "cannot bind: address family not supported (entry %i)",
  11527. portsTotal);
  11528. closesocket(so.sock);
  11529. so.sock = INVALID_SOCKET;
  11530. continue;
  11531. }
  11532. if (listen(so.sock, SOMAXCONN) != 0) {
  11533. mg_cry(fc(ctx),
  11534. "cannot listen to %.*s: %d (%s)",
  11535. (int)vec.len,
  11536. vec.ptr,
  11537. (int)ERRNO,
  11538. strerror(errno));
  11539. closesocket(so.sock);
  11540. so.sock = INVALID_SOCKET;
  11541. continue;
  11542. }
  11543. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  11544. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  11545. int err = (int)ERRNO;
  11546. mg_cry(fc(ctx),
  11547. "call to getsockname failed %.*s: %d (%s)",
  11548. (int)vec.len,
  11549. vec.ptr,
  11550. err,
  11551. strerror(errno));
  11552. closesocket(so.sock);
  11553. so.sock = INVALID_SOCKET;
  11554. continue;
  11555. }
  11556. /* Update lsa port in case of random free ports */
  11557. #if defined(USE_IPV6)
  11558. if (so.lsa.sa.sa_family == AF_INET6) {
  11559. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  11560. } else
  11561. #endif
  11562. {
  11563. so.lsa.sin.sin_port = usa.sin.sin_port;
  11564. }
  11565. if ((ptr = (struct socket *)
  11566. mg_realloc_ctx(ctx->listening_sockets,
  11567. (ctx->num_listening_sockets + 1)
  11568. * sizeof(ctx->listening_sockets[0]),
  11569. ctx)) == NULL) {
  11570. mg_cry(fc(ctx), "%s", "Out of memory");
  11571. closesocket(so.sock);
  11572. so.sock = INVALID_SOCKET;
  11573. continue;
  11574. }
  11575. if ((pfd = (struct pollfd *)
  11576. mg_realloc_ctx(ctx->listening_socket_fds,
  11577. (ctx->num_listening_sockets + 1)
  11578. * sizeof(ctx->listening_socket_fds[0]),
  11579. ctx)) == NULL) {
  11580. mg_cry(fc(ctx), "%s", "Out of memory");
  11581. closesocket(so.sock);
  11582. so.sock = INVALID_SOCKET;
  11583. mg_free(ptr);
  11584. continue;
  11585. }
  11586. set_close_on_exec(so.sock, fc(ctx));
  11587. ctx->listening_sockets = ptr;
  11588. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  11589. ctx->listening_socket_fds = pfd;
  11590. ctx->num_listening_sockets++;
  11591. portsOk++;
  11592. }
  11593. if (portsOk != portsTotal) {
  11594. close_all_listening_sockets(ctx);
  11595. portsOk = 0;
  11596. }
  11597. return portsOk;
  11598. }
  11599. static const char *
  11600. header_val(const struct mg_connection *conn, const char *header)
  11601. {
  11602. const char *header_value;
  11603. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11604. return "-";
  11605. } else {
  11606. return header_value;
  11607. }
  11608. }
  11609. static void
  11610. log_access(const struct mg_connection *conn)
  11611. {
  11612. const struct mg_request_info *ri;
  11613. struct mg_file fi;
  11614. char date[64], src_addr[IP_ADDR_STR_LEN];
  11615. struct tm *tm;
  11616. const char *referer;
  11617. const char *user_agent;
  11618. char buf[4096];
  11619. if (!conn || !conn->ctx) {
  11620. return;
  11621. }
  11622. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  11623. if (mg_fopen(conn,
  11624. conn->ctx->config[ACCESS_LOG_FILE],
  11625. MG_FOPEN_MODE_APPEND,
  11626. &fi) == 0) {
  11627. fi.access.fp = NULL;
  11628. }
  11629. } else {
  11630. fi.access.fp = NULL;
  11631. }
  11632. /* Log is written to a file and/or a callback. If both are not set,
  11633. * executing the rest of the function is pointless. */
  11634. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  11635. return;
  11636. }
  11637. tm = localtime(&conn->conn_birth_time);
  11638. if (tm != NULL) {
  11639. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11640. } else {
  11641. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11642. date[sizeof(date) - 1] = '\0';
  11643. }
  11644. ri = &conn->request_info;
  11645. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11646. referer = header_val(conn, "Referer");
  11647. user_agent = header_val(conn, "User-Agent");
  11648. mg_snprintf(conn,
  11649. NULL, /* Ignore truncation in access log */
  11650. buf,
  11651. sizeof(buf),
  11652. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11653. src_addr,
  11654. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11655. date,
  11656. ri->request_method ? ri->request_method : "-",
  11657. ri->request_uri ? ri->request_uri : "-",
  11658. ri->query_string ? "?" : "",
  11659. ri->query_string ? ri->query_string : "",
  11660. ri->http_version,
  11661. conn->status_code,
  11662. conn->num_bytes_sent,
  11663. referer,
  11664. user_agent);
  11665. if (conn->ctx->callbacks.log_access) {
  11666. conn->ctx->callbacks.log_access(conn, buf);
  11667. }
  11668. if (fi.access.fp) {
  11669. int ok = 1;
  11670. flockfile(fi.access.fp);
  11671. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11672. ok = 0;
  11673. }
  11674. if (fflush(fi.access.fp) != 0) {
  11675. ok = 0;
  11676. }
  11677. funlockfile(fi.access.fp);
  11678. if (mg_fclose(&fi.access) != 0) {
  11679. ok = 0;
  11680. }
  11681. if (!ok) {
  11682. mg_cry(conn,
  11683. "Error writing log file %s",
  11684. conn->ctx->config[ACCESS_LOG_FILE]);
  11685. }
  11686. }
  11687. }
  11688. /* Verify given socket address against the ACL.
  11689. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  11690. */
  11691. static int
  11692. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  11693. {
  11694. int allowed, flag;
  11695. uint32_t net, mask;
  11696. struct vec vec;
  11697. if (ctx) {
  11698. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  11699. /* If any ACL is set, deny by default */
  11700. allowed = (list == NULL) ? '+' : '-';
  11701. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11702. flag = vec.ptr[0];
  11703. if ((flag != '+' && flag != '-')
  11704. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  11705. mg_cry(fc(ctx),
  11706. "%s: subnet must be [+|-]x.x.x.x[/x]",
  11707. __func__);
  11708. return -1;
  11709. }
  11710. if (net == (remote_ip & mask)) {
  11711. allowed = flag;
  11712. }
  11713. }
  11714. return allowed == '+';
  11715. }
  11716. return -1;
  11717. }
  11718. #if !defined(_WIN32)
  11719. static int
  11720. set_uid_option(struct mg_context *ctx)
  11721. {
  11722. int success = 0;
  11723. if (ctx) {
  11724. /* We are currently running as curr_uid. */
  11725. const uid_t curr_uid = getuid();
  11726. /* If set, we want to run as run_as_user. */
  11727. const char *run_as_user = ctx->config[RUN_AS_USER];
  11728. const struct passwd *to_pw = NULL;
  11729. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  11730. /* run_as_user does not exist on the system. We can't proceed
  11731. * further. */
  11732. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, run_as_user);
  11733. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  11734. /* There was either no request to change user, or we're already
  11735. * running as run_as_user. Nothing else to do.
  11736. */
  11737. success = 1;
  11738. } else {
  11739. /* Valid change request. */
  11740. if (setgid(to_pw->pw_gid) == -1) {
  11741. mg_cry(fc(ctx),
  11742. "%s: setgid(%s): %s",
  11743. __func__,
  11744. run_as_user,
  11745. strerror(errno));
  11746. } else if (setgroups(0, NULL) == -1) {
  11747. mg_cry(fc(ctx),
  11748. "%s: setgroups(): %s",
  11749. __func__,
  11750. strerror(errno));
  11751. } else if (setuid(to_pw->pw_uid) == -1) {
  11752. mg_cry(fc(ctx),
  11753. "%s: setuid(%s): %s",
  11754. __func__,
  11755. run_as_user,
  11756. strerror(errno));
  11757. } else {
  11758. success = 1;
  11759. }
  11760. }
  11761. }
  11762. return success;
  11763. }
  11764. #endif /* !_WIN32 */
  11765. static void
  11766. tls_dtor(void *key)
  11767. {
  11768. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  11769. /* key == pthread_getspecific(sTlsKey); */
  11770. if (tls) {
  11771. if (tls->is_master == 2) {
  11772. tls->is_master = -3; /* Mark memory as dead */
  11773. mg_free(tls);
  11774. }
  11775. }
  11776. pthread_setspecific(sTlsKey, NULL);
  11777. }
  11778. #if !defined(NO_SSL)
  11779. static int
  11780. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  11781. static const char *ssl_error(void);
  11782. static int
  11783. refresh_trust(struct mg_connection *conn)
  11784. {
  11785. static int reload_lock = 0;
  11786. static long int data_check = 0;
  11787. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  11788. struct stat cert_buf;
  11789. long int t;
  11790. const char *pem;
  11791. const char *chain;
  11792. int should_verify_peer;
  11793. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  11794. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  11795. * refresh_trust still can not work. */
  11796. return 0;
  11797. }
  11798. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  11799. if (chain == NULL) {
  11800. /* pem is not NULL here */
  11801. chain = pem;
  11802. }
  11803. if (*chain == 0) {
  11804. chain = NULL;
  11805. }
  11806. t = data_check;
  11807. if (stat(pem, &cert_buf) != -1) {
  11808. t = (long int)cert_buf.st_mtime;
  11809. }
  11810. if (data_check != t) {
  11811. data_check = t;
  11812. should_verify_peer = 0;
  11813. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11814. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  11815. == 0) {
  11816. should_verify_peer = 1;
  11817. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  11818. "optional") == 0) {
  11819. should_verify_peer = 1;
  11820. }
  11821. }
  11822. if (should_verify_peer) {
  11823. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  11824. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  11825. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  11826. ca_file,
  11827. ca_path) != 1) {
  11828. mg_cry(fc(conn->ctx),
  11829. "SSL_CTX_load_verify_locations error: %s "
  11830. "ssl_verify_peer requires setting "
  11831. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11832. "present in "
  11833. "the .conf file?",
  11834. ssl_error());
  11835. return 0;
  11836. }
  11837. }
  11838. if (1 == mg_atomic_inc(p_reload_lock)) {
  11839. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  11840. return 0;
  11841. }
  11842. *p_reload_lock = 0;
  11843. }
  11844. }
  11845. /* lock while cert is reloading */
  11846. while (*p_reload_lock) {
  11847. sleep(1);
  11848. }
  11849. return 1;
  11850. }
  11851. #ifdef OPENSSL_API_1_1
  11852. #else
  11853. static pthread_mutex_t *ssl_mutexes;
  11854. #endif /* OPENSSL_API_1_1 */
  11855. static int
  11856. sslize(struct mg_connection *conn,
  11857. SSL_CTX *s,
  11858. int (*func)(SSL *),
  11859. volatile int *stop_server)
  11860. {
  11861. int ret, err;
  11862. int short_trust;
  11863. unsigned i;
  11864. if (!conn) {
  11865. return 0;
  11866. }
  11867. short_trust =
  11868. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  11869. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  11870. if (short_trust) {
  11871. int trust_ret = refresh_trust(conn);
  11872. if (!trust_ret) {
  11873. return trust_ret;
  11874. }
  11875. }
  11876. conn->ssl = SSL_new(s);
  11877. if (conn->ssl == NULL) {
  11878. return 0;
  11879. }
  11880. SSL_set_app_data(conn->ssl, (char *)conn);
  11881. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  11882. if (ret != 1) {
  11883. err = SSL_get_error(conn->ssl, ret);
  11884. (void)err; /* TODO: set some error message */
  11885. SSL_free(conn->ssl);
  11886. conn->ssl = NULL;
  11887. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11888. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11889. #ifndef OPENSSL_API_1_1
  11890. ERR_remove_state(0);
  11891. #endif
  11892. return 0;
  11893. }
  11894. /* SSL functions may fail and require to be called again:
  11895. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  11896. * Here "func" could be SSL_connect or SSL_accept. */
  11897. for (i = 16; i <= 1024; i *= 2) {
  11898. ret = func(conn->ssl);
  11899. if (ret != 1) {
  11900. err = SSL_get_error(conn->ssl, ret);
  11901. if ((err == SSL_ERROR_WANT_CONNECT)
  11902. || (err == SSL_ERROR_WANT_ACCEPT)
  11903. || (err == SSL_ERROR_WANT_READ)
  11904. || (err == SSL_ERROR_WANT_WRITE)) {
  11905. /* Need to retry the function call "later".
  11906. * See https://linux.die.net/man/3/ssl_get_error
  11907. * This is typical for non-blocking sockets. */
  11908. if (*stop_server) {
  11909. /* Don't wait if the server is going to be stopped. */
  11910. break;
  11911. }
  11912. mg_sleep(i);
  11913. } else if (err == SSL_ERROR_SYSCALL) {
  11914. /* This is an IO error. Look at errno. */
  11915. err = errno;
  11916. /* TODO: set some error message */
  11917. (void)err;
  11918. break;
  11919. } else {
  11920. /* This is an SSL specific error */
  11921. /* TODO: set some error message */
  11922. break;
  11923. }
  11924. } else {
  11925. /* success */
  11926. break;
  11927. }
  11928. }
  11929. if (ret != 1) {
  11930. SSL_free(conn->ssl);
  11931. conn->ssl = NULL;
  11932. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11933. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11934. #ifndef OPENSSL_API_1_1
  11935. ERR_remove_state(0);
  11936. #endif
  11937. return 0;
  11938. }
  11939. return 1;
  11940. }
  11941. /* Return OpenSSL error message (from CRYPTO lib) */
  11942. static const char *
  11943. ssl_error(void)
  11944. {
  11945. unsigned long err;
  11946. err = ERR_get_error();
  11947. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  11948. }
  11949. static int
  11950. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  11951. {
  11952. int i;
  11953. const char hexdigit[] = "0123456789abcdef";
  11954. if ((memlen <= 0) || (buflen <= 0)) {
  11955. return 0;
  11956. }
  11957. if (buflen < (3 * memlen)) {
  11958. return 0;
  11959. }
  11960. for (i = 0; i < memlen; i++) {
  11961. if (i > 0) {
  11962. buf[3 * i - 1] = ' ';
  11963. }
  11964. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  11965. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  11966. }
  11967. buf[3 * memlen - 1] = 0;
  11968. return 1;
  11969. }
  11970. static void
  11971. ssl_get_client_cert_info(struct mg_connection *conn)
  11972. {
  11973. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  11974. if (cert) {
  11975. char str_subject[1024];
  11976. char str_issuer[1024];
  11977. char str_finger[1024];
  11978. unsigned char buf[256];
  11979. char *str_serial = NULL;
  11980. unsigned int ulen;
  11981. int ilen;
  11982. unsigned char *tmp_buf;
  11983. unsigned char *tmp_p;
  11984. /* Handle to algorithm used for fingerprint */
  11985. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  11986. /* Get Subject and issuer */
  11987. X509_NAME *subj = X509_get_subject_name(cert);
  11988. X509_NAME *iss = X509_get_issuer_name(cert);
  11989. /* Get serial number */
  11990. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  11991. /* Translate serial number to a hex string */
  11992. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  11993. str_serial = BN_bn2hex(serial_bn);
  11994. BN_free(serial_bn);
  11995. /* Translate subject and issuer to a string */
  11996. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  11997. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  11998. /* Calculate SHA1 fingerprint and store as a hex string */
  11999. ulen = 0;
  12000. /* ASN1_digest is deprecated. Do the calculation manually,
  12001. * using EVP_Digest. */
  12002. ilen = i2d_X509(cert, NULL);
  12003. tmp_buf =
  12004. (ilen > 0)
  12005. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  12006. : NULL;
  12007. if (tmp_buf) {
  12008. tmp_p = tmp_buf;
  12009. (void)i2d_X509(cert, &tmp_p);
  12010. if (!EVP_Digest(
  12011. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12012. ulen = 0;
  12013. }
  12014. mg_free(tmp_buf);
  12015. }
  12016. if (!hexdump2string(
  12017. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12018. *str_finger = 0;
  12019. }
  12020. conn->request_info.client_cert = (struct mg_client_cert *)
  12021. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->ctx);
  12022. if (conn->request_info.client_cert) {
  12023. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  12024. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  12025. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  12026. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  12027. } else {
  12028. mg_cry(conn,
  12029. "Out of memory: Cannot allocate memory for client "
  12030. "certificate");
  12031. }
  12032. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  12033. * see https://linux.die.net/man/3/bn_bn2hex */
  12034. OPENSSL_free(str_serial);
  12035. /* Free certificate memory */
  12036. X509_free(cert);
  12037. }
  12038. }
  12039. #ifdef OPENSSL_API_1_1
  12040. #else
  12041. static void
  12042. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  12043. {
  12044. (void)line;
  12045. (void)file;
  12046. if (mode & 1) {
  12047. /* 1 is CRYPTO_LOCK */
  12048. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  12049. } else {
  12050. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  12051. }
  12052. }
  12053. #endif /* OPENSSL_API_1_1 */
  12054. #if !defined(NO_SSL_DL)
  12055. static void *
  12056. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  12057. {
  12058. union {
  12059. void *p;
  12060. void (*fp)(void);
  12061. } u;
  12062. void *dll_handle;
  12063. struct ssl_func *fp;
  12064. int ok;
  12065. int truncated = 0;
  12066. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  12067. mg_snprintf(NULL,
  12068. NULL, /* No truncation check for ebuf */
  12069. ebuf,
  12070. ebuf_len,
  12071. "%s: cannot load %s",
  12072. __func__,
  12073. dll_name);
  12074. return NULL;
  12075. }
  12076. ok = 1;
  12077. for (fp = sw; fp->name != NULL; fp++) {
  12078. #ifdef _WIN32
  12079. /* GetProcAddress() returns pointer to function */
  12080. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  12081. #else
  12082. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  12083. * pointers to function pointers. We need to use a union to make a
  12084. * cast. */
  12085. u.p = dlsym(dll_handle, fp->name);
  12086. #endif /* _WIN32 */
  12087. if (u.fp == NULL) {
  12088. if (ok) {
  12089. mg_snprintf(NULL,
  12090. &truncated,
  12091. ebuf,
  12092. ebuf_len,
  12093. "%s: %s: cannot find %s",
  12094. __func__,
  12095. dll_name,
  12096. fp->name);
  12097. ok = 0;
  12098. } else {
  12099. size_t cur_len = strlen(ebuf);
  12100. if (!truncated) {
  12101. mg_snprintf(NULL,
  12102. &truncated,
  12103. ebuf + cur_len,
  12104. ebuf_len - cur_len - 3,
  12105. ", %s",
  12106. fp->name);
  12107. if (truncated) {
  12108. /* If truncated, add "..." */
  12109. strcat(ebuf, "...");
  12110. }
  12111. }
  12112. }
  12113. /* Debug:
  12114. * printf("Missing function: %s\n", fp->name); */
  12115. } else {
  12116. fp->ptr = u.fp;
  12117. }
  12118. }
  12119. if (!ok) {
  12120. (void)dlclose(dll_handle);
  12121. return NULL;
  12122. }
  12123. return dll_handle;
  12124. }
  12125. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  12126. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  12127. #endif /* NO_SSL_DL */
  12128. #if defined(SSL_ALREADY_INITIALIZED)
  12129. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  12130. #else
  12131. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  12132. #endif
  12133. static int
  12134. initialize_ssl(char *ebuf, size_t ebuf_len)
  12135. {
  12136. #ifdef OPENSSL_API_1_1
  12137. if (ebuf_len > 0) {
  12138. ebuf[0] = 0;
  12139. }
  12140. #if !defined(NO_SSL_DL)
  12141. if (!cryptolib_dll_handle) {
  12142. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12143. if (!cryptolib_dll_handle) {
  12144. mg_snprintf(NULL,
  12145. NULL, /* No truncation check for ebuf */
  12146. ebuf,
  12147. ebuf_len,
  12148. "%s: error loading library %s",
  12149. __func__,
  12150. CRYPTO_LIB);
  12151. DEBUG_TRACE("%s", ebuf);
  12152. return 0;
  12153. }
  12154. }
  12155. #endif /* NO_SSL_DL */
  12156. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12157. return 1;
  12158. }
  12159. #else /* not OPENSSL_API_1_1 */
  12160. int i;
  12161. size_t size;
  12162. if (ebuf_len > 0) {
  12163. ebuf[0] = 0;
  12164. }
  12165. #if !defined(NO_SSL_DL)
  12166. if (!cryptolib_dll_handle) {
  12167. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12168. if (!cryptolib_dll_handle) {
  12169. mg_snprintf(NULL,
  12170. NULL, /* No truncation check for ebuf */
  12171. ebuf,
  12172. ebuf_len,
  12173. "%s: error loading library %s",
  12174. __func__,
  12175. CRYPTO_LIB);
  12176. DEBUG_TRACE("%s", ebuf);
  12177. return 0;
  12178. }
  12179. }
  12180. #endif /* NO_SSL_DL */
  12181. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12182. return 1;
  12183. }
  12184. /* Initialize locking callbacks, needed for thread safety.
  12185. * http://www.openssl.org/support/faq.html#PROG1
  12186. */
  12187. i = CRYPTO_num_locks();
  12188. if (i < 0) {
  12189. i = 0;
  12190. }
  12191. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  12192. if (size == 0) {
  12193. ssl_mutexes = NULL;
  12194. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  12195. mg_snprintf(NULL,
  12196. NULL, /* No truncation check for ebuf */
  12197. ebuf,
  12198. ebuf_len,
  12199. "%s: cannot allocate mutexes: %s",
  12200. __func__,
  12201. ssl_error());
  12202. DEBUG_TRACE("%s", ebuf);
  12203. return 0;
  12204. }
  12205. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12206. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  12207. }
  12208. CRYPTO_set_locking_callback(&ssl_locking_callback);
  12209. CRYPTO_set_id_callback(&mg_current_thread_id);
  12210. #endif /* OPENSSL_API_1_1 */
  12211. #if !defined(NO_SSL_DL)
  12212. if (!ssllib_dll_handle) {
  12213. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  12214. if (!ssllib_dll_handle) {
  12215. DEBUG_TRACE("%s", ebuf);
  12216. return 0;
  12217. }
  12218. }
  12219. #endif /* NO_SSL_DL */
  12220. #ifdef OPENSSL_API_1_1
  12221. /* Initialize SSL library */
  12222. OPENSSL_init_ssl(0, NULL);
  12223. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  12224. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  12225. NULL);
  12226. #else
  12227. /* Initialize SSL library */
  12228. SSL_library_init();
  12229. SSL_load_error_strings();
  12230. #endif
  12231. return 1;
  12232. }
  12233. static int
  12234. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  12235. {
  12236. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  12237. mg_cry(fc(ctx),
  12238. "%s: cannot open certificate file %s: %s",
  12239. __func__,
  12240. pem,
  12241. ssl_error());
  12242. return 0;
  12243. }
  12244. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  12245. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  12246. mg_cry(fc(ctx),
  12247. "%s: cannot open private key file %s: %s",
  12248. __func__,
  12249. pem,
  12250. ssl_error());
  12251. return 0;
  12252. }
  12253. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  12254. mg_cry(fc(ctx),
  12255. "%s: certificate and private key do not match: %s",
  12256. __func__,
  12257. pem);
  12258. return 0;
  12259. }
  12260. /* In contrast to OpenSSL, wolfSSL does not support certificate
  12261. * chain files that contain private keys and certificates in
  12262. * SSL_CTX_use_certificate_chain_file.
  12263. * The CivetWeb-Server used pem-Files that contained both information.
  12264. * In order to make wolfSSL work, it is split in two files.
  12265. * One file that contains key and certificate used by the server and
  12266. * an optional chain file for the ssl stack.
  12267. */
  12268. if (chain) {
  12269. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  12270. mg_cry(fc(ctx),
  12271. "%s: cannot use certificate chain file %s: %s",
  12272. __func__,
  12273. pem,
  12274. ssl_error());
  12275. return 0;
  12276. }
  12277. }
  12278. return 1;
  12279. }
  12280. #ifdef OPENSSL_API_1_1
  12281. static unsigned long
  12282. ssl_get_protocol(int version_id)
  12283. {
  12284. long unsigned ret = SSL_OP_ALL;
  12285. if (version_id > 0)
  12286. ret |= SSL_OP_NO_SSLv2;
  12287. if (version_id > 1)
  12288. ret |= SSL_OP_NO_SSLv3;
  12289. if (version_id > 2)
  12290. ret |= SSL_OP_NO_TLSv1;
  12291. if (version_id > 3)
  12292. ret |= SSL_OP_NO_TLSv1_1;
  12293. return ret;
  12294. }
  12295. #else
  12296. static long
  12297. ssl_get_protocol(int version_id)
  12298. {
  12299. long ret = SSL_OP_ALL;
  12300. if (version_id > 0)
  12301. ret |= SSL_OP_NO_SSLv2;
  12302. if (version_id > 1)
  12303. ret |= SSL_OP_NO_SSLv3;
  12304. if (version_id > 2)
  12305. ret |= SSL_OP_NO_TLSv1;
  12306. if (version_id > 3)
  12307. ret |= SSL_OP_NO_TLSv1_1;
  12308. return ret;
  12309. }
  12310. #endif /* OPENSSL_API_1_1 */
  12311. /* SSL callback documentation:
  12312. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  12313. * https://linux.die.net/man/3/ssl_set_info_callback */
  12314. static void
  12315. ssl_info_callback(SSL *ssl, int what, int ret)
  12316. {
  12317. (void)ret;
  12318. if (what & SSL_CB_HANDSHAKE_START) {
  12319. SSL_get_app_data(ssl);
  12320. }
  12321. if (what & SSL_CB_HANDSHAKE_DONE) {
  12322. /* TODO: check for openSSL 1.1 */
  12323. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  12324. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  12325. }
  12326. }
  12327. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  12328. static int
  12329. set_ssl_option(struct mg_context *ctx)
  12330. {
  12331. const char *pem;
  12332. const char *chain;
  12333. int callback_ret;
  12334. int should_verify_peer;
  12335. int peer_certificate_optional;
  12336. const char *ca_path;
  12337. const char *ca_file;
  12338. int use_default_verify_paths;
  12339. int verify_depth;
  12340. time_t now_rt = time(NULL);
  12341. struct timespec now_mt;
  12342. md5_byte_t ssl_context_id[16];
  12343. md5_state_t md5state;
  12344. int protocol_ver;
  12345. char ebuf[128];
  12346. if (!ctx) {
  12347. return 0;
  12348. }
  12349. if (!is_ssl_port_used(ctx->config[LISTENING_PORTS])) {
  12350. /* No SSL port is set. No need to setup SSL. */
  12351. return 1;
  12352. }
  12353. /* If PEM file is not specified and the init_ssl callback
  12354. * is not specified, setup will fail. */
  12355. if (((pem = ctx->config[SSL_CERTIFICATE]) == NULL)
  12356. && (ctx->callbacks.init_ssl == NULL)) {
  12357. /* No certificate and no callback:
  12358. * Essential data to set up TLS is missing.
  12359. */
  12360. mg_cry(fc(ctx),
  12361. "Initializing SSL failed: -%s is not set",
  12362. config_options[SSL_CERTIFICATE].name);
  12363. return 0;
  12364. }
  12365. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  12366. if (chain == NULL) {
  12367. chain = pem;
  12368. }
  12369. if ((chain != NULL) && (*chain == 0)) {
  12370. chain = NULL;
  12371. }
  12372. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12373. mg_cry(fc(ctx), "%s", ebuf);
  12374. return 0;
  12375. }
  12376. #ifdef OPENSSL_API_1_1
  12377. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  12378. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  12379. return 0;
  12380. }
  12381. #else
  12382. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  12383. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  12384. return 0;
  12385. }
  12386. #endif /* OPENSSL_API_1_1 */
  12387. SSL_CTX_clear_options(ctx->ssl_ctx,
  12388. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  12389. | SSL_OP_NO_TLSv1_1);
  12390. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  12391. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  12392. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  12393. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  12394. SSL_CTX_set_options(ctx->ssl_ctx,
  12395. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12396. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  12397. #if !defined(NO_SSL_DL)
  12398. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  12399. #endif /* NO_SSL_DL */
  12400. #ifdef __clang__
  12401. #pragma clang diagnostic push
  12402. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  12403. #endif
  12404. /* Depending on the OpenSSL version, the callback may be
  12405. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  12406. * yielding in an "incompatible-pointer-type" warning for the other
  12407. * version. It seems to be "unclear" what is correct:
  12408. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  12409. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  12410. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  12411. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  12412. * Disable this warning here.
  12413. * Alternative would be a version dependent ssl_info_callback and
  12414. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  12415. */
  12416. SSL_CTX_set_info_callback(ctx->ssl_ctx, ssl_info_callback);
  12417. #ifdef __clang__
  12418. #pragma clang diagnostic pop
  12419. #endif
  12420. /* If a callback has been specified, call it. */
  12421. callback_ret =
  12422. (ctx->callbacks.init_ssl == NULL)
  12423. ? 0
  12424. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  12425. /* If callback returns 0, civetweb sets up the SSL certificate.
  12426. * If it returns 1, civetweb assumes the calback already did this.
  12427. * If it returns -1, initializing ssl fails. */
  12428. if (callback_ret < 0) {
  12429. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  12430. return 0;
  12431. }
  12432. if (callback_ret > 0) {
  12433. /* Callback did everything. */
  12434. return 1;
  12435. }
  12436. /* Use some UID as session context ID. */
  12437. md5_init(&md5state);
  12438. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  12439. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  12440. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  12441. md5_append(&md5state,
  12442. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  12443. strlen(ctx->config[LISTENING_PORTS]));
  12444. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  12445. md5_finish(&md5state, ssl_context_id);
  12446. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  12447. (const unsigned char *)&ssl_context_id,
  12448. sizeof(ssl_context_id));
  12449. if (pem != NULL) {
  12450. if (!ssl_use_pem_file(ctx, pem, chain)) {
  12451. return 0;
  12452. }
  12453. }
  12454. /* Should we support client certificates? */
  12455. /* Default is "no". */
  12456. should_verify_peer = 0;
  12457. peer_certificate_optional = 0;
  12458. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12459. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  12460. /* Yes, they are mandatory */
  12461. should_verify_peer = 1;
  12462. peer_certificate_optional = 0;
  12463. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  12464. == 0) {
  12465. /* Yes, they are optional */
  12466. should_verify_peer = 1;
  12467. peer_certificate_optional = 1;
  12468. }
  12469. }
  12470. use_default_verify_paths =
  12471. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  12472. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  12473. if (should_verify_peer) {
  12474. ca_path = ctx->config[SSL_CA_PATH];
  12475. ca_file = ctx->config[SSL_CA_FILE];
  12476. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  12477. != 1) {
  12478. mg_cry(fc(ctx),
  12479. "SSL_CTX_load_verify_locations error: %s "
  12480. "ssl_verify_peer requires setting "
  12481. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12482. "present in "
  12483. "the .conf file?",
  12484. ssl_error());
  12485. return 0;
  12486. }
  12487. if (peer_certificate_optional) {
  12488. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  12489. } else {
  12490. SSL_CTX_set_verify(ctx->ssl_ctx,
  12491. SSL_VERIFY_PEER
  12492. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  12493. NULL);
  12494. }
  12495. if (use_default_verify_paths
  12496. && (SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1)) {
  12497. mg_cry(fc(ctx),
  12498. "SSL_CTX_set_default_verify_paths error: %s",
  12499. ssl_error());
  12500. return 0;
  12501. }
  12502. if (ctx->config[SSL_VERIFY_DEPTH]) {
  12503. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  12504. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  12505. }
  12506. }
  12507. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  12508. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  12509. != 1) {
  12510. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  12511. }
  12512. }
  12513. return 1;
  12514. }
  12515. static void
  12516. uninitialize_ssl(void)
  12517. {
  12518. #ifdef OPENSSL_API_1_1
  12519. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12520. /* Shutdown according to
  12521. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12522. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12523. */
  12524. CONF_modules_unload(1);
  12525. #else
  12526. int i;
  12527. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12528. /* Shutdown according to
  12529. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12530. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12531. */
  12532. CRYPTO_set_locking_callback(NULL);
  12533. CRYPTO_set_id_callback(NULL);
  12534. ENGINE_cleanup();
  12535. CONF_modules_unload(1);
  12536. ERR_free_strings();
  12537. EVP_cleanup();
  12538. CRYPTO_cleanup_all_ex_data();
  12539. ERR_remove_state(0);
  12540. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12541. pthread_mutex_destroy(&ssl_mutexes[i]);
  12542. }
  12543. mg_free(ssl_mutexes);
  12544. ssl_mutexes = NULL;
  12545. #endif /* OPENSSL_API_1_1 */
  12546. }
  12547. }
  12548. #endif /* !NO_SSL */
  12549. static int
  12550. set_gpass_option(struct mg_context *ctx)
  12551. {
  12552. if (ctx) {
  12553. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12554. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  12555. if ((path != NULL) && !mg_stat(fc(ctx), path, &file.stat)) {
  12556. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  12557. return 0;
  12558. }
  12559. return 1;
  12560. }
  12561. return 0;
  12562. }
  12563. static int
  12564. set_acl_option(struct mg_context *ctx)
  12565. {
  12566. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  12567. }
  12568. static void
  12569. reset_per_request_attributes(struct mg_connection *conn)
  12570. {
  12571. if (!conn) {
  12572. return;
  12573. }
  12574. conn->connection_type =
  12575. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  12576. conn->num_bytes_sent = conn->consumed_content = 0;
  12577. conn->path_info = NULL;
  12578. conn->status_code = -1;
  12579. conn->content_len = -1;
  12580. conn->is_chunked = 0;
  12581. conn->must_close = 0;
  12582. conn->request_len = 0;
  12583. conn->throttle = 0;
  12584. conn->data_len = 0;
  12585. conn->chunk_remainder = 0;
  12586. conn->accept_gzip = 0;
  12587. conn->response_info.content_length = conn->request_info.content_length = -1;
  12588. conn->response_info.http_version = conn->request_info.http_version = NULL;
  12589. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  12590. conn->response_info.status_text = NULL;
  12591. conn->response_info.status_code = 0;
  12592. conn->request_info.remote_user = NULL;
  12593. conn->request_info.request_method = NULL;
  12594. conn->request_info.request_uri = NULL;
  12595. conn->request_info.local_uri = NULL;
  12596. #if defined(MG_LEGACY_INTERFACE)
  12597. /* Legacy before split into local_uri and request_uri */
  12598. conn->request_info.uri = NULL;
  12599. #endif
  12600. }
  12601. #if 0
  12602. /* Note: set_sock_timeout is not required for non-blocking sockets.
  12603. * Leave this function here (commented out) for reference until
  12604. * CivetWeb 1.9 is tested, and the tests confirme this function is
  12605. * no longer required.
  12606. */
  12607. static int
  12608. set_sock_timeout(SOCKET sock, int milliseconds)
  12609. {
  12610. int r0 = 0, r1, r2;
  12611. #ifdef _WIN32
  12612. /* Windows specific */
  12613. DWORD tv = (DWORD)milliseconds;
  12614. #else
  12615. /* Linux, ... (not Windows) */
  12616. struct timeval tv;
  12617. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  12618. * max. time waiting for the acknowledged of TCP data before the connection
  12619. * will be forcefully closed and ETIMEDOUT is returned to the application.
  12620. * If this option is not set, the default timeout of 20-30 minutes is used.
  12621. */
  12622. /* #define TCP_USER_TIMEOUT (18) */
  12623. #if defined(TCP_USER_TIMEOUT)
  12624. unsigned int uto = (unsigned int)milliseconds;
  12625. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  12626. #endif
  12627. memset(&tv, 0, sizeof(tv));
  12628. tv.tv_sec = milliseconds / 1000;
  12629. tv.tv_usec = (milliseconds * 1000) % 1000000;
  12630. #endif /* _WIN32 */
  12631. r1 = setsockopt(
  12632. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12633. r2 = setsockopt(
  12634. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12635. return r0 || r1 || r2;
  12636. }
  12637. #endif
  12638. static int
  12639. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  12640. {
  12641. if (setsockopt(sock,
  12642. IPPROTO_TCP,
  12643. TCP_NODELAY,
  12644. (SOCK_OPT_TYPE)&nodelay_on,
  12645. sizeof(nodelay_on)) != 0) {
  12646. /* Error */
  12647. return 1;
  12648. }
  12649. /* OK */
  12650. return 0;
  12651. }
  12652. static void
  12653. close_socket_gracefully(struct mg_connection *conn)
  12654. {
  12655. #if defined(_WIN32)
  12656. char buf[MG_BUF_LEN];
  12657. int n;
  12658. #endif
  12659. struct linger linger;
  12660. int error_code = 0;
  12661. int linger_timeout = -2;
  12662. socklen_t opt_len = sizeof(error_code);
  12663. if (!conn) {
  12664. return;
  12665. }
  12666. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  12667. * "Note that enabling a nonzero timeout on a nonblocking socket
  12668. * is not recommended.", so set it to blocking now */
  12669. set_blocking_mode(conn->client.sock);
  12670. /* Send FIN to the client */
  12671. shutdown(conn->client.sock, SHUTDOWN_WR);
  12672. #if defined(_WIN32)
  12673. /* Read and discard pending incoming data. If we do not do that and
  12674. * close
  12675. * the socket, the data in the send buffer may be discarded. This
  12676. * behaviour is seen on Windows, when client keeps sending data
  12677. * when server decides to close the connection; then when client
  12678. * does recv() it gets no data back. */
  12679. do {
  12680. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  12681. } while (n > 0);
  12682. #endif
  12683. if (conn->ctx->config[LINGER_TIMEOUT]) {
  12684. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  12685. }
  12686. /* Set linger option according to configuration */
  12687. if (linger_timeout >= 0) {
  12688. /* Set linger option to avoid socket hanging out after close. This
  12689. * prevent ephemeral port exhaust problem under high QPS. */
  12690. linger.l_onoff = 1;
  12691. #if defined(_MSC_VER)
  12692. #pragma warning(push)
  12693. #pragma warning(disable : 4244)
  12694. #endif
  12695. #if defined(__GNUC__) || defined(__MINGW32__)
  12696. #pragma GCC diagnostic push
  12697. #pragma GCC diagnostic ignored "-Wconversion"
  12698. #endif
  12699. /* Data type of linger structure elements may differ,
  12700. * so we don't know what cast we need here.
  12701. * Disable type conversion warnings. */
  12702. linger.l_linger = (linger_timeout + 999) / 1000;
  12703. #if defined(__GNUC__) || defined(__MINGW32__)
  12704. #pragma GCC diagnostic pop
  12705. #endif
  12706. #if defined(_MSC_VER)
  12707. #pragma warning(pop)
  12708. #endif
  12709. } else {
  12710. linger.l_onoff = 0;
  12711. linger.l_linger = 0;
  12712. }
  12713. if (linger_timeout < -1) {
  12714. /* Default: don't configure any linger */
  12715. } else if (getsockopt(conn->client.sock,
  12716. SOL_SOCKET,
  12717. SO_ERROR,
  12718. (char *)&error_code,
  12719. &opt_len) != 0) {
  12720. /* Cannot determine if socket is already closed. This should
  12721. * not occur and never did in a test. Log an error message
  12722. * and continue. */
  12723. mg_cry(conn,
  12724. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  12725. __func__,
  12726. strerror(ERRNO));
  12727. } else if (error_code == ECONNRESET) {
  12728. /* Socket already closed by client/peer, close socket without linger
  12729. */
  12730. } else {
  12731. /* Set linger timeout */
  12732. if (setsockopt(conn->client.sock,
  12733. SOL_SOCKET,
  12734. SO_LINGER,
  12735. (char *)&linger,
  12736. sizeof(linger)) != 0) {
  12737. mg_cry(conn,
  12738. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  12739. __func__,
  12740. linger.l_onoff,
  12741. linger.l_linger,
  12742. strerror(ERRNO));
  12743. }
  12744. }
  12745. /* Now we know that our FIN is ACK-ed, safe to close */
  12746. closesocket(conn->client.sock);
  12747. conn->client.sock = INVALID_SOCKET;
  12748. }
  12749. static void
  12750. close_connection(struct mg_connection *conn)
  12751. {
  12752. #if defined(USE_SERVER_STATS)
  12753. conn->conn_state = 6; /* to close */
  12754. #endif
  12755. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12756. if (conn->lua_websocket_state) {
  12757. lua_websocket_close(conn, conn->lua_websocket_state);
  12758. conn->lua_websocket_state = NULL;
  12759. }
  12760. #endif
  12761. mg_lock_connection(conn);
  12762. /* Set close flag, so keep-alive loops will stop */
  12763. conn->must_close = 1;
  12764. /* call the connection_close callback if assigned */
  12765. if (conn->ctx->callbacks.connection_close != NULL) {
  12766. if (conn->ctx->context_type == CONTEXT_SERVER) {
  12767. conn->ctx->callbacks.connection_close(conn);
  12768. }
  12769. }
  12770. /* Reset user data, after close callback is called.
  12771. * Do not reuse it. If the user needs a destructor,
  12772. * it must be done in the connection_close callback. */
  12773. mg_set_user_connection_data(conn, NULL);
  12774. #if defined(USE_SERVER_STATS)
  12775. conn->conn_state = 7; /* closing */
  12776. #endif
  12777. #ifndef NO_SSL
  12778. if (conn->ssl != NULL) {
  12779. /* Run SSL_shutdown twice to ensure completly close SSL connection
  12780. */
  12781. SSL_shutdown(conn->ssl);
  12782. SSL_free(conn->ssl);
  12783. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12784. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12785. #ifndef OPENSSL_API_1_1
  12786. ERR_remove_state(0);
  12787. #endif
  12788. conn->ssl = NULL;
  12789. }
  12790. #endif
  12791. if (conn->client.sock != INVALID_SOCKET) {
  12792. close_socket_gracefully(conn);
  12793. conn->client.sock = INVALID_SOCKET;
  12794. }
  12795. mg_unlock_connection(conn);
  12796. #if defined(USE_SERVER_STATS)
  12797. conn->conn_state = 8; /* closed */
  12798. #endif
  12799. }
  12800. void
  12801. mg_close_connection(struct mg_connection *conn)
  12802. {
  12803. #if defined(USE_WEBSOCKET)
  12804. struct mg_context *client_ctx = NULL;
  12805. #endif /* defined(USE_WEBSOCKET) */
  12806. if ((conn == NULL) || (conn->ctx == NULL)) {
  12807. return;
  12808. }
  12809. #if defined(USE_WEBSOCKET)
  12810. if (conn->ctx->context_type == CONTEXT_SERVER) {
  12811. if (conn->in_websocket_handling) {
  12812. /* Set close flag, so the server thread can exit. */
  12813. conn->must_close = 1;
  12814. return;
  12815. }
  12816. }
  12817. if (conn->ctx->context_type == CONTEXT_WS_CLIENT) {
  12818. unsigned int i;
  12819. /* ws/wss client */
  12820. client_ctx = conn->ctx;
  12821. /* client context: loops must end */
  12822. conn->ctx->stop_flag = 1;
  12823. conn->must_close = 1;
  12824. /* We need to get the client thread out of the select/recv call
  12825. * here. */
  12826. /* Since we use a sleep quantum of some seconds to check for recv
  12827. * timeouts, we will just wait a few seconds in mg_join_thread. */
  12828. /* join worker thread */
  12829. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  12830. if (client_ctx->worker_threadids[i] != 0) {
  12831. mg_join_thread(client_ctx->worker_threadids[i]);
  12832. }
  12833. }
  12834. }
  12835. #endif /* defined(USE_WEBSOCKET) */
  12836. close_connection(conn);
  12837. #ifndef NO_SSL
  12838. if (conn->client_ssl_ctx != NULL) {
  12839. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  12840. }
  12841. #endif
  12842. #if defined(USE_WEBSOCKET)
  12843. if (client_ctx != NULL) {
  12844. /* free context */
  12845. mg_free(client_ctx->worker_threadids);
  12846. mg_free(client_ctx);
  12847. (void)pthread_mutex_destroy(&conn->mutex);
  12848. mg_free(conn);
  12849. } else if (conn->ctx->context_type == CONTEXT_HTTP_CLIENT) {
  12850. mg_free(conn);
  12851. }
  12852. #else
  12853. if (conn->ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  12854. mg_free(conn);
  12855. }
  12856. #endif /* defined(USE_WEBSOCKET) */
  12857. }
  12858. /* Only for memory statistics */
  12859. static struct mg_context common_client_context;
  12860. static struct mg_connection *
  12861. mg_connect_client_impl(const struct mg_client_options *client_options,
  12862. int use_ssl,
  12863. char *ebuf,
  12864. size_t ebuf_len)
  12865. {
  12866. struct mg_connection *conn = NULL;
  12867. SOCKET sock;
  12868. union usa sa;
  12869. struct sockaddr *psa;
  12870. socklen_t len;
  12871. unsigned max_req_size =
  12872. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  12873. /* Size of structures, aligned to 8 bytes */
  12874. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  12875. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  12876. conn = (struct mg_connection *)mg_calloc_ctx(1,
  12877. conn_size + ctx_size
  12878. + max_req_size,
  12879. &common_client_context);
  12880. if (conn == NULL) {
  12881. mg_snprintf(NULL,
  12882. NULL, /* No truncation check for ebuf */
  12883. ebuf,
  12884. ebuf_len,
  12885. "calloc(): %s",
  12886. strerror(ERRNO));
  12887. return NULL;
  12888. }
  12889. conn->ctx = (struct mg_context *)(((char *)conn) + conn_size);
  12890. conn->buf = (((char *)conn) + conn_size + ctx_size);
  12891. conn->buf_size = (int)max_req_size;
  12892. conn->ctx->context_type = CONTEXT_HTTP_CLIENT;
  12893. if (!connect_socket(&common_client_context,
  12894. client_options->host,
  12895. client_options->port,
  12896. use_ssl,
  12897. ebuf,
  12898. ebuf_len,
  12899. &sock,
  12900. &sa)) {
  12901. /* ebuf is set by connect_socket,
  12902. * free all memory and return NULL; */
  12903. mg_free(conn);
  12904. return NULL;
  12905. }
  12906. #ifndef NO_SSL
  12907. #ifdef OPENSSL_API_1_1
  12908. if (use_ssl
  12909. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  12910. mg_snprintf(NULL,
  12911. NULL, /* No truncation check for ebuf */
  12912. ebuf,
  12913. ebuf_len,
  12914. "SSL_CTX_new error");
  12915. closesocket(sock);
  12916. mg_free(conn);
  12917. return NULL;
  12918. }
  12919. #else
  12920. if (use_ssl
  12921. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  12922. == NULL) {
  12923. mg_snprintf(NULL,
  12924. NULL, /* No truncation check for ebuf */
  12925. ebuf,
  12926. ebuf_len,
  12927. "SSL_CTX_new error");
  12928. closesocket(sock);
  12929. mg_free(conn);
  12930. return NULL;
  12931. }
  12932. #endif /* OPENSSL_API_1_1 */
  12933. #endif /* NO_SSL */
  12934. #ifdef USE_IPV6
  12935. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  12936. : sizeof(conn->client.rsa.sin6);
  12937. psa = (sa.sa.sa_family == AF_INET)
  12938. ? (struct sockaddr *)&(conn->client.rsa.sin)
  12939. : (struct sockaddr *)&(conn->client.rsa.sin6);
  12940. #else
  12941. len = sizeof(conn->client.rsa.sin);
  12942. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  12943. #endif
  12944. conn->client.sock = sock;
  12945. conn->client.lsa = sa;
  12946. if (getsockname(sock, psa, &len) != 0) {
  12947. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  12948. }
  12949. conn->client.is_ssl = use_ssl ? 1 : 0;
  12950. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12951. #ifndef NO_SSL
  12952. if (use_ssl) {
  12953. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  12954. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  12955. * SSL_CTX_set_verify call is needed to switch off server
  12956. * certificate checking, which is off by default in OpenSSL and
  12957. * on in yaSSL. */
  12958. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  12959. * SSL_VERIFY_PEER, verify_ssl_server); */
  12960. if (client_options->client_cert) {
  12961. if (!ssl_use_pem_file(&common_client_context,
  12962. client_options->client_cert,
  12963. NULL)) {
  12964. mg_snprintf(NULL,
  12965. NULL, /* No truncation check for ebuf */
  12966. ebuf,
  12967. ebuf_len,
  12968. "Can not use SSL client certificate");
  12969. SSL_CTX_free(conn->client_ssl_ctx);
  12970. closesocket(sock);
  12971. mg_free(conn);
  12972. return NULL;
  12973. }
  12974. }
  12975. if (client_options->server_cert) {
  12976. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  12977. client_options->server_cert,
  12978. NULL);
  12979. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  12980. } else {
  12981. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  12982. }
  12983. if (!sslize(conn,
  12984. conn->client_ssl_ctx,
  12985. SSL_connect,
  12986. &(conn->ctx->stop_flag))) {
  12987. mg_snprintf(NULL,
  12988. NULL, /* No truncation check for ebuf */
  12989. ebuf,
  12990. ebuf_len,
  12991. "SSL connection error");
  12992. SSL_CTX_free(conn->client_ssl_ctx);
  12993. closesocket(sock);
  12994. mg_free(conn);
  12995. return NULL;
  12996. }
  12997. }
  12998. #endif
  12999. if (0 != set_non_blocking_mode(sock)) {
  13000. /* TODO: handle error */
  13001. ;
  13002. }
  13003. return conn;
  13004. }
  13005. CIVETWEB_API struct mg_connection *
  13006. mg_connect_client_secure(const struct mg_client_options *client_options,
  13007. char *error_buffer,
  13008. size_t error_buffer_size)
  13009. {
  13010. return mg_connect_client_impl(client_options,
  13011. 1,
  13012. error_buffer,
  13013. error_buffer_size);
  13014. }
  13015. struct mg_connection *
  13016. mg_connect_client(const char *host,
  13017. int port,
  13018. int use_ssl,
  13019. char *error_buffer,
  13020. size_t error_buffer_size)
  13021. {
  13022. struct mg_client_options opts;
  13023. memset(&opts, 0, sizeof(opts));
  13024. opts.host = host;
  13025. opts.port = port;
  13026. return mg_connect_client_impl(&opts,
  13027. use_ssl,
  13028. error_buffer,
  13029. error_buffer_size);
  13030. }
  13031. static const struct {
  13032. const char *proto;
  13033. size_t proto_len;
  13034. unsigned default_port;
  13035. } abs_uri_protocols[] = {{"http://", 7, 80},
  13036. {"https://", 8, 443},
  13037. {"ws://", 5, 80},
  13038. {"wss://", 6, 443},
  13039. {NULL, 0, 0}};
  13040. /* Check if the uri is valid.
  13041. * return 0 for invalid uri,
  13042. * return 1 for *,
  13043. * return 2 for relative uri,
  13044. * return 3 for absolute uri without port,
  13045. * return 4 for absolute uri with port */
  13046. static int
  13047. get_uri_type(const char *uri)
  13048. {
  13049. int i;
  13050. const char *hostend, *portbegin;
  13051. char *portend;
  13052. unsigned long port;
  13053. /* According to the HTTP standard
  13054. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  13055. * URI can be an asterisk (*) or should start with slash (relative uri),
  13056. * or it should start with the protocol (absolute uri). */
  13057. if ((uri[0] == '*') && (uri[1] == '\0')) {
  13058. /* asterisk */
  13059. return 1;
  13060. }
  13061. /* Valid URIs according to RFC 3986
  13062. * (https://www.ietf.org/rfc/rfc3986.txt)
  13063. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  13064. * and unreserved characters A-Z a-z 0-9 and -._~
  13065. * and % encoded symbols.
  13066. */
  13067. for (i = 0; uri[i] != 0; i++) {
  13068. if (uri[i] < 33) {
  13069. /* control characters and spaces are invalid */
  13070. return 0;
  13071. }
  13072. if (uri[i] > 126) {
  13073. /* non-ascii characters must be % encoded */
  13074. return 0;
  13075. } else {
  13076. switch (uri[i]) {
  13077. case '"': /* 34 */
  13078. case '<': /* 60 */
  13079. case '>': /* 62 */
  13080. case '\\': /* 92 */
  13081. case '^': /* 94 */
  13082. case '`': /* 96 */
  13083. case '{': /* 123 */
  13084. case '|': /* 124 */
  13085. case '}': /* 125 */
  13086. return 0;
  13087. default:
  13088. /* character is ok */
  13089. break;
  13090. }
  13091. }
  13092. }
  13093. /* A relative uri starts with a / character */
  13094. if (uri[0] == '/') {
  13095. /* relative uri */
  13096. return 2;
  13097. }
  13098. /* It could be an absolute uri: */
  13099. /* This function only checks if the uri is valid, not if it is
  13100. * addressing the current server. So civetweb can also be used
  13101. * as a proxy server. */
  13102. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13103. if (mg_strncasecmp(uri,
  13104. abs_uri_protocols[i].proto,
  13105. abs_uri_protocols[i].proto_len) == 0) {
  13106. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  13107. if (!hostend) {
  13108. return 0;
  13109. }
  13110. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  13111. if (!portbegin) {
  13112. return 3;
  13113. }
  13114. port = strtoul(portbegin + 1, &portend, 10);
  13115. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  13116. return 0;
  13117. }
  13118. return 4;
  13119. }
  13120. }
  13121. return 0;
  13122. }
  13123. /* Return NULL or the relative uri at the current server */
  13124. static const char *
  13125. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  13126. {
  13127. const char *server_domain;
  13128. size_t server_domain_len;
  13129. size_t request_domain_len = 0;
  13130. unsigned long port = 0;
  13131. int i, auth_domain_check_enabled;
  13132. const char *hostbegin = NULL;
  13133. const char *hostend = NULL;
  13134. const char *portbegin;
  13135. char *portend;
  13136. auth_domain_check_enabled =
  13137. !mg_strcasecmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  13138. if (!auth_domain_check_enabled) {
  13139. return 0;
  13140. }
  13141. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  13142. if (!server_domain) {
  13143. return 0;
  13144. }
  13145. server_domain_len = strlen(server_domain);
  13146. if (!server_domain_len) {
  13147. return 0;
  13148. }
  13149. /* DNS is case insensitive, so use case insensitive string compare here
  13150. */
  13151. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13152. if (mg_strncasecmp(uri,
  13153. abs_uri_protocols[i].proto,
  13154. abs_uri_protocols[i].proto_len) == 0) {
  13155. hostbegin = uri + abs_uri_protocols[i].proto_len;
  13156. hostend = strchr(hostbegin, '/');
  13157. if (!hostend) {
  13158. return 0;
  13159. }
  13160. portbegin = strchr(hostbegin, ':');
  13161. if ((!portbegin) || (portbegin > hostend)) {
  13162. port = abs_uri_protocols[i].default_port;
  13163. request_domain_len = (size_t)(hostend - hostbegin);
  13164. } else {
  13165. port = strtoul(portbegin + 1, &portend, 10);
  13166. if ((portend != hostend) || (port <= 0)
  13167. || !is_valid_port(port)) {
  13168. return 0;
  13169. }
  13170. request_domain_len = (size_t)(portbegin - hostbegin);
  13171. }
  13172. /* protocol found, port set */
  13173. break;
  13174. }
  13175. }
  13176. if (!port) {
  13177. /* port remains 0 if the protocol is not found */
  13178. return 0;
  13179. }
  13180. /* Check if the request is directed to a different server. */
  13181. /* First check if the port is the same (IPv4 and IPv6). */
  13182. #if defined(USE_IPV6)
  13183. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  13184. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  13185. /* Request is directed to a different port */
  13186. return 0;
  13187. }
  13188. } else
  13189. #endif
  13190. {
  13191. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  13192. /* Request is directed to a different port */
  13193. return 0;
  13194. }
  13195. }
  13196. /* Finally check if the server corresponds to the authentication
  13197. * domain of the server (the server domain).
  13198. * Allow full matches (like http://mydomain.com/path/file.ext), and
  13199. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  13200. * but do not allow substrings (like
  13201. * http://notmydomain.com/path/file.ext
  13202. * or http://mydomain.com.fake/path/file.ext).
  13203. */
  13204. if (auth_domain_check_enabled) {
  13205. if ((request_domain_len == server_domain_len)
  13206. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  13207. /* Request is directed to this server - full name match. */
  13208. } else {
  13209. if (request_domain_len < (server_domain_len + 2)) {
  13210. /* Request is directed to another server: The server name is
  13211. * longer
  13212. * than
  13213. * the request name. Drop this case here to avoid overflows
  13214. * in
  13215. * the
  13216. * following checks. */
  13217. return 0;
  13218. }
  13219. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  13220. /* Request is directed to another server: It could be a
  13221. * substring
  13222. * like notmyserver.com */
  13223. return 0;
  13224. }
  13225. if (0 != memcmp(server_domain,
  13226. hostbegin + request_domain_len - server_domain_len,
  13227. server_domain_len)) {
  13228. /* Request is directed to another server:
  13229. * The server name is different. */
  13230. return 0;
  13231. }
  13232. }
  13233. }
  13234. return hostend;
  13235. }
  13236. static int
  13237. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13238. {
  13239. if (ebuf_len > 0) {
  13240. ebuf[0] = '\0';
  13241. }
  13242. *err = 0;
  13243. reset_per_request_attributes(conn);
  13244. if (!conn) {
  13245. mg_snprintf(conn,
  13246. NULL, /* No truncation check for ebuf */
  13247. ebuf,
  13248. ebuf_len,
  13249. "%s",
  13250. "Internal error");
  13251. *err = 500;
  13252. return 0;
  13253. }
  13254. /* Set the time the request was received. This value should be used for
  13255. * timeouts. */
  13256. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  13257. conn->request_len =
  13258. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  13259. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  13260. */
  13261. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  13262. mg_snprintf(conn,
  13263. NULL, /* No truncation check for ebuf */
  13264. ebuf,
  13265. ebuf_len,
  13266. "%s",
  13267. "Invalid message size");
  13268. *err = 500;
  13269. return 0;
  13270. }
  13271. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  13272. mg_snprintf(conn,
  13273. NULL, /* No truncation check for ebuf */
  13274. ebuf,
  13275. ebuf_len,
  13276. "%s",
  13277. "Message too large");
  13278. *err = 413;
  13279. return 0;
  13280. }
  13281. if (conn->request_len <= 0) {
  13282. if (conn->data_len > 0) {
  13283. mg_snprintf(conn,
  13284. NULL, /* No truncation check for ebuf */
  13285. ebuf,
  13286. ebuf_len,
  13287. "%s",
  13288. "Malformed message");
  13289. *err = 400;
  13290. } else {
  13291. /* Server did not recv anything -> just close the connection */
  13292. conn->must_close = 1;
  13293. mg_snprintf(conn,
  13294. NULL, /* No truncation check for ebuf */
  13295. ebuf,
  13296. ebuf_len,
  13297. "%s",
  13298. "No data received");
  13299. *err = 0;
  13300. }
  13301. return 0;
  13302. }
  13303. return 1;
  13304. }
  13305. static int
  13306. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13307. {
  13308. const char *cl;
  13309. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13310. return 0;
  13311. }
  13312. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  13313. <= 0) {
  13314. mg_snprintf(conn,
  13315. NULL, /* No truncation check for ebuf */
  13316. ebuf,
  13317. ebuf_len,
  13318. "%s",
  13319. "Bad request");
  13320. *err = 400;
  13321. return 0;
  13322. }
  13323. /* Message is a valid request */
  13324. if ((cl = get_header(conn->request_info.http_headers,
  13325. conn->request_info.num_headers,
  13326. "Content-Length")) != NULL) {
  13327. /* Request/response has content length set */
  13328. char *endptr = NULL;
  13329. conn->content_len = strtoll(cl, &endptr, 10);
  13330. if (endptr == cl) {
  13331. mg_snprintf(conn,
  13332. NULL, /* No truncation check for ebuf */
  13333. ebuf,
  13334. ebuf_len,
  13335. "%s",
  13336. "Bad request");
  13337. *err = 411;
  13338. return 0;
  13339. }
  13340. /* Publish the content length back to the request info. */
  13341. conn->request_info.content_length = conn->content_len;
  13342. } else if ((cl = get_header(conn->request_info.http_headers,
  13343. conn->request_info.num_headers,
  13344. "Transfer-Encoding")) != NULL
  13345. && !mg_strcasecmp(cl, "chunked")) {
  13346. conn->is_chunked = 1;
  13347. conn->content_len = -1; /* unknown content length */
  13348. } else if (get_http_method_info(conn->request_info.request_method)
  13349. ->request_has_body) {
  13350. /* POST or PUT request without content length set */
  13351. conn->content_len = -1; /* unknown content length */
  13352. } else {
  13353. /* Other request */
  13354. conn->content_len = 0; /* No content */
  13355. }
  13356. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  13357. return 1;
  13358. }
  13359. /* conn is assumed to be valid in this internal function */
  13360. static int
  13361. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13362. {
  13363. const char *cl;
  13364. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13365. return 0;
  13366. }
  13367. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  13368. <= 0) {
  13369. mg_snprintf(conn,
  13370. NULL, /* No truncation check for ebuf */
  13371. ebuf,
  13372. ebuf_len,
  13373. "%s",
  13374. "Bad response");
  13375. *err = 400;
  13376. return 0;
  13377. }
  13378. /* Message is a valid response */
  13379. if ((cl = get_header(conn->response_info.http_headers,
  13380. conn->response_info.num_headers,
  13381. "Content-Length")) != NULL) {
  13382. /* Request/response has content length set */
  13383. char *endptr = NULL;
  13384. conn->content_len = strtoll(cl, &endptr, 10);
  13385. if (endptr == cl) {
  13386. mg_snprintf(conn,
  13387. NULL, /* No truncation check for ebuf */
  13388. ebuf,
  13389. ebuf_len,
  13390. "%s",
  13391. "Bad request");
  13392. *err = 411;
  13393. return 0;
  13394. }
  13395. /* Publish the content length back to the response info. */
  13396. conn->response_info.content_length = conn->content_len;
  13397. /* TODO: check if it is still used in response_info */
  13398. conn->request_info.content_length = conn->content_len;
  13399. } else if ((cl = get_header(conn->response_info.http_headers,
  13400. conn->response_info.num_headers,
  13401. "Transfer-Encoding")) != NULL
  13402. && !mg_strcasecmp(cl, "chunked")) {
  13403. conn->is_chunked = 1;
  13404. conn->content_len = -1; /* unknown content length */
  13405. } else {
  13406. conn->content_len = -1; /* unknown content length */
  13407. }
  13408. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  13409. return 1;
  13410. }
  13411. int
  13412. mg_get_response(struct mg_connection *conn,
  13413. char *ebuf,
  13414. size_t ebuf_len,
  13415. int timeout)
  13416. {
  13417. int err, ret;
  13418. char txt[32]; /* will not overflow */
  13419. struct mg_context *octx;
  13420. struct mg_context rctx;
  13421. if (ebuf_len > 0) {
  13422. ebuf[0] = '\0';
  13423. }
  13424. if (!conn) {
  13425. mg_snprintf(conn,
  13426. NULL, /* No truncation check for ebuf */
  13427. ebuf,
  13428. ebuf_len,
  13429. "%s",
  13430. "Parameter error");
  13431. return -1;
  13432. }
  13433. /* Implementation of API function for HTTP clients */
  13434. octx = conn->ctx;
  13435. rctx = *(conn->ctx);
  13436. if (timeout >= 0) {
  13437. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  13438. rctx.config[REQUEST_TIMEOUT] = txt;
  13439. /* Not required for non-blocking sockets.
  13440. set_sock_timeout(conn->client.sock, timeout);
  13441. */
  13442. } else {
  13443. rctx.config[REQUEST_TIMEOUT] = NULL;
  13444. }
  13445. conn->ctx = &rctx;
  13446. ret = get_response(conn, ebuf, ebuf_len, &err);
  13447. conn->ctx = octx;
  13448. #if defined(MG_LEGACY_INTERFACE)
  13449. /* TODO: 1) uri is deprecated;
  13450. * 2) here, ri.uri is the http response code */
  13451. conn->request_info.uri = conn->request_info.request_uri;
  13452. #endif
  13453. conn->request_info.local_uri = conn->request_info.request_uri;
  13454. /* TODO (mid): Define proper return values - maybe return length?
  13455. * For the first test use <0 for error and >0 for OK */
  13456. return (ret == 0) ? -1 : +1;
  13457. }
  13458. struct mg_connection *
  13459. mg_download(const char *host,
  13460. int port,
  13461. int use_ssl,
  13462. char *ebuf,
  13463. size_t ebuf_len,
  13464. const char *fmt,
  13465. ...)
  13466. {
  13467. struct mg_connection *conn;
  13468. va_list ap;
  13469. int i;
  13470. int reqerr;
  13471. if (ebuf_len > 0) {
  13472. ebuf[0] = '\0';
  13473. }
  13474. va_start(ap, fmt);
  13475. /* open a connection */
  13476. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  13477. if (conn != NULL) {
  13478. i = mg_vprintf(conn, fmt, ap);
  13479. if (i <= 0) {
  13480. mg_snprintf(conn,
  13481. NULL, /* No truncation check for ebuf */
  13482. ebuf,
  13483. ebuf_len,
  13484. "%s",
  13485. "Error sending request");
  13486. } else {
  13487. get_response(conn, ebuf, ebuf_len, &reqerr);
  13488. #if defined(MG_LEGACY_INTERFACE)
  13489. /* TODO: 1) uri is deprecated;
  13490. * 2) here, ri.uri is the http response code */
  13491. conn->request_info.uri = conn->request_info.request_uri;
  13492. #endif
  13493. conn->request_info.local_uri = conn->request_info.request_uri;
  13494. }
  13495. }
  13496. /* if an error occured, close the connection */
  13497. if ((ebuf[0] != '\0') && (conn != NULL)) {
  13498. mg_close_connection(conn);
  13499. conn = NULL;
  13500. }
  13501. va_end(ap);
  13502. return conn;
  13503. }
  13504. struct websocket_client_thread_data {
  13505. struct mg_connection *conn;
  13506. mg_websocket_data_handler data_handler;
  13507. mg_websocket_close_handler close_handler;
  13508. void *callback_data;
  13509. };
  13510. #if defined(USE_WEBSOCKET)
  13511. #ifdef _WIN32
  13512. static unsigned __stdcall websocket_client_thread(void *data)
  13513. #else
  13514. static void *
  13515. websocket_client_thread(void *data)
  13516. #endif
  13517. {
  13518. struct websocket_client_thread_data *cdata =
  13519. (struct websocket_client_thread_data *)data;
  13520. mg_set_thread_name("ws-clnt");
  13521. if (cdata->conn->ctx) {
  13522. if (cdata->conn->ctx->callbacks.init_thread) {
  13523. /* 3 indicates a websocket client thread */
  13524. /* TODO: check if conn->ctx can be set */
  13525. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  13526. }
  13527. }
  13528. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  13529. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  13530. if (cdata->close_handler != NULL) {
  13531. cdata->close_handler(cdata->conn, cdata->callback_data);
  13532. }
  13533. /* The websocket_client context has only this thread. If it runs out,
  13534. set the stop_flag to 2 (= "stopped"). */
  13535. cdata->conn->ctx->stop_flag = 2;
  13536. mg_free((void *)cdata);
  13537. #ifdef _WIN32
  13538. return 0;
  13539. #else
  13540. return NULL;
  13541. #endif
  13542. }
  13543. #endif
  13544. struct mg_connection *
  13545. mg_connect_websocket_client(const char *host,
  13546. int port,
  13547. int use_ssl,
  13548. char *error_buffer,
  13549. size_t error_buffer_size,
  13550. const char *path,
  13551. const char *origin,
  13552. mg_websocket_data_handler data_func,
  13553. mg_websocket_close_handler close_func,
  13554. void *user_data)
  13555. {
  13556. struct mg_connection *conn = NULL;
  13557. #if defined(USE_WEBSOCKET)
  13558. struct mg_context *newctx = NULL;
  13559. struct websocket_client_thread_data *thread_data;
  13560. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  13561. static const char *handshake_req;
  13562. if (origin != NULL) {
  13563. handshake_req = "GET %s HTTP/1.1\r\n"
  13564. "Host: %s\r\n"
  13565. "Upgrade: websocket\r\n"
  13566. "Connection: Upgrade\r\n"
  13567. "Sec-WebSocket-Key: %s\r\n"
  13568. "Sec-WebSocket-Version: 13\r\n"
  13569. "Origin: %s\r\n"
  13570. "\r\n";
  13571. } else {
  13572. handshake_req = "GET %s HTTP/1.1\r\n"
  13573. "Host: %s\r\n"
  13574. "Upgrade: websocket\r\n"
  13575. "Connection: Upgrade\r\n"
  13576. "Sec-WebSocket-Key: %s\r\n"
  13577. "Sec-WebSocket-Version: 13\r\n"
  13578. "\r\n";
  13579. }
  13580. /* Establish the client connection and request upgrade */
  13581. conn = mg_download(host,
  13582. port,
  13583. use_ssl,
  13584. error_buffer,
  13585. error_buffer_size,
  13586. handshake_req,
  13587. path,
  13588. host,
  13589. magic,
  13590. origin);
  13591. /* Connection object will be null if something goes wrong */
  13592. if (conn == NULL) {
  13593. if (!*error_buffer) {
  13594. /* There should be already an error message */
  13595. mg_snprintf(conn,
  13596. NULL, /* No truncation check for ebuf */
  13597. error_buffer,
  13598. error_buffer_size,
  13599. "Unexpected error");
  13600. }
  13601. return NULL;
  13602. }
  13603. if (conn->response_info.status_code != 101) {
  13604. /* We sent an "upgrade" request. For a correct websocket
  13605. * protocol handshake, we expect a "101 Continue" response.
  13606. * Otherwise it is a protocol violation. Maybe the HTTP
  13607. * Server does not know websockets. */
  13608. if (!*error_buffer) {
  13609. /* set an error, if not yet set */
  13610. mg_snprintf(conn,
  13611. NULL, /* No truncation check for ebuf */
  13612. error_buffer,
  13613. error_buffer_size,
  13614. "Unexpected server reply");
  13615. }
  13616. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  13617. mg_free(conn);
  13618. return NULL;
  13619. }
  13620. /* For client connections, mg_context is fake. Since we need to set a
  13621. * callback function, we need to create a copy and modify it. */
  13622. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  13623. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  13624. newctx->user_data = user_data;
  13625. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  13626. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  13627. newctx->worker_threadids =
  13628. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  13629. sizeof(pthread_t),
  13630. newctx);
  13631. conn->ctx = newctx;
  13632. thread_data = (struct websocket_client_thread_data *)
  13633. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  13634. thread_data->conn = conn;
  13635. thread_data->data_handler = data_func;
  13636. thread_data->close_handler = close_func;
  13637. thread_data->callback_data = user_data;
  13638. /* Start a thread to read the websocket client connection
  13639. * This thread will automatically stop when mg_disconnect is
  13640. * called on the client connection */
  13641. if (mg_start_thread_with_id(websocket_client_thread,
  13642. (void *)thread_data,
  13643. newctx->worker_threadids) != 0) {
  13644. mg_free((void *)thread_data);
  13645. mg_free((void *)newctx->worker_threadids);
  13646. mg_free((void *)newctx);
  13647. mg_free((void *)conn);
  13648. conn = NULL;
  13649. DEBUG_TRACE("%s",
  13650. "Websocket client connect thread could not be started\r\n");
  13651. }
  13652. #else
  13653. /* Appease "unused parameter" warnings */
  13654. (void)host;
  13655. (void)port;
  13656. (void)use_ssl;
  13657. (void)error_buffer;
  13658. (void)error_buffer_size;
  13659. (void)path;
  13660. (void)origin;
  13661. (void)user_data;
  13662. (void)data_func;
  13663. (void)close_func;
  13664. #endif
  13665. return conn;
  13666. }
  13667. /* Prepare connection data structure */
  13668. static void
  13669. init_connection(struct mg_connection *conn)
  13670. {
  13671. /* Is keep alive allowed by the server */
  13672. int keep_alive_enabled =
  13673. !mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  13674. if (!keep_alive_enabled) {
  13675. conn->must_close = 1;
  13676. }
  13677. /* Important: on new connection, reset the receiving buffer. Credit
  13678. * goes to crule42. */
  13679. conn->data_len = 0;
  13680. conn->handled_requests = 0;
  13681. mg_set_user_connection_data(conn, NULL);
  13682. #if defined(USE_SERVER_STATS)
  13683. conn->conn_state = 2; /* init */
  13684. #endif
  13685. /* call the init_connection callback if assigned */
  13686. if (conn->ctx->callbacks.init_connection != NULL) {
  13687. if (conn->ctx->context_type == CONTEXT_SERVER) {
  13688. void *conn_data = NULL;
  13689. conn->ctx->callbacks.init_connection(conn, &conn_data);
  13690. mg_set_user_connection_data(conn, conn_data);
  13691. }
  13692. }
  13693. }
  13694. /* Process a connection - may handle multiple requests
  13695. * using the same connection.
  13696. * Must be called with a valid connection (conn and
  13697. * conn->ctx must be valid).
  13698. */
  13699. static void
  13700. process_new_connection(struct mg_connection *conn)
  13701. {
  13702. struct mg_request_info *ri = &conn->request_info;
  13703. int keep_alive, discard_len;
  13704. char ebuf[100];
  13705. const char *hostend;
  13706. int reqerr, uri_type;
  13707. #if defined(USE_SERVER_STATS)
  13708. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  13709. mg_atomic_add(&(conn->ctx->total_connections), 1);
  13710. if (mcon > (conn->ctx->max_connections)) {
  13711. /* could use atomic compare exchange, but this
  13712. * seems overkill for statistics data */
  13713. conn->ctx->max_connections = mcon;
  13714. }
  13715. #endif
  13716. init_connection(conn);
  13717. DEBUG_TRACE("Start processing connection from %s",
  13718. conn->request_info.remote_addr);
  13719. /* Loop over multiple requests sent using the same connection
  13720. * (while "keep alive"). */
  13721. do {
  13722. DEBUG_TRACE("calling get_request (%i times for this connection)",
  13723. conn->handled_requests + 1);
  13724. #if defined(USE_SERVER_STATS)
  13725. conn->conn_state = 3; /* ready */
  13726. #endif
  13727. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  13728. /* The request sent by the client could not be understood by
  13729. * the server, or it was incomplete or a timeout. Send an
  13730. * error message and close the connection. */
  13731. if (reqerr > 0) {
  13732. /*assert(ebuf[0] != '\0');*/
  13733. mg_send_http_error(conn, reqerr, "%s", ebuf);
  13734. }
  13735. } else if (strcmp(ri->http_version, "1.0")
  13736. && strcmp(ri->http_version, "1.1")) {
  13737. mg_snprintf(conn,
  13738. NULL, /* No truncation check for ebuf */
  13739. ebuf,
  13740. sizeof(ebuf),
  13741. "Bad HTTP version: [%s]",
  13742. ri->http_version);
  13743. mg_send_http_error(conn, 505, "%s", ebuf);
  13744. }
  13745. if (ebuf[0] == '\0') {
  13746. uri_type = get_uri_type(conn->request_info.request_uri);
  13747. switch (uri_type) {
  13748. case 1:
  13749. /* Asterisk */
  13750. conn->request_info.local_uri = NULL;
  13751. break;
  13752. case 2:
  13753. /* relative uri */
  13754. conn->request_info.local_uri = conn->request_info.request_uri;
  13755. break;
  13756. case 3:
  13757. case 4:
  13758. /* absolute uri (with/without port) */
  13759. hostend = get_rel_url_at_current_server(
  13760. conn->request_info.request_uri, conn);
  13761. if (hostend) {
  13762. conn->request_info.local_uri = hostend;
  13763. } else {
  13764. conn->request_info.local_uri = NULL;
  13765. }
  13766. break;
  13767. default:
  13768. mg_snprintf(conn,
  13769. NULL, /* No truncation check for ebuf */
  13770. ebuf,
  13771. sizeof(ebuf),
  13772. "Invalid URI");
  13773. mg_send_http_error(conn, 400, "%s", ebuf);
  13774. conn->request_info.local_uri = NULL;
  13775. break;
  13776. }
  13777. #if defined(MG_LEGACY_INTERFACE)
  13778. /* Legacy before split into local_uri and request_uri */
  13779. conn->request_info.uri = conn->request_info.local_uri;
  13780. #endif
  13781. }
  13782. DEBUG_TRACE("http: %s, error: %s",
  13783. (ri->http_version ? ri->http_version : "none"),
  13784. (ebuf[0] ? ebuf : "none"));
  13785. if (ebuf[0] == '\0') {
  13786. if (conn->request_info.local_uri) {
  13787. /* handle request to local server */
  13788. #if defined(USE_SERVER_STATS)
  13789. conn->conn_state = 4; /* processing */
  13790. #endif
  13791. handle_request(conn);
  13792. #if defined(USE_SERVER_STATS)
  13793. conn->conn_state = 5; /* processed */
  13794. mg_atomic_add(&(conn->ctx->total_data_read),
  13795. conn->consumed_content);
  13796. mg_atomic_add(&(conn->ctx->total_data_written),
  13797. conn->num_bytes_sent);
  13798. #endif
  13799. DEBUG_TRACE("%s", "handle_request done");
  13800. if (conn->ctx->callbacks.end_request != NULL) {
  13801. conn->ctx->callbacks.end_request(conn, conn->status_code);
  13802. DEBUG_TRACE("%s", "end_request callback done");
  13803. }
  13804. log_access(conn);
  13805. } else {
  13806. /* TODO: handle non-local request (PROXY) */
  13807. conn->must_close = 1;
  13808. }
  13809. } else {
  13810. conn->must_close = 1;
  13811. }
  13812. if (ri->remote_user != NULL) {
  13813. mg_free((void *)ri->remote_user);
  13814. /* Important! When having connections with and without auth
  13815. * would cause double free and then crash */
  13816. ri->remote_user = NULL;
  13817. }
  13818. /* NOTE(lsm): order is important here. should_keep_alive() call
  13819. * is using parsed request, which will be invalid after
  13820. * memmove's below.
  13821. * Therefore, memorize should_keep_alive() result now for later
  13822. * use in loop exit condition. */
  13823. keep_alive = (conn->ctx->stop_flag == 0) && should_keep_alive(conn)
  13824. && (conn->content_len >= 0);
  13825. /* Discard all buffered data for this request */
  13826. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  13827. && ((conn->request_len + conn->content_len)
  13828. < (int64_t)conn->data_len))
  13829. ? (int)(conn->request_len + conn->content_len)
  13830. : conn->data_len;
  13831. /*assert(discard_len >= 0);*/
  13832. if (discard_len < 0) {
  13833. DEBUG_TRACE("internal error: discard_len = %li",
  13834. (long int)discard_len);
  13835. break;
  13836. }
  13837. conn->data_len -= discard_len;
  13838. if (conn->data_len > 0) {
  13839. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  13840. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  13841. }
  13842. /* assert(conn->data_len >= 0); */
  13843. /* assert(conn->data_len <= conn->buf_size); */
  13844. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  13845. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  13846. (long int)conn->data_len,
  13847. (long int)conn->buf_size);
  13848. break;
  13849. }
  13850. conn->handled_requests++;
  13851. } while (keep_alive);
  13852. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  13853. conn->request_info.remote_addr,
  13854. difftime(time(NULL), conn->conn_birth_time));
  13855. close_connection(conn);
  13856. #if defined(USE_SERVER_STATS)
  13857. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  13858. mg_atomic_dec(&(conn->ctx->active_connections));
  13859. #endif
  13860. }
  13861. #if defined(ALTERNATIVE_QUEUE)
  13862. static void
  13863. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13864. {
  13865. unsigned int i;
  13866. for (;;) {
  13867. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13868. /* find a free worker slot and signal it */
  13869. if (ctx->client_socks[i].in_use == 0) {
  13870. ctx->client_socks[i] = *sp;
  13871. ctx->client_socks[i].in_use = 1;
  13872. event_signal(ctx->client_wait_events[i]);
  13873. return;
  13874. }
  13875. }
  13876. /* queue is full */
  13877. mg_sleep(1);
  13878. }
  13879. }
  13880. static int
  13881. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13882. {
  13883. DEBUG_TRACE("%s", "going idle");
  13884. ctx->client_socks[thread_index].in_use = 0;
  13885. event_wait(ctx->client_wait_events[thread_index]);
  13886. *sp = ctx->client_socks[thread_index];
  13887. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13888. return !ctx->stop_flag;
  13889. }
  13890. #else /* ALTERNATIVE_QUEUE */
  13891. /* Worker threads take accepted socket from the queue */
  13892. static int
  13893. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13894. {
  13895. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13896. (void)thread_index;
  13897. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13898. DEBUG_TRACE("%s", "going idle");
  13899. /* If the queue is empty, wait. We're idle at this point. */
  13900. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  13901. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  13902. }
  13903. /* If we're stopping, sq_head may be equal to sq_tail. */
  13904. if (ctx->sq_head > ctx->sq_tail) {
  13905. /* Copy socket from the queue and increment tail */
  13906. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  13907. ctx->sq_tail++;
  13908. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13909. /* Wrap pointers if needed */
  13910. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  13911. ctx->sq_tail -= QUEUE_SIZE(ctx);
  13912. ctx->sq_head -= QUEUE_SIZE(ctx);
  13913. }
  13914. }
  13915. (void)pthread_cond_signal(&ctx->sq_empty);
  13916. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13917. return !ctx->stop_flag;
  13918. #undef QUEUE_SIZE
  13919. }
  13920. /* Master thread adds accepted socket to a queue */
  13921. static void
  13922. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13923. {
  13924. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13925. if (!ctx) {
  13926. return;
  13927. }
  13928. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13929. /* If the queue is full, wait */
  13930. while ((ctx->stop_flag == 0)
  13931. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  13932. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  13933. }
  13934. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  13935. /* Copy socket to the queue and increment head */
  13936. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  13937. ctx->sq_head++;
  13938. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  13939. }
  13940. (void)pthread_cond_signal(&ctx->sq_full);
  13941. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13942. #undef QUEUE_SIZE
  13943. }
  13944. #endif /* ALTERNATIVE_QUEUE */
  13945. struct worker_thread_args {
  13946. struct mg_context *ctx;
  13947. int index;
  13948. };
  13949. static void *
  13950. worker_thread_run(struct worker_thread_args *thread_args)
  13951. {
  13952. struct mg_context *ctx = thread_args->ctx;
  13953. struct mg_connection *conn;
  13954. struct mg_workerTLS tls;
  13955. #if defined(MG_LEGACY_INTERFACE)
  13956. uint32_t addr;
  13957. #endif
  13958. mg_set_thread_name("worker");
  13959. tls.is_master = 0;
  13960. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13961. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13962. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13963. #endif
  13964. /* Initialize thread local storage before calling any callback */
  13965. pthread_setspecific(sTlsKey, &tls);
  13966. if (ctx->callbacks.init_thread) {
  13967. /* call init_thread for a worker thread (type 1) */
  13968. ctx->callbacks.init_thread(ctx, 1);
  13969. }
  13970. /* Connection structure has been pre-allocated */
  13971. if (((int)thread_args->index < 0)
  13972. || ((unsigned)thread_args->index
  13973. >= (unsigned)ctx->cfg_worker_threads)) {
  13974. mg_cry(fc(ctx),
  13975. "Internal error: Invalid worker index %i",
  13976. (int)thread_args->index);
  13977. return NULL;
  13978. }
  13979. conn = ctx->worker_connections + thread_args->index;
  13980. /* Request buffers are not pre-allocated. They are private to the
  13981. * request and do not contain any state information that might be
  13982. * of interest to anyone observing a server status. */
  13983. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->ctx);
  13984. if (conn->buf == NULL) {
  13985. mg_cry(fc(ctx),
  13986. "Out of memory: Cannot allocate buffer for worker %i",
  13987. (int)thread_args->index);
  13988. return NULL;
  13989. }
  13990. conn->buf_size = (int)ctx->max_request_size;
  13991. conn->ctx = ctx;
  13992. conn->thread_index = thread_args->index;
  13993. conn->request_info.user_data = ctx->user_data;
  13994. /* Allocate a mutex for this connection to allow communication both
  13995. * within the request handler and from elsewhere in the application
  13996. */
  13997. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13998. #if defined(USE_SERVER_STATS)
  13999. conn->conn_state = 1; /* not consumed */
  14000. #endif
  14001. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  14002. * signal sq_empty condvar to wake up the master waiting in
  14003. * produce_socket() */
  14004. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  14005. conn->conn_birth_time = time(NULL);
  14006. /* Fill in IP, port info early so even if SSL setup below fails,
  14007. * error handler would have the corresponding info.
  14008. * Thanks to Johannes Winkelmann for the patch.
  14009. */
  14010. #if defined(USE_IPV6)
  14011. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  14012. conn->request_info.remote_port =
  14013. ntohs(conn->client.rsa.sin6.sin6_port);
  14014. } else
  14015. #endif
  14016. {
  14017. conn->request_info.remote_port =
  14018. ntohs(conn->client.rsa.sin.sin_port);
  14019. }
  14020. sockaddr_to_string(conn->request_info.remote_addr,
  14021. sizeof(conn->request_info.remote_addr),
  14022. &conn->client.rsa);
  14023. DEBUG_TRACE("Start processing connection from %s",
  14024. conn->request_info.remote_addr);
  14025. #if defined(MG_LEGACY_INTERFACE)
  14026. /* This legacy interface only works for the IPv4 case */
  14027. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  14028. memcpy(&conn->request_info.remote_ip, &addr, 4);
  14029. #endif
  14030. conn->request_info.is_ssl = conn->client.is_ssl;
  14031. if (conn->client.is_ssl) {
  14032. #ifndef NO_SSL
  14033. /* HTTPS connection */
  14034. if (sslize(conn,
  14035. conn->ctx->ssl_ctx,
  14036. SSL_accept,
  14037. &(conn->ctx->stop_flag))) {
  14038. /* Get SSL client certificate information (if set) */
  14039. ssl_get_client_cert_info(conn);
  14040. /* process HTTPS connection */
  14041. process_new_connection(conn);
  14042. /* Free client certificate info */
  14043. if (conn->request_info.client_cert) {
  14044. mg_free((void *)(conn->request_info.client_cert->subject));
  14045. mg_free((void *)(conn->request_info.client_cert->issuer));
  14046. mg_free((void *)(conn->request_info.client_cert->serial));
  14047. mg_free((void *)(conn->request_info.client_cert->finger));
  14048. conn->request_info.client_cert->subject = 0;
  14049. conn->request_info.client_cert->issuer = 0;
  14050. conn->request_info.client_cert->serial = 0;
  14051. conn->request_info.client_cert->finger = 0;
  14052. mg_free(conn->request_info.client_cert);
  14053. conn->request_info.client_cert = 0;
  14054. }
  14055. }
  14056. #endif
  14057. } else {
  14058. /* process HTTP connection */
  14059. process_new_connection(conn);
  14060. }
  14061. DEBUG_TRACE("%s", "Connection closed");
  14062. }
  14063. pthread_setspecific(sTlsKey, NULL);
  14064. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14065. CloseHandle(tls.pthread_cond_helper_mutex);
  14066. #endif
  14067. pthread_mutex_destroy(&conn->mutex);
  14068. /* Free the request buffer. */
  14069. conn->buf_size = 0;
  14070. mg_free(conn->buf);
  14071. conn->buf = NULL;
  14072. #if defined(USE_SERVER_STATS)
  14073. conn->conn_state = 9; /* done */
  14074. #endif
  14075. DEBUG_TRACE("%s", "exiting");
  14076. return NULL;
  14077. }
  14078. /* Threads have different return types on Windows and Unix. */
  14079. #ifdef _WIN32
  14080. static unsigned __stdcall worker_thread(void *thread_func_param)
  14081. {
  14082. struct worker_thread_args *pwta =
  14083. (struct worker_thread_args *)thread_func_param;
  14084. worker_thread_run(pwta);
  14085. mg_free(thread_func_param);
  14086. return 0;
  14087. }
  14088. #else
  14089. static void *
  14090. worker_thread(void *thread_func_param)
  14091. {
  14092. struct worker_thread_args *pwta =
  14093. (struct worker_thread_args *)thread_func_param;
  14094. worker_thread_run(pwta);
  14095. mg_free(thread_func_param);
  14096. return NULL;
  14097. }
  14098. #endif /* _WIN32 */
  14099. static void
  14100. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  14101. {
  14102. struct socket so;
  14103. char src_addr[IP_ADDR_STR_LEN];
  14104. socklen_t len = sizeof(so.rsa);
  14105. int on = 1;
  14106. if (!listener) {
  14107. return;
  14108. }
  14109. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  14110. == INVALID_SOCKET) {
  14111. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  14112. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  14113. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  14114. closesocket(so.sock);
  14115. } else {
  14116. /* Put so socket structure into the queue */
  14117. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  14118. set_close_on_exec(so.sock, fc(ctx));
  14119. so.is_ssl = listener->is_ssl;
  14120. so.ssl_redir = listener->ssl_redir;
  14121. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  14122. mg_cry(fc(ctx),
  14123. "%s: getsockname() failed: %s",
  14124. __func__,
  14125. strerror(ERRNO));
  14126. }
  14127. /* Set TCP keep-alive. This is needed because if HTTP-level
  14128. * keep-alive
  14129. * is enabled, and client resets the connection, server won't get
  14130. * TCP FIN or RST and will keep the connection open forever. With
  14131. * TCP keep-alive, next keep-alive handshake will figure out that
  14132. * the client is down and will close the server end.
  14133. * Thanks to Igor Klopov who suggested the patch. */
  14134. if (setsockopt(so.sock,
  14135. SOL_SOCKET,
  14136. SO_KEEPALIVE,
  14137. (SOCK_OPT_TYPE)&on,
  14138. sizeof(on)) != 0) {
  14139. mg_cry(fc(ctx),
  14140. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  14141. __func__,
  14142. strerror(ERRNO));
  14143. }
  14144. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  14145. * to effectively fill up the underlying IP packet payload and
  14146. * reduce the overhead of sending lots of small buffers. However
  14147. * this hurts the server's throughput (ie. operations per second)
  14148. * when HTTP 1.1 persistent connections are used and the responses
  14149. * are relatively small (eg. less than 1400 bytes).
  14150. */
  14151. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  14152. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  14153. if (set_tcp_nodelay(so.sock, 1) != 0) {
  14154. mg_cry(fc(ctx),
  14155. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  14156. __func__,
  14157. strerror(ERRNO));
  14158. }
  14159. }
  14160. /* We are using non-blocking sockets. Thus, the
  14161. * set_sock_timeout(so.sock, timeout);
  14162. * call is no longer required. */
  14163. /* The "non blocking" property should already be
  14164. * inherited from the parent socket. Set it for
  14165. * non-compliant socket implementations. */
  14166. set_non_blocking_mode(so.sock);
  14167. so.in_use = 0;
  14168. produce_socket(ctx, &so);
  14169. }
  14170. }
  14171. static void
  14172. master_thread_run(void *thread_func_param)
  14173. {
  14174. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  14175. struct mg_workerTLS tls;
  14176. struct pollfd *pfd;
  14177. unsigned int i;
  14178. unsigned int workerthreadcount;
  14179. if (!ctx) {
  14180. return;
  14181. }
  14182. mg_set_thread_name("master");
  14183. /* Increase priority of the master thread */
  14184. #if defined(_WIN32)
  14185. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  14186. #elif defined(USE_MASTER_THREAD_PRIORITY)
  14187. int min_prio = sched_get_priority_min(SCHED_RR);
  14188. int max_prio = sched_get_priority_max(SCHED_RR);
  14189. if ((min_prio >= 0) && (max_prio >= 0)
  14190. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  14191. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  14192. struct sched_param sched_param = {0};
  14193. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  14194. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  14195. }
  14196. #endif
  14197. /* Initialize thread local storage */
  14198. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14199. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14200. #endif
  14201. tls.is_master = 1;
  14202. pthread_setspecific(sTlsKey, &tls);
  14203. if (ctx->callbacks.init_thread) {
  14204. /* Callback for the master thread (type 0) */
  14205. ctx->callbacks.init_thread(ctx, 0);
  14206. }
  14207. /* Server starts *now* */
  14208. ctx->start_time = time(NULL);
  14209. /* Start the server */
  14210. pfd = ctx->listening_socket_fds;
  14211. while (ctx->stop_flag == 0) {
  14212. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14213. pfd[i].fd = ctx->listening_sockets[i].sock;
  14214. pfd[i].events = POLLIN;
  14215. }
  14216. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  14217. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14218. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  14219. * successful poll, and POLLIN is defined as
  14220. * (POLLRDNORM | POLLRDBAND)
  14221. * Therefore, we're checking pfd[i].revents & POLLIN, not
  14222. * pfd[i].revents == POLLIN. */
  14223. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  14224. accept_new_connection(&ctx->listening_sockets[i], ctx);
  14225. }
  14226. }
  14227. }
  14228. }
  14229. /* Here stop_flag is 1 - Initiate shutdown. */
  14230. DEBUG_TRACE("%s", "stopping workers");
  14231. /* Stop signal received: somebody called mg_stop. Quit. */
  14232. close_all_listening_sockets(ctx);
  14233. /* Wakeup workers that are waiting for connections to handle. */
  14234. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14235. #if defined(ALTERNATIVE_QUEUE)
  14236. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14237. event_signal(ctx->client_wait_events[i]);
  14238. /* Since we know all sockets, we can shutdown the connections. */
  14239. if (ctx->client_socks[i].in_use) {
  14240. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  14241. }
  14242. }
  14243. #else
  14244. pthread_cond_broadcast(&ctx->sq_full);
  14245. #endif
  14246. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14247. /* Join all worker threads to avoid leaking threads. */
  14248. workerthreadcount = ctx->cfg_worker_threads;
  14249. for (i = 0; i < workerthreadcount; i++) {
  14250. if (ctx->worker_threadids[i] != 0) {
  14251. mg_join_thread(ctx->worker_threadids[i]);
  14252. }
  14253. }
  14254. #if defined(USE_LUA)
  14255. /* Free Lua state of lua background task */
  14256. if (ctx->lua_background_state) {
  14257. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14258. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  14259. if (lua_istable(lstate, -1)) {
  14260. reg_boolean(lstate, "shutdown", 1);
  14261. lua_pop(lstate, 1);
  14262. mg_sleep(2);
  14263. }
  14264. lua_close(lstate);
  14265. ctx->lua_background_state = 0;
  14266. }
  14267. #endif
  14268. DEBUG_TRACE("%s", "exiting");
  14269. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14270. CloseHandle(tls.pthread_cond_helper_mutex);
  14271. #endif
  14272. pthread_setspecific(sTlsKey, NULL);
  14273. /* Signal mg_stop() that we're done.
  14274. * WARNING: This must be the very last thing this
  14275. * thread does, as ctx becomes invalid after this line. */
  14276. ctx->stop_flag = 2;
  14277. }
  14278. /* Threads have different return types on Windows and Unix. */
  14279. #ifdef _WIN32
  14280. static unsigned __stdcall master_thread(void *thread_func_param)
  14281. {
  14282. master_thread_run(thread_func_param);
  14283. return 0;
  14284. }
  14285. #else
  14286. static void *
  14287. master_thread(void *thread_func_param)
  14288. {
  14289. master_thread_run(thread_func_param);
  14290. return NULL;
  14291. }
  14292. #endif /* _WIN32 */
  14293. static void
  14294. free_context(struct mg_context *ctx)
  14295. {
  14296. int i;
  14297. struct mg_handler_info *tmp_rh;
  14298. if (ctx == NULL) {
  14299. return;
  14300. }
  14301. if (ctx->callbacks.exit_context) {
  14302. ctx->callbacks.exit_context(ctx);
  14303. }
  14304. /* All threads exited, no sync is needed. Destroy thread mutex and
  14305. * condvars
  14306. */
  14307. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  14308. #if defined(ALTERNATIVE_QUEUE)
  14309. mg_free(ctx->client_socks);
  14310. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14311. event_destroy(ctx->client_wait_events[i]);
  14312. }
  14313. mg_free(ctx->client_wait_events);
  14314. #else
  14315. (void)pthread_cond_destroy(&ctx->sq_empty);
  14316. (void)pthread_cond_destroy(&ctx->sq_full);
  14317. #endif
  14318. /* Destroy other context global data structures mutex */
  14319. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  14320. #if defined(USE_TIMERS)
  14321. timers_exit(ctx);
  14322. #endif
  14323. /* Deallocate config parameters */
  14324. for (i = 0; i < NUM_OPTIONS; i++) {
  14325. if (ctx->config[i] != NULL) {
  14326. #if defined(_MSC_VER)
  14327. #pragma warning(suppress : 6001)
  14328. #endif
  14329. mg_free(ctx->config[i]);
  14330. }
  14331. }
  14332. /* Deallocate request handlers */
  14333. while (ctx->handlers) {
  14334. tmp_rh = ctx->handlers;
  14335. ctx->handlers = tmp_rh->next;
  14336. mg_free(tmp_rh->uri);
  14337. mg_free(tmp_rh);
  14338. }
  14339. #ifndef NO_SSL
  14340. /* Deallocate SSL context */
  14341. if (ctx->ssl_ctx != NULL) {
  14342. SSL_CTX_free(ctx->ssl_ctx);
  14343. }
  14344. #endif /* !NO_SSL */
  14345. /* Deallocate worker thread ID array */
  14346. if (ctx->worker_threadids != NULL) {
  14347. mg_free(ctx->worker_threadids);
  14348. }
  14349. /* Deallocate worker thread ID array */
  14350. if (ctx->worker_connections != NULL) {
  14351. mg_free(ctx->worker_connections);
  14352. }
  14353. /* deallocate system name string */
  14354. mg_free(ctx->systemName);
  14355. /* Deallocate context itself */
  14356. mg_free(ctx);
  14357. }
  14358. void
  14359. mg_stop(struct mg_context *ctx)
  14360. {
  14361. pthread_t mt;
  14362. if (!ctx) {
  14363. return;
  14364. }
  14365. /* We don't use a lock here. Calling mg_stop with the same ctx from
  14366. * two threads is not allowed. */
  14367. mt = ctx->masterthreadid;
  14368. if (mt == 0) {
  14369. return;
  14370. }
  14371. ctx->masterthreadid = 0;
  14372. /* Set stop flag, so all threads know they have to exit. */
  14373. ctx->stop_flag = 1;
  14374. /* Wait until everything has stopped. */
  14375. while (ctx->stop_flag != 2) {
  14376. (void)mg_sleep(10);
  14377. }
  14378. mg_join_thread(mt);
  14379. free_context(ctx);
  14380. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14381. (void)WSACleanup();
  14382. #endif /* _WIN32 && !__SYMBIAN32__ */
  14383. }
  14384. static void
  14385. get_system_name(char **sysName)
  14386. {
  14387. #if defined(_WIN32)
  14388. #if !defined(__SYMBIAN32__)
  14389. #if defined(_WIN32_WCE)
  14390. *sysName = mg_strdup("WinCE");
  14391. #else
  14392. char name[128];
  14393. DWORD dwVersion = 0;
  14394. DWORD dwMajorVersion = 0;
  14395. DWORD dwMinorVersion = 0;
  14396. DWORD dwBuild = 0;
  14397. BOOL wowRet, isWoW = FALSE;
  14398. #ifdef _MSC_VER
  14399. #pragma warning(push)
  14400. /* GetVersion was declared deprecated */
  14401. #pragma warning(disable : 4996)
  14402. #endif
  14403. dwVersion = GetVersion();
  14404. #ifdef _MSC_VER
  14405. #pragma warning(pop)
  14406. #endif
  14407. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14408. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14409. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  14410. (void)dwBuild;
  14411. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  14412. sprintf(name,
  14413. "Windows %u.%u%s",
  14414. (unsigned)dwMajorVersion,
  14415. (unsigned)dwMinorVersion,
  14416. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  14417. *sysName = mg_strdup(name);
  14418. #endif
  14419. #else
  14420. *sysName = mg_strdup("Symbian");
  14421. #endif
  14422. #else
  14423. struct utsname name;
  14424. memset(&name, 0, sizeof(name));
  14425. uname(&name);
  14426. *sysName = mg_strdup(name.sysname);
  14427. #endif
  14428. }
  14429. struct mg_context *
  14430. mg_start(const struct mg_callbacks *callbacks,
  14431. void *user_data,
  14432. const char **options)
  14433. {
  14434. struct mg_context *ctx;
  14435. const char *name, *value, *default_value;
  14436. int idx, ok, workerthreadcount;
  14437. unsigned int i;
  14438. int itmp;
  14439. void (*exit_callback)(const struct mg_context *ctx) = 0;
  14440. struct mg_workerTLS tls;
  14441. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14442. WSADATA data;
  14443. WSAStartup(MAKEWORD(2, 2), &data);
  14444. #endif /* _WIN32 && !__SYMBIAN32__ */
  14445. /* Allocate context and initialize reasonable general case defaults. */
  14446. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  14447. return NULL;
  14448. }
  14449. /* Random number generator will initialize at the first call */
  14450. ctx->auth_nonce_mask =
  14451. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  14452. if (mg_init_library_called == 0) {
  14453. /* Legacy INIT, if mg_start is called without mg_init_library.
  14454. * Note: This may cause a memory leak */
  14455. const char *ports_option =
  14456. config_options[LISTENING_PORTS].default_value;
  14457. if (options) {
  14458. const char **run_options = options;
  14459. const char *optname = config_options[LISTENING_PORTS].name;
  14460. /* Try to find the "listening_ports" option */
  14461. while (*run_options) {
  14462. if (!strcmp(*run_options, optname)) {
  14463. ports_option = run_options[1];
  14464. }
  14465. run_options += 2;
  14466. }
  14467. }
  14468. if (is_ssl_port_used(ports_option)) {
  14469. /* Initialize with SSL support */
  14470. mg_init_library(MG_FEATURES_TLS);
  14471. } else {
  14472. /* Initialize without SSL support */
  14473. mg_init_library(MG_FEATURES_DEFAULT);
  14474. }
  14475. }
  14476. tls.is_master = -1;
  14477. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14478. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14479. tls.pthread_cond_helper_mutex = NULL;
  14480. #endif
  14481. pthread_setspecific(sTlsKey, &tls);
  14482. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  14483. #if !defined(ALTERNATIVE_QUEUE)
  14484. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  14485. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  14486. #endif
  14487. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  14488. if (!ok) {
  14489. /* Fatal error - abort start. However, this situation should never
  14490. * occur in practice. */
  14491. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  14492. mg_free(ctx);
  14493. pthread_setspecific(sTlsKey, NULL);
  14494. return NULL;
  14495. }
  14496. if (callbacks) {
  14497. ctx->callbacks = *callbacks;
  14498. exit_callback = callbacks->exit_context;
  14499. ctx->callbacks.exit_context = 0;
  14500. }
  14501. ctx->user_data = user_data;
  14502. ctx->handlers = NULL;
  14503. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14504. ctx->shared_lua_websockets = 0;
  14505. #endif
  14506. while (options && (name = *options++) != NULL) {
  14507. if ((idx = get_option_index(name)) == -1) {
  14508. mg_cry(fc(ctx), "Invalid option: %s", name);
  14509. free_context(ctx);
  14510. pthread_setspecific(sTlsKey, NULL);
  14511. return NULL;
  14512. } else if ((value = *options++) == NULL) {
  14513. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  14514. free_context(ctx);
  14515. pthread_setspecific(sTlsKey, NULL);
  14516. return NULL;
  14517. }
  14518. if (ctx->config[idx] != NULL) {
  14519. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  14520. mg_free(ctx->config[idx]);
  14521. }
  14522. ctx->config[idx] = mg_strdup(value);
  14523. DEBUG_TRACE("[%s] -> [%s]", name, value);
  14524. }
  14525. /* Set default value if needed */
  14526. for (i = 0; config_options[i].name != NULL; i++) {
  14527. default_value = config_options[i].default_value;
  14528. if ((ctx->config[i] == NULL) && (default_value != NULL)) {
  14529. ctx->config[i] = mg_strdup(default_value);
  14530. }
  14531. }
  14532. itmp = atoi(ctx->config[MAX_REQUEST_SIZE]);
  14533. if (itmp < 1024) {
  14534. mg_cry(fc(ctx), "max_request_size too small");
  14535. free_context(ctx);
  14536. pthread_setspecific(sTlsKey, NULL);
  14537. return NULL;
  14538. }
  14539. ctx->max_request_size = (unsigned)itmp;
  14540. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  14541. if (workerthreadcount > MAX_WORKER_THREADS) {
  14542. mg_cry(fc(ctx), "Too many worker threads");
  14543. free_context(ctx);
  14544. pthread_setspecific(sTlsKey, NULL);
  14545. return NULL;
  14546. }
  14547. if (workerthreadcount <= 0) {
  14548. mg_cry(fc(ctx), "Invalid number of worker threads");
  14549. free_context(ctx);
  14550. pthread_setspecific(sTlsKey, NULL);
  14551. return NULL;
  14552. }
  14553. #if defined(NO_FILES)
  14554. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  14555. mg_cry(fc(ctx), "%s", "Document root must not be set");
  14556. free_context(ctx);
  14557. pthread_setspecific(sTlsKey, NULL);
  14558. return NULL;
  14559. }
  14560. #endif
  14561. get_system_name(&ctx->systemName);
  14562. #if defined(USE_LUA)
  14563. /* If a Lua background script has been configured, start it. */
  14564. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  14565. char ebuf[256];
  14566. lua_State *state = (void *)mg_prepare_lua_context_script(
  14567. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  14568. if (!state) {
  14569. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  14570. free_context(ctx);
  14571. pthread_setspecific(sTlsKey, NULL);
  14572. return NULL;
  14573. }
  14574. ctx->lua_background_state = (void *)state;
  14575. lua_newtable(state);
  14576. reg_boolean(state, "shutdown", 0);
  14577. struct vec opt_vec;
  14578. struct vec eq_vec;
  14579. const char *sparams = ctx->config[LUA_BACKGROUND_SCRIPT_PARAMS];
  14580. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  14581. reg_llstring(
  14582. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  14583. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  14584. break;
  14585. }
  14586. lua_setglobal(state, LUABACKGROUNDPARAMS);
  14587. } else {
  14588. ctx->lua_background_state = 0;
  14589. }
  14590. #endif
  14591. /* NOTE(lsm): order is important here. SSL certificates must
  14592. * be initialized before listening ports. UID must be set last. */
  14593. if (!set_gpass_option(ctx) ||
  14594. #if !defined(NO_SSL)
  14595. !set_ssl_option(ctx) ||
  14596. #endif
  14597. !set_ports_option(ctx) ||
  14598. #if !defined(_WIN32)
  14599. !set_uid_option(ctx) ||
  14600. #endif
  14601. !set_acl_option(ctx)) {
  14602. free_context(ctx);
  14603. pthread_setspecific(sTlsKey, NULL);
  14604. return NULL;
  14605. }
  14606. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  14607. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  14608. * won't kill the whole process. */
  14609. (void)signal(SIGPIPE, SIG_IGN);
  14610. #endif /* !_WIN32 && !__SYMBIAN32__ */
  14611. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  14612. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14613. sizeof(pthread_t),
  14614. ctx);
  14615. if (ctx->worker_threadids == NULL) {
  14616. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  14617. free_context(ctx);
  14618. pthread_setspecific(sTlsKey, NULL);
  14619. return NULL;
  14620. }
  14621. ctx->worker_connections =
  14622. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14623. sizeof(struct mg_connection),
  14624. ctx);
  14625. if (ctx->worker_connections == NULL) {
  14626. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  14627. free_context(ctx);
  14628. pthread_setspecific(sTlsKey, NULL);
  14629. return NULL;
  14630. }
  14631. #if defined(ALTERNATIVE_QUEUE)
  14632. ctx->client_wait_events =
  14633. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  14634. ctx->cfg_worker_threads,
  14635. ctx);
  14636. if (ctx->client_wait_events == NULL) {
  14637. mg_cry(fc(ctx), "Not enough memory for worker event array");
  14638. mg_free(ctx->worker_threadids);
  14639. free_context(ctx);
  14640. pthread_setspecific(sTlsKey, NULL);
  14641. return NULL;
  14642. }
  14643. ctx->client_socks =
  14644. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  14645. ctx->cfg_worker_threads,
  14646. ctx);
  14647. if (ctx->client_wait_events == NULL) {
  14648. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  14649. mg_free(ctx->client_socks);
  14650. mg_free(ctx->worker_threadids);
  14651. free_context(ctx);
  14652. pthread_setspecific(sTlsKey, NULL);
  14653. return NULL;
  14654. }
  14655. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14656. ctx->client_wait_events[i] = event_create();
  14657. if (ctx->client_wait_events[i] == 0) {
  14658. mg_cry(fc(ctx), "Error creating worker event %i", i);
  14659. while (i > 0) {
  14660. i--;
  14661. event_destroy(ctx->client_wait_events[i]);
  14662. }
  14663. mg_free(ctx->client_socks);
  14664. mg_free(ctx->worker_threadids);
  14665. free_context(ctx);
  14666. pthread_setspecific(sTlsKey, NULL);
  14667. return NULL;
  14668. }
  14669. }
  14670. #endif
  14671. #if defined(USE_TIMERS)
  14672. if (timers_init(ctx) != 0) {
  14673. mg_cry(fc(ctx), "Error creating timers");
  14674. free_context(ctx);
  14675. pthread_setspecific(sTlsKey, NULL);
  14676. return NULL;
  14677. }
  14678. #endif
  14679. /* Context has been created - init user libraries */
  14680. if (ctx->callbacks.init_context) {
  14681. ctx->callbacks.init_context(ctx);
  14682. }
  14683. ctx->callbacks.exit_context = exit_callback;
  14684. ctx->context_type = CONTEXT_SERVER; /* server context */
  14685. /* Start master (listening) thread */
  14686. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  14687. /* Start worker threads */
  14688. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14689. struct worker_thread_args *wta = (struct worker_thread_args *)
  14690. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  14691. if (wta) {
  14692. wta->ctx = ctx;
  14693. wta->index = (int)i;
  14694. }
  14695. if ((wta == NULL)
  14696. || (mg_start_thread_with_id(worker_thread,
  14697. wta,
  14698. &ctx->worker_threadids[i]) != 0)) {
  14699. /* thread was not created */
  14700. if (wta != NULL) {
  14701. mg_free(wta);
  14702. }
  14703. if (i > 0) {
  14704. mg_cry(fc(ctx),
  14705. "Cannot start worker thread %i: error %ld",
  14706. i + 1,
  14707. (long)ERRNO);
  14708. } else {
  14709. mg_cry(fc(ctx),
  14710. "Cannot create threads: error %ld",
  14711. (long)ERRNO);
  14712. free_context(ctx);
  14713. pthread_setspecific(sTlsKey, NULL);
  14714. return NULL;
  14715. }
  14716. break;
  14717. }
  14718. }
  14719. pthread_setspecific(sTlsKey, NULL);
  14720. return ctx;
  14721. }
  14722. /* Feature check API function */
  14723. unsigned
  14724. mg_check_feature(unsigned feature)
  14725. {
  14726. static const unsigned feature_set = 0
  14727. /* Set bits for available features according to API documentation.
  14728. * This bit mask is created at compile time, according to the active
  14729. * preprocessor defines. It is a single const value at runtime. */
  14730. #if !defined(NO_FILES)
  14731. | 0x0001u
  14732. #endif
  14733. #if !defined(NO_SSL)
  14734. | 0x0002u
  14735. #endif
  14736. #if !defined(NO_CGI)
  14737. | 0x0004u
  14738. #endif
  14739. #if defined(USE_IPV6)
  14740. | 0x0008u
  14741. #endif
  14742. #if defined(USE_WEBSOCKET)
  14743. | 0x0010u
  14744. #endif
  14745. #if defined(USE_LUA)
  14746. | 0x0020u
  14747. #endif
  14748. #if defined(USE_DUKTAPE)
  14749. | 0x0040u
  14750. #endif
  14751. #if !defined(NO_CACHING)
  14752. | 0x0080u
  14753. #endif
  14754. #if defined(USE_SERVER_STATS)
  14755. | 0x0100u
  14756. #endif
  14757. /* Set some extra bits not defined in the API documentation.
  14758. * These bits may change without further notice. */
  14759. #if defined(MG_LEGACY_INTERFACE)
  14760. | 0x8000u
  14761. #endif
  14762. #if defined(MEMORY_DEBUGGING)
  14763. | 0x0100u
  14764. #endif
  14765. #if defined(USE_TIMERS)
  14766. | 0x0200u
  14767. #endif
  14768. #if !defined(NO_NONCE_CHECK)
  14769. | 0x0400u
  14770. #endif
  14771. #if !defined(NO_POPEN)
  14772. | 0x0800u
  14773. #endif
  14774. ;
  14775. return (feature & feature_set);
  14776. }
  14777. /* strcat with additional NULL check to avoid clang scan-build warning. */
  14778. #define strcat0(a, b) \
  14779. { \
  14780. if ((a != NULL) && (b != NULL)) { \
  14781. strcat(a, b); \
  14782. } \
  14783. }
  14784. /* Get system information. It can be printed or stored by the caller.
  14785. * Return the size of available information. */
  14786. static int
  14787. mg_get_system_info_impl(char *buffer, int buflen)
  14788. {
  14789. char block[256];
  14790. int system_info_length = 0;
  14791. #if defined(_WIN32)
  14792. const char *eol = "\r\n";
  14793. #else
  14794. const char *eol = "\n";
  14795. #endif
  14796. const char *eoobj = "}";
  14797. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  14798. if ((buffer == NULL) || (buflen < 1)) {
  14799. buflen = 0;
  14800. } else {
  14801. *buffer = 0;
  14802. }
  14803. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  14804. system_info_length += (int)strlen(block);
  14805. if (system_info_length < buflen) {
  14806. strcat0(buffer, block);
  14807. }
  14808. /* Server version */
  14809. {
  14810. const char *version = mg_version();
  14811. mg_snprintf(NULL,
  14812. NULL,
  14813. block,
  14814. sizeof(block),
  14815. "\"version\" : \"%s\",%s",
  14816. version,
  14817. eol);
  14818. system_info_length += (int)strlen(block);
  14819. if (system_info_length < buflen) {
  14820. strcat0(buffer, block);
  14821. }
  14822. }
  14823. /* System info */
  14824. {
  14825. #if defined(_WIN32)
  14826. #if !defined(__SYMBIAN32__)
  14827. DWORD dwVersion = 0;
  14828. DWORD dwMajorVersion = 0;
  14829. DWORD dwMinorVersion = 0;
  14830. SYSTEM_INFO si;
  14831. GetSystemInfo(&si);
  14832. #ifdef _MSC_VER
  14833. #pragma warning(push)
  14834. /* GetVersion was declared deprecated */
  14835. #pragma warning(disable : 4996)
  14836. #endif
  14837. dwVersion = GetVersion();
  14838. #ifdef _MSC_VER
  14839. #pragma warning(pop)
  14840. #endif
  14841. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14842. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14843. mg_snprintf(NULL,
  14844. NULL,
  14845. block,
  14846. sizeof(block),
  14847. "\"os\" : \"Windows %u.%u\",%s",
  14848. (unsigned)dwMajorVersion,
  14849. (unsigned)dwMinorVersion,
  14850. eol);
  14851. system_info_length += (int)strlen(block);
  14852. if (system_info_length < buflen) {
  14853. strcat0(buffer, block);
  14854. }
  14855. mg_snprintf(NULL,
  14856. NULL,
  14857. block,
  14858. sizeof(block),
  14859. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  14860. (unsigned)si.wProcessorArchitecture,
  14861. (unsigned)si.dwNumberOfProcessors,
  14862. (unsigned)si.dwActiveProcessorMask,
  14863. eol);
  14864. system_info_length += (int)strlen(block);
  14865. if (system_info_length < buflen) {
  14866. strcat0(buffer, block);
  14867. }
  14868. #else
  14869. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  14870. system_info_length += (int)strlen(block);
  14871. if (system_info_length < buflen) {
  14872. strcat0(buffer, block);
  14873. }
  14874. #endif
  14875. #else
  14876. struct utsname name;
  14877. memset(&name, 0, sizeof(name));
  14878. uname(&name);
  14879. mg_snprintf(NULL,
  14880. NULL,
  14881. block,
  14882. sizeof(block),
  14883. "\"os\" : \"%s %s (%s) - %s\",%s",
  14884. name.sysname,
  14885. name.version,
  14886. name.release,
  14887. name.machine,
  14888. eol);
  14889. system_info_length += (int)strlen(block);
  14890. if (system_info_length < buflen) {
  14891. strcat0(buffer, block);
  14892. }
  14893. #endif
  14894. }
  14895. /* Features */
  14896. {
  14897. mg_snprintf(NULL,
  14898. NULL,
  14899. block,
  14900. sizeof(block),
  14901. "\"features\" : %lu,%s"
  14902. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  14903. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  14904. eol,
  14905. mg_check_feature(1) ? " Files" : "",
  14906. mg_check_feature(2) ? " HTTPS" : "",
  14907. mg_check_feature(4) ? " CGI" : "",
  14908. mg_check_feature(8) ? " IPv6" : "",
  14909. mg_check_feature(16) ? " WebSockets" : "",
  14910. mg_check_feature(32) ? " Lua" : "",
  14911. mg_check_feature(64) ? " JavaScript" : "",
  14912. mg_check_feature(128) ? " Cache" : "",
  14913. mg_check_feature(256) ? " Stats" : "",
  14914. eol);
  14915. system_info_length += (int)strlen(block);
  14916. if (system_info_length < buflen) {
  14917. strcat0(buffer, block);
  14918. }
  14919. #ifdef USE_LUA
  14920. mg_snprintf(NULL,
  14921. NULL,
  14922. block,
  14923. sizeof(block),
  14924. "\"lua_version\" : \"%u (%s)\",%s",
  14925. (unsigned)LUA_VERSION_NUM,
  14926. LUA_RELEASE,
  14927. eol);
  14928. system_info_length += (int)strlen(block);
  14929. if (system_info_length < buflen) {
  14930. strcat0(buffer, block);
  14931. }
  14932. #endif
  14933. #if defined(USE_DUKTAPE)
  14934. mg_snprintf(NULL,
  14935. NULL,
  14936. block,
  14937. sizeof(block),
  14938. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  14939. (unsigned)DUK_VERSION / 10000,
  14940. ((unsigned)DUK_VERSION / 100) % 100,
  14941. (unsigned)DUK_VERSION % 100,
  14942. eol);
  14943. system_info_length += (int)strlen(block);
  14944. if (system_info_length < buflen) {
  14945. strcat0(buffer, block);
  14946. }
  14947. #endif
  14948. }
  14949. /* Build date */
  14950. {
  14951. #if defined(__GNUC__)
  14952. #pragma GCC diagnostic push
  14953. /* Disable bogus compiler warning -Wdate-time */
  14954. #pragma GCC diagnostic ignored "-Wall"
  14955. #pragma GCC diagnostic ignored "-Werror"
  14956. #endif
  14957. mg_snprintf(NULL,
  14958. NULL,
  14959. block,
  14960. sizeof(block),
  14961. "\"build\" : \"%s\",%s",
  14962. __DATE__,
  14963. eol);
  14964. #if defined(__GNUC__)
  14965. #pragma GCC diagnostic pop
  14966. #endif
  14967. system_info_length += (int)strlen(block);
  14968. if (system_info_length < buflen) {
  14969. strcat0(buffer, block);
  14970. }
  14971. }
  14972. /* Compiler information */
  14973. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  14974. {
  14975. #if defined(_MSC_VER)
  14976. mg_snprintf(NULL,
  14977. NULL,
  14978. block,
  14979. sizeof(block),
  14980. "\"compiler\" : \"MSC: %u (%u)\",%s",
  14981. (unsigned)_MSC_VER,
  14982. (unsigned)_MSC_FULL_VER,
  14983. eol);
  14984. system_info_length += (int)strlen(block);
  14985. if (system_info_length < buflen) {
  14986. strcat0(buffer, block);
  14987. }
  14988. #elif defined(__MINGW64__)
  14989. mg_snprintf(NULL,
  14990. NULL,
  14991. block,
  14992. sizeof(block),
  14993. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  14994. (unsigned)__MINGW64_VERSION_MAJOR,
  14995. (unsigned)__MINGW64_VERSION_MINOR,
  14996. eol);
  14997. system_info_length += (int)strlen(block);
  14998. if (system_info_length < buflen) {
  14999. strcat0(buffer, block);
  15000. }
  15001. mg_snprintf(NULL,
  15002. NULL,
  15003. block,
  15004. sizeof(block),
  15005. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15006. (unsigned)__MINGW32_MAJOR_VERSION,
  15007. (unsigned)__MINGW32_MINOR_VERSION,
  15008. eol);
  15009. system_info_length += (int)strlen(block);
  15010. if (system_info_length < buflen) {
  15011. strcat0(buffer, block);
  15012. }
  15013. #elif defined(__MINGW32__)
  15014. mg_snprintf(NULL,
  15015. NULL,
  15016. block,
  15017. sizeof(block),
  15018. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15019. (unsigned)__MINGW32_MAJOR_VERSION,
  15020. (unsigned)__MINGW32_MINOR_VERSION,
  15021. eol);
  15022. system_info_length += (int)strlen(block);
  15023. if (system_info_length < buflen) {
  15024. strcat0(buffer, block);
  15025. }
  15026. #elif defined(__clang__)
  15027. mg_snprintf(NULL,
  15028. NULL,
  15029. block,
  15030. sizeof(block),
  15031. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  15032. __clang_major__,
  15033. __clang_minor__,
  15034. __clang_patchlevel__,
  15035. __clang_version__,
  15036. eol);
  15037. system_info_length += (int)strlen(block);
  15038. if (system_info_length < buflen) {
  15039. strcat0(buffer, block);
  15040. }
  15041. #elif defined(__GNUC__)
  15042. mg_snprintf(NULL,
  15043. NULL,
  15044. block,
  15045. sizeof(block),
  15046. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  15047. (unsigned)__GNUC__,
  15048. (unsigned)__GNUC_MINOR__,
  15049. (unsigned)__GNUC_PATCHLEVEL__,
  15050. eol);
  15051. system_info_length += (int)strlen(block);
  15052. if (system_info_length < buflen) {
  15053. strcat0(buffer, block);
  15054. }
  15055. #elif defined(__INTEL_COMPILER)
  15056. mg_snprintf(NULL,
  15057. NULL,
  15058. block,
  15059. sizeof(block),
  15060. "\"compiler\" : \"Intel C/C++: %u\",%s",
  15061. (unsigned)__INTEL_COMPILER,
  15062. eol);
  15063. system_info_length += (int)strlen(block);
  15064. if (system_info_length < buflen) {
  15065. strcat0(buffer, block);
  15066. }
  15067. #elif defined(__BORLANDC__)
  15068. mg_snprintf(NULL,
  15069. NULL,
  15070. block,
  15071. sizeof(block),
  15072. "\"compiler\" : \"Borland C: 0x%x\",%s",
  15073. (unsigned)__BORLANDC__,
  15074. eol);
  15075. system_info_length += (int)strlen(block);
  15076. if (system_info_length < buflen) {
  15077. strcat0(buffer, block);
  15078. }
  15079. #elif defined(__SUNPRO_C)
  15080. mg_snprintf(NULL,
  15081. NULL,
  15082. block,
  15083. sizeof(block),
  15084. "\"compiler\" : \"Solaris: 0x%x\",%s",
  15085. (unsigned)__SUNPRO_C,
  15086. eol);
  15087. system_info_length += (int)strlen(block);
  15088. if (system_info_length < buflen) {
  15089. strcat0(buffer, block);
  15090. }
  15091. #else
  15092. mg_snprintf(NULL,
  15093. NULL,
  15094. block,
  15095. sizeof(block),
  15096. "\"compiler\" : \"other\",%s",
  15097. eol);
  15098. system_info_length += (int)strlen(block);
  15099. if (system_info_length < buflen) {
  15100. strcat0(buffer, block);
  15101. }
  15102. #endif
  15103. }
  15104. /* Determine 32/64 bit data mode.
  15105. * see https://en.wikipedia.org/wiki/64-bit_computing */
  15106. {
  15107. mg_snprintf(
  15108. NULL,
  15109. NULL,
  15110. block,
  15111. sizeof(block),
  15112. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  15113. "ptr:%u, size:%u, time:%u\"%s",
  15114. (unsigned)sizeof(short),
  15115. (unsigned)sizeof(int),
  15116. (unsigned)sizeof(long),
  15117. (unsigned)sizeof(long long),
  15118. (unsigned)sizeof(float),
  15119. (unsigned)sizeof(double),
  15120. (unsigned)sizeof(long double),
  15121. (unsigned)sizeof(char),
  15122. (unsigned)sizeof(wchar_t),
  15123. (unsigned)sizeof(void *),
  15124. (unsigned)sizeof(size_t),
  15125. (unsigned)sizeof(time_t),
  15126. eol);
  15127. system_info_length += (int)strlen(block);
  15128. if (system_info_length < buflen) {
  15129. strcat0(buffer, block);
  15130. }
  15131. }
  15132. /* Terminate string */
  15133. if ((buflen > 0) && buffer && buffer[0]) {
  15134. if (system_info_length < buflen) {
  15135. strcat0(buffer, eoobj);
  15136. strcat0(buffer, eol);
  15137. }
  15138. }
  15139. system_info_length += reserved_len;
  15140. return system_info_length;
  15141. }
  15142. #if defined(USE_SERVER_STATS)
  15143. /* Get context information. It can be printed or stored by the caller.
  15144. * Return the size of available information. */
  15145. static int
  15146. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  15147. {
  15148. char block[256];
  15149. int context_info_length = 0;
  15150. #if defined(_WIN32)
  15151. const char *eol = "\r\n";
  15152. #else
  15153. const char *eol = "\n";
  15154. #endif
  15155. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  15156. const char *eoobj = "}";
  15157. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15158. if ((buffer == NULL) || (buflen < 1)) {
  15159. buflen = 0;
  15160. } else {
  15161. *buffer = 0;
  15162. }
  15163. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15164. context_info_length += (int)strlen(block);
  15165. if (context_info_length < buflen) {
  15166. strcat0(buffer, block);
  15167. }
  15168. /* Memory information */
  15169. if (ms) {
  15170. mg_snprintf(NULL,
  15171. NULL,
  15172. block,
  15173. sizeof(block),
  15174. "\"memory\" : {%s"
  15175. "\"blocks\" : %i,%s"
  15176. "\"used\" : %" INT64_FMT ",%s"
  15177. "\"maxUsed\" : %" INT64_FMT "%s"
  15178. "}%s%s",
  15179. eol,
  15180. ms->blockCount,
  15181. eol,
  15182. ms->totalMemUsed,
  15183. eol,
  15184. ms->maxMemUsed,
  15185. eol,
  15186. (ctx ? "," : ""),
  15187. eol);
  15188. context_info_length += (int)strlen(block);
  15189. if (context_info_length + reserved_len < buflen) {
  15190. strcat0(buffer, block);
  15191. }
  15192. }
  15193. /* Connections information */
  15194. if (ctx) {
  15195. mg_snprintf(NULL,
  15196. NULL,
  15197. block,
  15198. sizeof(block),
  15199. "\"connections\" : {%s"
  15200. "\"active\" : %i,%s"
  15201. "\"maxActive\" : %i,%s"
  15202. "\"total\" : %" INT64_FMT "%s"
  15203. "},%s",
  15204. eol,
  15205. ctx->active_connections,
  15206. eol,
  15207. ctx->max_connections,
  15208. eol,
  15209. ctx->total_connections,
  15210. eol,
  15211. eol);
  15212. context_info_length += (int)strlen(block);
  15213. if (context_info_length + reserved_len < buflen) {
  15214. strcat0(buffer, block);
  15215. }
  15216. }
  15217. /* Requests information */
  15218. if (ctx) {
  15219. mg_snprintf(NULL,
  15220. NULL,
  15221. block,
  15222. sizeof(block),
  15223. "\"requests\" : {%s"
  15224. "\"total\" : %" INT64_FMT "%s"
  15225. "},%s",
  15226. eol,
  15227. ctx->total_requests,
  15228. eol,
  15229. eol);
  15230. context_info_length += (int)strlen(block);
  15231. if (context_info_length + reserved_len < buflen) {
  15232. strcat0(buffer, block);
  15233. }
  15234. }
  15235. /* Data information */
  15236. if (ctx) {
  15237. mg_snprintf(NULL,
  15238. NULL,
  15239. block,
  15240. sizeof(block),
  15241. "\"data\" : {%s"
  15242. "\"read\" : %" INT64_FMT "%s,"
  15243. "\"written\" : %" INT64_FMT "%s"
  15244. "},%s",
  15245. eol,
  15246. ctx->total_data_read,
  15247. eol,
  15248. ctx->total_data_written,
  15249. eol,
  15250. eol);
  15251. context_info_length += (int)strlen(block);
  15252. if (context_info_length + reserved_len < buflen) {
  15253. strcat0(buffer, block);
  15254. }
  15255. }
  15256. /* Execution time information */
  15257. if (ctx) {
  15258. char start_time_str[64] = {0};
  15259. char now_str[64] = {0};
  15260. time_t start_time = ctx->start_time;
  15261. time_t now = time(NULL);
  15262. gmt_time_string(start_time_str,
  15263. sizeof(start_time_str) - 1,
  15264. &start_time);
  15265. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15266. mg_snprintf(NULL,
  15267. NULL,
  15268. block,
  15269. sizeof(block),
  15270. "\"time\" : {%s"
  15271. "\"uptime\" : %.0f,%s"
  15272. "\"start\" : \"%s\",%s"
  15273. "\"now\" : \"%s\"%s"
  15274. "}%s",
  15275. eol,
  15276. difftime(now, start_time),
  15277. eol,
  15278. start_time_str,
  15279. eol,
  15280. now_str,
  15281. eol,
  15282. eol);
  15283. context_info_length += (int)strlen(block);
  15284. if (context_info_length + reserved_len < buflen) {
  15285. strcat0(buffer, block);
  15286. }
  15287. }
  15288. /* Terminate string */
  15289. if ((buflen > 0) && buffer && buffer[0]) {
  15290. if (context_info_length < buflen) {
  15291. strcat0(buffer, eoobj);
  15292. strcat0(buffer, eol);
  15293. }
  15294. }
  15295. context_info_length += reserved_len;
  15296. return context_info_length;
  15297. }
  15298. #endif
  15299. #ifdef MG_EXPERIMENTAL_INTERFACES
  15300. /* Get connection information. It can be printed or stored by the caller.
  15301. * Return the size of available information. */
  15302. static int
  15303. mg_get_connection_info_impl(const struct mg_context *ctx,
  15304. int idx,
  15305. char *buffer,
  15306. int buflen)
  15307. {
  15308. const struct mg_connection *conn;
  15309. const struct mg_request_info *ri;
  15310. char block[256];
  15311. int connection_info_length = 0;
  15312. int state = 0;
  15313. const char *state_str = "unknown";
  15314. #if defined(_WIN32)
  15315. const char *eol = "\r\n";
  15316. #else
  15317. const char *eol = "\n";
  15318. #endif
  15319. const char *eoobj = "}";
  15320. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15321. if ((buffer == NULL) || (buflen < 1)) {
  15322. buflen = 0;
  15323. } else {
  15324. *buffer = 0;
  15325. }
  15326. if ((ctx == NULL) || (idx < 0)) {
  15327. /* Parameter error */
  15328. return 0;
  15329. }
  15330. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  15331. /* Out of range */
  15332. return 0;
  15333. }
  15334. /* Take connection [idx]. This connection is not locked in
  15335. * any way, so some other thread might use it. */
  15336. conn = (ctx->worker_connections) + idx;
  15337. /* Initialize output string */
  15338. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15339. connection_info_length += (int)strlen(block);
  15340. if (connection_info_length < buflen) {
  15341. strcat0(buffer, block);
  15342. }
  15343. /* Init variables */
  15344. ri = &(conn->request_info);
  15345. #if defined(USE_SERVER_STATS)
  15346. state = conn->conn_state;
  15347. /* State as string */
  15348. switch (state) {
  15349. case 0:
  15350. state_str = "undefined";
  15351. break;
  15352. case 1:
  15353. state_str = "not used";
  15354. break;
  15355. case 2:
  15356. state_str = "init";
  15357. break;
  15358. case 3:
  15359. state_str = "ready";
  15360. break;
  15361. case 4:
  15362. state_str = "processing";
  15363. break;
  15364. case 5:
  15365. state_str = "processed";
  15366. break;
  15367. case 6:
  15368. state_str = "to close";
  15369. break;
  15370. case 7:
  15371. state_str = "closing";
  15372. break;
  15373. case 8:
  15374. state_str = "closed";
  15375. break;
  15376. case 9:
  15377. state_str = "done";
  15378. break;
  15379. }
  15380. #endif
  15381. /* Connection info */
  15382. if ((state >= 3) && (state < 9)) {
  15383. mg_snprintf(NULL,
  15384. NULL,
  15385. block,
  15386. sizeof(block),
  15387. "\"connection\" : {%s"
  15388. "\"remote\" : {%s"
  15389. "\"protocol\" : \"%s\",%s"
  15390. "\"addr\" : \"%s\",%s"
  15391. "\"port\" : %u%s"
  15392. "},%s"
  15393. "\"handled_requests\" : %u%s"
  15394. "},%s",
  15395. eol,
  15396. eol,
  15397. get_proto_name(conn),
  15398. eol,
  15399. ri->remote_addr,
  15400. eol,
  15401. ri->remote_port,
  15402. eol,
  15403. eol,
  15404. conn->handled_requests,
  15405. eol,
  15406. eol);
  15407. connection_info_length += (int)strlen(block);
  15408. if (connection_info_length + reserved_len < buflen) {
  15409. strcat0(buffer, block);
  15410. }
  15411. }
  15412. /* Request info */
  15413. if ((state >= 4) && (state < 6)) {
  15414. mg_snprintf(NULL,
  15415. NULL,
  15416. block,
  15417. sizeof(block),
  15418. "\"request_info\" : {%s"
  15419. "\"method\" : \"%s\",%s"
  15420. "\"uri\" : \"%s\",%s"
  15421. "\"query\" : %s%s%s%s"
  15422. "},%s",
  15423. eol,
  15424. ri->request_method,
  15425. eol,
  15426. ri->request_uri,
  15427. eol,
  15428. ri->query_string ? "\"" : "",
  15429. ri->query_string ? ri->query_string : "null",
  15430. ri->query_string ? "\"" : "",
  15431. eol,
  15432. eol);
  15433. connection_info_length += (int)strlen(block);
  15434. if (connection_info_length + reserved_len < buflen) {
  15435. strcat0(buffer, block);
  15436. }
  15437. }
  15438. /* Execution time information */
  15439. if ((state >= 2) && (state < 9)) {
  15440. char start_time_str[64] = {0};
  15441. char now_str[64] = {0};
  15442. time_t start_time = conn->conn_birth_time;
  15443. time_t now = time(NULL);
  15444. gmt_time_string(start_time_str,
  15445. sizeof(start_time_str) - 1,
  15446. &start_time);
  15447. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15448. mg_snprintf(NULL,
  15449. NULL,
  15450. block,
  15451. sizeof(block),
  15452. "\"time\" : {%s"
  15453. "\"uptime\" : %.0f,%s"
  15454. "\"start\" : \"%s\",%s"
  15455. "\"now\" : \"%s\"%s"
  15456. "},%s",
  15457. eol,
  15458. difftime(now, start_time),
  15459. eol,
  15460. start_time_str,
  15461. eol,
  15462. now_str,
  15463. eol,
  15464. eol);
  15465. connection_info_length += (int)strlen(block);
  15466. if (connection_info_length + reserved_len < buflen) {
  15467. strcat0(buffer, block);
  15468. }
  15469. }
  15470. /* Remote user name */
  15471. if ((ri->remote_user) && (state < 9)) {
  15472. mg_snprintf(NULL,
  15473. NULL,
  15474. block,
  15475. sizeof(block),
  15476. "\"user\" : {%s"
  15477. "\"name\" : \"%s\",%s"
  15478. "},%s",
  15479. eol,
  15480. ri->remote_user,
  15481. eol,
  15482. eol);
  15483. connection_info_length += (int)strlen(block);
  15484. if (connection_info_length + reserved_len < buflen) {
  15485. strcat0(buffer, block);
  15486. }
  15487. }
  15488. /* Data block */
  15489. if (state >= 3) {
  15490. mg_snprintf(NULL,
  15491. NULL,
  15492. block,
  15493. sizeof(block),
  15494. "\"data\" : {%s"
  15495. "\"read\" : %" INT64_FMT ",%s"
  15496. "\"written\" : %" INT64_FMT "%s"
  15497. "},%s",
  15498. eol,
  15499. conn->consumed_content,
  15500. eol,
  15501. conn->num_bytes_sent,
  15502. eol,
  15503. eol);
  15504. connection_info_length += (int)strlen(block);
  15505. if (connection_info_length + reserved_len < buflen) {
  15506. strcat0(buffer, block);
  15507. }
  15508. }
  15509. /* State */
  15510. mg_snprintf(NULL,
  15511. NULL,
  15512. block,
  15513. sizeof(block),
  15514. "\"state\" : \"%s\"%s",
  15515. state_str,
  15516. eol);
  15517. connection_info_length += (int)strlen(block);
  15518. if (connection_info_length + reserved_len < buflen) {
  15519. strcat0(buffer, block);
  15520. }
  15521. /* Terminate string */
  15522. if ((buflen > 0) && buffer && buffer[0]) {
  15523. if (connection_info_length < buflen) {
  15524. strcat0(buffer, eoobj);
  15525. strcat0(buffer, eol);
  15526. }
  15527. }
  15528. connection_info_length += reserved_len;
  15529. return connection_info_length;
  15530. }
  15531. #endif
  15532. /* Get system information. It can be printed or stored by the caller.
  15533. * Return the size of available information. */
  15534. int
  15535. mg_get_system_info(char *buffer, int buflen)
  15536. {
  15537. if ((buffer == NULL) || (buflen < 1)) {
  15538. return mg_get_system_info_impl(NULL, 0);
  15539. } else {
  15540. /* Reset buffer, so we can always use strcat. */
  15541. buffer[0] = 0;
  15542. return mg_get_system_info_impl(buffer, buflen);
  15543. }
  15544. }
  15545. /* Get context information. It can be printed or stored by the caller.
  15546. * Return the size of available information. */
  15547. int
  15548. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  15549. {
  15550. #if defined(USE_SERVER_STATS)
  15551. if ((buffer == NULL) || (buflen < 1)) {
  15552. return mg_get_context_info_impl(ctx, NULL, 0);
  15553. } else {
  15554. /* Reset buffer, so we can always use strcat. */
  15555. buffer[0] = 0;
  15556. return mg_get_context_info_impl(ctx, buffer, buflen);
  15557. }
  15558. #else
  15559. (void)ctx;
  15560. if ((buffer != NULL) && (buflen > 0)) {
  15561. buffer[0] = 0;
  15562. }
  15563. return 0;
  15564. #endif
  15565. }
  15566. #ifdef MG_EXPERIMENTAL_INTERFACES
  15567. int
  15568. mg_get_connection_info(const struct mg_context *ctx,
  15569. int idx,
  15570. char *buffer,
  15571. int buflen)
  15572. {
  15573. if ((buffer == NULL) || (buflen < 1)) {
  15574. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  15575. } else {
  15576. /* Reset buffer, so we can always use strcat. */
  15577. buffer[0] = 0;
  15578. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  15579. }
  15580. }
  15581. #endif
  15582. /* Initialize this library. This function does not need to be thread safe.
  15583. */
  15584. unsigned
  15585. mg_init_library(unsigned features)
  15586. {
  15587. #if !defined(NO_SSL)
  15588. char ebuf[128];
  15589. #endif
  15590. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  15591. unsigned features_inited = features_to_init;
  15592. if (mg_init_library_called <= 0) {
  15593. /* Not initialized yet */
  15594. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  15595. return 0;
  15596. }
  15597. }
  15598. mg_global_lock();
  15599. if (mg_init_library_called <= 0) {
  15600. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  15601. /* Fatal error - abort start. However, this situation should
  15602. * never occur in practice. */
  15603. return 0;
  15604. }
  15605. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15606. InitializeCriticalSection(&global_log_file_lock);
  15607. #endif /* _WIN32 && !__SYMBIAN32__ */
  15608. #if !defined(_WIN32)
  15609. pthread_mutexattr_init(&pthread_mutex_attr);
  15610. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  15611. #endif
  15612. #if defined(USE_LUA)
  15613. lua_init_optional_libraries();
  15614. #endif
  15615. }
  15616. #if !defined(NO_SSL)
  15617. if (features_to_init & 2) {
  15618. if (!mg_ssl_initialized) {
  15619. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  15620. mg_ssl_initialized = 1;
  15621. } else {
  15622. (void)ebuf;
  15623. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  15624. features_inited &= ~(2u);
  15625. }
  15626. } else {
  15627. /* ssl already initialized */
  15628. }
  15629. }
  15630. #endif
  15631. /* Start WinSock for Windows */
  15632. if (mg_init_library_called <= 0) {
  15633. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15634. WSADATA data;
  15635. WSAStartup(MAKEWORD(2, 2), &data);
  15636. #endif /* _WIN32 && !__SYMBIAN32__ */
  15637. mg_init_library_called = 1;
  15638. } else {
  15639. mg_init_library_called++;
  15640. }
  15641. mg_global_unlock();
  15642. return features_inited;
  15643. }
  15644. /* Un-initialize this library. */
  15645. unsigned
  15646. mg_exit_library(void)
  15647. {
  15648. if (mg_init_library_called <= 0) {
  15649. return 0;
  15650. }
  15651. mg_global_lock();
  15652. mg_init_library_called--;
  15653. if (mg_init_library_called == 0) {
  15654. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15655. (void)WSACleanup();
  15656. #endif /* _WIN32 && !__SYMBIAN32__ */
  15657. #if !defined(NO_SSL)
  15658. if (mg_ssl_initialized) {
  15659. uninitialize_ssl();
  15660. mg_ssl_initialized = 0;
  15661. }
  15662. #endif
  15663. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15664. (void)DeleteCriticalSection(&global_log_file_lock);
  15665. #endif /* _WIN32 && !__SYMBIAN32__ */
  15666. #if !defined(_WIN32)
  15667. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  15668. #endif
  15669. (void)pthread_key_delete(sTlsKey);
  15670. #if defined(USE_LUA)
  15671. lua_exit_optional_libraries();
  15672. #endif
  15673. mg_global_unlock();
  15674. (void)pthread_mutex_destroy(&global_lock_mutex);
  15675. return 1;
  15676. }
  15677. mg_global_unlock();
  15678. return 1;
  15679. }
  15680. /* End of civetweb.c */