civetweb.c 481 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301
  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. #define TLSEXT_TYPE_server_name (0)
  1359. #define TLSEXT_NAMETYPE_host_name (0)
  1360. #define SSL_TLSEXT_ERR_OK (0)
  1361. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1362. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1363. #define SSL_TLSEXT_ERR_NOACK (3)
  1364. struct ssl_func {
  1365. const char *name; /* SSL function name */
  1366. void (*ptr)(void); /* Function pointer */
  1367. };
  1368. #ifdef OPENSSL_API_1_1
  1369. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1370. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1371. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1372. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1373. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1374. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1375. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1376. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1377. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1378. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1379. #define OPENSSL_init_ssl \
  1380. (*(int (*)(uint64_t opts, \
  1381. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1382. #define SSL_CTX_use_PrivateKey_file \
  1383. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1384. #define SSL_CTX_use_certificate_file \
  1385. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1386. #define SSL_CTX_set_default_passwd_cb \
  1387. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1388. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1389. #define SSL_CTX_use_certificate_chain_file \
  1390. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1391. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1392. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1393. #define SSL_CTX_set_verify \
  1394. (*(void (*)(SSL_CTX *, \
  1395. int, \
  1396. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1397. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1398. #define SSL_CTX_load_verify_locations \
  1399. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1400. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1401. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1402. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1403. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1404. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1405. #define SSL_CIPHER_get_name \
  1406. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1407. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1408. #define SSL_CTX_set_session_id_context \
  1409. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1410. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1411. #define SSL_CTX_set_cipher_list \
  1412. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1413. #define SSL_CTX_set_options \
  1414. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1415. #define SSL_CTX_set_info_callback \
  1416. (*(void (*)(SSL_CTX * ctx, \
  1417. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1418. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1419. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1420. #define SSL_CTX_callback_ctrl \
  1421. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1422. #define SSL_get_servername \
  1423. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1424. #define SSL_CTX_clear_options(ctx, op) \
  1425. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1426. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1427. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1428. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1429. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1430. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1431. SSL_CTX_callback_ctrl(ctx, \
  1432. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1433. (void (*)(void))cb)
  1434. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1435. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1436. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1437. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1438. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1439. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1440. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1441. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1442. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1443. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1444. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1445. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1446. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1447. #define X509_NAME_oneline \
  1448. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1449. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1450. #define EVP_get_digestbyname \
  1451. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1452. #define EVP_Digest \
  1453. (*(int (*)( \
  1454. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1455. crypto_sw[10].ptr)
  1456. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1457. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1458. #define ASN1_INTEGER_to_BN \
  1459. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1460. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1461. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1462. #define OPENSSL_free(a) CRYPTO_free(a)
  1463. /* init_ssl_ctx() function updates this array.
  1464. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1465. * of respective functions. The macros above (like SSL_connect()) are really
  1466. * just calling these functions indirectly via the pointer. */
  1467. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1468. {"SSL_accept", NULL},
  1469. {"SSL_connect", NULL},
  1470. {"SSL_read", NULL},
  1471. {"SSL_write", NULL},
  1472. {"SSL_get_error", NULL},
  1473. {"SSL_set_fd", NULL},
  1474. {"SSL_new", NULL},
  1475. {"SSL_CTX_new", NULL},
  1476. {"TLS_server_method", NULL},
  1477. {"OPENSSL_init_ssl", NULL},
  1478. {"SSL_CTX_use_PrivateKey_file", NULL},
  1479. {"SSL_CTX_use_certificate_file", NULL},
  1480. {"SSL_CTX_set_default_passwd_cb", NULL},
  1481. {"SSL_CTX_free", NULL},
  1482. {"SSL_CTX_use_certificate_chain_file", NULL},
  1483. {"TLS_client_method", NULL},
  1484. {"SSL_pending", NULL},
  1485. {"SSL_CTX_set_verify", NULL},
  1486. {"SSL_shutdown", NULL},
  1487. {"SSL_CTX_load_verify_locations", NULL},
  1488. {"SSL_CTX_set_default_verify_paths", NULL},
  1489. {"SSL_CTX_set_verify_depth", NULL},
  1490. {"SSL_get_peer_certificate", NULL},
  1491. {"SSL_get_version", NULL},
  1492. {"SSL_get_current_cipher", NULL},
  1493. {"SSL_CIPHER_get_name", NULL},
  1494. {"SSL_CTX_check_private_key", NULL},
  1495. {"SSL_CTX_set_session_id_context", NULL},
  1496. {"SSL_CTX_ctrl", NULL},
  1497. {"SSL_CTX_set_cipher_list", NULL},
  1498. {"SSL_CTX_set_options", NULL},
  1499. {"SSL_CTX_set_info_callback", NULL},
  1500. {"SSL_get_ex_data", NULL},
  1501. {"SSL_set_ex_data", NULL},
  1502. {"SSL_CTX_callback_ctrl", NULL},
  1503. {"SSL_get_servername", NULL},
  1504. {NULL, NULL}};
  1505. /* Similar array as ssl_sw. These functions could be located in different
  1506. * lib. */
  1507. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1508. {"ERR_error_string", NULL},
  1509. {"ERR_remove_state", NULL},
  1510. {"CONF_modules_unload", NULL},
  1511. {"X509_free", NULL},
  1512. {"X509_get_subject_name", NULL},
  1513. {"X509_get_issuer_name", NULL},
  1514. {"X509_NAME_oneline", NULL},
  1515. {"X509_get_serialNumber", NULL},
  1516. {"EVP_get_digestbyname", NULL},
  1517. {"EVP_Digest", NULL},
  1518. {"i2d_X509", NULL},
  1519. {"BN_bn2hex", NULL},
  1520. {"ASN1_INTEGER_to_BN", NULL},
  1521. {"BN_free", NULL},
  1522. {"CRYPTO_free", NULL},
  1523. {NULL, NULL}};
  1524. #else
  1525. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1526. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1527. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1528. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1529. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1530. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1531. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1532. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1533. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1534. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1535. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1536. #define SSL_CTX_use_PrivateKey_file \
  1537. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1538. #define SSL_CTX_use_certificate_file \
  1539. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1540. #define SSL_CTX_set_default_passwd_cb \
  1541. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1542. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1543. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1544. #define SSL_CTX_use_certificate_chain_file \
  1545. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1546. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1547. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1548. #define SSL_CTX_set_verify \
  1549. (*(void (*)(SSL_CTX *, \
  1550. int, \
  1551. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1552. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1553. #define SSL_CTX_load_verify_locations \
  1554. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1555. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1556. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1557. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1558. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1559. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1560. #define SSL_CIPHER_get_name \
  1561. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1562. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1563. #define SSL_CTX_set_session_id_context \
  1564. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1565. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1566. #define SSL_CTX_set_cipher_list \
  1567. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1568. #define SSL_CTX_set_info_callback \
  1569. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1570. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1571. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1572. #define SSL_CTX_callback_ctrl \
  1573. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1574. #define SSL_get_servername \
  1575. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1576. #define SSL_CTX_set_options(ctx, op) \
  1577. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1578. #define SSL_CTX_clear_options(ctx, op) \
  1579. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1580. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1581. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1582. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1583. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1584. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1585. SSL_CTX_callback_ctrl(ctx, \
  1586. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1587. (void (*)(void))cb)
  1588. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1589. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1590. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1591. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1592. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1593. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1594. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1595. #define CRYPTO_set_locking_callback \
  1596. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1597. #define CRYPTO_set_id_callback \
  1598. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1599. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1600. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1601. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1602. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1603. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1604. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1605. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1606. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1607. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1608. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1609. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1610. #define X509_NAME_oneline \
  1611. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1612. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1613. #define i2c_ASN1_INTEGER \
  1614. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1615. #define EVP_get_digestbyname \
  1616. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1617. #define EVP_Digest \
  1618. (*(int (*)( \
  1619. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1620. crypto_sw[18].ptr)
  1621. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1622. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1623. #define ASN1_INTEGER_to_BN \
  1624. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1625. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1626. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1627. #define OPENSSL_free(a) CRYPTO_free(a)
  1628. /* init_ssl_ctx() function updates this array.
  1629. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1630. * of respective functions. The macros above (like SSL_connect()) are really
  1631. * just calling these functions indirectly via the pointer. */
  1632. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1633. {"SSL_accept", NULL},
  1634. {"SSL_connect", NULL},
  1635. {"SSL_read", NULL},
  1636. {"SSL_write", NULL},
  1637. {"SSL_get_error", NULL},
  1638. {"SSL_set_fd", NULL},
  1639. {"SSL_new", NULL},
  1640. {"SSL_CTX_new", NULL},
  1641. {"SSLv23_server_method", NULL},
  1642. {"SSL_library_init", NULL},
  1643. {"SSL_CTX_use_PrivateKey_file", NULL},
  1644. {"SSL_CTX_use_certificate_file", NULL},
  1645. {"SSL_CTX_set_default_passwd_cb", NULL},
  1646. {"SSL_CTX_free", NULL},
  1647. {"SSL_load_error_strings", NULL},
  1648. {"SSL_CTX_use_certificate_chain_file", NULL},
  1649. {"SSLv23_client_method", NULL},
  1650. {"SSL_pending", NULL},
  1651. {"SSL_CTX_set_verify", NULL},
  1652. {"SSL_shutdown", NULL},
  1653. {"SSL_CTX_load_verify_locations", NULL},
  1654. {"SSL_CTX_set_default_verify_paths", NULL},
  1655. {"SSL_CTX_set_verify_depth", NULL},
  1656. {"SSL_get_peer_certificate", NULL},
  1657. {"SSL_get_version", NULL},
  1658. {"SSL_get_current_cipher", NULL},
  1659. {"SSL_CIPHER_get_name", NULL},
  1660. {"SSL_CTX_check_private_key", NULL},
  1661. {"SSL_CTX_set_session_id_context", NULL},
  1662. {"SSL_CTX_ctrl", NULL},
  1663. {"SSL_CTX_set_cipher_list", NULL},
  1664. {"SSL_CTX_set_info_callback", NULL},
  1665. {"SSL_get_ex_data", NULL},
  1666. {"SSL_set_ex_data", NULL},
  1667. {"SSL_CTX_callback_ctrl", NULL},
  1668. {"SSL_get_servername", NULL},
  1669. {NULL, NULL}};
  1670. /* Similar array as ssl_sw. These functions could be located in different
  1671. * lib. */
  1672. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1673. {"CRYPTO_set_locking_callback", NULL},
  1674. {"CRYPTO_set_id_callback", NULL},
  1675. {"ERR_get_error", NULL},
  1676. {"ERR_error_string", NULL},
  1677. {"ERR_remove_state", NULL},
  1678. {"ERR_free_strings", NULL},
  1679. {"ENGINE_cleanup", NULL},
  1680. {"CONF_modules_unload", NULL},
  1681. {"CRYPTO_cleanup_all_ex_data", NULL},
  1682. {"EVP_cleanup", NULL},
  1683. {"X509_free", NULL},
  1684. {"X509_get_subject_name", NULL},
  1685. {"X509_get_issuer_name", NULL},
  1686. {"X509_NAME_oneline", NULL},
  1687. {"X509_get_serialNumber", NULL},
  1688. {"i2c_ASN1_INTEGER", NULL},
  1689. {"EVP_get_digestbyname", NULL},
  1690. {"EVP_Digest", NULL},
  1691. {"i2d_X509", NULL},
  1692. {"BN_bn2hex", NULL},
  1693. {"ASN1_INTEGER_to_BN", NULL},
  1694. {"BN_free", NULL},
  1695. {"CRYPTO_free", NULL},
  1696. {NULL, NULL}};
  1697. #endif /* OPENSSL_API_1_1 */
  1698. #endif /* NO_SSL_DL */
  1699. #endif /* NO_SSL */
  1700. #if !defined(NO_CACHING)
  1701. static const char *month_names[] = {"Jan",
  1702. "Feb",
  1703. "Mar",
  1704. "Apr",
  1705. "May",
  1706. "Jun",
  1707. "Jul",
  1708. "Aug",
  1709. "Sep",
  1710. "Oct",
  1711. "Nov",
  1712. "Dec"};
  1713. #endif /* !NO_CACHING */
  1714. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1715. * the
  1716. * union u. */
  1717. union usa {
  1718. struct sockaddr sa;
  1719. struct sockaddr_in sin;
  1720. #if defined(USE_IPV6)
  1721. struct sockaddr_in6 sin6;
  1722. #endif
  1723. };
  1724. /* Describes a string (chunk of memory). */
  1725. struct vec {
  1726. const char *ptr;
  1727. size_t len;
  1728. };
  1729. struct mg_file_stat {
  1730. /* File properties filled by mg_stat: */
  1731. uint64_t size;
  1732. time_t last_modified;
  1733. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1734. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1735. * case we need a "Content-Eencoding: gzip" header */
  1736. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1737. };
  1738. struct mg_file_in_memory {
  1739. char *p;
  1740. uint32_t pos;
  1741. char mode;
  1742. };
  1743. struct mg_file_access {
  1744. /* File properties filled by mg_fopen: */
  1745. FILE *fp;
  1746. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1747. * support library. Use some struct mg_file_in_memory *mf; instead of
  1748. * membuf char pointer. */
  1749. const char *membuf;
  1750. };
  1751. struct mg_file {
  1752. struct mg_file_stat stat;
  1753. struct mg_file_access access;
  1754. };
  1755. #define STRUCT_FILE_INITIALIZER \
  1756. { \
  1757. { \
  1758. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1759. } \
  1760. , \
  1761. { \
  1762. (FILE *) NULL, (const char *)NULL \
  1763. } \
  1764. }
  1765. /* Describes listening socket, or socket which was accept()-ed by the master
  1766. * thread and queued for future handling by the worker thread. */
  1767. struct socket {
  1768. SOCKET sock; /* Listening socket */
  1769. union usa lsa; /* Local socket address */
  1770. union usa rsa; /* Remote socket address */
  1771. unsigned char is_ssl; /* Is port SSL-ed */
  1772. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1773. * port */
  1774. unsigned char in_use; /* Is valid */
  1775. };
  1776. /* Enum const for all options must be in sync with
  1777. * static struct mg_option config_options[]
  1778. * This is tested in the unit test (test/private.c)
  1779. * "Private Config Options"
  1780. */
  1781. enum {
  1782. CGI_EXTENSIONS,
  1783. CGI_ENVIRONMENT,
  1784. PUT_DELETE_PASSWORDS_FILE,
  1785. CGI_INTERPRETER,
  1786. PROTECT_URI,
  1787. AUTHENTICATION_DOMAIN,
  1788. ENABLE_AUTH_DOMAIN_CHECK,
  1789. SSI_EXTENSIONS,
  1790. THROTTLE,
  1791. ACCESS_LOG_FILE,
  1792. ENABLE_DIRECTORY_LISTING,
  1793. ERROR_LOG_FILE,
  1794. GLOBAL_PASSWORDS_FILE,
  1795. INDEX_FILES,
  1796. ENABLE_KEEP_ALIVE,
  1797. ACCESS_CONTROL_LIST,
  1798. EXTRA_MIME_TYPES,
  1799. LISTENING_PORTS,
  1800. DOCUMENT_ROOT,
  1801. SSL_CERTIFICATE,
  1802. SSL_CERTIFICATE_CHAIN,
  1803. NUM_THREADS,
  1804. RUN_AS_USER,
  1805. URL_REWRITE_PATTERN,
  1806. HIDE_FILES,
  1807. REQUEST_TIMEOUT,
  1808. KEEP_ALIVE_TIMEOUT,
  1809. LINGER_TIMEOUT,
  1810. SSL_DO_VERIFY_PEER,
  1811. SSL_CA_PATH,
  1812. SSL_CA_FILE,
  1813. SSL_VERIFY_DEPTH,
  1814. SSL_DEFAULT_VERIFY_PATHS,
  1815. SSL_CIPHER_LIST,
  1816. SSL_PROTOCOL_VERSION,
  1817. SSL_SHORT_TRUST,
  1818. #if defined(USE_WEBSOCKET)
  1819. WEBSOCKET_TIMEOUT,
  1820. #endif
  1821. DECODE_URL,
  1822. #if defined(USE_LUA)
  1823. LUA_PRELOAD_FILE,
  1824. LUA_SCRIPT_EXTENSIONS,
  1825. LUA_SERVER_PAGE_EXTENSIONS,
  1826. #endif
  1827. #if defined(USE_DUKTAPE)
  1828. DUKTAPE_SCRIPT_EXTENSIONS,
  1829. #endif
  1830. #if defined(USE_WEBSOCKET)
  1831. WEBSOCKET_ROOT,
  1832. #endif
  1833. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1834. LUA_WEBSOCKET_EXTENSIONS,
  1835. #endif
  1836. ACCESS_CONTROL_ALLOW_ORIGIN,
  1837. ACCESS_CONTROL_ALLOW_METHODS,
  1838. ACCESS_CONTROL_ALLOW_HEADERS,
  1839. ERROR_PAGES,
  1840. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1841. * socket option typedef TCP_NODELAY. */
  1842. #if !defined(NO_CACHING)
  1843. STATIC_FILE_MAX_AGE,
  1844. #endif
  1845. #if !defined(NO_SSL)
  1846. STRICT_HTTPS_MAX_AGE,
  1847. #endif
  1848. #if defined(__linux__)
  1849. ALLOW_SENDFILE_CALL,
  1850. #endif
  1851. #if defined(_WIN32)
  1852. CASE_SENSITIVE_FILES,
  1853. #endif
  1854. #if defined(USE_LUA)
  1855. LUA_BACKGROUND_SCRIPT,
  1856. LUA_BACKGROUND_SCRIPT_PARAMS,
  1857. #endif
  1858. ADDITIONAL_HEADER,
  1859. MAX_REQUEST_SIZE,
  1860. ALLOW_INDEX_SCRIPT_SUB_RES,
  1861. NUM_OPTIONS
  1862. };
  1863. /* Config option name, config types, default value.
  1864. * Must be in the same order as the enum const above.
  1865. */
  1866. static struct mg_option config_options[] = {
  1867. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1868. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1869. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1870. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1871. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1872. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1873. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1874. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1875. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1876. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1877. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1878. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1879. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1880. {"index_files",
  1881. MG_CONFIG_TYPE_STRING_LIST,
  1882. #ifdef USE_LUA
  1883. "index.xhtml,index.html,index.htm,"
  1884. "index.lp,index.lsp,index.lua,index.cgi,"
  1885. "index.shtml,index.php"},
  1886. #else
  1887. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1888. #endif
  1889. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1890. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1891. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1892. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1893. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1894. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1895. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1896. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1897. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1898. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1899. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1900. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1901. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1902. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1903. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1904. {"ssl_verify_peer", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1905. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1906. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1907. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1908. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1909. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1910. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  1911. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1912. #if defined(USE_WEBSOCKET)
  1913. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1914. #endif
  1915. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1916. #if defined(USE_LUA)
  1917. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1918. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1919. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1920. #endif
  1921. #if defined(USE_DUKTAPE)
  1922. /* The support for duktape is still in alpha version state.
  1923. * The name of this config option might change. */
  1924. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1925. #endif
  1926. #if defined(USE_WEBSOCKET)
  1927. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1928. #endif
  1929. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1930. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1931. #endif
  1932. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1933. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1934. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1935. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1936. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1937. #if !defined(NO_CACHING)
  1938. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1939. #endif
  1940. #if !defined(NO_SSL)
  1941. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1942. #endif
  1943. #if defined(__linux__)
  1944. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1945. #endif
  1946. #if defined(_WIN32)
  1947. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1948. #endif
  1949. #if defined(USE_LUA)
  1950. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1951. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1952. #endif
  1953. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1954. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1955. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1956. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1957. /* Check if the config_options and the corresponding enum have compatible
  1958. * sizes. */
  1959. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1960. == (NUM_OPTIONS + 1),
  1961. "config_options and enum not sync");
  1962. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1963. struct mg_handler_info {
  1964. /* Name/Pattern of the URI. */
  1965. char *uri;
  1966. size_t uri_len;
  1967. /* handler type */
  1968. int handler_type;
  1969. /* Handler for http/https or authorization requests. */
  1970. mg_request_handler handler;
  1971. /* Handler for ws/wss (websocket) requests. */
  1972. mg_websocket_connect_handler connect_handler;
  1973. mg_websocket_ready_handler ready_handler;
  1974. mg_websocket_data_handler data_handler;
  1975. mg_websocket_close_handler close_handler;
  1976. /* accepted subprotocols for ws/wss requests. */
  1977. struct mg_websocket_subprotocols *subprotocols;
  1978. /* Handler for authorization requests */
  1979. mg_authorization_handler auth_handler;
  1980. /* User supplied argument for the handler function. */
  1981. void *cbdata;
  1982. /* next handler in a linked list */
  1983. struct mg_handler_info *next;
  1984. };
  1985. enum {
  1986. CONTEXT_INVALID,
  1987. CONTEXT_SERVER,
  1988. CONTEXT_HTTP_CLIENT,
  1989. CONTEXT_WS_CLIENT
  1990. };
  1991. struct mg_context {
  1992. volatile int stop_flag; /* Should we stop event loop */
  1993. SSL_CTX *ssl_ctx; /* SSL context */
  1994. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1995. struct mg_callbacks callbacks; /* User-defined callback function */
  1996. void *user_data; /* User-defined data */
  1997. int context_type; /* See CONTEXT_* above */
  1998. struct socket *listening_sockets;
  1999. struct pollfd *listening_socket_fds;
  2000. unsigned int num_listening_sockets;
  2001. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2002. #ifdef ALTERNATIVE_QUEUE
  2003. struct socket *client_socks;
  2004. void **client_wait_events;
  2005. #else
  2006. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2007. volatile int sq_head; /* Head of the socket queue */
  2008. volatile int sq_tail; /* Tail of the socket queue */
  2009. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2010. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2011. #endif
  2012. unsigned int max_request_size; /* The max request size */
  2013. pthread_t masterthreadid; /* The master thread ID */
  2014. unsigned int
  2015. cfg_worker_threads; /* The number of configured worker threads. */
  2016. pthread_t *worker_threadids; /* The worker thread IDs */
  2017. struct mg_connection *worker_connections; /* The connection struct, pre-
  2018. * allocated for each worker */
  2019. time_t start_time; /* Server start time, used for authentication
  2020. * and for diagnstics. */
  2021. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2022. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2023. unsigned long nonce_count; /* Used nonces, used for authentication */
  2024. char *systemName; /* What operating system is running */
  2025. /* linked list of uri handlers */
  2026. struct mg_handler_info *handlers;
  2027. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2028. /* linked list of shared lua websockets */
  2029. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2030. #endif
  2031. #if defined(USE_TIMERS)
  2032. struct ttimers *timers;
  2033. #endif
  2034. #if defined(USE_LUA)
  2035. void *lua_background_state;
  2036. #endif
  2037. #if defined(USE_SERVER_STATS)
  2038. int active_connections;
  2039. int max_connections;
  2040. int64_t total_connections;
  2041. int64_t total_requests;
  2042. struct mg_memory_stat ctx_memory;
  2043. int64_t total_data_read;
  2044. int64_t total_data_written;
  2045. #endif
  2046. };
  2047. #if defined(USE_SERVER_STATS)
  2048. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2049. static struct mg_memory_stat *
  2050. get_memory_stat(struct mg_context *ctx)
  2051. {
  2052. if (ctx) {
  2053. return &(ctx->ctx_memory);
  2054. }
  2055. return &mg_common_memory;
  2056. }
  2057. #endif
  2058. enum {
  2059. CONNECTION_TYPE_INVALID,
  2060. CONNECTION_TYPE_REQUEST,
  2061. CONNECTION_TYPE_RESPONSE
  2062. };
  2063. struct mg_connection {
  2064. int connection_type; /* see CONNECTION_TYPE_* above */
  2065. struct mg_request_info request_info;
  2066. struct mg_response_info response_info;
  2067. struct mg_context *ctx;
  2068. #if defined(USE_SERVER_STATS)
  2069. int conn_state; /* 0 = undef, numerical value may change in different
  2070. * versions. For the current definition, see
  2071. * mg_get_connection_info_impl */
  2072. #endif
  2073. SSL *ssl; /* SSL descriptor */
  2074. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2075. struct socket client; /* Connected client */
  2076. time_t conn_birth_time; /* Time (wall clock) when connection was
  2077. * established */
  2078. struct timespec req_time; /* Time (since system start) when the request
  2079. * was received */
  2080. int64_t num_bytes_sent; /* Total bytes sent to client */
  2081. int64_t content_len; /* Content-Length header value */
  2082. int64_t consumed_content; /* How many bytes of content have been read */
  2083. int is_chunked; /* Transfer-Encoding is chunked:
  2084. * 0 = not chunked,
  2085. * 1 = chunked, do data read yet,
  2086. * 2 = chunked, some data read,
  2087. * 3 = chunked, all data read
  2088. */
  2089. size_t chunk_remainder; /* Unread data from the last chunk */
  2090. char *buf; /* Buffer for received data */
  2091. char *path_info; /* PATH_INFO part of the URL */
  2092. int must_close; /* 1 if connection must be closed */
  2093. int accept_gzip; /* 1 if gzip encoding is accepted */
  2094. int in_error_handler; /* 1 if in handler for user defined error
  2095. * pages */
  2096. #if defined(USE_WEBSOCKET)
  2097. int in_websocket_handling; /* 1 if in read_websocket */
  2098. #endif
  2099. int handled_requests; /* Number of requests handled by this connection
  2100. */
  2101. int buf_size; /* Buffer size */
  2102. int request_len; /* Size of the request + headers in a buffer */
  2103. int data_len; /* Total size of data in a buffer */
  2104. int status_code; /* HTTP reply status code, e.g. 200 */
  2105. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2106. * throttle */
  2107. time_t last_throttle_time; /* Last time throttled data was sent */
  2108. int64_t last_throttle_bytes; /* Bytes sent this second */
  2109. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2110. * atomic transmissions for websockets */
  2111. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2112. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2113. #endif
  2114. int thread_index; /* Thread index within ctx */
  2115. };
  2116. /* Directory entry */
  2117. struct de {
  2118. struct mg_connection *conn;
  2119. char *file_name;
  2120. struct mg_file_stat file;
  2121. };
  2122. #if defined(USE_WEBSOCKET)
  2123. static int is_websocket_protocol(const struct mg_connection *conn);
  2124. #else
  2125. #define is_websocket_protocol(conn) (0)
  2126. #endif
  2127. #if !defined(NO_THREAD_NAME)
  2128. #if defined(_WIN32) && defined(_MSC_VER)
  2129. /* Set the thread name for debugging purposes in Visual Studio
  2130. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2131. */
  2132. #pragma pack(push, 8)
  2133. typedef struct tagTHREADNAME_INFO {
  2134. DWORD dwType; /* Must be 0x1000. */
  2135. LPCSTR szName; /* Pointer to name (in user addr space). */
  2136. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2137. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2138. } THREADNAME_INFO;
  2139. #pragma pack(pop)
  2140. #elif defined(__linux__)
  2141. #include <sys/prctl.h>
  2142. #include <sys/sendfile.h>
  2143. #ifdef ALTERNATIVE_QUEUE
  2144. #include <sys/eventfd.h>
  2145. #endif /* ALTERNATIVE_QUEUE */
  2146. #if defined(ALTERNATIVE_QUEUE)
  2147. #ifdef __clang__
  2148. #pragma clang diagnostic push
  2149. #pragma clang diagnostic ignored "-Wunreachable-code"
  2150. /* For every system, "(sizeof(int) == sizeof(void *))" is either always
  2151. * true or always false. One of the two branches is unreachable in any case.
  2152. * Unfortunately the C standard does not define a way to check this at
  2153. * compile time, since the #if preprocessor conditions can not use the sizeof
  2154. * operator as an argument. */
  2155. #endif
  2156. #if defined(__GNUC__) || defined(__MINGW32__)
  2157. /* GCC does not realize one branch is unreachable, so it raises some
  2158. * pointer cast warning within the unreachable branch.
  2159. */
  2160. #pragma GCC diagnostic push
  2161. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
  2162. #pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
  2163. #endif
  2164. static void *
  2165. event_create(void)
  2166. {
  2167. int evhdl = eventfd(0, EFD_CLOEXEC);
  2168. int *ret;
  2169. if (evhdl == -1) {
  2170. /* Linux uses -1 on error, Windows NULL. */
  2171. /* However, Linux does not return 0 on success either. */
  2172. return 0;
  2173. }
  2174. if (sizeof(int) == sizeof(void *)) {
  2175. ret = (void *)evhdl;
  2176. } else {
  2177. ret = (int *)mg_malloc(sizeof(int));
  2178. if (ret) {
  2179. *ret = evhdl;
  2180. } else {
  2181. (void)close(evhdl);
  2182. }
  2183. }
  2184. return (void *)ret;
  2185. }
  2186. static int
  2187. event_wait(void *eventhdl)
  2188. {
  2189. uint64_t u;
  2190. int evhdl, s;
  2191. if (sizeof(int) == sizeof(void *)) {
  2192. evhdl = (int)eventhdl;
  2193. } else {
  2194. if (!eventhdl) {
  2195. /* error */
  2196. return 0;
  2197. }
  2198. evhdl = *(int *)eventhdl;
  2199. }
  2200. s = (int)read(evhdl, &u, sizeof(u));
  2201. if (s != sizeof(uint64_t)) {
  2202. /* error */
  2203. return 0;
  2204. }
  2205. (void)u; /* the value is not required */
  2206. return 1;
  2207. }
  2208. static int
  2209. event_signal(void *eventhdl)
  2210. {
  2211. uint64_t u = 1;
  2212. int evhdl, s;
  2213. if (sizeof(int) == sizeof(void *)) {
  2214. evhdl = (int)eventhdl;
  2215. } else {
  2216. if (!eventhdl) {
  2217. /* error */
  2218. return 0;
  2219. }
  2220. evhdl = *(int *)eventhdl;
  2221. }
  2222. s = (int)write(evhdl, &u, sizeof(u));
  2223. if (s != sizeof(uint64_t)) {
  2224. /* error */
  2225. return 0;
  2226. }
  2227. return 1;
  2228. }
  2229. static void
  2230. event_destroy(void *eventhdl)
  2231. {
  2232. int evhdl;
  2233. if (sizeof(int) == sizeof(void *)) {
  2234. evhdl = (int)eventhdl;
  2235. close(evhdl);
  2236. } else {
  2237. if (!eventhdl) {
  2238. /* error */
  2239. return;
  2240. }
  2241. evhdl = *(int *)eventhdl;
  2242. close(evhdl);
  2243. mg_free(eventhdl);
  2244. }
  2245. }
  2246. #if defined(__GNUC__) || defined(__MINGW32__)
  2247. #pragma GCC diagnostic pop
  2248. #endif
  2249. #ifdef __clang__
  2250. #pragma clang diagnostic pop
  2251. #endif
  2252. #endif
  2253. #endif
  2254. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2255. struct posix_event {
  2256. pthread_mutex_t mutex;
  2257. pthread_cond_t cond;
  2258. };
  2259. static void *
  2260. event_create(void)
  2261. {
  2262. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2263. if (ret == 0) {
  2264. /* out of memory */
  2265. return 0;
  2266. }
  2267. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2268. /* pthread mutex not available */
  2269. mg_free(ret);
  2270. return 0;
  2271. }
  2272. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2273. /* pthread cond not available */
  2274. pthread_mutex_destroy(&(ret->mutex));
  2275. mg_free(ret);
  2276. return 0;
  2277. }
  2278. return (void *)ret;
  2279. }
  2280. static int
  2281. event_wait(void *eventhdl)
  2282. {
  2283. struct posix_event *ev = (struct posix_event *)eventhdl;
  2284. pthread_mutex_lock(&(ev->mutex));
  2285. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2286. pthread_mutex_unlock(&(ev->mutex));
  2287. return 1;
  2288. }
  2289. static int
  2290. event_signal(void *eventhdl)
  2291. {
  2292. struct posix_event *ev = (struct posix_event *)eventhdl;
  2293. pthread_mutex_lock(&(ev->mutex));
  2294. pthread_cond_signal(&(ev->cond));
  2295. pthread_mutex_unlock(&(ev->mutex));
  2296. return 1;
  2297. }
  2298. static void
  2299. event_destroy(void *eventhdl)
  2300. {
  2301. struct posix_event *ev = (struct posix_event *)eventhdl;
  2302. pthread_cond_destroy(&(ev->cond));
  2303. pthread_mutex_destroy(&(ev->mutex));
  2304. mg_free(ev);
  2305. }
  2306. #endif
  2307. static void
  2308. mg_set_thread_name(const char *name)
  2309. {
  2310. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2311. mg_snprintf(
  2312. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2313. #if defined(_WIN32)
  2314. #if defined(_MSC_VER)
  2315. /* Windows and Visual Studio Compiler */
  2316. __try
  2317. {
  2318. THREADNAME_INFO info;
  2319. info.dwType = 0x1000;
  2320. info.szName = threadName;
  2321. info.dwThreadID = ~0U;
  2322. info.dwFlags = 0;
  2323. RaiseException(0x406D1388,
  2324. 0,
  2325. sizeof(info) / sizeof(ULONG_PTR),
  2326. (ULONG_PTR *)&info);
  2327. }
  2328. __except(EXCEPTION_EXECUTE_HANDLER)
  2329. {
  2330. }
  2331. #elif defined(__MINGW32__)
  2332. /* No option known to set thread name for MinGW */
  2333. #endif
  2334. #elif defined(__GLIBC__) \
  2335. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2336. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2337. (void)pthread_setname_np(pthread_self(), threadName);
  2338. #elif defined(__linux__)
  2339. /* on linux we can use the old prctl function */
  2340. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2341. #endif
  2342. }
  2343. #else /* !defined(NO_THREAD_NAME) */
  2344. void
  2345. mg_set_thread_name(const char *threadName)
  2346. {
  2347. }
  2348. #endif
  2349. #if defined(MG_LEGACY_INTERFACE)
  2350. const char **
  2351. mg_get_valid_option_names(void)
  2352. {
  2353. /* This function is deprecated. Use mg_get_valid_options instead. */
  2354. static const char *
  2355. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2356. int i;
  2357. for (i = 0; config_options[i].name != NULL; i++) {
  2358. data[i * 2] = config_options[i].name;
  2359. data[i * 2 + 1] = config_options[i].default_value;
  2360. }
  2361. return data;
  2362. }
  2363. #endif
  2364. const struct mg_option *
  2365. mg_get_valid_options(void)
  2366. {
  2367. return config_options;
  2368. }
  2369. /* Do not open file (used in is_file_in_memory) */
  2370. #define MG_FOPEN_MODE_NONE (0)
  2371. /* Open file for read only access */
  2372. #define MG_FOPEN_MODE_READ (1)
  2373. /* Open file for writing, create and overwrite */
  2374. #define MG_FOPEN_MODE_WRITE (2)
  2375. /* Open file for writing, create and append */
  2376. #define MG_FOPEN_MODE_APPEND (4)
  2377. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2378. * output filep and return 1, otherwise return 0 and don't modify anything.
  2379. */
  2380. static int
  2381. open_file_in_memory(const struct mg_connection *conn,
  2382. const char *path,
  2383. struct mg_file *filep,
  2384. int mode)
  2385. {
  2386. #if defined(MG_USE_OPEN_FILE)
  2387. size_t size = 0;
  2388. const char *buf = NULL;
  2389. if (!conn) {
  2390. return 0;
  2391. }
  2392. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2393. return 0;
  2394. }
  2395. if (conn->ctx->callbacks.open_file) {
  2396. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2397. if (buf != NULL) {
  2398. if (filep == NULL) {
  2399. /* This is a file in memory, but we cannot store the
  2400. * properties
  2401. * now.
  2402. * Called from "is_file_in_memory" function. */
  2403. return 1;
  2404. }
  2405. /* NOTE: override filep->size only on success. Otherwise, it
  2406. * might
  2407. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2408. filep->access.membuf = buf;
  2409. filep->access.fp = NULL;
  2410. /* Size was set by the callback */
  2411. filep->stat.size = size;
  2412. /* Assume the data may change during runtime by setting
  2413. * last_modified = now */
  2414. filep->stat.last_modified = time(NULL);
  2415. filep->stat.is_directory = 0;
  2416. filep->stat.is_gzipped = 0;
  2417. }
  2418. }
  2419. return (buf != NULL);
  2420. #else
  2421. (void)conn;
  2422. (void)path;
  2423. (void)filep;
  2424. (void)mode;
  2425. return 0;
  2426. #endif
  2427. }
  2428. static int
  2429. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2430. {
  2431. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2432. }
  2433. static int
  2434. is_file_opened(const struct mg_file_access *fileacc)
  2435. {
  2436. if (!fileacc) {
  2437. return 0;
  2438. }
  2439. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2440. }
  2441. static int mg_stat(const struct mg_connection *conn,
  2442. const char *path,
  2443. struct mg_file_stat *filep);
  2444. /* mg_fopen will open a file either in memory or on the disk.
  2445. * The input parameter path is a string in UTF-8 encoding.
  2446. * The input parameter mode is MG_FOPEN_MODE_*
  2447. * On success, either fp or membuf will be set in the output
  2448. * struct file. All status members will also be set.
  2449. * The function returns 1 on success, 0 on error. */
  2450. static int
  2451. mg_fopen(const struct mg_connection *conn,
  2452. const char *path,
  2453. int mode,
  2454. struct mg_file *filep)
  2455. {
  2456. int found;
  2457. if (!filep) {
  2458. return 0;
  2459. }
  2460. filep->access.fp = NULL;
  2461. filep->access.membuf = NULL;
  2462. if (!is_file_in_memory(conn, path)) {
  2463. /* filep is initialized in mg_stat: all fields with memset to,
  2464. * some fields like size and modification date with values */
  2465. found = mg_stat(conn, path, &(filep->stat));
  2466. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2467. /* file does not exist and will not be created */
  2468. return 0;
  2469. }
  2470. #ifdef _WIN32
  2471. {
  2472. wchar_t wbuf[PATH_MAX];
  2473. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2474. switch (mode) {
  2475. case MG_FOPEN_MODE_READ:
  2476. filep->access.fp = _wfopen(wbuf, L"rb");
  2477. break;
  2478. case MG_FOPEN_MODE_WRITE:
  2479. filep->access.fp = _wfopen(wbuf, L"wb");
  2480. break;
  2481. case MG_FOPEN_MODE_APPEND:
  2482. filep->access.fp = _wfopen(wbuf, L"ab");
  2483. break;
  2484. }
  2485. }
  2486. #else
  2487. /* Linux et al already use unicode. No need to convert. */
  2488. switch (mode) {
  2489. case MG_FOPEN_MODE_READ:
  2490. filep->access.fp = fopen(path, "r");
  2491. break;
  2492. case MG_FOPEN_MODE_WRITE:
  2493. filep->access.fp = fopen(path, "w");
  2494. break;
  2495. case MG_FOPEN_MODE_APPEND:
  2496. filep->access.fp = fopen(path, "a");
  2497. break;
  2498. }
  2499. #endif
  2500. if (!found) {
  2501. /* File did not exist before fopen was called.
  2502. * Maybe it has been created now. Get stat info
  2503. * like creation time now. */
  2504. found = mg_stat(conn, path, &(filep->stat));
  2505. (void)found;
  2506. }
  2507. /* file is on disk */
  2508. return (filep->access.fp != NULL);
  2509. } else {
  2510. /* is_file_in_memory returned true */
  2511. if (open_file_in_memory(conn, path, filep, mode)) {
  2512. /* file is in memory */
  2513. return (filep->access.membuf != NULL);
  2514. }
  2515. }
  2516. /* Open failed */
  2517. return 0;
  2518. }
  2519. /* return 0 on success, just like fclose */
  2520. static int
  2521. mg_fclose(struct mg_file_access *fileacc)
  2522. {
  2523. int ret = -1;
  2524. if (fileacc != NULL) {
  2525. if (fileacc->fp != NULL) {
  2526. ret = fclose(fileacc->fp);
  2527. } else if (fileacc->membuf != NULL) {
  2528. ret = 0;
  2529. }
  2530. /* reset all members of fileacc */
  2531. memset(fileacc, 0, sizeof(*fileacc));
  2532. }
  2533. return ret;
  2534. }
  2535. static void
  2536. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2537. {
  2538. for (; *src != '\0' && n > 1; n--) {
  2539. *dst++ = *src++;
  2540. }
  2541. *dst = '\0';
  2542. }
  2543. static int
  2544. lowercase(const char *s)
  2545. {
  2546. return tolower(*(const unsigned char *)s);
  2547. }
  2548. int
  2549. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2550. {
  2551. int diff = 0;
  2552. if (len > 0) {
  2553. do {
  2554. diff = lowercase(s1++) - lowercase(s2++);
  2555. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2556. }
  2557. return diff;
  2558. }
  2559. int
  2560. mg_strcasecmp(const char *s1, const char *s2)
  2561. {
  2562. int diff;
  2563. do {
  2564. diff = lowercase(s1++) - lowercase(s2++);
  2565. } while (diff == 0 && s1[-1] != '\0');
  2566. return diff;
  2567. }
  2568. static char *
  2569. mg_strndup(const char *ptr, size_t len)
  2570. {
  2571. char *p;
  2572. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2573. mg_strlcpy(p, ptr, len + 1);
  2574. }
  2575. return p;
  2576. }
  2577. static char *
  2578. mg_strdup(const char *str)
  2579. {
  2580. return mg_strndup(str, strlen(str));
  2581. }
  2582. static const char *
  2583. mg_strcasestr(const char *big_str, const char *small_str)
  2584. {
  2585. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2586. if (big_len >= small_len) {
  2587. for (i = 0; i <= (big_len - small_len); i++) {
  2588. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2589. return big_str + i;
  2590. }
  2591. }
  2592. }
  2593. return NULL;
  2594. }
  2595. /* Return null terminated string of given maximum length.
  2596. * Report errors if length is exceeded. */
  2597. static void
  2598. mg_vsnprintf(const struct mg_connection *conn,
  2599. int *truncated,
  2600. char *buf,
  2601. size_t buflen,
  2602. const char *fmt,
  2603. va_list ap)
  2604. {
  2605. int n, ok;
  2606. if (buflen == 0) {
  2607. if (truncated) {
  2608. *truncated = 1;
  2609. }
  2610. return;
  2611. }
  2612. #ifdef __clang__
  2613. #pragma clang diagnostic push
  2614. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2615. /* Using fmt as a non-literal is intended here, since it is mostly called
  2616. * indirectly by mg_snprintf */
  2617. #endif
  2618. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2619. ok = (n >= 0) && ((size_t)n < buflen);
  2620. #ifdef __clang__
  2621. #pragma clang diagnostic pop
  2622. #endif
  2623. if (ok) {
  2624. if (truncated) {
  2625. *truncated = 0;
  2626. }
  2627. } else {
  2628. if (truncated) {
  2629. *truncated = 1;
  2630. }
  2631. mg_cry(conn,
  2632. "truncating vsnprintf buffer: [%.*s]",
  2633. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2634. buf);
  2635. n = (int)buflen - 1;
  2636. }
  2637. buf[n] = '\0';
  2638. }
  2639. static void
  2640. mg_snprintf(const struct mg_connection *conn,
  2641. int *truncated,
  2642. char *buf,
  2643. size_t buflen,
  2644. const char *fmt,
  2645. ...)
  2646. {
  2647. va_list ap;
  2648. va_start(ap, fmt);
  2649. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2650. va_end(ap);
  2651. }
  2652. static int
  2653. get_option_index(const char *name)
  2654. {
  2655. int i;
  2656. for (i = 0; config_options[i].name != NULL; i++) {
  2657. if (strcmp(config_options[i].name, name) == 0) {
  2658. return i;
  2659. }
  2660. }
  2661. return -1;
  2662. }
  2663. const char *
  2664. mg_get_option(const struct mg_context *ctx, const char *name)
  2665. {
  2666. int i;
  2667. if ((i = get_option_index(name)) == -1) {
  2668. return NULL;
  2669. } else if (!ctx || ctx->config[i] == NULL) {
  2670. return "";
  2671. } else {
  2672. return ctx->config[i];
  2673. }
  2674. }
  2675. struct mg_context *
  2676. mg_get_context(const struct mg_connection *conn)
  2677. {
  2678. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2679. }
  2680. void *
  2681. mg_get_user_data(const struct mg_context *ctx)
  2682. {
  2683. return (ctx == NULL) ? NULL : ctx->user_data;
  2684. }
  2685. void
  2686. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2687. {
  2688. if (conn != NULL) {
  2689. conn->request_info.conn_data = data;
  2690. }
  2691. }
  2692. void *
  2693. mg_get_user_connection_data(const struct mg_connection *conn)
  2694. {
  2695. if (conn != NULL) {
  2696. return conn->request_info.conn_data;
  2697. }
  2698. return NULL;
  2699. }
  2700. #if defined(MG_LEGACY_INTERFACE)
  2701. /* Deprecated: Use mg_get_server_ports instead. */
  2702. size_t
  2703. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2704. {
  2705. size_t i;
  2706. if (!ctx) {
  2707. return 0;
  2708. }
  2709. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2710. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2711. ports[i] =
  2712. #if defined(USE_IPV6)
  2713. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2714. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2715. :
  2716. #endif
  2717. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2718. }
  2719. return i;
  2720. }
  2721. #endif
  2722. int
  2723. mg_get_server_ports(const struct mg_context *ctx,
  2724. int size,
  2725. struct mg_server_ports *ports)
  2726. {
  2727. int i, cnt = 0;
  2728. if (size <= 0) {
  2729. return -1;
  2730. }
  2731. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2732. if (!ctx) {
  2733. return -1;
  2734. }
  2735. if (!ctx->listening_sockets) {
  2736. return -1;
  2737. }
  2738. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2739. ports[cnt].port =
  2740. #if defined(USE_IPV6)
  2741. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2742. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2743. :
  2744. #endif
  2745. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2746. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2747. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2748. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2749. /* IPv4 */
  2750. ports[cnt].protocol = 1;
  2751. cnt++;
  2752. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2753. /* IPv6 */
  2754. ports[cnt].protocol = 3;
  2755. cnt++;
  2756. }
  2757. }
  2758. return cnt;
  2759. }
  2760. static void
  2761. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2762. {
  2763. buf[0] = '\0';
  2764. if (!usa) {
  2765. return;
  2766. }
  2767. if (usa->sa.sa_family == AF_INET) {
  2768. getnameinfo(&usa->sa,
  2769. sizeof(usa->sin),
  2770. buf,
  2771. (unsigned)len,
  2772. NULL,
  2773. 0,
  2774. NI_NUMERICHOST);
  2775. }
  2776. #if defined(USE_IPV6)
  2777. else if (usa->sa.sa_family == AF_INET6) {
  2778. getnameinfo(&usa->sa,
  2779. sizeof(usa->sin6),
  2780. buf,
  2781. (unsigned)len,
  2782. NULL,
  2783. 0,
  2784. NI_NUMERICHOST);
  2785. }
  2786. #endif
  2787. }
  2788. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2789. * included in all responses other than 100, 101, 5xx. */
  2790. static void
  2791. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2792. {
  2793. struct tm *tm;
  2794. tm = ((t != NULL) ? gmtime(t) : NULL);
  2795. if (tm != NULL) {
  2796. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2797. } else {
  2798. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2799. buf[buf_len - 1] = '\0';
  2800. }
  2801. }
  2802. /* difftime for struct timespec. Return value is in seconds. */
  2803. static double
  2804. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2805. {
  2806. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2807. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2808. }
  2809. /* Print error message to the opened error log stream. */
  2810. void
  2811. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2812. {
  2813. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2814. va_list ap;
  2815. struct mg_file fi;
  2816. time_t timestamp;
  2817. va_start(ap, fmt);
  2818. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2819. va_end(ap);
  2820. buf[sizeof(buf) - 1] = 0;
  2821. DEBUG_TRACE("mg_cry: %s", buf);
  2822. if (!conn) {
  2823. puts(buf);
  2824. return;
  2825. }
  2826. /* Do not lock when getting the callback value, here and below.
  2827. * I suppose this is fine, since function cannot disappear in the
  2828. * same way string option can. */
  2829. if ((conn->ctx->callbacks.log_message == NULL)
  2830. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2831. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2832. if (mg_fopen(conn,
  2833. conn->ctx->config[ERROR_LOG_FILE],
  2834. MG_FOPEN_MODE_APPEND,
  2835. &fi) == 0) {
  2836. fi.access.fp = NULL;
  2837. }
  2838. } else {
  2839. fi.access.fp = NULL;
  2840. }
  2841. if (fi.access.fp != NULL) {
  2842. flockfile(fi.access.fp);
  2843. timestamp = time(NULL);
  2844. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2845. fprintf(fi.access.fp,
  2846. "[%010lu] [error] [client %s] ",
  2847. (unsigned long)timestamp,
  2848. src_addr);
  2849. if (conn->request_info.request_method != NULL) {
  2850. fprintf(fi.access.fp,
  2851. "%s %s: ",
  2852. conn->request_info.request_method,
  2853. conn->request_info.request_uri
  2854. ? conn->request_info.request_uri
  2855. : "");
  2856. }
  2857. fprintf(fi.access.fp, "%s", buf);
  2858. fputc('\n', fi.access.fp);
  2859. fflush(fi.access.fp);
  2860. funlockfile(fi.access.fp);
  2861. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2862. * mg_cry here anyway ;-) */
  2863. }
  2864. }
  2865. }
  2866. /* Return fake connection structure. Used for logging, if connection
  2867. * is not applicable at the moment of logging. */
  2868. static struct mg_connection *
  2869. fc(struct mg_context *ctx)
  2870. {
  2871. static struct mg_connection fake_connection;
  2872. fake_connection.ctx = ctx;
  2873. return &fake_connection;
  2874. }
  2875. const char *
  2876. mg_version(void)
  2877. {
  2878. return CIVETWEB_VERSION;
  2879. }
  2880. const struct mg_request_info *
  2881. mg_get_request_info(const struct mg_connection *conn)
  2882. {
  2883. if (!conn) {
  2884. return NULL;
  2885. }
  2886. #if 1 /* TODO: deal with legacy */
  2887. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2888. static char txt[16];
  2889. sprintf(txt, "%03i", conn->response_info.status_code);
  2890. ((struct mg_connection *)conn)->request_info.local_uri =
  2891. ((struct mg_connection *)conn)->request_info.request_uri =
  2892. txt; /* TODO: not thread safe */
  2893. ((struct mg_connection *)conn)->request_info.num_headers =
  2894. conn->response_info.num_headers;
  2895. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2896. conn->response_info.http_headers,
  2897. sizeof(conn->response_info.http_headers));
  2898. } else
  2899. #endif
  2900. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2901. return NULL;
  2902. }
  2903. return &conn->request_info;
  2904. }
  2905. const struct mg_response_info *
  2906. mg_get_response_info(const struct mg_connection *conn)
  2907. {
  2908. if (!conn) {
  2909. return NULL;
  2910. }
  2911. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2912. return NULL;
  2913. }
  2914. return &conn->response_info;
  2915. }
  2916. static const char *
  2917. get_proto_name(const struct mg_connection *conn)
  2918. {
  2919. #ifdef __clang__
  2920. #pragma clang diagnostic push
  2921. #pragma clang diagnostic ignored "-Wunreachable-code"
  2922. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2923. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2924. * unreachable, but splitting into four different #ifdef clauses here is more
  2925. * complicated.
  2926. */
  2927. #endif
  2928. const struct mg_request_info *ri = &conn->request_info;
  2929. const char *proto =
  2930. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2931. : (ri->is_ssl ? "https" : "http"));
  2932. return proto;
  2933. #ifdef __clang__
  2934. #pragma clang diagnostic pop
  2935. #endif
  2936. }
  2937. int
  2938. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2939. {
  2940. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2941. return -1;
  2942. } else {
  2943. int truncated = 0;
  2944. const struct mg_request_info *ri = &conn->request_info;
  2945. const char *proto = get_proto_name(conn);
  2946. if (ri->local_uri == NULL) {
  2947. return -1;
  2948. }
  2949. if ((ri->request_uri != NULL)
  2950. && strcmp(ri->local_uri, ri->request_uri)) {
  2951. mg_snprintf(conn,
  2952. &truncated,
  2953. buf,
  2954. buflen,
  2955. "%s://%s",
  2956. proto,
  2957. ri->request_uri);
  2958. if (truncated) {
  2959. return -1;
  2960. }
  2961. return 0;
  2962. } else {
  2963. #if defined(USE_IPV6)
  2964. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2965. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2966. : htons(conn->client.lsa.sin.sin_port);
  2967. #else
  2968. int port = htons(conn->client.lsa.sin.sin_port);
  2969. #endif
  2970. int def_port = ri->is_ssl ? 443 : 80;
  2971. int auth_domain_check_enabled =
  2972. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2973. && (!mg_strcasecmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2974. "yes"));
  2975. const char *server_domain =
  2976. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2977. char portstr[16];
  2978. char server_ip[48];
  2979. if (port != def_port) {
  2980. sprintf(portstr, ":%u", (unsigned)port);
  2981. } else {
  2982. portstr[0] = 0;
  2983. }
  2984. if (!auth_domain_check_enabled || !server_domain) {
  2985. sockaddr_to_string(server_ip,
  2986. sizeof(server_ip),
  2987. &conn->client.lsa);
  2988. server_domain = server_ip;
  2989. }
  2990. mg_snprintf(conn,
  2991. &truncated,
  2992. buf,
  2993. buflen,
  2994. "%s://%s%s%s",
  2995. proto,
  2996. server_domain,
  2997. portstr,
  2998. ri->local_uri);
  2999. if (truncated) {
  3000. return -1;
  3001. }
  3002. return 0;
  3003. }
  3004. }
  3005. }
  3006. /* Skip the characters until one of the delimiters characters found.
  3007. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3008. * Advance pointer to buffer to the next word. Return found 0-terminated
  3009. * word.
  3010. * Delimiters can be quoted with quotechar. */
  3011. static char *
  3012. skip_quoted(char **buf,
  3013. const char *delimiters,
  3014. const char *whitespace,
  3015. char quotechar)
  3016. {
  3017. char *p, *begin_word, *end_word, *end_whitespace;
  3018. begin_word = *buf;
  3019. end_word = begin_word + strcspn(begin_word, delimiters);
  3020. /* Check for quotechar */
  3021. if (end_word > begin_word) {
  3022. p = end_word - 1;
  3023. while (*p == quotechar) {
  3024. /* While the delimiter is quoted, look for the next delimiter.
  3025. */
  3026. /* This happens, e.g., in calls from parse_auth_header,
  3027. * if the user name contains a " character. */
  3028. /* If there is anything beyond end_word, copy it. */
  3029. if (*end_word != '\0') {
  3030. size_t end_off = strcspn(end_word + 1, delimiters);
  3031. memmove(p, end_word, end_off + 1);
  3032. p += end_off; /* p must correspond to end_word - 1 */
  3033. end_word += end_off + 1;
  3034. } else {
  3035. *p = '\0';
  3036. break;
  3037. }
  3038. }
  3039. for (p++; p < end_word; p++) {
  3040. *p = '\0';
  3041. }
  3042. }
  3043. if (*end_word == '\0') {
  3044. *buf = end_word;
  3045. } else {
  3046. #if defined(__GNUC__) || defined(__MINGW32__)
  3047. /* Disable spurious conversion warning for GCC */
  3048. #if GCC_VERSION >= 40500
  3049. #pragma GCC diagnostic push
  3050. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3051. #endif /* GCC_VERSION >= 40500 */
  3052. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3053. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3054. #if defined(__GNUC__) || defined(__MINGW32__)
  3055. #if GCC_VERSION >= 40500
  3056. #pragma GCC diagnostic pop
  3057. #endif /* GCC_VERSION >= 40500 */
  3058. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3059. for (p = end_word; p < end_whitespace; p++) {
  3060. *p = '\0';
  3061. }
  3062. *buf = end_whitespace;
  3063. }
  3064. return begin_word;
  3065. }
  3066. /* Return HTTP header value, or NULL if not found. */
  3067. static const char *
  3068. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3069. {
  3070. int i;
  3071. for (i = 0; i < num_hdr; i++) {
  3072. if (!mg_strcasecmp(name, hdr[i].name)) {
  3073. return hdr[i].value;
  3074. }
  3075. }
  3076. return NULL;
  3077. }
  3078. #if defined(USE_WEBSOCKET)
  3079. /* Retrieve requested HTTP header multiple values, and return the number of
  3080. * found occurences */
  3081. static int
  3082. get_req_headers(const struct mg_request_info *ri,
  3083. const char *name,
  3084. const char **output,
  3085. int output_max_size)
  3086. {
  3087. int i;
  3088. int cnt = 0;
  3089. if (ri) {
  3090. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3091. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3092. output[cnt++] = ri->http_headers[i].value;
  3093. }
  3094. }
  3095. }
  3096. return cnt;
  3097. }
  3098. #endif
  3099. const char *
  3100. mg_get_header(const struct mg_connection *conn, const char *name)
  3101. {
  3102. if (!conn) {
  3103. return NULL;
  3104. }
  3105. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3106. return get_header(conn->request_info.http_headers,
  3107. conn->request_info.num_headers,
  3108. name);
  3109. }
  3110. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3111. return get_header(conn->response_info.http_headers,
  3112. conn->response_info.num_headers,
  3113. name);
  3114. }
  3115. return NULL;
  3116. }
  3117. static const char *
  3118. get_http_version(const struct mg_connection *conn)
  3119. {
  3120. if (!conn) {
  3121. return NULL;
  3122. }
  3123. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3124. return conn->request_info.http_version;
  3125. }
  3126. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3127. return conn->response_info.http_version;
  3128. }
  3129. return NULL;
  3130. }
  3131. /* A helper function for traversing a comma separated list of values.
  3132. * It returns a list pointer shifted to the next value, or NULL if the end
  3133. * of the list found.
  3134. * Value is stored in val vector. If value has form "x=y", then eq_val
  3135. * vector is initialized to point to the "y" part, and val vector length
  3136. * is adjusted to point only to "x". */
  3137. static const char *
  3138. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3139. {
  3140. int end;
  3141. reparse:
  3142. if (val == NULL || list == NULL || *list == '\0') {
  3143. /* End of the list */
  3144. return NULL;
  3145. }
  3146. /* Skip over leading LWS */
  3147. while (*list == ' ' || *list == '\t')
  3148. list++;
  3149. val->ptr = list;
  3150. if ((list = strchr(val->ptr, ',')) != NULL) {
  3151. /* Comma found. Store length and shift the list ptr */
  3152. val->len = ((size_t)(list - val->ptr));
  3153. list++;
  3154. } else {
  3155. /* This value is the last one */
  3156. list = val->ptr + strlen(val->ptr);
  3157. val->len = ((size_t)(list - val->ptr));
  3158. }
  3159. /* Adjust length for trailing LWS */
  3160. end = (int)val->len - 1;
  3161. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3162. end--;
  3163. val->len = (size_t)(end + 1);
  3164. if (val->len == 0) {
  3165. /* Ignore any empty entries. */
  3166. goto reparse;
  3167. }
  3168. if (eq_val != NULL) {
  3169. /* Value has form "x=y", adjust pointers and lengths
  3170. * so that val points to "x", and eq_val points to "y". */
  3171. eq_val->len = 0;
  3172. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3173. if (eq_val->ptr != NULL) {
  3174. eq_val->ptr++; /* Skip over '=' character */
  3175. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3176. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3177. }
  3178. }
  3179. return list;
  3180. }
  3181. /* A helper function for checking if a comma separated list of values
  3182. * contains
  3183. * the given option (case insensitvely).
  3184. * 'header' can be NULL, in which case false is returned. */
  3185. static int
  3186. header_has_option(const char *header, const char *option)
  3187. {
  3188. struct vec opt_vec;
  3189. struct vec eq_vec;
  3190. /*
  3191. assert(option != NULL);
  3192. assert(option[0] != '\0');
  3193. */
  3194. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3195. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3196. return 1;
  3197. }
  3198. return 0;
  3199. }
  3200. /* Perform case-insensitive match of string against pattern */
  3201. static int
  3202. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3203. {
  3204. const char *or_str;
  3205. size_t i;
  3206. int j, len, res;
  3207. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3208. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3209. return (res > 0) ? res : match_prefix(or_str + 1,
  3210. (size_t)((pattern + pattern_len)
  3211. - (or_str + 1)),
  3212. str);
  3213. }
  3214. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  3215. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3216. continue;
  3217. } else if (pattern[i] == '$') {
  3218. return (str[j] == '\0') ? j : -1;
  3219. } else if (pattern[i] == '*') {
  3220. i++;
  3221. if (pattern[i] == '*') {
  3222. i++;
  3223. len = (int)strlen(str + j);
  3224. } else {
  3225. len = (int)strcspn(str + j, "/");
  3226. }
  3227. if (i == pattern_len) {
  3228. return j + len;
  3229. }
  3230. do {
  3231. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3232. } while (res == -1 && len-- > 0);
  3233. return (res == -1) ? -1 : j + res + len;
  3234. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3235. return -1;
  3236. }
  3237. }
  3238. return j;
  3239. }
  3240. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3241. * This function must tolerate situations when connection info is not
  3242. * set up, for example if request parsing failed. */
  3243. static int
  3244. should_keep_alive(const struct mg_connection *conn)
  3245. {
  3246. const char *http_version;
  3247. const char *header;
  3248. /* First satisfy needs of the server */
  3249. if ((conn == NULL) || conn->must_close) {
  3250. /* Close, if civetweb framework needs to close */
  3251. return 0;
  3252. }
  3253. if (mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3254. /* Close, if keep alive is not enabled */
  3255. return 0;
  3256. }
  3257. /* Check explicit wish of the client */
  3258. header = mg_get_header(conn, "Connection");
  3259. if (header) {
  3260. /* If there is a connection header from the client, obey */
  3261. if (header_has_option(header, "keep-alive")) {
  3262. return 1;
  3263. }
  3264. return 0;
  3265. }
  3266. /* Use default of the standard */
  3267. http_version = get_http_version(conn);
  3268. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3269. /* HTTP 1.1 default is keep alive */
  3270. return 1;
  3271. }
  3272. /* HTTP 1.0 (and earlier) default is to close the connection */
  3273. return 0;
  3274. }
  3275. static int
  3276. should_decode_url(const struct mg_connection *conn)
  3277. {
  3278. if (!conn || !conn->ctx) {
  3279. return 0;
  3280. }
  3281. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  3282. }
  3283. static const char *
  3284. suggest_connection_header(const struct mg_connection *conn)
  3285. {
  3286. return should_keep_alive(conn) ? "keep-alive" : "close";
  3287. }
  3288. static int
  3289. send_no_cache_header(struct mg_connection *conn)
  3290. {
  3291. /* Send all current and obsolete cache opt-out directives. */
  3292. return mg_printf(conn,
  3293. "Cache-Control: no-cache, no-store, "
  3294. "must-revalidate, private, max-age=0\r\n"
  3295. "Pragma: no-cache\r\n"
  3296. "Expires: 0\r\n");
  3297. }
  3298. static int
  3299. send_static_cache_header(struct mg_connection *conn)
  3300. {
  3301. #if !defined(NO_CACHING)
  3302. /* Read the server config to check how long a file may be cached.
  3303. * The configuration is in seconds. */
  3304. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  3305. if (max_age <= 0) {
  3306. /* 0 means "do not cache". All values <0 are reserved
  3307. * and may be used differently in the future. */
  3308. /* If a file should not be cached, do not only send
  3309. * max-age=0, but also pragmas and Expires headers. */
  3310. return send_no_cache_header(conn);
  3311. }
  3312. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3313. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3314. /* See also https://www.mnot.net/cache_docs/ */
  3315. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3316. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3317. * leap
  3318. * year to 31622400 seconds. For the moment, we just send whatever has
  3319. * been configured, still the behavior for >1 year should be considered
  3320. * as undefined. */
  3321. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3322. #else /* NO_CACHING */
  3323. return send_no_cache_header(conn);
  3324. #endif /* !NO_CACHING */
  3325. }
  3326. static int
  3327. send_additional_header(struct mg_connection *conn)
  3328. {
  3329. int i = 0;
  3330. const char *header = conn->ctx->config[ADDITIONAL_HEADER];
  3331. #if !defined(NO_SSL)
  3332. if (conn->ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3333. int max_age = atoi(conn->ctx->config[STRICT_HTTPS_MAX_AGE]);
  3334. if (max_age >= 0) {
  3335. i += mg_printf(conn,
  3336. "Strict-Transport-Security: max-age=%u\r\n",
  3337. (unsigned)max_age);
  3338. }
  3339. }
  3340. #endif
  3341. if (header && header[0]) {
  3342. i += mg_printf(conn, "%s\r\n", header);
  3343. }
  3344. return i;
  3345. }
  3346. static void handle_file_based_request(struct mg_connection *conn,
  3347. const char *path,
  3348. struct mg_file *filep);
  3349. const char *
  3350. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3351. {
  3352. /* See IANA HTTP status code assignment:
  3353. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3354. */
  3355. switch (response_code) {
  3356. /* RFC2616 Section 10.1 - Informational 1xx */
  3357. case 100:
  3358. return "Continue"; /* RFC2616 Section 10.1.1 */
  3359. case 101:
  3360. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3361. case 102:
  3362. return "Processing"; /* RFC2518 Section 10.1 */
  3363. /* RFC2616 Section 10.2 - Successful 2xx */
  3364. case 200:
  3365. return "OK"; /* RFC2616 Section 10.2.1 */
  3366. case 201:
  3367. return "Created"; /* RFC2616 Section 10.2.2 */
  3368. case 202:
  3369. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3370. case 203:
  3371. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3372. case 204:
  3373. return "No Content"; /* RFC2616 Section 10.2.5 */
  3374. case 205:
  3375. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3376. case 206:
  3377. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3378. case 207:
  3379. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3380. */
  3381. case 208:
  3382. return "Already Reported"; /* RFC5842 Section 7.1 */
  3383. case 226:
  3384. return "IM used"; /* RFC3229 Section 10.4.1 */
  3385. /* RFC2616 Section 10.3 - Redirection 3xx */
  3386. case 300:
  3387. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3388. case 301:
  3389. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3390. case 302:
  3391. return "Found"; /* RFC2616 Section 10.3.3 */
  3392. case 303:
  3393. return "See Other"; /* RFC2616 Section 10.3.4 */
  3394. case 304:
  3395. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3396. case 305:
  3397. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3398. case 307:
  3399. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3400. case 308:
  3401. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3402. /* RFC2616 Section 10.4 - Client Error 4xx */
  3403. case 400:
  3404. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3405. case 401:
  3406. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3407. case 402:
  3408. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3409. case 403:
  3410. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3411. case 404:
  3412. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3413. case 405:
  3414. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3415. case 406:
  3416. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3417. case 407:
  3418. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3419. case 408:
  3420. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3421. case 409:
  3422. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3423. case 410:
  3424. return "Gone"; /* RFC2616 Section 10.4.11 */
  3425. case 411:
  3426. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3427. case 412:
  3428. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3429. case 413:
  3430. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3431. case 414:
  3432. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3433. case 415:
  3434. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3435. case 416:
  3436. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3437. */
  3438. case 417:
  3439. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3440. case 421:
  3441. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3442. case 422:
  3443. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3444. * Section 11.2 */
  3445. case 423:
  3446. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3447. case 424:
  3448. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3449. * Section 11.4 */
  3450. case 426:
  3451. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3452. case 428:
  3453. return "Precondition Required"; /* RFC 6585, Section 3 */
  3454. case 429:
  3455. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3456. case 431:
  3457. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3458. case 451:
  3459. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3460. * Section 3 */
  3461. /* RFC2616 Section 10.5 - Server Error 5xx */
  3462. case 500:
  3463. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3464. case 501:
  3465. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3466. case 502:
  3467. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3468. case 503:
  3469. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3470. case 504:
  3471. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3472. case 505:
  3473. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3474. case 506:
  3475. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3476. case 507:
  3477. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3478. * Section 11.5 */
  3479. case 508:
  3480. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3481. case 510:
  3482. return "Not Extended"; /* RFC 2774, Section 7 */
  3483. case 511:
  3484. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3485. /* Other status codes, not shown in the IANA HTTP status code
  3486. * assignment.
  3487. * E.g., "de facto" standards due to common use, ... */
  3488. case 418:
  3489. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3490. case 419:
  3491. return "Authentication Timeout"; /* common use */
  3492. case 420:
  3493. return "Enhance Your Calm"; /* common use */
  3494. case 440:
  3495. return "Login Timeout"; /* common use */
  3496. case 509:
  3497. return "Bandwidth Limit Exceeded"; /* common use */
  3498. default:
  3499. /* This error code is unknown. This should not happen. */
  3500. if (conn) {
  3501. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3502. }
  3503. /* Return at least a category according to RFC 2616 Section 10. */
  3504. if (response_code >= 100 && response_code < 200) {
  3505. /* Unknown informational status code */
  3506. return "Information";
  3507. }
  3508. if (response_code >= 200 && response_code < 300) {
  3509. /* Unknown success code */
  3510. return "Success";
  3511. }
  3512. if (response_code >= 300 && response_code < 400) {
  3513. /* Unknown redirection code */
  3514. return "Redirection";
  3515. }
  3516. if (response_code >= 400 && response_code < 500) {
  3517. /* Unknown request error code */
  3518. return "Client Error";
  3519. }
  3520. if (response_code >= 500 && response_code < 600) {
  3521. /* Unknown server error code */
  3522. return "Server Error";
  3523. }
  3524. /* Response code not even within reasonable range */
  3525. return "";
  3526. }
  3527. }
  3528. void
  3529. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3530. {
  3531. char buf[MG_BUF_LEN];
  3532. va_list ap;
  3533. int len, i, page_handler_found, scope, truncated, has_body;
  3534. char date[64];
  3535. time_t curtime = time(NULL);
  3536. const char *error_handler = NULL;
  3537. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3538. const char *error_page_file_ext, *tstr;
  3539. const char *status_text = mg_get_response_code_text(conn, status);
  3540. if (conn == NULL) {
  3541. return;
  3542. }
  3543. conn->status_code = status;
  3544. if (conn->in_error_handler || (conn->ctx->callbacks.http_error == NULL)
  3545. || conn->ctx->callbacks.http_error(conn, status)) {
  3546. /* Check for recursion */
  3547. if (conn->in_error_handler) {
  3548. DEBUG_TRACE(
  3549. "Recursion when handling error %u - fall back to default",
  3550. status);
  3551. } else {
  3552. /* Send user defined error pages, if defined */
  3553. error_handler = conn->ctx->config[ERROR_PAGES];
  3554. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3555. page_handler_found = 0;
  3556. if (error_handler != NULL) {
  3557. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3558. switch (scope) {
  3559. case 1: /* Handler for specific error, e.g. 404 error */
  3560. mg_snprintf(conn,
  3561. &truncated,
  3562. buf,
  3563. sizeof(buf) - 32,
  3564. "%serror%03u.",
  3565. error_handler,
  3566. status);
  3567. break;
  3568. case 2: /* Handler for error group, e.g., 5xx error
  3569. * handler
  3570. * for all server errors (500-599) */
  3571. mg_snprintf(conn,
  3572. &truncated,
  3573. buf,
  3574. sizeof(buf) - 32,
  3575. "%serror%01uxx.",
  3576. error_handler,
  3577. status / 100);
  3578. break;
  3579. default: /* Handler for all errors */
  3580. mg_snprintf(conn,
  3581. &truncated,
  3582. buf,
  3583. sizeof(buf) - 32,
  3584. "%serror.",
  3585. error_handler);
  3586. break;
  3587. }
  3588. /* String truncation in buf may only occur if
  3589. * error_handler is too long. This string is
  3590. * from the config, not from a client. */
  3591. (void)truncated;
  3592. len = (int)strlen(buf);
  3593. tstr = strchr(error_page_file_ext, '.');
  3594. while (tstr) {
  3595. for (i = 1;
  3596. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3597. i++)
  3598. buf[len + i - 1] = tstr[i];
  3599. buf[len + i - 1] = 0;
  3600. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3601. DEBUG_TRACE("Check error page %s - found", buf);
  3602. page_handler_found = 1;
  3603. break;
  3604. }
  3605. DEBUG_TRACE("Check error page %s - not found", buf);
  3606. tstr = strchr(tstr + i, '.');
  3607. }
  3608. }
  3609. }
  3610. if (page_handler_found) {
  3611. conn->in_error_handler = 1;
  3612. handle_file_based_request(conn, buf, &error_page_file);
  3613. conn->in_error_handler = 0;
  3614. return;
  3615. }
  3616. }
  3617. /* No custom error page. Send default error page. */
  3618. gmt_time_string(date, sizeof(date), &curtime);
  3619. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3620. has_body = ((status > 199) && (status != 204) && (status != 304));
  3621. conn->must_close = 1;
  3622. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3623. send_no_cache_header(conn);
  3624. send_additional_header(conn);
  3625. if (has_body) {
  3626. mg_printf(conn,
  3627. "%s",
  3628. "Content-Type: text/plain; charset=utf-8\r\n");
  3629. }
  3630. mg_printf(conn,
  3631. "Date: %s\r\n"
  3632. "Connection: close\r\n\r\n",
  3633. date);
  3634. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3635. if (has_body) {
  3636. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3637. if (fmt != NULL) {
  3638. va_start(ap, fmt);
  3639. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3640. va_end(ap);
  3641. mg_write(conn, buf, strlen(buf));
  3642. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3643. }
  3644. } else {
  3645. /* No body allowed. Close the connection. */
  3646. DEBUG_TRACE("Error %i", status);
  3647. }
  3648. }
  3649. }
  3650. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3651. /* Create substitutes for POSIX functions in Win32. */
  3652. #if defined(__MINGW32__)
  3653. /* Show no warning in case system functions are not used. */
  3654. #pragma GCC diagnostic push
  3655. #pragma GCC diagnostic ignored "-Wunused-function"
  3656. #endif
  3657. FUNCTION_MAY_BE_UNUSED
  3658. static int
  3659. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3660. {
  3661. (void)unused;
  3662. *mutex = CreateMutex(NULL, FALSE, NULL);
  3663. return (*mutex == NULL) ? -1 : 0;
  3664. }
  3665. FUNCTION_MAY_BE_UNUSED
  3666. static int
  3667. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3668. {
  3669. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3670. }
  3671. FUNCTION_MAY_BE_UNUSED
  3672. static int
  3673. pthread_mutex_lock(pthread_mutex_t *mutex)
  3674. {
  3675. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  3676. : -1;
  3677. }
  3678. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3679. FUNCTION_MAY_BE_UNUSED
  3680. static int
  3681. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3682. {
  3683. switch (WaitForSingleObject(*mutex, 0)) {
  3684. case WAIT_OBJECT_0:
  3685. return 0;
  3686. case WAIT_TIMEOUT:
  3687. return -2; /* EBUSY */
  3688. }
  3689. return -1;
  3690. }
  3691. #endif
  3692. FUNCTION_MAY_BE_UNUSED
  3693. static int
  3694. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3695. {
  3696. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3697. }
  3698. FUNCTION_MAY_BE_UNUSED
  3699. static int
  3700. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3701. {
  3702. (void)unused;
  3703. InitializeCriticalSection(&cv->threadIdSec);
  3704. cv->waiting_thread = NULL;
  3705. return 0;
  3706. }
  3707. FUNCTION_MAY_BE_UNUSED
  3708. static int
  3709. pthread_cond_timedwait(pthread_cond_t *cv,
  3710. pthread_mutex_t *mutex,
  3711. const struct timespec *abstime)
  3712. {
  3713. struct mg_workerTLS **ptls,
  3714. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3715. int ok;
  3716. int64_t nsnow, nswaitabs, nswaitrel;
  3717. DWORD mswaitrel;
  3718. EnterCriticalSection(&cv->threadIdSec);
  3719. /* Add this thread to cv's waiting list */
  3720. ptls = &cv->waiting_thread;
  3721. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3722. ;
  3723. tls->next_waiting_thread = NULL;
  3724. *ptls = tls;
  3725. LeaveCriticalSection(&cv->threadIdSec);
  3726. if (abstime) {
  3727. nsnow = mg_get_current_time_ns();
  3728. nswaitabs =
  3729. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3730. nswaitrel = nswaitabs - nsnow;
  3731. if (nswaitrel < 0) {
  3732. nswaitrel = 0;
  3733. }
  3734. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3735. } else {
  3736. mswaitrel = (DWORD)INFINITE;
  3737. }
  3738. pthread_mutex_unlock(mutex);
  3739. ok = (WAIT_OBJECT_0
  3740. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3741. if (!ok) {
  3742. ok = 1;
  3743. EnterCriticalSection(&cv->threadIdSec);
  3744. ptls = &cv->waiting_thread;
  3745. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3746. if (*ptls == tls) {
  3747. *ptls = tls->next_waiting_thread;
  3748. ok = 0;
  3749. break;
  3750. }
  3751. }
  3752. LeaveCriticalSection(&cv->threadIdSec);
  3753. if (ok) {
  3754. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  3755. (DWORD)INFINITE);
  3756. }
  3757. }
  3758. /* This thread has been removed from cv's waiting list */
  3759. pthread_mutex_lock(mutex);
  3760. return ok ? 0 : -1;
  3761. }
  3762. FUNCTION_MAY_BE_UNUSED
  3763. static int
  3764. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3765. {
  3766. return pthread_cond_timedwait(cv, mutex, NULL);
  3767. }
  3768. FUNCTION_MAY_BE_UNUSED
  3769. static int
  3770. pthread_cond_signal(pthread_cond_t *cv)
  3771. {
  3772. HANDLE wkup = NULL;
  3773. BOOL ok = FALSE;
  3774. EnterCriticalSection(&cv->threadIdSec);
  3775. if (cv->waiting_thread) {
  3776. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3777. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3778. ok = SetEvent(wkup);
  3779. assert(ok);
  3780. }
  3781. LeaveCriticalSection(&cv->threadIdSec);
  3782. return ok ? 0 : 1;
  3783. }
  3784. FUNCTION_MAY_BE_UNUSED
  3785. static int
  3786. pthread_cond_broadcast(pthread_cond_t *cv)
  3787. {
  3788. EnterCriticalSection(&cv->threadIdSec);
  3789. while (cv->waiting_thread) {
  3790. pthread_cond_signal(cv);
  3791. }
  3792. LeaveCriticalSection(&cv->threadIdSec);
  3793. return 0;
  3794. }
  3795. FUNCTION_MAY_BE_UNUSED
  3796. static int
  3797. pthread_cond_destroy(pthread_cond_t *cv)
  3798. {
  3799. EnterCriticalSection(&cv->threadIdSec);
  3800. assert(cv->waiting_thread == NULL);
  3801. LeaveCriticalSection(&cv->threadIdSec);
  3802. DeleteCriticalSection(&cv->threadIdSec);
  3803. return 0;
  3804. }
  3805. #ifdef ALTERNATIVE_QUEUE
  3806. FUNCTION_MAY_BE_UNUSED
  3807. static void *
  3808. event_create(void)
  3809. {
  3810. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3811. }
  3812. FUNCTION_MAY_BE_UNUSED
  3813. static int
  3814. event_wait(void *eventhdl)
  3815. {
  3816. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  3817. return (res == WAIT_OBJECT_0);
  3818. }
  3819. FUNCTION_MAY_BE_UNUSED
  3820. static int
  3821. event_signal(void *eventhdl)
  3822. {
  3823. return (int)SetEvent((HANDLE)eventhdl);
  3824. }
  3825. FUNCTION_MAY_BE_UNUSED
  3826. static void
  3827. event_destroy(void *eventhdl)
  3828. {
  3829. CloseHandle((HANDLE)eventhdl);
  3830. }
  3831. #endif
  3832. #if defined(__MINGW32__)
  3833. /* Enable unused function warning again */
  3834. #pragma GCC diagnostic pop
  3835. #endif
  3836. /* For Windows, change all slashes to backslashes in path names. */
  3837. static void
  3838. change_slashes_to_backslashes(char *path)
  3839. {
  3840. int i;
  3841. for (i = 0; path[i] != '\0'; i++) {
  3842. if (path[i] == '/') {
  3843. path[i] = '\\';
  3844. }
  3845. /* remove double backslash (check i > 0 to preserve UNC paths,
  3846. * like \\server\file.txt) */
  3847. if ((path[i] == '\\') && (i > 0)) {
  3848. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3849. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3850. }
  3851. }
  3852. }
  3853. }
  3854. static int
  3855. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3856. {
  3857. int diff;
  3858. do {
  3859. diff = tolower(*s1) - tolower(*s2);
  3860. s1++;
  3861. s2++;
  3862. } while ((diff == 0) && (s1[-1] != '\0'));
  3863. return diff;
  3864. }
  3865. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3866. * wbuf and wbuf_len is a target buffer and its length. */
  3867. static void
  3868. path_to_unicode(const struct mg_connection *conn,
  3869. const char *path,
  3870. wchar_t *wbuf,
  3871. size_t wbuf_len)
  3872. {
  3873. char buf[PATH_MAX], buf2[PATH_MAX];
  3874. wchar_t wbuf2[MAX_PATH + 1];
  3875. DWORD long_len, err;
  3876. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3877. mg_strlcpy(buf, path, sizeof(buf));
  3878. change_slashes_to_backslashes(buf);
  3879. /* Convert to Unicode and back. If doubly-converted string does not
  3880. * match the original, something is fishy, reject. */
  3881. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3882. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3883. WideCharToMultiByte(
  3884. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3885. if (strcmp(buf, buf2) != 0) {
  3886. wbuf[0] = L'\0';
  3887. }
  3888. /* Windows file systems are not case sensitive, but you can still use
  3889. * uppercase and lowercase letters (on all modern file systems).
  3890. * The server can check if the URI uses the same upper/lowercase
  3891. * letters an the file system, effectively making Windows servers
  3892. * case sensitive (like Linux servers are). It is still not possible
  3893. * to use two files with the same name in different cases on Windows
  3894. * (like /a and /A) - this would be possible in Linux.
  3895. * As a default, Windows is not case sensitive, but the case sensitive
  3896. * file name check can be activated by an additional configuration. */
  3897. if (conn) {
  3898. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3899. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3900. /* Use case sensitive compare function */
  3901. fcompare = wcscmp;
  3902. }
  3903. }
  3904. (void)conn; /* conn is currently unused */
  3905. #if !defined(_WIN32_WCE)
  3906. /* Only accept a full file path, not a Windows short (8.3) path. */
  3907. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3908. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3909. if (long_len == 0) {
  3910. err = GetLastError();
  3911. if (err == ERROR_FILE_NOT_FOUND) {
  3912. /* File does not exist. This is not always a problem here. */
  3913. return;
  3914. }
  3915. }
  3916. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3917. /* Short name is used. */
  3918. wbuf[0] = L'\0';
  3919. }
  3920. #else
  3921. (void)long_len;
  3922. (void)wbuf2;
  3923. (void)err;
  3924. if (strchr(path, '~')) {
  3925. wbuf[0] = L'\0';
  3926. }
  3927. #endif
  3928. }
  3929. /* Windows happily opens files with some garbage at the end of file name.
  3930. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3931. * "a.cgi", despite one would expect an error back.
  3932. * This function returns non-0 if path ends with some garbage. */
  3933. static int
  3934. path_cannot_disclose_cgi(const char *path)
  3935. {
  3936. static const char *allowed_last_characters = "_-";
  3937. int last = path[strlen(path) - 1];
  3938. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3939. }
  3940. static int
  3941. mg_stat(const struct mg_connection *conn,
  3942. const char *path,
  3943. struct mg_file_stat *filep)
  3944. {
  3945. wchar_t wbuf[PATH_MAX];
  3946. WIN32_FILE_ATTRIBUTE_DATA info;
  3947. time_t creation_time;
  3948. if (!filep) {
  3949. return 0;
  3950. }
  3951. memset(filep, 0, sizeof(*filep));
  3952. if (conn && is_file_in_memory(conn, path)) {
  3953. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3954. * memset */
  3955. /* Quick fix (for 1.9.x): */
  3956. /* mg_stat must fill all fields, also for files in memory */
  3957. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3958. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3959. filep->size = tmp_file.stat.size;
  3960. filep->location = 2;
  3961. /* TODO: for 1.10: restructure how files in memory are handled */
  3962. /* The "file in memory" feature is a candidate for deletion.
  3963. * Please join the discussion at
  3964. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3965. */
  3966. filep->last_modified = time(NULL); /* TODO */
  3967. /* last_modified = now ... assumes the file may change during
  3968. * runtime,
  3969. * so every mg_fopen call may return different data */
  3970. /* last_modified = conn->ctx.start_time;
  3971. * May be used it the data does not change during runtime. This
  3972. * allows
  3973. * browser caching. Since we do not know, we have to assume the file
  3974. * in memory may change. */
  3975. return 1;
  3976. }
  3977. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3978. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3979. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3980. filep->last_modified =
  3981. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3982. info.ftLastWriteTime.dwHighDateTime);
  3983. /* On Windows, the file creation time can be higher than the
  3984. * modification time, e.g. when a file is copied.
  3985. * Since the Last-Modified timestamp is used for caching
  3986. * it should be based on the most recent timestamp. */
  3987. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3988. info.ftCreationTime.dwHighDateTime);
  3989. if (creation_time > filep->last_modified) {
  3990. filep->last_modified = creation_time;
  3991. }
  3992. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3993. /* If file name is fishy, reset the file structure and return
  3994. * error.
  3995. * Note it is important to reset, not just return the error, cause
  3996. * functions like is_file_opened() check the struct. */
  3997. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3998. memset(filep, 0, sizeof(*filep));
  3999. return 0;
  4000. }
  4001. return 1;
  4002. }
  4003. return 0;
  4004. }
  4005. static int
  4006. mg_remove(const struct mg_connection *conn, const char *path)
  4007. {
  4008. wchar_t wbuf[PATH_MAX];
  4009. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4010. return DeleteFileW(wbuf) ? 0 : -1;
  4011. }
  4012. static int
  4013. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4014. {
  4015. wchar_t wbuf[PATH_MAX];
  4016. (void)mode;
  4017. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4018. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4019. }
  4020. /* Create substitutes for POSIX functions in Win32. */
  4021. #if defined(__MINGW32__)
  4022. /* Show no warning in case system functions are not used. */
  4023. #pragma GCC diagnostic push
  4024. #pragma GCC diagnostic ignored "-Wunused-function"
  4025. #endif
  4026. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4027. FUNCTION_MAY_BE_UNUSED
  4028. static DIR *
  4029. mg_opendir(const struct mg_connection *conn, const char *name)
  4030. {
  4031. DIR *dir = NULL;
  4032. wchar_t wpath[PATH_MAX];
  4033. DWORD attrs;
  4034. if (name == NULL) {
  4035. SetLastError(ERROR_BAD_ARGUMENTS);
  4036. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4037. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4038. } else {
  4039. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4040. attrs = GetFileAttributesW(wpath);
  4041. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  4042. == FILE_ATTRIBUTE_DIRECTORY)) {
  4043. (void)wcscat(wpath, L"\\*");
  4044. dir->handle = FindFirstFileW(wpath, &dir->info);
  4045. dir->result.d_name[0] = '\0';
  4046. } else {
  4047. mg_free(dir);
  4048. dir = NULL;
  4049. }
  4050. }
  4051. return dir;
  4052. }
  4053. FUNCTION_MAY_BE_UNUSED
  4054. static int
  4055. mg_closedir(DIR *dir)
  4056. {
  4057. int result = 0;
  4058. if (dir != NULL) {
  4059. if (dir->handle != INVALID_HANDLE_VALUE)
  4060. result = FindClose(dir->handle) ? 0 : -1;
  4061. mg_free(dir);
  4062. } else {
  4063. result = -1;
  4064. SetLastError(ERROR_BAD_ARGUMENTS);
  4065. }
  4066. return result;
  4067. }
  4068. FUNCTION_MAY_BE_UNUSED
  4069. static struct dirent *
  4070. mg_readdir(DIR *dir)
  4071. {
  4072. struct dirent *result = 0;
  4073. if (dir) {
  4074. if (dir->handle != INVALID_HANDLE_VALUE) {
  4075. result = &dir->result;
  4076. (void)WideCharToMultiByte(CP_UTF8,
  4077. 0,
  4078. dir->info.cFileName,
  4079. -1,
  4080. result->d_name,
  4081. sizeof(result->d_name),
  4082. NULL,
  4083. NULL);
  4084. if (!FindNextFileW(dir->handle, &dir->info)) {
  4085. (void)FindClose(dir->handle);
  4086. dir->handle = INVALID_HANDLE_VALUE;
  4087. }
  4088. } else {
  4089. SetLastError(ERROR_FILE_NOT_FOUND);
  4090. }
  4091. } else {
  4092. SetLastError(ERROR_BAD_ARGUMENTS);
  4093. }
  4094. return result;
  4095. }
  4096. #ifndef HAVE_POLL
  4097. FUNCTION_MAY_BE_UNUSED
  4098. static int
  4099. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4100. {
  4101. struct timeval tv;
  4102. fd_set set;
  4103. unsigned int i;
  4104. int result;
  4105. SOCKET maxfd = 0;
  4106. memset(&tv, 0, sizeof(tv));
  4107. tv.tv_sec = milliseconds / 1000;
  4108. tv.tv_usec = (milliseconds % 1000) * 1000;
  4109. FD_ZERO(&set);
  4110. for (i = 0; i < n; i++) {
  4111. FD_SET((SOCKET)pfd[i].fd, &set);
  4112. pfd[i].revents = 0;
  4113. if (pfd[i].fd > maxfd) {
  4114. maxfd = pfd[i].fd;
  4115. }
  4116. }
  4117. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4118. for (i = 0; i < n; i++) {
  4119. if (FD_ISSET(pfd[i].fd, &set)) {
  4120. pfd[i].revents = POLLIN;
  4121. }
  4122. }
  4123. }
  4124. /* We should subtract the time used in select from remaining
  4125. * "milliseconds", in particular if called from mg_poll with a
  4126. * timeout quantum.
  4127. * Unfortunately, the remaining time is not stored in "tv" in all
  4128. * implementations, so the result in "tv" must be considered undefined.
  4129. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4130. return result;
  4131. }
  4132. #endif /* HAVE_POLL */
  4133. #if defined(__MINGW32__)
  4134. /* Enable unused function warning again */
  4135. #pragma GCC diagnostic pop
  4136. #endif
  4137. static void
  4138. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4139. {
  4140. (void)conn; /* Unused. */
  4141. #if defined(_WIN32_WCE)
  4142. (void)sock;
  4143. #else
  4144. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4145. #endif
  4146. }
  4147. int
  4148. mg_start_thread(mg_thread_func_t f, void *p)
  4149. {
  4150. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4151. /* Compile-time option to control stack size, e.g.
  4152. * -DUSE_STACK_SIZE=16384
  4153. */
  4154. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4155. == ((uintptr_t)(-1L)))
  4156. ? -1
  4157. : 0);
  4158. #else
  4159. return (
  4160. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4161. ? -1
  4162. : 0);
  4163. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4164. }
  4165. /* Start a thread storing the thread context. */
  4166. static int
  4167. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4168. void *p,
  4169. pthread_t *threadidptr)
  4170. {
  4171. uintptr_t uip;
  4172. HANDLE threadhandle;
  4173. int result = -1;
  4174. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4175. threadhandle = (HANDLE)uip;
  4176. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4177. *threadidptr = threadhandle;
  4178. result = 0;
  4179. }
  4180. return result;
  4181. }
  4182. /* Wait for a thread to finish. */
  4183. static int
  4184. mg_join_thread(pthread_t threadid)
  4185. {
  4186. int result;
  4187. DWORD dwevent;
  4188. result = -1;
  4189. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4190. if (dwevent == WAIT_FAILED) {
  4191. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4192. } else {
  4193. if (dwevent == WAIT_OBJECT_0) {
  4194. CloseHandle(threadid);
  4195. result = 0;
  4196. }
  4197. }
  4198. return result;
  4199. }
  4200. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4201. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4202. /* Create substitutes for POSIX functions in Win32. */
  4203. #if defined(__MINGW32__)
  4204. /* Show no warning in case system functions are not used. */
  4205. #pragma GCC diagnostic push
  4206. #pragma GCC diagnostic ignored "-Wunused-function"
  4207. #endif
  4208. FUNCTION_MAY_BE_UNUSED
  4209. static HANDLE
  4210. dlopen(const char *dll_name, int flags)
  4211. {
  4212. wchar_t wbuf[PATH_MAX];
  4213. (void)flags;
  4214. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4215. return LoadLibraryW(wbuf);
  4216. }
  4217. FUNCTION_MAY_BE_UNUSED
  4218. static int
  4219. dlclose(void *handle)
  4220. {
  4221. int result;
  4222. if (FreeLibrary((HMODULE)handle) != 0) {
  4223. result = 0;
  4224. } else {
  4225. result = -1;
  4226. }
  4227. return result;
  4228. }
  4229. #if defined(__MINGW32__)
  4230. /* Enable unused function warning again */
  4231. #pragma GCC diagnostic pop
  4232. #endif
  4233. #endif
  4234. #if !defined(NO_CGI)
  4235. #define SIGKILL (0)
  4236. static int
  4237. kill(pid_t pid, int sig_num)
  4238. {
  4239. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4240. (void)CloseHandle((HANDLE)pid);
  4241. return 0;
  4242. }
  4243. static void
  4244. trim_trailing_whitespaces(char *s)
  4245. {
  4246. char *e = s + strlen(s) - 1;
  4247. while ((e > s) && isspace(*(unsigned char *)e)) {
  4248. *e-- = '\0';
  4249. }
  4250. }
  4251. static pid_t
  4252. spawn_process(struct mg_connection *conn,
  4253. const char *prog,
  4254. char *envblk,
  4255. char *envp[],
  4256. int fdin[2],
  4257. int fdout[2],
  4258. int fderr[2],
  4259. const char *dir)
  4260. {
  4261. HANDLE me;
  4262. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4263. cmdline[PATH_MAX], buf[PATH_MAX];
  4264. int truncated;
  4265. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4266. STARTUPINFOA si;
  4267. PROCESS_INFORMATION pi = {0};
  4268. (void)envp;
  4269. memset(&si, 0, sizeof(si));
  4270. si.cb = sizeof(si);
  4271. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4272. si.wShowWindow = SW_HIDE;
  4273. me = GetCurrentProcess();
  4274. DuplicateHandle(me,
  4275. (HANDLE)_get_osfhandle(fdin[0]),
  4276. me,
  4277. &si.hStdInput,
  4278. 0,
  4279. TRUE,
  4280. DUPLICATE_SAME_ACCESS);
  4281. DuplicateHandle(me,
  4282. (HANDLE)_get_osfhandle(fdout[1]),
  4283. me,
  4284. &si.hStdOutput,
  4285. 0,
  4286. TRUE,
  4287. DUPLICATE_SAME_ACCESS);
  4288. DuplicateHandle(me,
  4289. (HANDLE)_get_osfhandle(fderr[1]),
  4290. me,
  4291. &si.hStdError,
  4292. 0,
  4293. TRUE,
  4294. DUPLICATE_SAME_ACCESS);
  4295. /* Mark handles that should not be inherited. See
  4296. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4297. */
  4298. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4299. HANDLE_FLAG_INHERIT,
  4300. 0);
  4301. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4302. HANDLE_FLAG_INHERIT,
  4303. 0);
  4304. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4305. HANDLE_FLAG_INHERIT,
  4306. 0);
  4307. /* If CGI file is a script, try to read the interpreter line */
  4308. interp = conn->ctx->config[CGI_INTERPRETER];
  4309. if (interp == NULL) {
  4310. buf[0] = buf[1] = '\0';
  4311. /* Read the first line of the script into the buffer */
  4312. mg_snprintf(
  4313. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4314. if (truncated) {
  4315. pi.hProcess = (pid_t)-1;
  4316. goto spawn_cleanup;
  4317. }
  4318. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4319. p = (char *)file.access.membuf;
  4320. mg_fgets(buf, sizeof(buf), &file, &p);
  4321. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4322. buf[sizeof(buf) - 1] = '\0';
  4323. }
  4324. if ((buf[0] == '#') && (buf[1] == '!')) {
  4325. trim_trailing_whitespaces(buf + 2);
  4326. } else {
  4327. buf[2] = '\0';
  4328. }
  4329. interp = buf + 2;
  4330. }
  4331. if (interp[0] != '\0') {
  4332. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4333. interp = full_interp;
  4334. }
  4335. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4336. if (interp[0] != '\0') {
  4337. mg_snprintf(conn,
  4338. &truncated,
  4339. cmdline,
  4340. sizeof(cmdline),
  4341. "\"%s\" \"%s\\%s\"",
  4342. interp,
  4343. full_dir,
  4344. prog);
  4345. } else {
  4346. mg_snprintf(conn,
  4347. &truncated,
  4348. cmdline,
  4349. sizeof(cmdline),
  4350. "\"%s\\%s\"",
  4351. full_dir,
  4352. prog);
  4353. }
  4354. if (truncated) {
  4355. pi.hProcess = (pid_t)-1;
  4356. goto spawn_cleanup;
  4357. }
  4358. DEBUG_TRACE("Running [%s]", cmdline);
  4359. if (CreateProcessA(NULL,
  4360. cmdline,
  4361. NULL,
  4362. NULL,
  4363. TRUE,
  4364. CREATE_NEW_PROCESS_GROUP,
  4365. envblk,
  4366. NULL,
  4367. &si,
  4368. &pi) == 0) {
  4369. mg_cry(
  4370. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4371. pi.hProcess = (pid_t)-1;
  4372. /* goto spawn_cleanup; */
  4373. }
  4374. spawn_cleanup:
  4375. (void)CloseHandle(si.hStdOutput);
  4376. (void)CloseHandle(si.hStdError);
  4377. (void)CloseHandle(si.hStdInput);
  4378. if (pi.hThread != NULL) {
  4379. (void)CloseHandle(pi.hThread);
  4380. }
  4381. return (pid_t)pi.hProcess;
  4382. }
  4383. #endif /* !NO_CGI */
  4384. static int
  4385. set_blocking_mode(SOCKET sock)
  4386. {
  4387. unsigned long non_blocking = 0;
  4388. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4389. }
  4390. static int
  4391. set_non_blocking_mode(SOCKET sock)
  4392. {
  4393. unsigned long non_blocking = 1;
  4394. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4395. }
  4396. #else
  4397. static int
  4398. mg_stat(const struct mg_connection *conn,
  4399. const char *path,
  4400. struct mg_file_stat *filep)
  4401. {
  4402. struct stat st;
  4403. if (!filep) {
  4404. return 0;
  4405. }
  4406. memset(filep, 0, sizeof(*filep));
  4407. if (conn && is_file_in_memory(conn, path)) {
  4408. /* Quick fix (for 1.9.x): */
  4409. /* mg_stat must fill all fields, also for files in memory */
  4410. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4411. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4412. filep->size = tmp_file.stat.size;
  4413. filep->last_modified = time(NULL);
  4414. filep->location = 2;
  4415. /* TODO: for 1.10: restructure how files in memory are handled */
  4416. return 1;
  4417. }
  4418. if (0 == stat(path, &st)) {
  4419. filep->size = (uint64_t)(st.st_size);
  4420. filep->last_modified = st.st_mtime;
  4421. filep->is_directory = S_ISDIR(st.st_mode);
  4422. return 1;
  4423. }
  4424. return 0;
  4425. }
  4426. static void
  4427. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4428. {
  4429. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4430. if (conn) {
  4431. mg_cry(conn,
  4432. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4433. __func__,
  4434. strerror(ERRNO));
  4435. }
  4436. }
  4437. }
  4438. int
  4439. mg_start_thread(mg_thread_func_t func, void *param)
  4440. {
  4441. pthread_t thread_id;
  4442. pthread_attr_t attr;
  4443. int result;
  4444. (void)pthread_attr_init(&attr);
  4445. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4446. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4447. /* Compile-time option to control stack size,
  4448. * e.g. -DUSE_STACK_SIZE=16384 */
  4449. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4450. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4451. result = pthread_create(&thread_id, &attr, func, param);
  4452. pthread_attr_destroy(&attr);
  4453. return result;
  4454. }
  4455. /* Start a thread storing the thread context. */
  4456. static int
  4457. mg_start_thread_with_id(mg_thread_func_t func,
  4458. void *param,
  4459. pthread_t *threadidptr)
  4460. {
  4461. pthread_t thread_id;
  4462. pthread_attr_t attr;
  4463. int result;
  4464. (void)pthread_attr_init(&attr);
  4465. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4466. /* Compile-time option to control stack size,
  4467. * e.g. -DUSE_STACK_SIZE=16384 */
  4468. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4469. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4470. result = pthread_create(&thread_id, &attr, func, param);
  4471. pthread_attr_destroy(&attr);
  4472. if ((result == 0) && (threadidptr != NULL)) {
  4473. *threadidptr = thread_id;
  4474. }
  4475. return result;
  4476. }
  4477. /* Wait for a thread to finish. */
  4478. static int
  4479. mg_join_thread(pthread_t threadid)
  4480. {
  4481. int result;
  4482. result = pthread_join(threadid, NULL);
  4483. return result;
  4484. }
  4485. #ifndef NO_CGI
  4486. static pid_t
  4487. spawn_process(struct mg_connection *conn,
  4488. const char *prog,
  4489. char *envblk,
  4490. char *envp[],
  4491. int fdin[2],
  4492. int fdout[2],
  4493. int fderr[2],
  4494. const char *dir)
  4495. {
  4496. pid_t pid;
  4497. const char *interp;
  4498. (void)envblk;
  4499. if (conn == NULL) {
  4500. return 0;
  4501. }
  4502. if ((pid = fork()) == -1) {
  4503. /* Parent */
  4504. mg_send_http_error(conn,
  4505. 500,
  4506. "Error: Creating CGI process\nfork(): %s",
  4507. strerror(ERRNO));
  4508. } else if (pid == 0) {
  4509. /* Child */
  4510. if (chdir(dir) != 0) {
  4511. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4512. } else if (dup2(fdin[0], 0) == -1) {
  4513. mg_cry(conn,
  4514. "%s: dup2(%d, 0): %s",
  4515. __func__,
  4516. fdin[0],
  4517. strerror(ERRNO));
  4518. } else if (dup2(fdout[1], 1) == -1) {
  4519. mg_cry(conn,
  4520. "%s: dup2(%d, 1): %s",
  4521. __func__,
  4522. fdout[1],
  4523. strerror(ERRNO));
  4524. } else if (dup2(fderr[1], 2) == -1) {
  4525. mg_cry(conn,
  4526. "%s: dup2(%d, 2): %s",
  4527. __func__,
  4528. fderr[1],
  4529. strerror(ERRNO));
  4530. } else {
  4531. /* Keep stderr and stdout in two different pipes.
  4532. * Stdout will be sent back to the client,
  4533. * stderr should go into a server error log. */
  4534. (void)close(fdin[0]);
  4535. (void)close(fdout[1]);
  4536. (void)close(fderr[1]);
  4537. /* Close write end fdin and read end fdout and fderr */
  4538. (void)close(fdin[1]);
  4539. (void)close(fdout[0]);
  4540. (void)close(fderr[0]);
  4541. /* After exec, all signal handlers are restored to their default
  4542. * values, with one exception of SIGCHLD. According to
  4543. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4544. * leave unchanged after exec if it was set to be ignored. Restore
  4545. * it to default action. */
  4546. signal(SIGCHLD, SIG_DFL);
  4547. interp = conn->ctx->config[CGI_INTERPRETER];
  4548. if (interp == NULL) {
  4549. (void)execle(prog, prog, NULL, envp);
  4550. mg_cry(conn,
  4551. "%s: execle(%s): %s",
  4552. __func__,
  4553. prog,
  4554. strerror(ERRNO));
  4555. } else {
  4556. (void)execle(interp, interp, prog, NULL, envp);
  4557. mg_cry(conn,
  4558. "%s: execle(%s %s): %s",
  4559. __func__,
  4560. interp,
  4561. prog,
  4562. strerror(ERRNO));
  4563. }
  4564. }
  4565. exit(EXIT_FAILURE);
  4566. }
  4567. return pid;
  4568. }
  4569. #endif /* !NO_CGI */
  4570. static int
  4571. set_non_blocking_mode(SOCKET sock)
  4572. {
  4573. int flags = fcntl(sock, F_GETFL, 0);
  4574. if (flags < 0) {
  4575. return -1;
  4576. }
  4577. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4578. return -1;
  4579. }
  4580. return 0;
  4581. }
  4582. static int
  4583. set_blocking_mode(SOCKET sock)
  4584. {
  4585. int flags = fcntl(sock, F_GETFL, 0);
  4586. if (flags < 0) {
  4587. return -1;
  4588. }
  4589. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4590. return -1;
  4591. }
  4592. return 0;
  4593. }
  4594. #endif /* _WIN32 / else */
  4595. /* End of initial operating system specific define block. */
  4596. /* Get a random number (independent of C rand function) */
  4597. static uint64_t
  4598. get_random(void)
  4599. {
  4600. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4601. static uint64_t lcg = 0; /* Linear congruential generator */
  4602. uint64_t now = mg_get_current_time_ns();
  4603. if (lfsr == 0) {
  4604. /* lfsr will be only 0 if has not been initialized,
  4605. * so this code is called only once. */
  4606. lfsr = mg_get_current_time_ns();
  4607. lcg = mg_get_current_time_ns();
  4608. } else {
  4609. /* Get the next step of both random number generators. */
  4610. lfsr = (lfsr >> 1)
  4611. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4612. << 63);
  4613. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4614. }
  4615. /* Combining two pseudo-random number generators and a high resolution
  4616. * part
  4617. * of the current server time will make it hard (impossible?) to guess
  4618. * the
  4619. * next number. */
  4620. return (lfsr ^ lcg ^ now);
  4621. }
  4622. static int
  4623. mg_poll(struct pollfd *pfd,
  4624. unsigned int n,
  4625. int milliseconds,
  4626. volatile int *stop_server)
  4627. {
  4628. /* Call poll, but only for a maximum time of a few seconds.
  4629. * This will allow to stop the server after some seconds, instead
  4630. * of having to wait for a long socket timeout. */
  4631. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4632. do {
  4633. int result;
  4634. if (*stop_server) {
  4635. /* Shut down signal */
  4636. return -2;
  4637. }
  4638. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4639. ms_now = milliseconds;
  4640. }
  4641. result = poll(pfd, n, ms_now);
  4642. if (result != 0) {
  4643. /* Poll returned either success (1) or error (-1).
  4644. * Forward both to the caller. */
  4645. return result;
  4646. }
  4647. /* Poll returned timeout (0). */
  4648. if (milliseconds > 0) {
  4649. milliseconds -= ms_now;
  4650. }
  4651. } while (milliseconds != 0);
  4652. /* timeout: return 0 */
  4653. return 0;
  4654. }
  4655. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4656. * descriptor.
  4657. * Return value:
  4658. * >=0 .. number of bytes successfully written
  4659. * -1 .. timeout
  4660. * -2 .. error
  4661. */
  4662. static int
  4663. push_inner(struct mg_context *ctx,
  4664. FILE *fp,
  4665. SOCKET sock,
  4666. SSL *ssl,
  4667. const char *buf,
  4668. int len,
  4669. double timeout)
  4670. {
  4671. uint64_t start = 0, now = 0, timeout_ns = 0;
  4672. int n, err;
  4673. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4674. #ifdef _WIN32
  4675. typedef int len_t;
  4676. #else
  4677. typedef size_t len_t;
  4678. #endif
  4679. if (timeout > 0) {
  4680. now = mg_get_current_time_ns();
  4681. start = now;
  4682. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4683. }
  4684. if (ctx == NULL) {
  4685. return -2;
  4686. }
  4687. #ifdef NO_SSL
  4688. if (ssl) {
  4689. return -2;
  4690. }
  4691. #endif
  4692. /* Try to read until it succeeds, fails, times out, or the server
  4693. * shuts down. */
  4694. for (;;) {
  4695. #ifndef NO_SSL
  4696. if (ssl != NULL) {
  4697. n = SSL_write(ssl, buf, len);
  4698. if (n <= 0) {
  4699. err = SSL_get_error(ssl, n);
  4700. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4701. err = ERRNO;
  4702. } else if ((err == SSL_ERROR_WANT_READ)
  4703. || (err == SSL_ERROR_WANT_WRITE)) {
  4704. n = 0;
  4705. } else {
  4706. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4707. return -2;
  4708. }
  4709. } else {
  4710. err = 0;
  4711. }
  4712. } else
  4713. #endif
  4714. if (fp != NULL) {
  4715. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4716. if (ferror(fp)) {
  4717. n = -1;
  4718. err = ERRNO;
  4719. } else {
  4720. err = 0;
  4721. }
  4722. } else {
  4723. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4724. err = (n < 0) ? ERRNO : 0;
  4725. #ifdef _WIN32
  4726. if (err == WSAEWOULDBLOCK) {
  4727. err = 0;
  4728. n = 0;
  4729. }
  4730. #else
  4731. if (err == EWOULDBLOCK) {
  4732. err = 0;
  4733. n = 0;
  4734. }
  4735. #endif
  4736. if (n < 0) {
  4737. /* shutdown of the socket at client side */
  4738. return -2;
  4739. }
  4740. }
  4741. if (ctx->stop_flag) {
  4742. return -2;
  4743. }
  4744. if ((n > 0) || ((n == 0) && (len == 0))) {
  4745. /* some data has been read, or no data was requested */
  4746. return n;
  4747. }
  4748. if (n < 0) {
  4749. /* socket error - check errno */
  4750. DEBUG_TRACE("send() failed, error %d", err);
  4751. /* TODO (mid): error handling depending on the error code.
  4752. * These codes are different between Windows and Linux.
  4753. * Currently there is no problem with failing send calls,
  4754. * if there is a reproducible situation, it should be
  4755. * investigated in detail.
  4756. */
  4757. return -2;
  4758. }
  4759. /* Only in case n=0 (timeout), repeat calling the write function */
  4760. /* If send failed, wait before retry */
  4761. if (fp != NULL) {
  4762. /* For files, just wait a fixed time,
  4763. * maybe an average disk seek time. */
  4764. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4765. } else {
  4766. /* For sockets, wait for the socket using select */
  4767. fd_set wfds;
  4768. struct timeval tv;
  4769. int sret;
  4770. #if defined(__GNUC__) || defined(__MINGW32__)
  4771. /* GCC seems to have a flaw with it's own socket macros:
  4772. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4773. */
  4774. #pragma GCC diagnostic push
  4775. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4776. #endif
  4777. FD_ZERO(&wfds);
  4778. FD_SET(sock, &wfds);
  4779. tv.tv_sec = (time_t)(ms_wait / 1000);
  4780. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4781. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4782. #if defined(__GNUC__) || defined(__MINGW32__)
  4783. #pragma GCC diagnostic pop
  4784. #endif
  4785. if (sret > 0) {
  4786. /* We got ready to write. Don't check the timeout
  4787. * but directly go back to write again. */
  4788. continue;
  4789. }
  4790. }
  4791. if (timeout > 0) {
  4792. now = mg_get_current_time_ns();
  4793. if ((now - start) > timeout_ns) {
  4794. /* Timeout */
  4795. break;
  4796. }
  4797. }
  4798. }
  4799. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4800. used */
  4801. return -1;
  4802. }
  4803. static int64_t
  4804. push_all(struct mg_context *ctx,
  4805. FILE *fp,
  4806. SOCKET sock,
  4807. SSL *ssl,
  4808. const char *buf,
  4809. int64_t len)
  4810. {
  4811. double timeout = -1.0;
  4812. int64_t n, nwritten = 0;
  4813. if (ctx == NULL) {
  4814. return -1;
  4815. }
  4816. if (ctx->config[REQUEST_TIMEOUT]) {
  4817. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4818. }
  4819. while ((len > 0) && (ctx->stop_flag == 0)) {
  4820. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4821. if (n < 0) {
  4822. if (nwritten == 0) {
  4823. nwritten = n; /* Propagate the error */
  4824. }
  4825. break;
  4826. } else if (n == 0) {
  4827. break; /* No more data to write */
  4828. } else {
  4829. nwritten += n;
  4830. len -= n;
  4831. }
  4832. }
  4833. return nwritten;
  4834. }
  4835. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4836. * Return value:
  4837. * >=0 .. number of bytes successfully read
  4838. * -1 .. timeout
  4839. * -2 .. error
  4840. */
  4841. static int
  4842. pull_inner(FILE *fp,
  4843. struct mg_connection *conn,
  4844. char *buf,
  4845. int len,
  4846. double timeout)
  4847. {
  4848. int nread, err = 0;
  4849. #ifdef _WIN32
  4850. typedef int len_t;
  4851. #else
  4852. typedef size_t len_t;
  4853. #endif
  4854. #ifndef NO_SSL
  4855. int ssl_pending;
  4856. #endif
  4857. /* We need an additional wait loop around this, because in some cases
  4858. * with TLSwe may get data from the socket but not from SSL_read.
  4859. * In this case we need to repeat at least once.
  4860. */
  4861. if (fp != NULL) {
  4862. #if !defined(_WIN32_WCE)
  4863. /* Use read() instead of fread(), because if we're reading from the
  4864. * CGI pipe, fread() may block until IO buffer is filled up. We
  4865. * cannot afford to block and must pass all read bytes immediately
  4866. * to the client. */
  4867. nread = (int)read(fileno(fp), buf, (size_t)len);
  4868. #else
  4869. /* WinCE does not support CGI pipes */
  4870. nread = (int)fread(buf, 1, (size_t)len, fp);
  4871. #endif
  4872. err = (nread < 0) ? ERRNO : 0;
  4873. if ((nread == 0) && (len > 0)) {
  4874. /* Should get data, but got EOL */
  4875. return -2;
  4876. }
  4877. #ifndef NO_SSL
  4878. } else if ((conn->ssl != NULL)
  4879. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4880. /* We already know there is no more data buffered in conn->buf
  4881. * but there is more available in the SSL layer. So don't poll
  4882. * conn->client.sock yet. */
  4883. if (ssl_pending > len) {
  4884. ssl_pending = len;
  4885. }
  4886. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4887. if (nread <= 0) {
  4888. err = SSL_get_error(conn->ssl, nread);
  4889. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4890. err = ERRNO;
  4891. } else if ((err == SSL_ERROR_WANT_READ)
  4892. || (err == SSL_ERROR_WANT_WRITE)) {
  4893. nread = 0;
  4894. } else {
  4895. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4896. return -1;
  4897. }
  4898. } else {
  4899. err = 0;
  4900. }
  4901. } else if (conn->ssl != NULL) {
  4902. struct pollfd pfd[1];
  4903. int pollres;
  4904. pfd[0].fd = conn->client.sock;
  4905. pfd[0].events = POLLIN;
  4906. pollres =
  4907. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4908. if (conn->ctx->stop_flag) {
  4909. return -2;
  4910. }
  4911. if (pollres > 0) {
  4912. nread = SSL_read(conn->ssl, buf, len);
  4913. if (nread <= 0) {
  4914. err = SSL_get_error(conn->ssl, nread);
  4915. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4916. err = ERRNO;
  4917. } else if ((err == SSL_ERROR_WANT_READ)
  4918. || (err == SSL_ERROR_WANT_WRITE)) {
  4919. nread = 0;
  4920. } else {
  4921. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4922. return -2;
  4923. }
  4924. } else {
  4925. err = 0;
  4926. }
  4927. } else if (pollres < 0) {
  4928. /* Error */
  4929. return -2;
  4930. } else {
  4931. /* pollres = 0 means timeout */
  4932. nread = 0;
  4933. }
  4934. #endif
  4935. } else {
  4936. struct pollfd pfd[1];
  4937. int pollres;
  4938. pfd[0].fd = conn->client.sock;
  4939. pfd[0].events = POLLIN;
  4940. pollres =
  4941. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4942. if (conn->ctx->stop_flag) {
  4943. return -2;
  4944. }
  4945. if (pollres > 0) {
  4946. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4947. err = (nread < 0) ? ERRNO : 0;
  4948. if (nread <= 0) {
  4949. /* shutdown of the socket at client side */
  4950. return -2;
  4951. }
  4952. } else if (pollres < 0) {
  4953. /* error callint poll */
  4954. return -2;
  4955. } else {
  4956. /* pollres = 0 means timeout */
  4957. nread = 0;
  4958. }
  4959. }
  4960. if (conn->ctx->stop_flag) {
  4961. return -2;
  4962. }
  4963. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  4964. /* some data has been read, or no data was requested */
  4965. return nread;
  4966. }
  4967. if (nread < 0) {
  4968. /* socket error - check errno */
  4969. #ifdef _WIN32
  4970. if (err == WSAEWOULDBLOCK) {
  4971. /* TODO (low): check if this is still required */
  4972. /* standard case if called from close_socket_gracefully */
  4973. return -2;
  4974. } else if (err == WSAETIMEDOUT) {
  4975. /* TODO (low): check if this is still required */
  4976. /* timeout is handled by the while loop */
  4977. return 0;
  4978. } else if (err == WSAECONNABORTED) {
  4979. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4980. return -2;
  4981. } else {
  4982. DEBUG_TRACE("recv() failed, error %d", err);
  4983. return -2;
  4984. }
  4985. #else
  4986. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4987. * if the timeout is reached and if the socket was set to non-
  4988. * blocking in close_socket_gracefully, so we can not distinguish
  4989. * here. We have to wait for the timeout in both cases for now.
  4990. */
  4991. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  4992. /* TODO (low): check if this is still required */
  4993. /* EAGAIN/EWOULDBLOCK:
  4994. * standard case if called from close_socket_gracefully
  4995. * => should return -1 */
  4996. /* or timeout occured
  4997. * => the code must stay in the while loop */
  4998. /* EINTR can be generated on a socket with a timeout set even
  4999. * when SA_RESTART is effective for all relevant signals
  5000. * (see signal(7)).
  5001. * => stay in the while loop */
  5002. } else {
  5003. DEBUG_TRACE("recv() failed, error %d", err);
  5004. return -2;
  5005. }
  5006. #endif
  5007. }
  5008. /* Timeout occured, but no data available. */
  5009. return -1;
  5010. }
  5011. static int
  5012. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5013. {
  5014. int n, nread = 0;
  5015. double timeout = -1.0;
  5016. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5017. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5018. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5019. }
  5020. if (timeout >= 0.0) {
  5021. start_time = mg_get_current_time_ns();
  5022. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5023. }
  5024. while ((len > 0) && (conn->ctx->stop_flag == 0)) {
  5025. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5026. if (n == -2) {
  5027. if (nread == 0) {
  5028. nread = -1; /* Propagate the error */
  5029. }
  5030. break;
  5031. } else if (n == -1) {
  5032. /* timeout */
  5033. if (timeout >= 0.0) {
  5034. now = mg_get_current_time_ns();
  5035. if ((now - start_time) <= timeout_ns) {
  5036. continue;
  5037. }
  5038. }
  5039. break;
  5040. } else if (n == 0) {
  5041. break; /* No more data to read */
  5042. } else {
  5043. conn->consumed_content += n;
  5044. nread += n;
  5045. len -= n;
  5046. }
  5047. }
  5048. return nread;
  5049. }
  5050. static void
  5051. discard_unread_request_data(struct mg_connection *conn)
  5052. {
  5053. char buf[MG_BUF_LEN];
  5054. size_t to_read;
  5055. int nread;
  5056. if (conn == NULL) {
  5057. return;
  5058. }
  5059. to_read = sizeof(buf);
  5060. if (conn->is_chunked) {
  5061. /* Chunked encoding: 3=chunk read completely
  5062. * completely */
  5063. while (conn->is_chunked != 3) {
  5064. nread = mg_read(conn, buf, to_read);
  5065. if (nread <= 0) {
  5066. break;
  5067. }
  5068. }
  5069. } else {
  5070. /* Not chunked: content length is known */
  5071. while (conn->consumed_content < conn->content_len) {
  5072. if (to_read
  5073. > (size_t)(conn->content_len - conn->consumed_content)) {
  5074. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5075. }
  5076. nread = mg_read(conn, buf, to_read);
  5077. if (nread <= 0) {
  5078. break;
  5079. }
  5080. }
  5081. }
  5082. }
  5083. static int
  5084. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5085. {
  5086. int64_t n, buffered_len, nread;
  5087. int64_t len64 =
  5088. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5089. * int, we may not read more
  5090. * bytes */
  5091. const char *body;
  5092. if (conn == NULL) {
  5093. return 0;
  5094. }
  5095. /* If Content-Length is not set for a request with body data
  5096. * (e.g., a PUT or POST request), we do not know in advance
  5097. * how much data should be read. */
  5098. if (conn->consumed_content == 0) {
  5099. if (conn->is_chunked == 1) {
  5100. conn->content_len = len64;
  5101. conn->is_chunked = 2;
  5102. } else if (conn->content_len == -1) {
  5103. /* The body data is completed when the connection
  5104. * is closed. */
  5105. conn->content_len = INT64_MAX;
  5106. conn->must_close = 1;
  5107. }
  5108. }
  5109. nread = 0;
  5110. if (conn->consumed_content < conn->content_len) {
  5111. /* Adjust number of bytes to read. */
  5112. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5113. if (left_to_read < len64) {
  5114. /* Do not read more than the total content length of the
  5115. * request.
  5116. */
  5117. len64 = left_to_read;
  5118. }
  5119. /* Return buffered data */
  5120. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5121. - conn->consumed_content;
  5122. if (buffered_len > 0) {
  5123. if (len64 < buffered_len) {
  5124. buffered_len = len64;
  5125. }
  5126. body = conn->buf + conn->request_len + conn->consumed_content;
  5127. memcpy(buf, body, (size_t)buffered_len);
  5128. len64 -= buffered_len;
  5129. conn->consumed_content += buffered_len;
  5130. nread += buffered_len;
  5131. buf = (char *)buf + buffered_len;
  5132. }
  5133. /* We have returned all buffered data. Read new data from the remote
  5134. * socket.
  5135. */
  5136. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5137. nread += n;
  5138. } else {
  5139. nread = ((nread > 0) ? nread : n);
  5140. }
  5141. }
  5142. return (int)nread;
  5143. }
  5144. static char
  5145. mg_getc(struct mg_connection *conn)
  5146. {
  5147. char c;
  5148. if (conn == NULL) {
  5149. return 0;
  5150. }
  5151. if (mg_read_inner(conn, &c, 1) <= 0) {
  5152. return (char)0;
  5153. }
  5154. return c;
  5155. }
  5156. int
  5157. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5158. {
  5159. if (len > INT_MAX) {
  5160. len = INT_MAX;
  5161. }
  5162. if (conn == NULL) {
  5163. return 0;
  5164. }
  5165. if (conn->is_chunked) {
  5166. size_t all_read = 0;
  5167. while (len > 0) {
  5168. if (conn->is_chunked == 3) {
  5169. /* No more data left to read */
  5170. return 0;
  5171. }
  5172. if (conn->chunk_remainder) {
  5173. /* copy from the remainder of the last received chunk */
  5174. long read_ret;
  5175. size_t read_now =
  5176. ((conn->chunk_remainder > len) ? (len)
  5177. : (conn->chunk_remainder));
  5178. conn->content_len += (int)read_now;
  5179. read_ret =
  5180. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5181. if (read_ret < 1) {
  5182. /* read error */
  5183. return -1;
  5184. }
  5185. all_read += (size_t)read_ret;
  5186. conn->chunk_remainder -= (size_t)read_ret;
  5187. len -= (size_t)read_ret;
  5188. if (conn->chunk_remainder == 0) {
  5189. /* Add data bytes in the current chunk have been read,
  5190. * so we are expecting \r\n now. */
  5191. char x1, x2;
  5192. conn->content_len += 2;
  5193. x1 = mg_getc(conn);
  5194. x2 = mg_getc(conn);
  5195. if ((x1 != '\r') || (x2 != '\n')) {
  5196. /* Protocol violation */
  5197. return -1;
  5198. }
  5199. }
  5200. } else {
  5201. /* fetch a new chunk */
  5202. int i = 0;
  5203. char lenbuf[64];
  5204. char *end = 0;
  5205. unsigned long chunkSize = 0;
  5206. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5207. conn->content_len++;
  5208. lenbuf[i] = mg_getc(conn);
  5209. if ((i > 0) && (lenbuf[i] == '\r')
  5210. && (lenbuf[i - 1] != '\r')) {
  5211. continue;
  5212. }
  5213. if ((i > 1) && (lenbuf[i] == '\n')
  5214. && (lenbuf[i - 1] == '\r')) {
  5215. lenbuf[i + 1] = 0;
  5216. chunkSize = strtoul(lenbuf, &end, 16);
  5217. if (chunkSize == 0) {
  5218. /* regular end of content */
  5219. conn->is_chunked = 3;
  5220. }
  5221. break;
  5222. }
  5223. if (!isxdigit(lenbuf[i])) {
  5224. /* illegal character for chunk length */
  5225. return -1;
  5226. }
  5227. }
  5228. if ((end == NULL) || (*end != '\r')) {
  5229. /* chunksize not set correctly */
  5230. return -1;
  5231. }
  5232. if (chunkSize == 0) {
  5233. break;
  5234. }
  5235. conn->chunk_remainder = chunkSize;
  5236. }
  5237. }
  5238. return (int)all_read;
  5239. }
  5240. return mg_read_inner(conn, buf, len);
  5241. }
  5242. int
  5243. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5244. {
  5245. time_t now;
  5246. int64_t n, total, allowed;
  5247. if (conn == NULL) {
  5248. return 0;
  5249. }
  5250. if (conn->throttle > 0) {
  5251. if ((now = time(NULL)) != conn->last_throttle_time) {
  5252. conn->last_throttle_time = now;
  5253. conn->last_throttle_bytes = 0;
  5254. }
  5255. allowed = conn->throttle - conn->last_throttle_bytes;
  5256. if (allowed > (int64_t)len) {
  5257. allowed = (int64_t)len;
  5258. }
  5259. if ((total = push_all(conn->ctx,
  5260. NULL,
  5261. conn->client.sock,
  5262. conn->ssl,
  5263. (const char *)buf,
  5264. (int64_t)allowed)) == allowed) {
  5265. buf = (const char *)buf + total;
  5266. conn->last_throttle_bytes += total;
  5267. while ((total < (int64_t)len) && (conn->ctx->stop_flag == 0)) {
  5268. allowed = (conn->throttle > ((int64_t)len - total))
  5269. ? (int64_t)len - total
  5270. : conn->throttle;
  5271. if ((n = push_all(conn->ctx,
  5272. NULL,
  5273. conn->client.sock,
  5274. conn->ssl,
  5275. (const char *)buf,
  5276. (int64_t)allowed)) != allowed) {
  5277. break;
  5278. }
  5279. sleep(1);
  5280. conn->last_throttle_bytes = allowed;
  5281. conn->last_throttle_time = time(NULL);
  5282. buf = (const char *)buf + n;
  5283. total += n;
  5284. }
  5285. }
  5286. } else {
  5287. total = push_all(conn->ctx,
  5288. NULL,
  5289. conn->client.sock,
  5290. conn->ssl,
  5291. (const char *)buf,
  5292. (int64_t)len);
  5293. }
  5294. if (total > 0) {
  5295. conn->num_bytes_sent += total;
  5296. }
  5297. return (int)total;
  5298. }
  5299. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5300. int
  5301. mg_send_chunk(struct mg_connection *conn,
  5302. const char *chunk,
  5303. unsigned int chunk_len)
  5304. {
  5305. char lenbuf[16];
  5306. size_t lenbuf_len;
  5307. int ret;
  5308. int t;
  5309. /* First store the length information in a text buffer. */
  5310. sprintf(lenbuf, "%x\r\n", chunk_len);
  5311. lenbuf_len = strlen(lenbuf);
  5312. /* Then send length information, chunk and terminating \r\n. */
  5313. ret = mg_write(conn, lenbuf, lenbuf_len);
  5314. if (ret != (int)lenbuf_len) {
  5315. return -1;
  5316. }
  5317. t = ret;
  5318. ret = mg_write(conn, chunk, chunk_len);
  5319. if (ret != (int)chunk_len) {
  5320. return -1;
  5321. }
  5322. t += ret;
  5323. ret = mg_write(conn, "\r\n", 2);
  5324. if (ret != 2) {
  5325. return -1;
  5326. }
  5327. t += ret;
  5328. return t;
  5329. }
  5330. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5331. static int
  5332. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5333. {
  5334. va_list ap_copy;
  5335. size_t size = MG_BUF_LEN / 4;
  5336. int len = -1;
  5337. *buf = NULL;
  5338. while (len < 0) {
  5339. if (*buf) {
  5340. mg_free(*buf);
  5341. }
  5342. size *= 4;
  5343. *buf = (char *)mg_malloc(size);
  5344. if (!*buf) {
  5345. break;
  5346. }
  5347. va_copy(ap_copy, ap);
  5348. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5349. va_end(ap_copy);
  5350. (*buf)[size - 1] = 0;
  5351. }
  5352. return len;
  5353. }
  5354. /* Print message to buffer. If buffer is large enough to hold the message,
  5355. * return buffer. If buffer is to small, allocate large enough buffer on
  5356. * heap,
  5357. * and return allocated buffer. */
  5358. static int
  5359. alloc_vprintf(char **out_buf,
  5360. char *prealloc_buf,
  5361. size_t prealloc_size,
  5362. const char *fmt,
  5363. va_list ap)
  5364. {
  5365. va_list ap_copy;
  5366. int len;
  5367. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5368. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5369. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5370. * Therefore, we make two passes: on first pass, get required message
  5371. * length.
  5372. * On second pass, actually print the message. */
  5373. va_copy(ap_copy, ap);
  5374. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5375. va_end(ap_copy);
  5376. if (len < 0) {
  5377. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5378. * Switch to alternative code path that uses incremental
  5379. * allocations.
  5380. */
  5381. va_copy(ap_copy, ap);
  5382. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5383. va_end(ap_copy);
  5384. } else if ((size_t)(len) >= prealloc_size) {
  5385. /* The pre-allocated buffer not large enough. */
  5386. /* Allocate a new buffer. */
  5387. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5388. if (!*out_buf) {
  5389. /* Allocation failed. Return -1 as "out of memory" error. */
  5390. return -1;
  5391. }
  5392. /* Buffer allocation successful. Store the string there. */
  5393. va_copy(ap_copy, ap);
  5394. IGNORE_UNUSED_RESULT(
  5395. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5396. va_end(ap_copy);
  5397. } else {
  5398. /* The pre-allocated buffer is large enough.
  5399. * Use it to store the string and return the address. */
  5400. va_copy(ap_copy, ap);
  5401. IGNORE_UNUSED_RESULT(
  5402. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5403. va_end(ap_copy);
  5404. *out_buf = prealloc_buf;
  5405. }
  5406. return len;
  5407. }
  5408. static int
  5409. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5410. {
  5411. char mem[MG_BUF_LEN];
  5412. char *buf = NULL;
  5413. int len;
  5414. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5415. len = mg_write(conn, buf, (size_t)len);
  5416. }
  5417. if ((buf != mem) && (buf != NULL)) {
  5418. mg_free(buf);
  5419. }
  5420. return len;
  5421. }
  5422. int
  5423. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5424. {
  5425. va_list ap;
  5426. int result;
  5427. va_start(ap, fmt);
  5428. result = mg_vprintf(conn, fmt, ap);
  5429. va_end(ap);
  5430. return result;
  5431. }
  5432. int
  5433. mg_url_decode(const char *src,
  5434. int src_len,
  5435. char *dst,
  5436. int dst_len,
  5437. int is_form_url_encoded)
  5438. {
  5439. int i, j, a, b;
  5440. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5441. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5442. if ((i < src_len - 2) && (src[i] == '%')
  5443. && isxdigit(*(const unsigned char *)(src + i + 1))
  5444. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5445. a = tolower(*(const unsigned char *)(src + i + 1));
  5446. b = tolower(*(const unsigned char *)(src + i + 2));
  5447. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5448. i += 2;
  5449. } else if (is_form_url_encoded && (src[i] == '+')) {
  5450. dst[j] = ' ';
  5451. } else {
  5452. dst[j] = src[i];
  5453. }
  5454. }
  5455. dst[j] = '\0'; /* Null-terminate the destination */
  5456. return (i >= src_len) ? j : -1;
  5457. }
  5458. int
  5459. mg_get_var(const char *data,
  5460. size_t data_len,
  5461. const char *name,
  5462. char *dst,
  5463. size_t dst_len)
  5464. {
  5465. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5466. }
  5467. int
  5468. mg_get_var2(const char *data,
  5469. size_t data_len,
  5470. const char *name,
  5471. char *dst,
  5472. size_t dst_len,
  5473. size_t occurrence)
  5474. {
  5475. const char *p, *e, *s;
  5476. size_t name_len;
  5477. int len;
  5478. if ((dst == NULL) || (dst_len == 0)) {
  5479. len = -2;
  5480. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5481. len = -1;
  5482. dst[0] = '\0';
  5483. } else {
  5484. name_len = strlen(name);
  5485. e = data + data_len;
  5486. len = -1;
  5487. dst[0] = '\0';
  5488. /* data is "var1=val1&var2=val2...". Find variable first */
  5489. for (p = data; p + name_len < e; p++) {
  5490. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5491. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5492. /* Point p to variable value */
  5493. p += name_len + 1;
  5494. /* Point s to the end of the value */
  5495. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5496. if (s == NULL) {
  5497. s = e;
  5498. }
  5499. /* assert(s >= p); */
  5500. if (s < p) {
  5501. return -3;
  5502. }
  5503. /* Decode variable into destination buffer */
  5504. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5505. /* Redirect error code from -1 to -2 (destination buffer too
  5506. * small). */
  5507. if (len == -1) {
  5508. len = -2;
  5509. }
  5510. break;
  5511. }
  5512. }
  5513. }
  5514. return len;
  5515. }
  5516. /* HCP24: some changes to compare hole var_name */
  5517. int
  5518. mg_get_cookie(const char *cookie_header,
  5519. const char *var_name,
  5520. char *dst,
  5521. size_t dst_size)
  5522. {
  5523. const char *s, *p, *end;
  5524. int name_len, len = -1;
  5525. if ((dst == NULL) || (dst_size == 0)) {
  5526. return -2;
  5527. }
  5528. dst[0] = '\0';
  5529. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5530. return -1;
  5531. }
  5532. name_len = (int)strlen(var_name);
  5533. end = s + strlen(s);
  5534. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5535. if (s[name_len] == '=') {
  5536. /* HCP24: now check is it a substring or a full cookie name */
  5537. if ((s == cookie_header) || (s[-1] == ' ')) {
  5538. s += name_len + 1;
  5539. if ((p = strchr(s, ' ')) == NULL) {
  5540. p = end;
  5541. }
  5542. if (p[-1] == ';') {
  5543. p--;
  5544. }
  5545. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5546. s++;
  5547. p--;
  5548. }
  5549. if ((size_t)(p - s) < dst_size) {
  5550. len = (int)(p - s);
  5551. mg_strlcpy(dst, s, (size_t)len + 1);
  5552. } else {
  5553. len = -3;
  5554. }
  5555. break;
  5556. }
  5557. }
  5558. }
  5559. return len;
  5560. }
  5561. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5562. static void
  5563. base64_encode(const unsigned char *src, int src_len, char *dst)
  5564. {
  5565. static const char *b64 =
  5566. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5567. int i, j, a, b, c;
  5568. for (i = j = 0; i < src_len; i += 3) {
  5569. a = src[i];
  5570. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5571. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5572. dst[j++] = b64[a >> 2];
  5573. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5574. if (i + 1 < src_len) {
  5575. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5576. }
  5577. if (i + 2 < src_len) {
  5578. dst[j++] = b64[c & 63];
  5579. }
  5580. }
  5581. while (j % 4 != 0) {
  5582. dst[j++] = '=';
  5583. }
  5584. dst[j++] = '\0';
  5585. }
  5586. #endif
  5587. #if defined(USE_LUA)
  5588. static unsigned char
  5589. b64reverse(char letter)
  5590. {
  5591. if ((letter >= 'A') && (letter <= 'Z')) {
  5592. return letter - 'A';
  5593. }
  5594. if ((letter >= 'a') && (letter <= 'z')) {
  5595. return letter - 'a' + 26;
  5596. }
  5597. if ((letter >= '0') && (letter <= '9')) {
  5598. return letter - '0' + 52;
  5599. }
  5600. if (letter == '+') {
  5601. return 62;
  5602. }
  5603. if (letter == '/') {
  5604. return 63;
  5605. }
  5606. if (letter == '=') {
  5607. return 255; /* normal end */
  5608. }
  5609. return 254; /* error */
  5610. }
  5611. static int
  5612. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5613. {
  5614. int i;
  5615. unsigned char a, b, c, d;
  5616. *dst_len = 0;
  5617. for (i = 0; i < src_len; i += 4) {
  5618. a = b64reverse(src[i]);
  5619. if (a >= 254) {
  5620. return i;
  5621. }
  5622. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5623. if (b >= 254) {
  5624. return i + 1;
  5625. }
  5626. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5627. if (c == 254) {
  5628. return i + 2;
  5629. }
  5630. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5631. if (d == 254) {
  5632. return i + 3;
  5633. }
  5634. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5635. if (c != 255) {
  5636. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5637. if (d != 255) {
  5638. dst[(*dst_len)++] = (c << 6) + d;
  5639. }
  5640. }
  5641. }
  5642. return -1;
  5643. }
  5644. #endif
  5645. static int
  5646. is_put_or_delete_method(const struct mg_connection *conn)
  5647. {
  5648. if (conn) {
  5649. const char *s = conn->request_info.request_method;
  5650. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5651. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5652. }
  5653. return 0;
  5654. }
  5655. #if !defined(NO_FILES)
  5656. static int
  5657. extention_matches_script(
  5658. struct mg_connection *conn, /* in: request (must be valid) */
  5659. const char *filename /* in: filename (must be valid) */
  5660. )
  5661. {
  5662. #if !defined(NO_CGI)
  5663. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5664. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5665. filename) > 0) {
  5666. return 1;
  5667. }
  5668. #endif
  5669. #if defined(USE_LUA)
  5670. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5671. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5672. filename) > 0) {
  5673. return 1;
  5674. }
  5675. #endif
  5676. #if defined(USE_DUKTAPE)
  5677. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5678. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5679. filename) > 0) {
  5680. return 1;
  5681. }
  5682. #endif
  5683. /* filename and conn could be unused, if all preocessor conditions
  5684. * are false (no script language supported). */
  5685. (void)filename;
  5686. (void)conn;
  5687. return 0;
  5688. }
  5689. /* For given directory path, substitute it to valid index file.
  5690. * Return 1 if index file has been found, 0 if not found.
  5691. * If the file is found, it's stats is returned in stp. */
  5692. static int
  5693. substitute_index_file(struct mg_connection *conn,
  5694. char *path,
  5695. size_t path_len,
  5696. struct mg_file_stat *filestat)
  5697. {
  5698. const char *list = conn->ctx->config[INDEX_FILES];
  5699. struct vec filename_vec;
  5700. size_t n = strlen(path);
  5701. int found = 0;
  5702. /* The 'path' given to us points to the directory. Remove all trailing
  5703. * directory separator characters from the end of the path, and
  5704. * then append single directory separator character. */
  5705. while ((n > 0) && (path[n - 1] == '/')) {
  5706. n--;
  5707. }
  5708. path[n] = '/';
  5709. /* Traverse index files list. For each entry, append it to the given
  5710. * path and see if the file exists. If it exists, break the loop */
  5711. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5712. /* Ignore too long entries that may overflow path buffer */
  5713. if (filename_vec.len > (path_len - (n + 2))) {
  5714. continue;
  5715. }
  5716. /* Prepare full path to the index file */
  5717. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5718. /* Does it exist? */
  5719. if (mg_stat(conn, path, filestat)) {
  5720. /* Yes it does, break the loop */
  5721. found = 1;
  5722. break;
  5723. }
  5724. }
  5725. /* If no index file exists, restore directory path */
  5726. if (!found) {
  5727. path[n] = '\0';
  5728. }
  5729. return found;
  5730. }
  5731. #endif
  5732. static void
  5733. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  5734. char *filename, /* out: filename */
  5735. size_t filename_buf_len, /* in: size of filename buffer */
  5736. struct mg_file_stat *filestat, /* out: file status structure */
  5737. int *is_found, /* out: file found (directly) */
  5738. int *is_script_resource, /* out: handled by a script? */
  5739. int *is_websocket_request, /* out: websocket connetion? */
  5740. int *is_put_or_delete_request /* out: put/delete a file? */
  5741. )
  5742. {
  5743. char const *accept_encoding;
  5744. #if !defined(NO_FILES)
  5745. const char *uri = conn->request_info.local_uri;
  5746. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5747. const char *rewrite;
  5748. struct vec a, b;
  5749. int match_len;
  5750. char gz_path[PATH_MAX];
  5751. int truncated;
  5752. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5753. char *tmp_str;
  5754. size_t tmp_str_len, sep_pos;
  5755. int allow_substitute_script_subresources;
  5756. #endif
  5757. #else
  5758. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5759. #endif
  5760. /* Step 1: Set all initially unknown outputs to zero */
  5761. memset(filestat, 0, sizeof(*filestat));
  5762. *filename = 0;
  5763. *is_found = 0;
  5764. *is_script_resource = 0;
  5765. /* Step 2: Check if the request attempts to modify the file system */
  5766. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5767. /* Step 3: Check if it is a websocket request, and modify the document
  5768. * root if required */
  5769. #if defined(USE_WEBSOCKET)
  5770. *is_websocket_request = is_websocket_protocol(conn);
  5771. #if !defined(NO_FILES)
  5772. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5773. root = conn->ctx->config[WEBSOCKET_ROOT];
  5774. }
  5775. #endif /* !NO_FILES */
  5776. #else /* USE_WEBSOCKET */
  5777. *is_websocket_request = 0;
  5778. #endif /* USE_WEBSOCKET */
  5779. /* Step 4: Check if gzip encoded response is allowed */
  5780. conn->accept_gzip = 0;
  5781. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5782. if (strstr(accept_encoding, "gzip") != NULL) {
  5783. conn->accept_gzip = 1;
  5784. }
  5785. }
  5786. #if !defined(NO_FILES)
  5787. /* Step 5: If there is no root directory, don't look for files. */
  5788. /* Note that root == NULL is a regular use case here. This occurs,
  5789. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5790. * config is not required. */
  5791. if (root == NULL) {
  5792. /* all file related outputs have already been set to 0, just return
  5793. */
  5794. return;
  5795. }
  5796. /* Step 6: Determine the local file path from the root path and the
  5797. * request uri. */
  5798. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5799. * part of the path one byte on the right. */
  5800. mg_snprintf(
  5801. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5802. if (truncated) {
  5803. goto interpret_cleanup;
  5804. }
  5805. /* Step 7: URI rewriting */
  5806. rewrite = conn->ctx->config[URL_REWRITE_PATTERN];
  5807. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5808. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5809. mg_snprintf(conn,
  5810. &truncated,
  5811. filename,
  5812. filename_buf_len - 1,
  5813. "%.*s%s",
  5814. (int)b.len,
  5815. b.ptr,
  5816. uri + match_len);
  5817. break;
  5818. }
  5819. }
  5820. if (truncated) {
  5821. goto interpret_cleanup;
  5822. }
  5823. /* Step 8: Check if the file exists at the server */
  5824. /* Local file path and name, corresponding to requested URI
  5825. * is now stored in "filename" variable. */
  5826. if (mg_stat(conn, filename, filestat)) {
  5827. /* 8.1: File exists. */
  5828. *is_found = 1;
  5829. /* 8.2: Check if it is a script type. */
  5830. if (extention_matches_script(conn, filename)) {
  5831. /* The request addresses a CGI resource, Lua script or
  5832. * server-side javascript.
  5833. * The URI corresponds to the script itself (like
  5834. * /path/script.cgi), and there is no additional resource
  5835. * path (like /path/script.cgi/something).
  5836. * Requests that modify (replace or delete) a resource, like
  5837. * PUT and DELETE requests, should replace/delete the script
  5838. * file.
  5839. * Requests that read or write from/to a resource, like GET and
  5840. * POST requests, should call the script and return the
  5841. * generated response. */
  5842. *is_script_resource = (!*is_put_or_delete_request);
  5843. }
  5844. /* 8.3: If the request target is a directory, there could be
  5845. * a substitute file (index.html, index.cgi, ...). */
  5846. if (filestat->is_directory) {
  5847. /* Use a local copy here, since substitute_index_file will
  5848. * change the content of the file status */
  5849. struct mg_file_stat tmp_filestat;
  5850. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5851. if (substitute_index_file(
  5852. conn, filename, filename_buf_len, &tmp_filestat)) {
  5853. /* Substitute file found. Copy stat to the output, then
  5854. * check if the file is a script file */
  5855. *filestat = tmp_filestat;
  5856. if (extention_matches_script(conn, filename)) {
  5857. /* Substitute file is a script file */
  5858. *is_script_resource = 1;
  5859. } else {
  5860. /* Substitute file is a regular file */
  5861. *is_script_resource = 0;
  5862. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5863. }
  5864. }
  5865. /* If there is no substitute file, the server could return
  5866. * a directory listing in a later step */
  5867. }
  5868. return;
  5869. }
  5870. /* Step 9: Check for zipped files: */
  5871. /* If we can't find the actual file, look for the file
  5872. * with the same name but a .gz extension. If we find it,
  5873. * use that and set the gzipped flag in the file struct
  5874. * to indicate that the response need to have the content-
  5875. * encoding: gzip header.
  5876. * We can only do this if the browser declares support. */
  5877. if (conn->accept_gzip) {
  5878. mg_snprintf(
  5879. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5880. if (truncated) {
  5881. goto interpret_cleanup;
  5882. }
  5883. if (mg_stat(conn, gz_path, filestat)) {
  5884. if (filestat) {
  5885. filestat->is_gzipped = 1;
  5886. *is_found = 1;
  5887. }
  5888. /* Currently gz files can not be scripts. */
  5889. return;
  5890. }
  5891. }
  5892. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5893. /* Step 10: Script resources may handle sub-resources */
  5894. /* Support PATH_INFO for CGI scripts. */
  5895. tmp_str_len = strlen(filename);
  5896. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->ctx);
  5897. if (!tmp_str) {
  5898. /* Out of memory */
  5899. goto interpret_cleanup;
  5900. }
  5901. memcpy(tmp_str, filename, tmp_str_len + 1);
  5902. /* Check config, if index scripts may have sub-resources */
  5903. allow_substitute_script_subresources =
  5904. !mg_strcasecmp(conn->ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES], "yes");
  5905. sep_pos = tmp_str_len;
  5906. while (sep_pos > 0) {
  5907. sep_pos--;
  5908. if (tmp_str[sep_pos] == '/') {
  5909. int is_script = 0, does_exist = 0;
  5910. tmp_str[sep_pos] = 0;
  5911. if (tmp_str[0]) {
  5912. is_script = extention_matches_script(conn, tmp_str);
  5913. does_exist = mg_stat(conn, tmp_str, filestat);
  5914. }
  5915. if (does_exist && is_script) {
  5916. filename[sep_pos] = 0;
  5917. memmove(filename + sep_pos + 2,
  5918. filename + sep_pos + 1,
  5919. strlen(filename + sep_pos + 1) + 1);
  5920. conn->path_info = filename + sep_pos + 1;
  5921. filename[sep_pos + 1] = '/';
  5922. *is_script_resource = 1;
  5923. *is_found = 1;
  5924. break;
  5925. }
  5926. if (allow_substitute_script_subresources) {
  5927. if (substitute_index_file(
  5928. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5929. /* some intermediate directory has an index file */
  5930. if (extention_matches_script(conn, tmp_str)) {
  5931. char *tmp_str2;
  5932. DEBUG_TRACE("Substitute script %s serving path %s",
  5933. tmp_str,
  5934. filename);
  5935. /* this index file is a script */
  5936. tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5937. mg_snprintf(conn,
  5938. &truncated,
  5939. filename,
  5940. filename_buf_len,
  5941. "%s//%s",
  5942. tmp_str,
  5943. tmp_str2);
  5944. mg_free(tmp_str2);
  5945. if (truncated) {
  5946. mg_free(tmp_str);
  5947. goto interpret_cleanup;
  5948. }
  5949. sep_pos = strlen(tmp_str);
  5950. filename[sep_pos] = 0;
  5951. conn->path_info = filename + sep_pos + 1;
  5952. *is_script_resource = 1;
  5953. *is_found = 1;
  5954. break;
  5955. } else {
  5956. DEBUG_TRACE("Substitute file %s serving path %s",
  5957. tmp_str,
  5958. filename);
  5959. /* non-script files will not have sub-resources */
  5960. filename[sep_pos] = 0;
  5961. conn->path_info = 0;
  5962. *is_script_resource = 0;
  5963. *is_found = 0;
  5964. break;
  5965. }
  5966. }
  5967. }
  5968. tmp_str[sep_pos] = '/';
  5969. }
  5970. }
  5971. mg_free(tmp_str);
  5972. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5973. #endif /* !defined(NO_FILES) */
  5974. return;
  5975. #if !defined(NO_FILES)
  5976. /* Reset all outputs */
  5977. interpret_cleanup:
  5978. memset(filestat, 0, sizeof(*filestat));
  5979. *filename = 0;
  5980. *is_found = 0;
  5981. *is_script_resource = 0;
  5982. *is_websocket_request = 0;
  5983. *is_put_or_delete_request = 0;
  5984. #endif /* !defined(NO_FILES) */
  5985. }
  5986. /* Check whether full request is buffered. Return:
  5987. * -1 if request or response is malformed
  5988. * 0 if request or response is not yet fully buffered
  5989. * >0 actual request length, including last \r\n\r\n */
  5990. static int
  5991. get_http_header_len(const char *buf, int buflen)
  5992. {
  5993. int i;
  5994. for (i = 0; i < buflen; i++) {
  5995. /* Do an unsigned comparison in some conditions below */
  5996. const unsigned char c = ((const unsigned char *)buf)[i];
  5997. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  5998. && !isprint(c)) {
  5999. /* abort scan as soon as one malformed character is found */
  6000. return -1;
  6001. }
  6002. if (i < buflen - 1) {
  6003. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6004. /* Two newline, no carriage return - not standard compliant,
  6005. * but
  6006. * it
  6007. * should be accepted */
  6008. return i + 2;
  6009. }
  6010. }
  6011. if (i < buflen - 3) {
  6012. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6013. && (buf[i + 3] == '\n')) {
  6014. /* Two \r\n - standard compliant */
  6015. return i + 4;
  6016. }
  6017. }
  6018. }
  6019. return 0;
  6020. }
  6021. #if !defined(NO_CACHING)
  6022. /* Convert month to the month number. Return -1 on error, or month number */
  6023. static int
  6024. get_month_index(const char *s)
  6025. {
  6026. size_t i;
  6027. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6028. if (!strcmp(s, month_names[i])) {
  6029. return (int)i;
  6030. }
  6031. }
  6032. return -1;
  6033. }
  6034. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6035. static time_t
  6036. parse_date_string(const char *datetime)
  6037. {
  6038. char month_str[32] = {0};
  6039. int second, minute, hour, day, month, year;
  6040. time_t result = (time_t)0;
  6041. struct tm tm;
  6042. if ((sscanf(datetime,
  6043. "%d/%3s/%d %d:%d:%d",
  6044. &day,
  6045. month_str,
  6046. &year,
  6047. &hour,
  6048. &minute,
  6049. &second) == 6) || (sscanf(datetime,
  6050. "%d %3s %d %d:%d:%d",
  6051. &day,
  6052. month_str,
  6053. &year,
  6054. &hour,
  6055. &minute,
  6056. &second) == 6)
  6057. || (sscanf(datetime,
  6058. "%*3s, %d %3s %d %d:%d:%d",
  6059. &day,
  6060. month_str,
  6061. &year,
  6062. &hour,
  6063. &minute,
  6064. &second) == 6) || (sscanf(datetime,
  6065. "%d-%3s-%d %d:%d:%d",
  6066. &day,
  6067. month_str,
  6068. &year,
  6069. &hour,
  6070. &minute,
  6071. &second) == 6)) {
  6072. month = get_month_index(month_str);
  6073. if ((month >= 0) && (year >= 1970)) {
  6074. memset(&tm, 0, sizeof(tm));
  6075. tm.tm_year = year - 1900;
  6076. tm.tm_mon = month;
  6077. tm.tm_mday = day;
  6078. tm.tm_hour = hour;
  6079. tm.tm_min = minute;
  6080. tm.tm_sec = second;
  6081. result = timegm(&tm);
  6082. }
  6083. }
  6084. return result;
  6085. }
  6086. #endif /* !NO_CACHING */
  6087. /* Protect against directory disclosure attack by removing '..',
  6088. * excessive '/' and '\' characters */
  6089. static void
  6090. remove_double_dots_and_double_slashes(char *s)
  6091. {
  6092. char *p = s;
  6093. while ((s[0] == '.') && (s[1] == '.')) {
  6094. s++;
  6095. }
  6096. while (*s != '\0') {
  6097. *p++ = *s++;
  6098. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6099. /* Skip all following slashes, backslashes and double-dots */
  6100. while (s[0] != '\0') {
  6101. if ((s[0] == '/') || (s[0] == '\\')) {
  6102. s++;
  6103. } else if ((s[0] == '.') && (s[1] == '.')) {
  6104. s += 2;
  6105. } else {
  6106. break;
  6107. }
  6108. }
  6109. }
  6110. }
  6111. *p = '\0';
  6112. }
  6113. static const struct {
  6114. const char *extension;
  6115. size_t ext_len;
  6116. const char *mime_type;
  6117. } builtin_mime_types[] = {
  6118. /* IANA registered MIME types
  6119. * (http://www.iana.org/assignments/media-types)
  6120. * application types */
  6121. {".doc", 4, "application/msword"},
  6122. {".eps", 4, "application/postscript"},
  6123. {".exe", 4, "application/octet-stream"},
  6124. {".js", 3, "application/javascript"},
  6125. {".json", 5, "application/json"},
  6126. {".pdf", 4, "application/pdf"},
  6127. {".ps", 3, "application/postscript"},
  6128. {".rtf", 4, "application/rtf"},
  6129. {".xhtml", 6, "application/xhtml+xml"},
  6130. {".xsl", 4, "application/xml"},
  6131. {".xslt", 5, "application/xml"},
  6132. /* fonts */
  6133. {".ttf", 4, "application/font-sfnt"},
  6134. {".cff", 4, "application/font-sfnt"},
  6135. {".otf", 4, "application/font-sfnt"},
  6136. {".aat", 4, "application/font-sfnt"},
  6137. {".sil", 4, "application/font-sfnt"},
  6138. {".pfr", 4, "application/font-tdpfr"},
  6139. {".woff", 5, "application/font-woff"},
  6140. /* audio */
  6141. {".mp3", 4, "audio/mpeg"},
  6142. {".oga", 4, "audio/ogg"},
  6143. {".ogg", 4, "audio/ogg"},
  6144. /* image */
  6145. {".gif", 4, "image/gif"},
  6146. {".ief", 4, "image/ief"},
  6147. {".jpeg", 5, "image/jpeg"},
  6148. {".jpg", 4, "image/jpeg"},
  6149. {".jpm", 4, "image/jpm"},
  6150. {".jpx", 4, "image/jpx"},
  6151. {".png", 4, "image/png"},
  6152. {".svg", 4, "image/svg+xml"},
  6153. {".tif", 4, "image/tiff"},
  6154. {".tiff", 5, "image/tiff"},
  6155. /* model */
  6156. {".wrl", 4, "model/vrml"},
  6157. /* text */
  6158. {".css", 4, "text/css"},
  6159. {".csv", 4, "text/csv"},
  6160. {".htm", 4, "text/html"},
  6161. {".html", 5, "text/html"},
  6162. {".sgm", 4, "text/sgml"},
  6163. {".shtm", 5, "text/html"},
  6164. {".shtml", 6, "text/html"},
  6165. {".txt", 4, "text/plain"},
  6166. {".xml", 4, "text/xml"},
  6167. /* video */
  6168. {".mov", 4, "video/quicktime"},
  6169. {".mp4", 4, "video/mp4"},
  6170. {".mpeg", 5, "video/mpeg"},
  6171. {".mpg", 4, "video/mpeg"},
  6172. {".ogv", 4, "video/ogg"},
  6173. {".qt", 3, "video/quicktime"},
  6174. /* not registered types
  6175. * (http://reference.sitepoint.com/html/mime-types-full,
  6176. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6177. {".arj", 4, "application/x-arj-compressed"},
  6178. {".gz", 3, "application/x-gunzip"},
  6179. {".rar", 4, "application/x-arj-compressed"},
  6180. {".swf", 4, "application/x-shockwave-flash"},
  6181. {".tar", 4, "application/x-tar"},
  6182. {".tgz", 4, "application/x-tar-gz"},
  6183. {".torrent", 8, "application/x-bittorrent"},
  6184. {".ppt", 4, "application/x-mspowerpoint"},
  6185. {".xls", 4, "application/x-msexcel"},
  6186. {".zip", 4, "application/x-zip-compressed"},
  6187. {".aac",
  6188. 4,
  6189. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6190. {".aif", 4, "audio/x-aif"},
  6191. {".m3u", 4, "audio/x-mpegurl"},
  6192. {".mid", 4, "audio/x-midi"},
  6193. {".ra", 3, "audio/x-pn-realaudio"},
  6194. {".ram", 4, "audio/x-pn-realaudio"},
  6195. {".wav", 4, "audio/x-wav"},
  6196. {".bmp", 4, "image/bmp"},
  6197. {".ico", 4, "image/x-icon"},
  6198. {".pct", 4, "image/x-pct"},
  6199. {".pict", 5, "image/pict"},
  6200. {".rgb", 4, "image/x-rgb"},
  6201. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6202. {".asf", 4, "video/x-ms-asf"},
  6203. {".avi", 4, "video/x-msvideo"},
  6204. {".m4v", 4, "video/x-m4v"},
  6205. {NULL, 0, NULL}};
  6206. const char *
  6207. mg_get_builtin_mime_type(const char *path)
  6208. {
  6209. const char *ext;
  6210. size_t i, path_len;
  6211. path_len = strlen(path);
  6212. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6213. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6214. if ((path_len > builtin_mime_types[i].ext_len)
  6215. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6216. return builtin_mime_types[i].mime_type;
  6217. }
  6218. }
  6219. return "text/plain";
  6220. }
  6221. /* Look at the "path" extension and figure what mime type it has.
  6222. * Store mime type in the vector. */
  6223. static void
  6224. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  6225. {
  6226. struct vec ext_vec, mime_vec;
  6227. const char *list, *ext;
  6228. size_t path_len;
  6229. path_len = strlen(path);
  6230. if ((ctx == NULL) || (vec == NULL)) {
  6231. if (vec != NULL) {
  6232. memset(vec, '\0', sizeof(struct vec));
  6233. }
  6234. return;
  6235. }
  6236. /* Scan user-defined mime types first, in case user wants to
  6237. * override default mime types. */
  6238. list = ctx->config[EXTRA_MIME_TYPES];
  6239. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6240. /* ext now points to the path suffix */
  6241. ext = path + path_len - ext_vec.len;
  6242. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6243. *vec = mime_vec;
  6244. return;
  6245. }
  6246. }
  6247. vec->ptr = mg_get_builtin_mime_type(path);
  6248. vec->len = strlen(vec->ptr);
  6249. }
  6250. /* Stringify binary data. Output buffer must be twice as big as input,
  6251. * because each byte takes 2 bytes in string representation */
  6252. static void
  6253. bin2str(char *to, const unsigned char *p, size_t len)
  6254. {
  6255. static const char *hex = "0123456789abcdef";
  6256. for (; len--; p++) {
  6257. *to++ = hex[p[0] >> 4];
  6258. *to++ = hex[p[0] & 0x0f];
  6259. }
  6260. *to = '\0';
  6261. }
  6262. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6263. */
  6264. char *
  6265. mg_md5(char buf[33], ...)
  6266. {
  6267. md5_byte_t hash[16];
  6268. const char *p;
  6269. va_list ap;
  6270. md5_state_t ctx;
  6271. md5_init(&ctx);
  6272. va_start(ap, buf);
  6273. while ((p = va_arg(ap, const char *)) != NULL) {
  6274. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6275. }
  6276. va_end(ap);
  6277. md5_finish(&ctx, hash);
  6278. bin2str(buf, hash, sizeof(hash));
  6279. return buf;
  6280. }
  6281. /* Check the user's password, return 1 if OK */
  6282. static int
  6283. check_password(const char *method,
  6284. const char *ha1,
  6285. const char *uri,
  6286. const char *nonce,
  6287. const char *nc,
  6288. const char *cnonce,
  6289. const char *qop,
  6290. const char *response)
  6291. {
  6292. char ha2[32 + 1], expected_response[32 + 1];
  6293. /* Some of the parameters may be NULL */
  6294. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6295. || (qop == NULL) || (response == NULL)) {
  6296. return 0;
  6297. }
  6298. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6299. if (strlen(response) != 32) {
  6300. return 0;
  6301. }
  6302. mg_md5(ha2, method, ":", uri, NULL);
  6303. mg_md5(expected_response,
  6304. ha1,
  6305. ":",
  6306. nonce,
  6307. ":",
  6308. nc,
  6309. ":",
  6310. cnonce,
  6311. ":",
  6312. qop,
  6313. ":",
  6314. ha2,
  6315. NULL);
  6316. return mg_strcasecmp(response, expected_response) == 0;
  6317. }
  6318. /* Use the global passwords file, if specified by auth_gpass option,
  6319. * or search for .htpasswd in the requested directory. */
  6320. static void
  6321. open_auth_file(struct mg_connection *conn,
  6322. const char *path,
  6323. struct mg_file *filep)
  6324. {
  6325. if ((conn != NULL) && (conn->ctx != NULL)) {
  6326. char name[PATH_MAX];
  6327. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  6328. int truncated;
  6329. if (gpass != NULL) {
  6330. /* Use global passwords file */
  6331. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6332. #ifdef DEBUG
  6333. /* Use mg_cry here, since gpass has been configured. */
  6334. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6335. #endif
  6336. }
  6337. /* Important: using local struct mg_file to test path for
  6338. * is_directory flag. If filep is used, mg_stat() makes it
  6339. * appear as if auth file was opened.
  6340. * TODO(mid): Check if this is still required after rewriting
  6341. * mg_stat */
  6342. } else if (mg_stat(conn, path, &filep->stat)
  6343. && filep->stat.is_directory) {
  6344. mg_snprintf(conn,
  6345. &truncated,
  6346. name,
  6347. sizeof(name),
  6348. "%s/%s",
  6349. path,
  6350. PASSWORDS_FILE_NAME);
  6351. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6352. #ifdef DEBUG
  6353. /* Don't use mg_cry here, but only a trace, since this is
  6354. * a typical case. It will occur for every directory
  6355. * without a password file. */
  6356. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6357. #endif
  6358. }
  6359. } else {
  6360. /* Try to find .htpasswd in requested directory. */
  6361. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6362. if (e[0] == '/') {
  6363. break;
  6364. }
  6365. }
  6366. mg_snprintf(conn,
  6367. &truncated,
  6368. name,
  6369. sizeof(name),
  6370. "%.*s/%s",
  6371. (int)(e - p),
  6372. p,
  6373. PASSWORDS_FILE_NAME);
  6374. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6375. #ifdef DEBUG
  6376. /* Don't use mg_cry here, but only a trace, since this is
  6377. * a typical case. It will occur for every directory
  6378. * without a password file. */
  6379. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6380. #endif
  6381. }
  6382. }
  6383. }
  6384. }
  6385. /* Parsed Authorization header */
  6386. struct ah {
  6387. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6388. };
  6389. /* Return 1 on success. Always initializes the ah structure. */
  6390. static int
  6391. parse_auth_header(struct mg_connection *conn,
  6392. char *buf,
  6393. size_t buf_size,
  6394. struct ah *ah)
  6395. {
  6396. char *name, *value, *s;
  6397. const char *auth_header;
  6398. uint64_t nonce;
  6399. if (!ah || !conn) {
  6400. return 0;
  6401. }
  6402. (void)memset(ah, 0, sizeof(*ah));
  6403. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6404. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6405. return 0;
  6406. }
  6407. /* Make modifiable copy of the auth header */
  6408. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6409. s = buf;
  6410. /* Parse authorization header */
  6411. for (;;) {
  6412. /* Gobble initial spaces */
  6413. while (isspace(*(unsigned char *)s)) {
  6414. s++;
  6415. }
  6416. name = skip_quoted(&s, "=", " ", 0);
  6417. /* Value is either quote-delimited, or ends at first comma or space.
  6418. */
  6419. if (s[0] == '\"') {
  6420. s++;
  6421. value = skip_quoted(&s, "\"", " ", '\\');
  6422. if (s[0] == ',') {
  6423. s++;
  6424. }
  6425. } else {
  6426. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6427. * spaces */
  6428. }
  6429. if (*name == '\0') {
  6430. break;
  6431. }
  6432. if (!strcmp(name, "username")) {
  6433. ah->user = value;
  6434. } else if (!strcmp(name, "cnonce")) {
  6435. ah->cnonce = value;
  6436. } else if (!strcmp(name, "response")) {
  6437. ah->response = value;
  6438. } else if (!strcmp(name, "uri")) {
  6439. ah->uri = value;
  6440. } else if (!strcmp(name, "qop")) {
  6441. ah->qop = value;
  6442. } else if (!strcmp(name, "nc")) {
  6443. ah->nc = value;
  6444. } else if (!strcmp(name, "nonce")) {
  6445. ah->nonce = value;
  6446. }
  6447. }
  6448. #ifndef NO_NONCE_CHECK
  6449. /* Read the nonce from the response. */
  6450. if (ah->nonce == NULL) {
  6451. return 0;
  6452. }
  6453. s = NULL;
  6454. nonce = strtoull(ah->nonce, &s, 10);
  6455. if ((s == NULL) || (*s != 0)) {
  6456. return 0;
  6457. }
  6458. /* Convert the nonce from the client to a number. */
  6459. nonce ^= conn->ctx->auth_nonce_mask;
  6460. /* The converted number corresponds to the time the nounce has been
  6461. * created. This should not be earlier than the server start. */
  6462. /* Server side nonce check is valuable in all situations but one:
  6463. * if the server restarts frequently, but the client should not see
  6464. * that, so the server should accept nonces from previous starts. */
  6465. /* However, the reasonable default is to not accept a nonce from a
  6466. * previous start, so if anyone changed the access rights between
  6467. * two restarts, a new login is required. */
  6468. if (nonce < (uint64_t)conn->ctx->start_time) {
  6469. /* nonce is from a previous start of the server and no longer valid
  6470. * (replay attack?) */
  6471. return 0;
  6472. }
  6473. /* Check if the nonce is too high, so it has not (yet) been used by the
  6474. * server. */
  6475. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  6476. return 0;
  6477. }
  6478. #else
  6479. (void)nonce;
  6480. #endif
  6481. /* CGI needs it as REMOTE_USER */
  6482. if (ah->user != NULL) {
  6483. conn->request_info.remote_user = mg_strdup(ah->user);
  6484. } else {
  6485. return 0;
  6486. }
  6487. return 1;
  6488. }
  6489. static const char *
  6490. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6491. {
  6492. const char *eof;
  6493. size_t len;
  6494. const char *memend;
  6495. if (!filep) {
  6496. return NULL;
  6497. }
  6498. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6499. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6500. /* Search for \n from p till the end of stream */
  6501. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6502. if (eof != NULL) {
  6503. eof += 1; /* Include \n */
  6504. } else {
  6505. eof = memend; /* Copy remaining data */
  6506. }
  6507. len =
  6508. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6509. memcpy(buf, *p, len);
  6510. buf[len] = '\0';
  6511. *p += len;
  6512. return len ? eof : NULL;
  6513. } else if (filep->access.fp != NULL) {
  6514. return fgets(buf, (int)size, filep->access.fp);
  6515. } else {
  6516. return NULL;
  6517. }
  6518. }
  6519. /* Define the initial recursion depth for procesesing htpasswd files that
  6520. * include other htpasswd
  6521. * (or even the same) files. It is not difficult to provide a file or files
  6522. * s.t. they force civetweb
  6523. * to infinitely recurse and then crash.
  6524. */
  6525. #define INITIAL_DEPTH 9
  6526. #if INITIAL_DEPTH <= 0
  6527. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6528. #endif
  6529. struct read_auth_file_struct {
  6530. struct mg_connection *conn;
  6531. struct ah ah;
  6532. const char *domain;
  6533. char buf[256 + 256 + 40];
  6534. const char *f_user;
  6535. const char *f_domain;
  6536. const char *f_ha1;
  6537. };
  6538. static int
  6539. read_auth_file(struct mg_file *filep,
  6540. struct read_auth_file_struct *workdata,
  6541. int depth)
  6542. {
  6543. char *p;
  6544. int is_authorized = 0;
  6545. struct mg_file fp;
  6546. size_t l;
  6547. if (!filep || !workdata || (0 == depth)) {
  6548. return 0;
  6549. }
  6550. /* Loop over passwords file */
  6551. p = (char *)filep->access.membuf;
  6552. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6553. l = strlen(workdata->buf);
  6554. while (l > 0) {
  6555. if (isspace(workdata->buf[l - 1])
  6556. || iscntrl(workdata->buf[l - 1])) {
  6557. l--;
  6558. workdata->buf[l] = 0;
  6559. } else
  6560. break;
  6561. }
  6562. if (l < 1) {
  6563. continue;
  6564. }
  6565. workdata->f_user = workdata->buf;
  6566. if (workdata->f_user[0] == ':') {
  6567. /* user names may not contain a ':' and may not be empty,
  6568. * so lines starting with ':' may be used for a special purpose
  6569. */
  6570. if (workdata->f_user[1] == '#') {
  6571. /* :# is a comment */
  6572. continue;
  6573. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6574. if (mg_fopen(workdata->conn,
  6575. workdata->f_user + 9,
  6576. MG_FOPEN_MODE_READ,
  6577. &fp)) {
  6578. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6579. (void)mg_fclose(
  6580. &fp.access); /* ignore error on read only file */
  6581. /* No need to continue processing files once we have a
  6582. * match, since nothing will reset it back
  6583. * to 0.
  6584. */
  6585. if (is_authorized) {
  6586. return is_authorized;
  6587. }
  6588. } else {
  6589. mg_cry(workdata->conn,
  6590. "%s: cannot open authorization file: %s",
  6591. __func__,
  6592. workdata->buf);
  6593. }
  6594. continue;
  6595. }
  6596. /* everything is invalid for the moment (might change in the
  6597. * future) */
  6598. mg_cry(workdata->conn,
  6599. "%s: syntax error in authorization file: %s",
  6600. __func__,
  6601. workdata->buf);
  6602. continue;
  6603. }
  6604. workdata->f_domain = strchr(workdata->f_user, ':');
  6605. if (workdata->f_domain == NULL) {
  6606. mg_cry(workdata->conn,
  6607. "%s: syntax error in authorization file: %s",
  6608. __func__,
  6609. workdata->buf);
  6610. continue;
  6611. }
  6612. *(char *)(workdata->f_domain) = 0;
  6613. (workdata->f_domain)++;
  6614. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6615. if (workdata->f_ha1 == NULL) {
  6616. mg_cry(workdata->conn,
  6617. "%s: syntax error in authorization file: %s",
  6618. __func__,
  6619. workdata->buf);
  6620. continue;
  6621. }
  6622. *(char *)(workdata->f_ha1) = 0;
  6623. (workdata->f_ha1)++;
  6624. if (!strcmp(workdata->ah.user, workdata->f_user)
  6625. && !strcmp(workdata->domain, workdata->f_domain)) {
  6626. return check_password(workdata->conn->request_info.request_method,
  6627. workdata->f_ha1,
  6628. workdata->ah.uri,
  6629. workdata->ah.nonce,
  6630. workdata->ah.nc,
  6631. workdata->ah.cnonce,
  6632. workdata->ah.qop,
  6633. workdata->ah.response);
  6634. }
  6635. }
  6636. return is_authorized;
  6637. }
  6638. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6639. static int
  6640. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  6641. {
  6642. struct read_auth_file_struct workdata;
  6643. char buf[MG_BUF_LEN];
  6644. if (!conn || !conn->ctx) {
  6645. return 0;
  6646. }
  6647. memset(&workdata, 0, sizeof(workdata));
  6648. workdata.conn = conn;
  6649. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6650. return 0;
  6651. }
  6652. if (realm) {
  6653. workdata.domain = realm;
  6654. } else {
  6655. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6656. }
  6657. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6658. }
  6659. /* Public function to check http digest authentication header */
  6660. int
  6661. mg_check_digest_access_authentication(struct mg_connection *conn,
  6662. const char *realm,
  6663. const char *filename)
  6664. {
  6665. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6666. int auth;
  6667. if (!conn || !filename) {
  6668. return -1;
  6669. }
  6670. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  6671. return -2;
  6672. }
  6673. auth = authorize(conn, &file, realm);
  6674. mg_fclose(&file.access);
  6675. return auth;
  6676. }
  6677. /* Return 1 if request is authorised, 0 otherwise. */
  6678. static int
  6679. check_authorization(struct mg_connection *conn, const char *path)
  6680. {
  6681. char fname[PATH_MAX];
  6682. struct vec uri_vec, filename_vec;
  6683. const char *list;
  6684. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6685. int authorized = 1, truncated;
  6686. if (!conn || !conn->ctx) {
  6687. return 0;
  6688. }
  6689. list = conn->ctx->config[PROTECT_URI];
  6690. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6691. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6692. mg_snprintf(conn,
  6693. &truncated,
  6694. fname,
  6695. sizeof(fname),
  6696. "%.*s",
  6697. (int)filename_vec.len,
  6698. filename_vec.ptr);
  6699. if (truncated
  6700. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6701. mg_cry(conn,
  6702. "%s: cannot open %s: %s",
  6703. __func__,
  6704. fname,
  6705. strerror(errno));
  6706. }
  6707. break;
  6708. }
  6709. }
  6710. if (!is_file_opened(&file.access)) {
  6711. open_auth_file(conn, path, &file);
  6712. }
  6713. if (is_file_opened(&file.access)) {
  6714. authorized = authorize(conn, &file, NULL);
  6715. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6716. }
  6717. return authorized;
  6718. }
  6719. /* Internal function. Assumes conn is valid */
  6720. static void
  6721. send_authorization_request(struct mg_connection *conn, const char *realm)
  6722. {
  6723. char date[64];
  6724. time_t curtime = time(NULL);
  6725. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6726. if (!realm) {
  6727. realm = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6728. }
  6729. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6730. nonce += conn->ctx->nonce_count;
  6731. ++conn->ctx->nonce_count;
  6732. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6733. nonce ^= conn->ctx->auth_nonce_mask;
  6734. conn->status_code = 401;
  6735. conn->must_close = 1;
  6736. gmt_time_string(date, sizeof(date), &curtime);
  6737. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6738. send_no_cache_header(conn);
  6739. send_additional_header(conn);
  6740. mg_printf(conn,
  6741. "Date: %s\r\n"
  6742. "Connection: %s\r\n"
  6743. "Content-Length: 0\r\n"
  6744. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6745. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6746. date,
  6747. suggest_connection_header(conn),
  6748. realm,
  6749. nonce);
  6750. }
  6751. /* Interface function. Parameters are provided by the user, so do
  6752. * at least some basic checks.
  6753. */
  6754. int
  6755. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  6756. const char *realm)
  6757. {
  6758. if (conn && conn->ctx) {
  6759. send_authorization_request(conn, realm);
  6760. return 0;
  6761. }
  6762. return -1;
  6763. }
  6764. #if !defined(NO_FILES)
  6765. static int
  6766. is_authorized_for_put(struct mg_connection *conn)
  6767. {
  6768. if (conn) {
  6769. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6770. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6771. int ret = 0;
  6772. if (passfile != NULL
  6773. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6774. ret = authorize(conn, &file, NULL);
  6775. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6776. }
  6777. return ret;
  6778. }
  6779. return 0;
  6780. }
  6781. #endif
  6782. int
  6783. mg_modify_passwords_file(const char *fname,
  6784. const char *domain,
  6785. const char *user,
  6786. const char *pass)
  6787. {
  6788. int found, i;
  6789. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6790. FILE *fp, *fp2;
  6791. found = 0;
  6792. fp = fp2 = NULL;
  6793. /* Regard empty password as no password - remove user record. */
  6794. if ((pass != NULL) && (pass[0] == '\0')) {
  6795. pass = NULL;
  6796. }
  6797. /* Other arguments must not be empty */
  6798. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6799. return 0;
  6800. }
  6801. /* Using the given file format, user name and domain must not contain
  6802. * ':'
  6803. */
  6804. if (strchr(user, ':') != NULL) {
  6805. return 0;
  6806. }
  6807. if (strchr(domain, ':') != NULL) {
  6808. return 0;
  6809. }
  6810. /* Do not allow control characters like newline in user name and domain.
  6811. * Do not allow excessively long names either. */
  6812. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6813. if (iscntrl(user[i])) {
  6814. return 0;
  6815. }
  6816. }
  6817. if (user[i]) {
  6818. return 0;
  6819. }
  6820. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6821. if (iscntrl(domain[i])) {
  6822. return 0;
  6823. }
  6824. }
  6825. if (domain[i]) {
  6826. return 0;
  6827. }
  6828. /* The maximum length of the path to the password file is limited */
  6829. if ((strlen(fname) + 4) >= PATH_MAX) {
  6830. return 0;
  6831. }
  6832. /* Create a temporary file name. Length has been checked before. */
  6833. strcpy(tmp, fname);
  6834. strcat(tmp, ".tmp");
  6835. /* Create the file if does not exist */
  6836. /* Use of fopen here is OK, since fname is only ASCII */
  6837. if ((fp = fopen(fname, "a+")) != NULL) {
  6838. (void)fclose(fp);
  6839. }
  6840. /* Open the given file and temporary file */
  6841. if ((fp = fopen(fname, "r")) == NULL) {
  6842. return 0;
  6843. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6844. fclose(fp);
  6845. return 0;
  6846. }
  6847. /* Copy the stuff to temporary file */
  6848. while (fgets(line, sizeof(line), fp) != NULL) {
  6849. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6850. continue;
  6851. }
  6852. u[255] = 0;
  6853. d[255] = 0;
  6854. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6855. found++;
  6856. if (pass != NULL) {
  6857. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6858. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6859. }
  6860. } else {
  6861. fprintf(fp2, "%s", line);
  6862. }
  6863. }
  6864. /* If new user, just add it */
  6865. if (!found && (pass != NULL)) {
  6866. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6867. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6868. }
  6869. /* Close files */
  6870. fclose(fp);
  6871. fclose(fp2);
  6872. /* Put the temp file in place of real file */
  6873. IGNORE_UNUSED_RESULT(remove(fname));
  6874. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6875. return 1;
  6876. }
  6877. static int
  6878. is_valid_port(unsigned long port)
  6879. {
  6880. return (port <= 0xffff);
  6881. }
  6882. static int
  6883. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6884. {
  6885. struct addrinfo hints, *res, *ressave;
  6886. int func_ret = 0;
  6887. int gai_ret;
  6888. memset(&hints, 0, sizeof(struct addrinfo));
  6889. hints.ai_family = af;
  6890. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6891. if (gai_ret != 0) {
  6892. /* gai_strerror could be used to convert gai_ret to a string */
  6893. /* POSIX return values: see
  6894. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6895. */
  6896. /* Windows return values: see
  6897. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6898. */
  6899. return 0;
  6900. }
  6901. ressave = res;
  6902. while (res) {
  6903. if (dstlen >= (size_t)res->ai_addrlen) {
  6904. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6905. func_ret = 1;
  6906. }
  6907. res = res->ai_next;
  6908. }
  6909. freeaddrinfo(ressave);
  6910. return func_ret;
  6911. }
  6912. static int
  6913. connect_socket(struct mg_context *ctx /* may be NULL */,
  6914. const char *host,
  6915. int port,
  6916. int use_ssl,
  6917. char *ebuf,
  6918. size_t ebuf_len,
  6919. SOCKET *sock /* output: socket, must not be NULL */,
  6920. union usa *sa /* output: socket address, must not be NULL */
  6921. )
  6922. {
  6923. int ip_ver = 0;
  6924. int conn_ret = -1;
  6925. *sock = INVALID_SOCKET;
  6926. memset(sa, 0, sizeof(*sa));
  6927. if (ebuf_len > 0) {
  6928. *ebuf = 0;
  6929. }
  6930. if (host == NULL) {
  6931. mg_snprintf(NULL,
  6932. NULL, /* No truncation check for ebuf */
  6933. ebuf,
  6934. ebuf_len,
  6935. "%s",
  6936. "NULL host");
  6937. return 0;
  6938. }
  6939. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  6940. mg_snprintf(NULL,
  6941. NULL, /* No truncation check for ebuf */
  6942. ebuf,
  6943. ebuf_len,
  6944. "%s",
  6945. "invalid port");
  6946. return 0;
  6947. }
  6948. #if !defined(NO_SSL)
  6949. #if !defined(NO_SSL_DL)
  6950. #ifdef OPENSSL_API_1_1
  6951. if (use_ssl && (TLS_client_method == NULL)) {
  6952. mg_snprintf(NULL,
  6953. NULL, /* No truncation check for ebuf */
  6954. ebuf,
  6955. ebuf_len,
  6956. "%s",
  6957. "SSL is not initialized");
  6958. return 0;
  6959. }
  6960. #else
  6961. if (use_ssl && (SSLv23_client_method == NULL)) {
  6962. mg_snprintf(NULL,
  6963. NULL, /* No truncation check for ebuf */
  6964. ebuf,
  6965. ebuf_len,
  6966. "%s",
  6967. "SSL is not initialized");
  6968. return 0;
  6969. }
  6970. #endif /* OPENSSL_API_1_1 */
  6971. #else
  6972. (void)use_ssl;
  6973. #endif /* NO_SSL_DL */
  6974. #else
  6975. (void)use_ssl;
  6976. #endif /* !defined(NO_SSL) */
  6977. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6978. sa->sin.sin_family = AF_INET;
  6979. sa->sin.sin_port = htons((uint16_t)port);
  6980. ip_ver = 4;
  6981. #ifdef USE_IPV6
  6982. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6983. sa->sin6.sin6_family = AF_INET6;
  6984. sa->sin6.sin6_port = htons((uint16_t)port);
  6985. ip_ver = 6;
  6986. } else if (host[0] == '[') {
  6987. /* While getaddrinfo on Windows will work with [::1],
  6988. * getaddrinfo on Linux only works with ::1 (without []). */
  6989. size_t l = strlen(host + 1);
  6990. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6991. if (h) {
  6992. h[l - 1] = 0;
  6993. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6994. sa->sin6.sin6_family = AF_INET6;
  6995. sa->sin6.sin6_port = htons((uint16_t)port);
  6996. ip_ver = 6;
  6997. }
  6998. mg_free(h);
  6999. }
  7000. #endif
  7001. }
  7002. if (ip_ver == 0) {
  7003. mg_snprintf(NULL,
  7004. NULL, /* No truncation check for ebuf */
  7005. ebuf,
  7006. ebuf_len,
  7007. "%s",
  7008. "host not found");
  7009. return 0;
  7010. }
  7011. if (ip_ver == 4) {
  7012. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7013. }
  7014. #ifdef USE_IPV6
  7015. else if (ip_ver == 6) {
  7016. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7017. }
  7018. #endif
  7019. if (*sock == INVALID_SOCKET) {
  7020. mg_snprintf(NULL,
  7021. NULL, /* No truncation check for ebuf */
  7022. ebuf,
  7023. ebuf_len,
  7024. "socket(): %s",
  7025. strerror(ERRNO));
  7026. return 0;
  7027. }
  7028. if (0 != set_non_blocking_mode(*sock)) {
  7029. mg_snprintf(NULL,
  7030. NULL, /* No truncation check for ebuf */
  7031. ebuf,
  7032. ebuf_len,
  7033. "Cannot set socket to non-blocking: %s",
  7034. strerror(ERRNO));
  7035. closesocket(*sock);
  7036. *sock = INVALID_SOCKET;
  7037. return 0;
  7038. }
  7039. set_close_on_exec(*sock, fc(ctx));
  7040. if (ip_ver == 4) {
  7041. /* connected with IPv4 */
  7042. conn_ret = connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin));
  7043. }
  7044. #ifdef USE_IPV6
  7045. else if (ip_ver == 6) {
  7046. /* connected with IPv6 */
  7047. conn_ret =
  7048. connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6));
  7049. }
  7050. #endif
  7051. if (conn_ret != 0) {
  7052. fd_set fdset;
  7053. struct timeval timeout;
  7054. int sockerr = -1;
  7055. #if defined(_WIN32)
  7056. int len = (int)sizeof(sockerr);
  7057. #else
  7058. socklen_t len = (socklen_t)sizeof(sockerr);
  7059. #endif
  7060. FD_ZERO(&fdset);
  7061. FD_SET(*sock, &fdset);
  7062. timeout.tv_sec = 10; /* 10 second timeout */
  7063. timeout.tv_usec = 0;
  7064. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7065. /* Not connected */
  7066. mg_snprintf(NULL,
  7067. NULL, /* No truncation check for ebuf */
  7068. ebuf,
  7069. ebuf_len,
  7070. "connect(%s:%d): timeout",
  7071. host,
  7072. port);
  7073. closesocket(*sock);
  7074. *sock = INVALID_SOCKET;
  7075. return 0;
  7076. }
  7077. #if defined(_WIN32)
  7078. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)&sockerr, &len);
  7079. #else
  7080. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &len);
  7081. #endif
  7082. if (sockerr != 0) {
  7083. /* Not connected */
  7084. mg_snprintf(NULL,
  7085. NULL, /* No truncation check for ebuf */
  7086. ebuf,
  7087. ebuf_len,
  7088. "connect(%s:%d): error %s",
  7089. host,
  7090. port,
  7091. strerror(sockerr));
  7092. closesocket(*sock);
  7093. *sock = INVALID_SOCKET;
  7094. return 0;
  7095. }
  7096. }
  7097. return 1;
  7098. }
  7099. int
  7100. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7101. {
  7102. static const char *dont_escape = "._-$,;~()";
  7103. static const char *hex = "0123456789abcdef";
  7104. char *pos = dst;
  7105. const char *end = dst + dst_len - 1;
  7106. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7107. if (isalnum(*(const unsigned char *)src)
  7108. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7109. *pos = *src;
  7110. } else if (pos + 2 < end) {
  7111. pos[0] = '%';
  7112. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7113. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7114. pos += 2;
  7115. } else {
  7116. break;
  7117. }
  7118. }
  7119. *pos = '\0';
  7120. return (*src == '\0') ? (int)(pos - dst) : -1;
  7121. }
  7122. /* Return 0 on success, non-zero if an error occurs. */
  7123. static int
  7124. print_dir_entry(struct de *de)
  7125. {
  7126. size_t hrefsize;
  7127. char *href;
  7128. char size[64], mod[64];
  7129. struct tm *tm;
  7130. hrefsize = PATH_MAX * 3; /* worst case */
  7131. href = (char *)mg_malloc(hrefsize);
  7132. if (href == NULL) {
  7133. return -1;
  7134. }
  7135. if (de->file.is_directory) {
  7136. mg_snprintf(de->conn,
  7137. NULL, /* Buffer is big enough */
  7138. size,
  7139. sizeof(size),
  7140. "%s",
  7141. "[DIRECTORY]");
  7142. } else {
  7143. /* We use (signed) cast below because MSVC 6 compiler cannot
  7144. * convert unsigned __int64 to double. Sigh. */
  7145. if (de->file.size < 1024) {
  7146. mg_snprintf(de->conn,
  7147. NULL, /* Buffer is big enough */
  7148. size,
  7149. sizeof(size),
  7150. "%d",
  7151. (int)de->file.size);
  7152. } else if (de->file.size < 0x100000) {
  7153. mg_snprintf(de->conn,
  7154. NULL, /* Buffer is big enough */
  7155. size,
  7156. sizeof(size),
  7157. "%.1fk",
  7158. (double)de->file.size / 1024.0);
  7159. } else if (de->file.size < 0x40000000) {
  7160. mg_snprintf(de->conn,
  7161. NULL, /* Buffer is big enough */
  7162. size,
  7163. sizeof(size),
  7164. "%.1fM",
  7165. (double)de->file.size / 1048576);
  7166. } else {
  7167. mg_snprintf(de->conn,
  7168. NULL, /* Buffer is big enough */
  7169. size,
  7170. sizeof(size),
  7171. "%.1fG",
  7172. (double)de->file.size / 1073741824);
  7173. }
  7174. }
  7175. /* Note: mg_snprintf will not cause a buffer overflow above.
  7176. * So, string truncation checks are not required here. */
  7177. tm = localtime(&de->file.last_modified);
  7178. if (tm != NULL) {
  7179. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7180. } else {
  7181. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7182. mod[sizeof(mod) - 1] = '\0';
  7183. }
  7184. mg_url_encode(de->file_name, href, hrefsize);
  7185. mg_printf(de->conn,
  7186. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7187. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7188. de->conn->request_info.local_uri,
  7189. href,
  7190. de->file.is_directory ? "/" : "",
  7191. de->file_name,
  7192. de->file.is_directory ? "/" : "",
  7193. mod,
  7194. size);
  7195. mg_free(href);
  7196. return 0;
  7197. }
  7198. /* This function is called from send_directory() and used for
  7199. * sorting directory entries by size, or name, or modification time.
  7200. * On windows, __cdecl specification is needed in case if project is built
  7201. * with __stdcall convention. qsort always requires __cdels callback. */
  7202. static int WINCDECL
  7203. compare_dir_entries(const void *p1, const void *p2)
  7204. {
  7205. if (p1 && p2) {
  7206. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7207. const char *query_string = a->conn->request_info.query_string;
  7208. int cmp_result = 0;
  7209. if (query_string == NULL) {
  7210. query_string = "na";
  7211. }
  7212. if (a->file.is_directory && !b->file.is_directory) {
  7213. return -1; /* Always put directories on top */
  7214. } else if (!a->file.is_directory && b->file.is_directory) {
  7215. return 1; /* Always put directories on top */
  7216. } else if (*query_string == 'n') {
  7217. cmp_result = strcmp(a->file_name, b->file_name);
  7218. } else if (*query_string == 's') {
  7219. cmp_result = (a->file.size == b->file.size)
  7220. ? 0
  7221. : ((a->file.size > b->file.size) ? 1 : -1);
  7222. } else if (*query_string == 'd') {
  7223. cmp_result =
  7224. (a->file.last_modified == b->file.last_modified)
  7225. ? 0
  7226. : ((a->file.last_modified > b->file.last_modified) ? 1
  7227. : -1);
  7228. }
  7229. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7230. }
  7231. return 0;
  7232. }
  7233. static int
  7234. must_hide_file(struct mg_connection *conn, const char *path)
  7235. {
  7236. if (conn && conn->ctx) {
  7237. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7238. const char *pattern = conn->ctx->config[HIDE_FILES];
  7239. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7240. || ((pattern != NULL)
  7241. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7242. }
  7243. return 0;
  7244. }
  7245. static int
  7246. scan_directory(struct mg_connection *conn,
  7247. const char *dir,
  7248. void *data,
  7249. int (*cb)(struct de *, void *))
  7250. {
  7251. char path[PATH_MAX];
  7252. struct dirent *dp;
  7253. DIR *dirp;
  7254. struct de de;
  7255. int truncated;
  7256. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7257. return 0;
  7258. } else {
  7259. de.conn = conn;
  7260. while ((dp = mg_readdir(dirp)) != NULL) {
  7261. /* Do not show current dir and hidden files */
  7262. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7263. || must_hide_file(conn, dp->d_name)) {
  7264. continue;
  7265. }
  7266. mg_snprintf(
  7267. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7268. /* If we don't memset stat structure to zero, mtime will have
  7269. * garbage and strftime() will segfault later on in
  7270. * print_dir_entry(). memset is required only if mg_stat()
  7271. * fails. For more details, see
  7272. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7273. memset(&de.file, 0, sizeof(de.file));
  7274. if (truncated) {
  7275. /* If the path is not complete, skip processing. */
  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. }
  7285. de.file_name = dp->d_name;
  7286. cb(&de, data);
  7287. }
  7288. (void)mg_closedir(dirp);
  7289. }
  7290. return 1;
  7291. }
  7292. #if !defined(NO_FILES)
  7293. static int
  7294. remove_directory(struct mg_connection *conn, const char *dir)
  7295. {
  7296. char path[PATH_MAX];
  7297. struct dirent *dp;
  7298. DIR *dirp;
  7299. struct de de;
  7300. int truncated;
  7301. int ok = 1;
  7302. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7303. return 0;
  7304. } else {
  7305. de.conn = conn;
  7306. while ((dp = mg_readdir(dirp)) != NULL) {
  7307. /* Do not show current dir (but show hidden files as they will
  7308. * also be removed) */
  7309. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7310. continue;
  7311. }
  7312. mg_snprintf(
  7313. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7314. /* If we don't memset stat structure to zero, mtime will have
  7315. * garbage and strftime() will segfault later on in
  7316. * print_dir_entry(). memset is required only if mg_stat()
  7317. * fails. For more details, see
  7318. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7319. memset(&de.file, 0, sizeof(de.file));
  7320. if (truncated) {
  7321. /* Do not delete anything shorter */
  7322. ok = 0;
  7323. continue;
  7324. }
  7325. if (!mg_stat(conn, path, &de.file)) {
  7326. mg_cry(conn,
  7327. "%s: mg_stat(%s) failed: %s",
  7328. __func__,
  7329. path,
  7330. strerror(ERRNO));
  7331. ok = 0;
  7332. }
  7333. if (de.file.is_directory) {
  7334. if (remove_directory(conn, path) == 0) {
  7335. ok = 0;
  7336. }
  7337. } else {
  7338. /* This will fail file is the file is in memory */
  7339. if (mg_remove(conn, path) == 0) {
  7340. ok = 0;
  7341. }
  7342. }
  7343. }
  7344. (void)mg_closedir(dirp);
  7345. IGNORE_UNUSED_RESULT(rmdir(dir));
  7346. }
  7347. return ok;
  7348. }
  7349. #endif
  7350. struct dir_scan_data {
  7351. struct de *entries;
  7352. unsigned int num_entries;
  7353. unsigned int arr_size;
  7354. };
  7355. /* Behaves like realloc(), but frees original pointer on failure */
  7356. static void *
  7357. realloc2(void *ptr, size_t size)
  7358. {
  7359. void *new_ptr = mg_realloc(ptr, size);
  7360. if (new_ptr == NULL) {
  7361. mg_free(ptr);
  7362. }
  7363. return new_ptr;
  7364. }
  7365. static int
  7366. dir_scan_callback(struct de *de, void *data)
  7367. {
  7368. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7369. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7370. dsd->arr_size *= 2;
  7371. dsd->entries =
  7372. (struct de *)realloc2(dsd->entries,
  7373. dsd->arr_size * sizeof(dsd->entries[0]));
  7374. }
  7375. if (dsd->entries == NULL) {
  7376. /* TODO(lsm, low): propagate an error to the caller */
  7377. dsd->num_entries = 0;
  7378. } else {
  7379. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7380. dsd->entries[dsd->num_entries].file = de->file;
  7381. dsd->entries[dsd->num_entries].conn = de->conn;
  7382. dsd->num_entries++;
  7383. }
  7384. return 0;
  7385. }
  7386. static void
  7387. handle_directory_request(struct mg_connection *conn, const char *dir)
  7388. {
  7389. unsigned int i;
  7390. int sort_direction;
  7391. struct dir_scan_data data = {NULL, 0, 128};
  7392. char date[64];
  7393. time_t curtime = time(NULL);
  7394. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7395. mg_send_http_error(conn,
  7396. 500,
  7397. "Error: Cannot open directory\nopendir(%s): %s",
  7398. dir,
  7399. strerror(ERRNO));
  7400. return;
  7401. }
  7402. gmt_time_string(date, sizeof(date), &curtime);
  7403. if (!conn) {
  7404. return;
  7405. }
  7406. sort_direction = ((conn->request_info.query_string != NULL)
  7407. && (conn->request_info.query_string[1] == 'd'))
  7408. ? 'a'
  7409. : 'd';
  7410. conn->must_close = 1;
  7411. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7412. send_static_cache_header(conn);
  7413. send_additional_header(conn);
  7414. mg_printf(conn,
  7415. "Date: %s\r\n"
  7416. "Connection: close\r\n"
  7417. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7418. date);
  7419. mg_printf(conn,
  7420. "<html><head><title>Index of %s</title>"
  7421. "<style>th {text-align: left;}</style></head>"
  7422. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7423. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7424. "<th><a href=\"?d%c\">Modified</a></th>"
  7425. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7426. "<tr><td colspan=\"3\"><hr></td></tr>",
  7427. conn->request_info.local_uri,
  7428. conn->request_info.local_uri,
  7429. sort_direction,
  7430. sort_direction,
  7431. sort_direction);
  7432. /* Print first entry - link to a parent directory */
  7433. mg_printf(conn,
  7434. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7435. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7436. conn->request_info.local_uri,
  7437. "..",
  7438. "Parent directory",
  7439. "-",
  7440. "-");
  7441. /* Sort and print directory entries */
  7442. if (data.entries != NULL) {
  7443. qsort(data.entries,
  7444. (size_t)data.num_entries,
  7445. sizeof(data.entries[0]),
  7446. compare_dir_entries);
  7447. for (i = 0; i < data.num_entries; i++) {
  7448. print_dir_entry(&data.entries[i]);
  7449. mg_free(data.entries[i].file_name);
  7450. }
  7451. mg_free(data.entries);
  7452. }
  7453. mg_printf(conn, "%s", "</table></body></html>");
  7454. conn->status_code = 200;
  7455. }
  7456. /* Send len bytes from the opened file to the client. */
  7457. static void
  7458. send_file_data(struct mg_connection *conn,
  7459. struct mg_file *filep,
  7460. int64_t offset,
  7461. int64_t len)
  7462. {
  7463. char buf[MG_BUF_LEN];
  7464. int to_read, num_read, num_written;
  7465. int64_t size;
  7466. if (!filep || !conn) {
  7467. return;
  7468. }
  7469. /* Sanity check the offset */
  7470. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7471. : (int64_t)(filep->stat.size);
  7472. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7473. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7474. /* file stored in memory */
  7475. if (len > size - offset) {
  7476. len = size - offset;
  7477. }
  7478. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7479. } else if (len > 0 && filep->access.fp != NULL) {
  7480. /* file stored on disk */
  7481. #if defined(__linux__)
  7482. /* sendfile is only available for Linux */
  7483. if ((conn->ssl == 0) && (conn->throttle == 0)
  7484. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  7485. "yes"))) {
  7486. off_t sf_offs = (off_t)offset;
  7487. ssize_t sf_sent;
  7488. int sf_file = fileno(filep->access.fp);
  7489. int loop_cnt = 0;
  7490. do {
  7491. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7492. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7493. size_t sf_tosend =
  7494. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7495. sf_sent =
  7496. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7497. if (sf_sent > 0) {
  7498. len -= sf_sent;
  7499. offset += sf_sent;
  7500. } else if (loop_cnt == 0) {
  7501. /* This file can not be sent using sendfile.
  7502. * This might be the case for pseudo-files in the
  7503. * /sys/ and /proc/ file system.
  7504. * Use the regular user mode copy code instead. */
  7505. break;
  7506. } else if (sf_sent == 0) {
  7507. /* No error, but 0 bytes sent. May be EOF? */
  7508. return;
  7509. }
  7510. loop_cnt++;
  7511. } while ((len > 0) && (sf_sent >= 0));
  7512. if (sf_sent > 0) {
  7513. return; /* OK */
  7514. }
  7515. /* sf_sent<0 means error, thus fall back to the classic way */
  7516. /* This is always the case, if sf_file is not a "normal" file,
  7517. * e.g., for sending data from the output of a CGI process. */
  7518. offset = (int64_t)sf_offs;
  7519. }
  7520. #endif
  7521. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7522. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  7523. mg_send_http_error(
  7524. conn,
  7525. 500,
  7526. "%s",
  7527. "Error: Unable to access file at requested position.");
  7528. } else {
  7529. while (len > 0) {
  7530. /* Calculate how much to read from the file in the buffer */
  7531. to_read = sizeof(buf);
  7532. if ((int64_t)to_read > len) {
  7533. to_read = (int)len;
  7534. }
  7535. /* Read from file, exit the loop on error */
  7536. if ((num_read =
  7537. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7538. <= 0) {
  7539. break;
  7540. }
  7541. /* Send read bytes to the client, exit the loop on error */
  7542. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7543. != num_read) {
  7544. break;
  7545. }
  7546. /* Both read and were successful, adjust counters */
  7547. len -= num_written;
  7548. }
  7549. }
  7550. }
  7551. }
  7552. static int
  7553. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7554. {
  7555. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7556. }
  7557. static void
  7558. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7559. {
  7560. if ((filestat != NULL) && (buf != NULL)) {
  7561. mg_snprintf(NULL,
  7562. NULL, /* All calls to construct_etag use 64 byte buffer */
  7563. buf,
  7564. buf_len,
  7565. "\"%lx.%" INT64_FMT "\"",
  7566. (unsigned long)filestat->last_modified,
  7567. filestat->size);
  7568. }
  7569. }
  7570. static void
  7571. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7572. {
  7573. if (filep != NULL && filep->fp != NULL) {
  7574. #ifdef _WIN32
  7575. (void)conn; /* Unused. */
  7576. #else
  7577. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7578. mg_cry(conn,
  7579. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7580. __func__,
  7581. strerror(ERRNO));
  7582. }
  7583. #endif
  7584. }
  7585. }
  7586. static void
  7587. handle_static_file_request(struct mg_connection *conn,
  7588. const char *path,
  7589. struct mg_file *filep,
  7590. const char *mime_type,
  7591. const char *additional_headers)
  7592. {
  7593. char date[64], lm[64], etag[64];
  7594. char range[128]; /* large enough, so there will be no overflow */
  7595. const char *msg = "OK", *hdr;
  7596. time_t curtime = time(NULL);
  7597. int64_t cl, r1, r2;
  7598. struct vec mime_vec;
  7599. int n, truncated;
  7600. char gz_path[PATH_MAX];
  7601. const char *encoding = "";
  7602. const char *cors1, *cors2, *cors3;
  7603. int allow_on_the_fly_compression;
  7604. if ((conn == NULL) || (conn->ctx == NULL) || (filep == NULL)) {
  7605. return;
  7606. }
  7607. if (mime_type == NULL) {
  7608. get_mime_type(conn->ctx, path, &mime_vec);
  7609. } else {
  7610. mime_vec.ptr = mime_type;
  7611. mime_vec.len = strlen(mime_type);
  7612. }
  7613. if (filep->stat.size > INT64_MAX) {
  7614. mg_send_http_error(conn,
  7615. 500,
  7616. "Error: File size is too large to send\n%" INT64_FMT,
  7617. filep->stat.size);
  7618. return;
  7619. }
  7620. cl = (int64_t)filep->stat.size;
  7621. conn->status_code = 200;
  7622. range[0] = '\0';
  7623. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7624. * it's important to rewrite the filename after resolving
  7625. * the mime type from it, to preserve the actual file's type */
  7626. allow_on_the_fly_compression = conn->accept_gzip;
  7627. if (filep->stat.is_gzipped) {
  7628. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7629. if (truncated) {
  7630. mg_send_http_error(conn,
  7631. 500,
  7632. "Error: Path of zipped file too long (%s)",
  7633. path);
  7634. return;
  7635. }
  7636. path = gz_path;
  7637. encoding = "Content-Encoding: gzip\r\n";
  7638. /* File is already compressed. No "on the fly" compression. */
  7639. allow_on_the_fly_compression = 0;
  7640. }
  7641. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7642. mg_send_http_error(conn,
  7643. 500,
  7644. "Error: Cannot open file\nfopen(%s): %s",
  7645. path,
  7646. strerror(ERRNO));
  7647. return;
  7648. }
  7649. fclose_on_exec(&filep->access, conn);
  7650. /* If Range: header specified, act accordingly */
  7651. r1 = r2 = 0;
  7652. hdr = mg_get_header(conn, "Range");
  7653. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7654. && (r1 >= 0) && (r2 >= 0)) {
  7655. /* actually, range requests don't play well with a pre-gzipped
  7656. * file (since the range is specified in the uncompressed space) */
  7657. if (filep->stat.is_gzipped) {
  7658. mg_send_http_error(
  7659. conn,
  7660. 416, /* 416 = Range Not Satisfiable */
  7661. "%s",
  7662. "Error: Range requests in gzipped files are not supported");
  7663. (void)mg_fclose(
  7664. &filep->access); /* ignore error on read only file */
  7665. return;
  7666. }
  7667. conn->status_code = 206;
  7668. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7669. mg_snprintf(conn,
  7670. NULL, /* range buffer is big enough */
  7671. range,
  7672. sizeof(range),
  7673. "Content-Range: bytes "
  7674. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7675. r1,
  7676. r1 + cl - 1,
  7677. filep->stat.size);
  7678. msg = "Partial Content";
  7679. /* Do not compress ranges. */
  7680. allow_on_the_fly_compression = 0;
  7681. }
  7682. hdr = mg_get_header(conn, "Origin");
  7683. if (hdr) {
  7684. /* Cross-origin resource sharing (CORS), see
  7685. * http://www.html5rocks.com/en/tutorials/cors/,
  7686. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7687. * -
  7688. * preflight is not supported for files. */
  7689. cors1 = "Access-Control-Allow-Origin: ";
  7690. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7691. cors3 = "\r\n";
  7692. } else {
  7693. cors1 = cors2 = cors3 = "";
  7694. }
  7695. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  7696. * according to
  7697. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7698. gmt_time_string(date, sizeof(date), &curtime);
  7699. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7700. construct_etag(etag, sizeof(etag), &filep->stat);
  7701. /* On the fly compression allowed */
  7702. if (allow_on_the_fly_compression) {
  7703. ;
  7704. /* TODO: add interface to compression module */
  7705. /* e.g., def from https://zlib.net/zlib_how.html */
  7706. /* Check license (zlib has a permissive license, but */
  7707. /* is still not MIT) and use dynamic binding like */
  7708. /* done with OpenSSL */
  7709. /* See #199 (https://github.com/civetweb/civetweb/issues/199) */
  7710. }
  7711. /* Send header */
  7712. (void)mg_printf(conn,
  7713. "HTTP/1.1 %d %s\r\n"
  7714. "%s%s%s"
  7715. "Date: %s\r\n",
  7716. conn->status_code,
  7717. msg,
  7718. cors1,
  7719. cors2,
  7720. cors3,
  7721. date);
  7722. send_static_cache_header(conn);
  7723. send_additional_header(conn);
  7724. (void)mg_printf(conn,
  7725. "Last-Modified: %s\r\n"
  7726. "Etag: %s\r\n"
  7727. "Content-Type: %.*s\r\n"
  7728. "Content-Length: %" INT64_FMT "\r\n"
  7729. "Connection: %s\r\n"
  7730. "Accept-Ranges: bytes\r\n"
  7731. "%s%s",
  7732. lm,
  7733. etag,
  7734. (int)mime_vec.len,
  7735. mime_vec.ptr,
  7736. cl,
  7737. suggest_connection_header(conn),
  7738. range,
  7739. encoding);
  7740. /* The previous code must not add any header starting with X- to make
  7741. * sure no one of the additional_headers is included twice */
  7742. if (additional_headers != NULL) {
  7743. (void)mg_printf(conn,
  7744. "%.*s\r\n\r\n",
  7745. (int)strlen(additional_headers),
  7746. additional_headers);
  7747. } else {
  7748. (void)mg_printf(conn, "\r\n");
  7749. }
  7750. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7751. send_file_data(conn, filep, r1, cl);
  7752. }
  7753. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7754. }
  7755. #if !defined(NO_CACHING)
  7756. static void
  7757. handle_not_modified_static_file_request(struct mg_connection *conn,
  7758. struct mg_file *filep)
  7759. {
  7760. char date[64], lm[64], etag[64];
  7761. time_t curtime = time(NULL);
  7762. if ((conn == NULL) || (filep == NULL)) {
  7763. return;
  7764. }
  7765. conn->status_code = 304;
  7766. gmt_time_string(date, sizeof(date), &curtime);
  7767. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7768. construct_etag(etag, sizeof(etag), &filep->stat);
  7769. (void)mg_printf(conn,
  7770. "HTTP/1.1 %d %s\r\n"
  7771. "Date: %s\r\n",
  7772. conn->status_code,
  7773. mg_get_response_code_text(conn, conn->status_code),
  7774. date);
  7775. send_static_cache_header(conn);
  7776. send_additional_header(conn);
  7777. (void)mg_printf(conn,
  7778. "Last-Modified: %s\r\n"
  7779. "Etag: %s\r\n"
  7780. "Connection: %s\r\n"
  7781. "\r\n",
  7782. lm,
  7783. etag,
  7784. suggest_connection_header(conn));
  7785. }
  7786. #endif
  7787. void
  7788. mg_send_file(struct mg_connection *conn, const char *path)
  7789. {
  7790. mg_send_mime_file(conn, path, NULL);
  7791. }
  7792. void
  7793. mg_send_mime_file(struct mg_connection *conn,
  7794. const char *path,
  7795. const char *mime_type)
  7796. {
  7797. mg_send_mime_file2(conn, path, mime_type, NULL);
  7798. }
  7799. void
  7800. mg_send_mime_file2(struct mg_connection *conn,
  7801. const char *path,
  7802. const char *mime_type,
  7803. const char *additional_headers)
  7804. {
  7805. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7806. if (!conn) {
  7807. /* No conn */
  7808. return;
  7809. }
  7810. if (mg_stat(conn, path, &file.stat)) {
  7811. if (file.stat.is_directory) {
  7812. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7813. "yes")) {
  7814. handle_directory_request(conn, path);
  7815. } else {
  7816. mg_send_http_error(conn,
  7817. 403,
  7818. "%s",
  7819. "Error: Directory listing denied");
  7820. }
  7821. } else {
  7822. handle_static_file_request(
  7823. conn, path, &file, mime_type, additional_headers);
  7824. }
  7825. } else {
  7826. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7827. }
  7828. }
  7829. /* For a given PUT path, create all intermediate subdirectories.
  7830. * Return 0 if the path itself is a directory.
  7831. * Return 1 if the path leads to a file.
  7832. * Return -1 for if the path is too long.
  7833. * Return -2 if path can not be created.
  7834. */
  7835. static int
  7836. put_dir(struct mg_connection *conn, const char *path)
  7837. {
  7838. char buf[PATH_MAX];
  7839. const char *s, *p;
  7840. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7841. size_t len;
  7842. int res = 1;
  7843. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7844. len = (size_t)(p - path);
  7845. if (len >= sizeof(buf)) {
  7846. /* path too long */
  7847. res = -1;
  7848. break;
  7849. }
  7850. memcpy(buf, path, len);
  7851. buf[len] = '\0';
  7852. /* Try to create intermediate directory */
  7853. DEBUG_TRACE("mkdir(%s)", buf);
  7854. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7855. /* path does not exixt and can not be created */
  7856. res = -2;
  7857. break;
  7858. }
  7859. /* Is path itself a directory? */
  7860. if (p[1] == '\0') {
  7861. res = 0;
  7862. }
  7863. }
  7864. return res;
  7865. }
  7866. static void
  7867. remove_bad_file(const struct mg_connection *conn, const char *path)
  7868. {
  7869. int r = mg_remove(conn, path);
  7870. if (r != 0) {
  7871. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7872. }
  7873. }
  7874. long long
  7875. mg_store_body(struct mg_connection *conn, const char *path)
  7876. {
  7877. char buf[MG_BUF_LEN];
  7878. long long len = 0;
  7879. int ret, n;
  7880. struct mg_file fi;
  7881. if (conn->consumed_content != 0) {
  7882. mg_cry(conn, "%s: Contents already consumed", __func__);
  7883. return -11;
  7884. }
  7885. ret = put_dir(conn, path);
  7886. if (ret < 0) {
  7887. /* -1 for path too long,
  7888. * -2 for path can not be created. */
  7889. return ret;
  7890. }
  7891. if (ret != 1) {
  7892. /* Return 0 means, path itself is a directory. */
  7893. return 0;
  7894. }
  7895. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7896. return -12;
  7897. }
  7898. ret = mg_read(conn, buf, sizeof(buf));
  7899. while (ret > 0) {
  7900. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7901. if (n != ret) {
  7902. (void)mg_fclose(
  7903. &fi.access); /* File is bad and will be removed anyway. */
  7904. remove_bad_file(conn, path);
  7905. return -13;
  7906. }
  7907. len += ret;
  7908. ret = mg_read(conn, buf, sizeof(buf));
  7909. }
  7910. /* File is open for writing. If fclose fails, there was probably an
  7911. * error flushing the buffer to disk, so the file on disk might be
  7912. * broken. Delete it and return an error to the caller. */
  7913. if (mg_fclose(&fi.access) != 0) {
  7914. remove_bad_file(conn, path);
  7915. return -14;
  7916. }
  7917. return len;
  7918. }
  7919. /* Parse a buffer:
  7920. * Forward the string pointer till the end of a word, then
  7921. * terminate it and forward till the begin of the next word.
  7922. */
  7923. static int
  7924. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  7925. {
  7926. /* Forward until a space is found - use isgraph here */
  7927. /* See http://www.cplusplus.com/reference/cctype/ */
  7928. while (isgraph(**ppw)) {
  7929. (*ppw)++;
  7930. }
  7931. /* Check end of word */
  7932. if (eol) {
  7933. /* must be a end of line */
  7934. if ((**ppw != '\r') && (**ppw != '\n')) {
  7935. return -1;
  7936. }
  7937. } else {
  7938. /* must be a end of a word, but not a line */
  7939. if (**ppw != ' ') {
  7940. return -1;
  7941. }
  7942. }
  7943. /* Terminate and forward to the next word */
  7944. do {
  7945. **ppw = 0;
  7946. (*ppw)++;
  7947. } while ((**ppw) && isspace(**ppw));
  7948. /* Check after term */
  7949. if (!eol) {
  7950. /* if it's not the end of line, there must be a next word */
  7951. if (!isgraph(**ppw)) {
  7952. return -1;
  7953. }
  7954. }
  7955. /* ok */
  7956. return 1;
  7957. }
  7958. /* Parse HTTP headers from the given buffer, advance buf pointer
  7959. * to the point where parsing stopped.
  7960. * All parameters must be valid pointers (not NULL).
  7961. * Return <0 on error. */
  7962. static int
  7963. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  7964. {
  7965. int i;
  7966. int num_headers = 0;
  7967. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  7968. char *dp = *buf;
  7969. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7970. dp++;
  7971. }
  7972. if (dp == *buf) {
  7973. /* End of headers reached. */
  7974. break;
  7975. }
  7976. if (*dp != ':') {
  7977. /* This is not a valid field. */
  7978. return -1;
  7979. }
  7980. /* End of header key (*dp == ':') */
  7981. /* Truncate here and set the key name */
  7982. *dp = 0;
  7983. hdr[i].name = *buf;
  7984. do {
  7985. dp++;
  7986. } while (*dp == ' ');
  7987. /* The rest of the line is the value */
  7988. hdr[i].value = dp;
  7989. *buf = dp + strcspn(dp, "\r\n");
  7990. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7991. *buf = NULL;
  7992. }
  7993. num_headers = i + 1;
  7994. if (*buf) {
  7995. (*buf)[0] = 0;
  7996. (*buf)[1] = 0;
  7997. *buf += 2;
  7998. } else {
  7999. *buf = dp;
  8000. break;
  8001. }
  8002. if ((*buf)[0] == '\r') {
  8003. /* This is the end of the header */
  8004. break;
  8005. }
  8006. }
  8007. return num_headers;
  8008. }
  8009. struct mg_http_method_info {
  8010. const char *name;
  8011. int request_has_body;
  8012. int response_has_body;
  8013. int is_safe;
  8014. int is_idempotent;
  8015. int is_cacheable;
  8016. };
  8017. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8018. static struct mg_http_method_info http_methods[] = {
  8019. /* HTTP (RFC 2616) */
  8020. {"GET", 0, 1, 1, 1, 1},
  8021. {"POST", 1, 1, 0, 0, 0},
  8022. {"PUT", 1, 0, 0, 1, 0},
  8023. {"DELETE", 0, 0, 0, 1, 0},
  8024. {"HEAD", 0, 0, 1, 1, 1},
  8025. {"OPTIONS", 0, 0, 1, 1, 0},
  8026. {"CONNECT", 1, 1, 0, 0, 0},
  8027. /* TRACE method (RFC 2616) is not supported for security reasons */
  8028. /* PATCH method (RFC 5789) */
  8029. {"PATCH", 1, 0, 0, 0, 0},
  8030. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8031. /* WEBDAV (RFC 2518) */
  8032. {"PROPFIND", 0, 1, 1, 1, 0},
  8033. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8034. * Some PROPFIND results MAY be cached, with care,
  8035. * as there is no cache validation mechanism for
  8036. * most properties. This method is both safe and
  8037. * idempotent (see Section 9.1 of [RFC2616]). */
  8038. {"MKCOL", 0, 0, 0, 1, 0},
  8039. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8040. * When MKCOL is invoked without a request body,
  8041. * the newly created collection SHOULD have no
  8042. * members. A MKCOL request message may contain
  8043. * a message body. The precise behavior of a MKCOL
  8044. * request when the body is present is undefined,
  8045. * ... ==> We do not support MKCOL with body data.
  8046. * This method is idempotent, but not safe (see
  8047. * Section 9.1 of [RFC2616]). Responses to this
  8048. * method MUST NOT be cached. */
  8049. /* Unsupported WEBDAV Methods: */
  8050. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8051. /* + 11 methods from RFC 3253 */
  8052. /* ORDERPATCH (RFC 3648) */
  8053. /* ACL (RFC 3744) */
  8054. /* SEARCH (RFC 5323) */
  8055. /* + MicroSoft extensions
  8056. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8057. /* REPORT method (RFC 3253) */
  8058. {"REPORT", 1, 1, 1, 1, 1},
  8059. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8060. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8061. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8062. * to be useful for REST in case a "GET request with body" is
  8063. * required. */
  8064. {NULL, 0, 0, 0, 0, 0}
  8065. /* end of list */
  8066. };
  8067. static const struct mg_http_method_info *
  8068. get_http_method_info(const char *method)
  8069. {
  8070. /* Check if the method is known to the server. The list of all known
  8071. * HTTP methods can be found here at
  8072. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8073. */
  8074. const struct mg_http_method_info *m = http_methods;
  8075. while (m->name) {
  8076. if (!strcmp(m->name, method)) {
  8077. return m;
  8078. }
  8079. m++;
  8080. }
  8081. return NULL;
  8082. }
  8083. static int
  8084. is_valid_http_method(const char *method)
  8085. {
  8086. return (get_http_method_info(method) != NULL);
  8087. }
  8088. /* Parse HTTP request, fill in mg_request_info structure.
  8089. * This function modifies the buffer by NUL-terminating
  8090. * HTTP request components, header names and header values.
  8091. * Parameters:
  8092. * buf (in/out): pointer to the HTTP header to parse and split
  8093. * len (in): length of HTTP header buffer
  8094. * re (out): parsed header as mg_request_info
  8095. * buf and ri must be valid pointers (not NULL), len>0.
  8096. * Returns <0 on error. */
  8097. static int
  8098. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8099. {
  8100. int request_length;
  8101. int init_skip = 0;
  8102. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  8103. * remote_port */
  8104. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8105. NULL;
  8106. ri->num_headers = 0;
  8107. /* RFC says that all initial whitespaces should be ingored */
  8108. /* This included all leading \r and \n (isspace) */
  8109. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8110. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8111. buf++;
  8112. len--;
  8113. init_skip++;
  8114. }
  8115. if (len == 0) {
  8116. /* Incomplete request */
  8117. return 0;
  8118. }
  8119. /* Control characters are not allowed, including zero */
  8120. if (iscntrl(*(unsigned char *)buf)) {
  8121. return -1;
  8122. }
  8123. /* Find end of HTTP header */
  8124. request_length = get_http_header_len(buf, len);
  8125. if (request_length <= 0) {
  8126. return request_length;
  8127. }
  8128. buf[request_length - 1] = '\0';
  8129. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8130. return -1;
  8131. }
  8132. /* The first word has to be the HTTP method */
  8133. ri->request_method = buf;
  8134. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8135. return -1;
  8136. }
  8137. /* Check for a valid http method */
  8138. if (!is_valid_http_method(ri->request_method)) {
  8139. return -1;
  8140. }
  8141. /* The second word is the URI */
  8142. ri->request_uri = buf;
  8143. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8144. return -1;
  8145. }
  8146. /* Next would be the HTTP version */
  8147. ri->http_version = buf;
  8148. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8149. return -1;
  8150. }
  8151. /* Check for a valid HTTP version key */
  8152. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8153. /* Invalid request */
  8154. return -1;
  8155. }
  8156. ri->http_version += 5;
  8157. /* Parse all HTTP headers */
  8158. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8159. if (ri->num_headers < 0) {
  8160. /* Error while parsing headers */
  8161. return -1;
  8162. }
  8163. return request_length + init_skip;
  8164. }
  8165. static int
  8166. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8167. {
  8168. int response_length;
  8169. int init_skip = 0;
  8170. char *tmp, *tmp2;
  8171. long l;
  8172. /* Initialize elements. */
  8173. ri->http_version = ri->status_text = NULL;
  8174. ri->num_headers = ri->status_code = 0;
  8175. /* RFC says that all initial whitespaces should be ingored */
  8176. /* This included all leading \r and \n (isspace) */
  8177. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8178. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8179. buf++;
  8180. len--;
  8181. init_skip++;
  8182. }
  8183. if (len == 0) {
  8184. /* Incomplete request */
  8185. return 0;
  8186. }
  8187. /* Control characters are not allowed, including zero */
  8188. if (iscntrl(*(unsigned char *)buf)) {
  8189. return -1;
  8190. }
  8191. /* Find end of HTTP header */
  8192. response_length = get_http_header_len(buf, len);
  8193. if (response_length <= 0) {
  8194. return response_length;
  8195. }
  8196. buf[response_length - 1] = '\0';
  8197. /* TODO: Define mg_response_info and implement parsing */
  8198. (void)buf;
  8199. (void)len;
  8200. (void)ri;
  8201. /* RFC says that all initial whitespaces should be ingored */
  8202. while ((*buf != '\0') && isspace(*(unsigned char *)buf)) {
  8203. buf++;
  8204. }
  8205. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8206. return -1;
  8207. }
  8208. /* The first word is the HTTP version */
  8209. /* Check for a valid HTTP version key */
  8210. if (strncmp(buf, "HTTP/", 5) != 0) {
  8211. /* Invalid request */
  8212. return -1;
  8213. }
  8214. buf += 5;
  8215. if (!isgraph(buf[0])) {
  8216. /* Invalid request */
  8217. return -1;
  8218. }
  8219. ri->http_version = buf;
  8220. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8221. return -1;
  8222. }
  8223. /* The second word is the status as a number */
  8224. tmp = buf;
  8225. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8226. return -1;
  8227. }
  8228. l = strtol(tmp, &tmp2, 10);
  8229. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8230. /* Everything else but a 3 digit code is invalid */
  8231. return -1;
  8232. }
  8233. ri->status_code = (int)l;
  8234. /* The rest of the line is the status text */
  8235. ri->status_text = buf;
  8236. /* Find end of status text */
  8237. /* isgraph or isspace = isprint */
  8238. while (isprint(*buf)) {
  8239. buf++;
  8240. }
  8241. if ((*buf != '\r') && (*buf != '\n')) {
  8242. return -1;
  8243. }
  8244. /* Terminate string and forward buf to next line */
  8245. do {
  8246. *buf = 0;
  8247. buf++;
  8248. } while ((*buf) && isspace(*buf));
  8249. /* Parse all HTTP headers */
  8250. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8251. if (ri->num_headers < 0) {
  8252. /* Error while parsing headers */
  8253. return -1;
  8254. }
  8255. return response_length + init_skip;
  8256. }
  8257. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8258. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8259. * buffer (which marks the end of HTTP request). Buffer buf may already
  8260. * have some data. The length of the data is stored in nread.
  8261. * Upon every read operation, increase nread by the number of bytes read. */
  8262. static int
  8263. read_message(FILE *fp,
  8264. struct mg_connection *conn,
  8265. char *buf,
  8266. int bufsiz,
  8267. int *nread)
  8268. {
  8269. int request_len, n = 0;
  8270. struct timespec last_action_time;
  8271. double request_timeout;
  8272. if (!conn) {
  8273. return 0;
  8274. }
  8275. memset(&last_action_time, 0, sizeof(last_action_time));
  8276. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  8277. /* value of request_timeout is in seconds, config in milliseconds */
  8278. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8279. } else {
  8280. request_timeout = -1.0;
  8281. }
  8282. if (conn->handled_requests > 0) {
  8283. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8284. request_timeout =
  8285. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8286. }
  8287. }
  8288. request_len = get_http_header_len(buf, *nread);
  8289. /* first time reading from this connection */
  8290. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8291. while (request_len == 0) {
  8292. /* Full request not yet received */
  8293. if (conn->ctx->stop_flag != 0) {
  8294. /* Server is to be stopped. */
  8295. return -1;
  8296. }
  8297. if (*nread >= bufsiz) {
  8298. /* Request too long */
  8299. return -2;
  8300. }
  8301. n = pull_inner(
  8302. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8303. if (n == -2) {
  8304. /* Receive error */
  8305. return -1;
  8306. }
  8307. if (n > 0) {
  8308. *nread += n;
  8309. request_len = get_http_header_len(buf, *nread);
  8310. } else {
  8311. request_len = 0;
  8312. }
  8313. if ((request_len == 0) && (request_timeout >= 0)) {
  8314. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8315. > request_timeout) {
  8316. /* Timeout */
  8317. return -1;
  8318. }
  8319. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8320. }
  8321. }
  8322. return request_len;
  8323. }
  8324. #if !defined(NO_CACHING)
  8325. /* Return True if we should reply 304 Not Modified. */
  8326. static int
  8327. is_not_modified(const struct mg_connection *conn,
  8328. const struct mg_file_stat *filestat)
  8329. {
  8330. char etag[64];
  8331. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8332. const char *inm = mg_get_header(conn, "If-None-Match");
  8333. construct_etag(etag, sizeof(etag), filestat);
  8334. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8335. || ((ims != NULL)
  8336. && (filestat->last_modified <= parse_date_string(ims)));
  8337. }
  8338. #endif /* !NO_CACHING */
  8339. #if !defined(NO_CGI) || !defined(NO_FILES)
  8340. static int
  8341. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8342. {
  8343. const char *expect, *body;
  8344. char buf[MG_BUF_LEN];
  8345. int to_read, nread, success = 0;
  8346. int64_t buffered_len;
  8347. double timeout = -1.0;
  8348. if (!conn) {
  8349. return 0;
  8350. }
  8351. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  8352. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8353. }
  8354. expect = mg_get_header(conn, "Expect");
  8355. /* assert(fp != NULL); */
  8356. if (!fp) {
  8357. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8358. return 0;
  8359. }
  8360. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8361. /* Content length is not specified by the client. */
  8362. mg_send_http_error(conn,
  8363. 411,
  8364. "%s",
  8365. "Error: Client did not specify content length");
  8366. } else if ((expect != NULL)
  8367. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8368. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8369. */
  8370. mg_send_http_error(conn,
  8371. 417,
  8372. "Error: Can not fulfill expectation %s",
  8373. expect);
  8374. } else {
  8375. if (expect != NULL) {
  8376. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8377. conn->status_code = 100;
  8378. } else {
  8379. conn->status_code = 200;
  8380. }
  8381. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8382. - conn->consumed_content;
  8383. /* assert(buffered_len >= 0); */
  8384. /* assert(conn->consumed_content == 0); */
  8385. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8386. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8387. return 0;
  8388. }
  8389. if (buffered_len > 0) {
  8390. if ((int64_t)buffered_len > conn->content_len) {
  8391. buffered_len = (int)conn->content_len;
  8392. }
  8393. body = conn->buf + conn->request_len + conn->consumed_content;
  8394. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8395. conn->consumed_content += buffered_len;
  8396. }
  8397. nread = 0;
  8398. while (conn->consumed_content < conn->content_len) {
  8399. to_read = sizeof(buf);
  8400. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8401. to_read = (int)(conn->content_len - conn->consumed_content);
  8402. }
  8403. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8404. if (nread == -2) {
  8405. /* error */
  8406. break;
  8407. }
  8408. if (nread > 0) {
  8409. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  8410. break;
  8411. }
  8412. }
  8413. conn->consumed_content += nread;
  8414. }
  8415. if (conn->consumed_content == conn->content_len) {
  8416. success = (nread >= 0);
  8417. }
  8418. /* Each error code path in this function must send an error */
  8419. if (!success) {
  8420. /* NOTE: Maybe some data has already been sent. */
  8421. /* TODO (low): If some data has been sent, a correct error
  8422. * reply can no longer be sent, so just close the connection */
  8423. mg_send_http_error(conn, 500, "%s", "");
  8424. }
  8425. }
  8426. return success;
  8427. }
  8428. #endif
  8429. #if !defined(NO_CGI)
  8430. /* This structure helps to create an environment for the spawned CGI
  8431. * program.
  8432. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8433. * last element must be NULL.
  8434. * However, on Windows there is a requirement that all these
  8435. * VARIABLE=VALUE\0
  8436. * strings must reside in a contiguous buffer. The end of the buffer is
  8437. * marked by two '\0' characters.
  8438. * We satisfy both worlds: we create an envp array (which is vars), all
  8439. * entries are actually pointers inside buf. */
  8440. struct cgi_environment {
  8441. struct mg_connection *conn;
  8442. /* Data block */
  8443. char *buf; /* Environment buffer */
  8444. size_t buflen; /* Space available in buf */
  8445. size_t bufused; /* Space taken in buf */
  8446. /* Index block */
  8447. char **var; /* char **envp */
  8448. size_t varlen; /* Number of variables available in var */
  8449. size_t varused; /* Number of variables stored in var */
  8450. };
  8451. static void addenv(struct cgi_environment *env,
  8452. PRINTF_FORMAT_STRING(const char *fmt),
  8453. ...) PRINTF_ARGS(2, 3);
  8454. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8455. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8456. static void
  8457. addenv(struct cgi_environment *env, const char *fmt, ...)
  8458. {
  8459. size_t n, space;
  8460. int truncated = 0;
  8461. char *added;
  8462. va_list ap;
  8463. /* Calculate how much space is left in the buffer */
  8464. space = (env->buflen - env->bufused);
  8465. /* Calculate an estimate for the required space */
  8466. n = strlen(fmt) + 2 + 128;
  8467. do {
  8468. if (space <= n) {
  8469. /* Allocate new buffer */
  8470. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8471. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  8472. if (!added) {
  8473. /* Out of memory */
  8474. mg_cry(env->conn,
  8475. "%s: Cannot allocate memory for CGI variable [%s]",
  8476. __func__,
  8477. fmt);
  8478. return;
  8479. }
  8480. env->buf = added;
  8481. env->buflen = n;
  8482. space = (env->buflen - env->bufused);
  8483. }
  8484. /* Make a pointer to the free space int the buffer */
  8485. added = env->buf + env->bufused;
  8486. /* Copy VARIABLE=VALUE\0 string into the free space */
  8487. va_start(ap, fmt);
  8488. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8489. va_end(ap);
  8490. /* Do not add truncated strings to the environment */
  8491. if (truncated) {
  8492. /* Reallocate the buffer */
  8493. space = 0;
  8494. n = 1;
  8495. }
  8496. } while (truncated);
  8497. /* Calculate number of bytes added to the environment */
  8498. n = strlen(added) + 1;
  8499. env->bufused += n;
  8500. /* Now update the variable index */
  8501. space = (env->varlen - env->varused);
  8502. if (space < 2) {
  8503. mg_cry(env->conn,
  8504. "%s: Cannot register CGI variable [%s]",
  8505. __func__,
  8506. fmt);
  8507. return;
  8508. }
  8509. /* Append a pointer to the added string into the envp array */
  8510. env->var[env->varused] = added;
  8511. env->varused++;
  8512. }
  8513. /* Return 0 on success, non-zero if an error occurs. */
  8514. static int
  8515. prepare_cgi_environment(struct mg_connection *conn,
  8516. const char *prog,
  8517. struct cgi_environment *env)
  8518. {
  8519. const char *s;
  8520. struct vec var_vec;
  8521. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8522. int i, truncated, uri_len;
  8523. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8524. return -1;
  8525. }
  8526. env->conn = conn;
  8527. env->buflen = CGI_ENVIRONMENT_SIZE;
  8528. env->bufused = 0;
  8529. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  8530. if (env->buf == NULL) {
  8531. mg_cry(conn,
  8532. "%s: Not enough memory for environmental buffer",
  8533. __func__);
  8534. return -1;
  8535. }
  8536. env->varlen = MAX_CGI_ENVIR_VARS;
  8537. env->varused = 0;
  8538. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  8539. if (env->var == NULL) {
  8540. mg_cry(conn,
  8541. "%s: Not enough memory for environmental variables",
  8542. __func__);
  8543. mg_free(env->buf);
  8544. return -1;
  8545. }
  8546. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  8547. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8548. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8549. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8550. /* Prepare the environment block */
  8551. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8552. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8553. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8554. #if defined(USE_IPV6)
  8555. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8556. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8557. } else
  8558. #endif
  8559. {
  8560. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8561. }
  8562. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8563. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8564. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8565. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8566. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8567. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8568. /* SCRIPT_NAME */
  8569. uri_len = (int)strlen(conn->request_info.local_uri);
  8570. if (conn->path_info == NULL) {
  8571. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8572. /* URI: /path_to_script/script.cgi */
  8573. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8574. } else {
  8575. /* URI: /path_to_script/ ... using index.cgi */
  8576. const char *index_file = strrchr(prog, '/');
  8577. if (index_file) {
  8578. addenv(env,
  8579. "SCRIPT_NAME=%s%s",
  8580. conn->request_info.local_uri,
  8581. index_file + 1);
  8582. }
  8583. }
  8584. } else {
  8585. /* URI: /path_to_script/script.cgi/path_info */
  8586. addenv(env,
  8587. "SCRIPT_NAME=%.*s",
  8588. uri_len - (int)strlen(conn->path_info),
  8589. conn->request_info.local_uri);
  8590. }
  8591. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8592. if (conn->path_info == NULL) {
  8593. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8594. } else {
  8595. addenv(env,
  8596. "PATH_TRANSLATED=%s%s",
  8597. conn->ctx->config[DOCUMENT_ROOT],
  8598. conn->path_info);
  8599. }
  8600. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8601. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8602. addenv(env, "CONTENT_TYPE=%s", s);
  8603. }
  8604. if (conn->request_info.query_string != NULL) {
  8605. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8606. }
  8607. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8608. addenv(env, "CONTENT_LENGTH=%s", s);
  8609. }
  8610. if ((s = getenv("PATH")) != NULL) {
  8611. addenv(env, "PATH=%s", s);
  8612. }
  8613. if (conn->path_info != NULL) {
  8614. addenv(env, "PATH_INFO=%s", conn->path_info);
  8615. }
  8616. if (conn->status_code > 0) {
  8617. /* CGI error handler should show the status code */
  8618. addenv(env, "STATUS=%d", conn->status_code);
  8619. }
  8620. #if defined(_WIN32)
  8621. if ((s = getenv("COMSPEC")) != NULL) {
  8622. addenv(env, "COMSPEC=%s", s);
  8623. }
  8624. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8625. addenv(env, "SYSTEMROOT=%s", s);
  8626. }
  8627. if ((s = getenv("SystemDrive")) != NULL) {
  8628. addenv(env, "SystemDrive=%s", s);
  8629. }
  8630. if ((s = getenv("ProgramFiles")) != NULL) {
  8631. addenv(env, "ProgramFiles=%s", s);
  8632. }
  8633. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8634. addenv(env, "ProgramFiles(x86)=%s", s);
  8635. }
  8636. #else
  8637. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8638. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8639. }
  8640. #endif /* _WIN32 */
  8641. if ((s = getenv("PERLLIB")) != NULL) {
  8642. addenv(env, "PERLLIB=%s", s);
  8643. }
  8644. if (conn->request_info.remote_user != NULL) {
  8645. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8646. addenv(env, "%s", "AUTH_TYPE=Digest");
  8647. }
  8648. /* Add all headers as HTTP_* variables */
  8649. for (i = 0; i < conn->request_info.num_headers; i++) {
  8650. (void)mg_snprintf(conn,
  8651. &truncated,
  8652. http_var_name,
  8653. sizeof(http_var_name),
  8654. "HTTP_%s",
  8655. conn->request_info.http_headers[i].name);
  8656. if (truncated) {
  8657. mg_cry(conn,
  8658. "%s: HTTP header variable too long [%s]",
  8659. __func__,
  8660. conn->request_info.http_headers[i].name);
  8661. continue;
  8662. }
  8663. /* Convert variable name into uppercase, and change - to _ */
  8664. for (p = http_var_name; *p != '\0'; p++) {
  8665. if (*p == '-') {
  8666. *p = '_';
  8667. }
  8668. *p = (char)toupper(*(unsigned char *)p);
  8669. }
  8670. addenv(env,
  8671. "%s=%s",
  8672. http_var_name,
  8673. conn->request_info.http_headers[i].value);
  8674. }
  8675. /* Add user-specified variables */
  8676. s = conn->ctx->config[CGI_ENVIRONMENT];
  8677. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8678. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8679. }
  8680. env->var[env->varused] = NULL;
  8681. env->buf[env->bufused] = '\0';
  8682. return 0;
  8683. }
  8684. static void
  8685. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8686. {
  8687. char *buf;
  8688. size_t buflen;
  8689. int headers_len, data_len, i, truncated;
  8690. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8691. const char *status, *status_text, *connection_state;
  8692. char *pbuf, dir[PATH_MAX], *p;
  8693. struct mg_request_info ri;
  8694. struct cgi_environment blk;
  8695. FILE *in = NULL, *out = NULL, *err = NULL;
  8696. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8697. pid_t pid = (pid_t)-1;
  8698. if (conn == NULL) {
  8699. return;
  8700. }
  8701. buf = NULL;
  8702. buflen = 16384;
  8703. i = prepare_cgi_environment(conn, prog, &blk);
  8704. if (i != 0) {
  8705. blk.buf = NULL;
  8706. blk.var = NULL;
  8707. goto done;
  8708. }
  8709. /* CGI must be executed in its own directory. 'dir' must point to the
  8710. * directory containing executable program, 'p' must point to the
  8711. * executable program name relative to 'dir'. */
  8712. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8713. if (truncated) {
  8714. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  8715. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8716. goto done;
  8717. }
  8718. if ((p = strrchr(dir, '/')) != NULL) {
  8719. *p++ = '\0';
  8720. } else {
  8721. dir[0] = '.';
  8722. dir[1] = '\0';
  8723. p = (char *)prog;
  8724. }
  8725. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8726. status = strerror(ERRNO);
  8727. mg_cry(conn,
  8728. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8729. prog,
  8730. status);
  8731. mg_send_http_error(conn,
  8732. 500,
  8733. "Error: Cannot create CGI pipe: %s",
  8734. status);
  8735. goto done;
  8736. }
  8737. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  8738. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8739. if (pid == (pid_t)-1) {
  8740. status = strerror(ERRNO);
  8741. mg_cry(conn,
  8742. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8743. prog,
  8744. status);
  8745. mg_send_http_error(conn,
  8746. 500,
  8747. "Error: Cannot spawn CGI process [%s]: %s",
  8748. prog,
  8749. status);
  8750. goto done;
  8751. }
  8752. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  8753. */
  8754. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8755. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8756. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8757. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8758. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8759. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8760. /* Parent closes only one side of the pipes.
  8761. * If we don't mark them as closed, close() attempt before
  8762. * return from this function throws an exception on Windows.
  8763. * Windows does not like when closed descriptor is closed again. */
  8764. (void)close(fdin[0]);
  8765. (void)close(fdout[1]);
  8766. (void)close(fderr[1]);
  8767. fdin[0] = fdout[1] = fderr[1] = -1;
  8768. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8769. status = strerror(ERRNO);
  8770. mg_cry(conn,
  8771. "Error: CGI program \"%s\": Can not open stdin: %s",
  8772. prog,
  8773. status);
  8774. mg_send_http_error(conn,
  8775. 500,
  8776. "Error: CGI can not open fdin\nfopen: %s",
  8777. status);
  8778. goto done;
  8779. }
  8780. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8781. status = strerror(ERRNO);
  8782. mg_cry(conn,
  8783. "Error: CGI program \"%s\": Can not open stdout: %s",
  8784. prog,
  8785. status);
  8786. mg_send_http_error(conn,
  8787. 500,
  8788. "Error: CGI can not open fdout\nfopen: %s",
  8789. status);
  8790. goto done;
  8791. }
  8792. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8793. status = strerror(ERRNO);
  8794. mg_cry(conn,
  8795. "Error: CGI program \"%s\": Can not open stderr: %s",
  8796. prog,
  8797. status);
  8798. mg_send_http_error(conn,
  8799. 500,
  8800. "Error: CGI can not open fdout\nfopen: %s",
  8801. status);
  8802. goto done;
  8803. }
  8804. setbuf(in, NULL);
  8805. setbuf(out, NULL);
  8806. setbuf(err, NULL);
  8807. fout.access.fp = out;
  8808. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  8809. DEBUG_TRACE("CGI: send body data (%lli)\n",
  8810. (signed long long)conn->request_info.content_length);
  8811. /* This is a POST/PUT request, or another request with body data. */
  8812. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8813. /* Error sending the body data */
  8814. mg_cry(conn,
  8815. "Error: CGI program \"%s\": Forward body data failed",
  8816. prog);
  8817. goto done;
  8818. }
  8819. }
  8820. /* Close so child gets an EOF. */
  8821. fclose(in);
  8822. in = NULL;
  8823. fdin[1] = -1;
  8824. /* Now read CGI reply into a buffer. We need to set correct
  8825. * status code, thus we need to see all HTTP headers first.
  8826. * Do not send anything back to client, until we buffer in all
  8827. * HTTP headers. */
  8828. data_len = 0;
  8829. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  8830. if (buf == NULL) {
  8831. mg_send_http_error(conn,
  8832. 500,
  8833. "Error: Not enough memory for CGI buffer (%u bytes)",
  8834. (unsigned int)buflen);
  8835. mg_cry(conn,
  8836. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  8837. "bytes)",
  8838. prog,
  8839. (unsigned int)buflen);
  8840. goto done;
  8841. }
  8842. DEBUG_TRACE("CGI: %s", "wait for response");
  8843. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  8844. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  8845. if (headers_len <= 0) {
  8846. /* Could not parse the CGI response. Check if some error message on
  8847. * stderr. */
  8848. i = pull_all(err, conn, buf, (int)buflen);
  8849. if (i > 0) {
  8850. mg_cry(conn,
  8851. "Error: CGI program \"%s\" sent error "
  8852. "message: [%.*s]",
  8853. prog,
  8854. i,
  8855. buf);
  8856. mg_send_http_error(conn,
  8857. 500,
  8858. "Error: CGI program \"%s\" sent error "
  8859. "message: [%.*s]",
  8860. prog,
  8861. i,
  8862. buf);
  8863. } else {
  8864. mg_cry(conn,
  8865. "Error: CGI program sent malformed or too big "
  8866. "(>%u bytes) HTTP headers: [%.*s]",
  8867. (unsigned)buflen,
  8868. data_len,
  8869. buf);
  8870. mg_send_http_error(conn,
  8871. 500,
  8872. "Error: CGI program sent malformed or too big "
  8873. "(>%u bytes) HTTP headers: [%.*s]",
  8874. (unsigned)buflen,
  8875. data_len,
  8876. buf);
  8877. }
  8878. goto done;
  8879. }
  8880. pbuf = buf;
  8881. buf[headers_len - 1] = '\0';
  8882. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  8883. /* Make up and send the status line */
  8884. status_text = "OK";
  8885. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  8886. != NULL) {
  8887. conn->status_code = atoi(status);
  8888. status_text = status;
  8889. while (isdigit(*(const unsigned char *)status_text)
  8890. || *status_text == ' ') {
  8891. status_text++;
  8892. }
  8893. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  8894. != NULL) {
  8895. conn->status_code = 302;
  8896. } else {
  8897. conn->status_code = 200;
  8898. }
  8899. connection_state =
  8900. get_header(ri.http_headers, ri.num_headers, "Connection");
  8901. if (!header_has_option(connection_state, "keep-alive")) {
  8902. conn->must_close = 1;
  8903. }
  8904. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  8905. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  8906. /* Send headers */
  8907. for (i = 0; i < ri.num_headers; i++) {
  8908. mg_printf(conn,
  8909. "%s: %s\r\n",
  8910. ri.http_headers[i].name,
  8911. ri.http_headers[i].value);
  8912. }
  8913. mg_write(conn, "\r\n", 2);
  8914. /* Send chunk of data that may have been read after the headers */
  8915. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  8916. /* Read the rest of CGI output and send to the client */
  8917. send_file_data(conn, &fout, 0, INT64_MAX);
  8918. DEBUG_TRACE("CGI: %s", "all data sent");
  8919. done:
  8920. mg_free(blk.var);
  8921. mg_free(blk.buf);
  8922. if (pid != (pid_t)-1) {
  8923. kill(pid, SIGKILL);
  8924. #if !defined(_WIN32)
  8925. {
  8926. int st;
  8927. while (waitpid(pid, &st, 0) != -1)
  8928. ; /* clean zombies */
  8929. }
  8930. #endif
  8931. }
  8932. if (fdin[0] != -1) {
  8933. close(fdin[0]);
  8934. }
  8935. if (fdout[1] != -1) {
  8936. close(fdout[1]);
  8937. }
  8938. if (in != NULL) {
  8939. fclose(in);
  8940. } else if (fdin[1] != -1) {
  8941. close(fdin[1]);
  8942. }
  8943. if (out != NULL) {
  8944. fclose(out);
  8945. } else if (fdout[0] != -1) {
  8946. close(fdout[0]);
  8947. }
  8948. if (err != NULL) {
  8949. fclose(err);
  8950. } else if (fderr[0] != -1) {
  8951. close(fderr[0]);
  8952. }
  8953. if (buf != NULL) {
  8954. mg_free(buf);
  8955. }
  8956. }
  8957. #endif /* !NO_CGI */
  8958. #if !defined(NO_FILES)
  8959. static void
  8960. mkcol(struct mg_connection *conn, const char *path)
  8961. {
  8962. int rc, body_len;
  8963. struct de de;
  8964. char date[64];
  8965. time_t curtime = time(NULL);
  8966. if (conn == NULL) {
  8967. return;
  8968. }
  8969. /* TODO (mid): Check the mg_send_http_error situations in this function
  8970. */
  8971. memset(&de.file, 0, sizeof(de.file));
  8972. if (!mg_stat(conn, path, &de.file)) {
  8973. mg_cry(conn,
  8974. "%s: mg_stat(%s) failed: %s",
  8975. __func__,
  8976. path,
  8977. strerror(ERRNO));
  8978. }
  8979. if (de.file.last_modified) {
  8980. /* TODO (mid): This check does not seem to make any sense ! */
  8981. /* TODO (mid): Add a webdav unit test first, before changing
  8982. * anything here. */
  8983. mg_send_http_error(
  8984. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8985. return;
  8986. }
  8987. body_len = conn->data_len - conn->request_len;
  8988. if (body_len > 0) {
  8989. mg_send_http_error(
  8990. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8991. return;
  8992. }
  8993. rc = mg_mkdir(conn, path, 0755);
  8994. if (rc == 0) {
  8995. conn->status_code = 201;
  8996. gmt_time_string(date, sizeof(date), &curtime);
  8997. mg_printf(conn,
  8998. "HTTP/1.1 %d Created\r\n"
  8999. "Date: %s\r\n",
  9000. conn->status_code,
  9001. date);
  9002. send_static_cache_header(conn);
  9003. send_additional_header(conn);
  9004. mg_printf(conn,
  9005. "Content-Length: 0\r\n"
  9006. "Connection: %s\r\n\r\n",
  9007. suggest_connection_header(conn));
  9008. } else if (rc == -1) {
  9009. if (errno == EEXIST) {
  9010. mg_send_http_error(
  9011. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9012. } else if (errno == EACCES) {
  9013. mg_send_http_error(
  9014. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9015. } else if (errno == ENOENT) {
  9016. mg_send_http_error(
  9017. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9018. } else {
  9019. mg_send_http_error(
  9020. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9021. }
  9022. }
  9023. }
  9024. static void
  9025. put_file(struct mg_connection *conn, const char *path)
  9026. {
  9027. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9028. const char *range;
  9029. int64_t r1, r2;
  9030. int rc;
  9031. char date[64];
  9032. time_t curtime = time(NULL);
  9033. if (conn == NULL) {
  9034. return;
  9035. }
  9036. if (mg_stat(conn, path, &file.stat)) {
  9037. /* File already exists */
  9038. conn->status_code = 200;
  9039. if (file.stat.is_directory) {
  9040. /* This is an already existing directory,
  9041. * so there is nothing to do for the server. */
  9042. rc = 0;
  9043. } else {
  9044. /* File exists and is not a directory. */
  9045. /* Can it be replaced? */
  9046. if (file.access.membuf != NULL) {
  9047. /* This is an "in-memory" file, that can not be replaced */
  9048. mg_send_http_error(conn,
  9049. 405,
  9050. "Error: Put not possible\nReplacing %s "
  9051. "is not supported",
  9052. path);
  9053. return;
  9054. }
  9055. /* Check if the server may write this file */
  9056. if (access(path, W_OK) == 0) {
  9057. /* Access granted */
  9058. conn->status_code = 200;
  9059. rc = 1;
  9060. } else {
  9061. mg_send_http_error(
  9062. conn,
  9063. 403,
  9064. "Error: Put not possible\nReplacing %s is not allowed",
  9065. path);
  9066. return;
  9067. }
  9068. }
  9069. } else {
  9070. /* File should be created */
  9071. conn->status_code = 201;
  9072. rc = put_dir(conn, path);
  9073. }
  9074. if (rc == 0) {
  9075. /* put_dir returns 0 if path is a directory */
  9076. gmt_time_string(date, sizeof(date), &curtime);
  9077. mg_printf(conn,
  9078. "HTTP/1.1 %d %s\r\n",
  9079. conn->status_code,
  9080. mg_get_response_code_text(NULL, conn->status_code));
  9081. send_no_cache_header(conn);
  9082. send_additional_header(conn);
  9083. mg_printf(conn,
  9084. "Date: %s\r\n"
  9085. "Content-Length: 0\r\n"
  9086. "Connection: %s\r\n\r\n",
  9087. date,
  9088. suggest_connection_header(conn));
  9089. /* Request to create a directory has been fulfilled successfully.
  9090. * No need to put a file. */
  9091. return;
  9092. }
  9093. if (rc == -1) {
  9094. /* put_dir returns -1 if the path is too long */
  9095. mg_send_http_error(conn,
  9096. 414,
  9097. "Error: Path too long\nput_dir(%s): %s",
  9098. path,
  9099. strerror(ERRNO));
  9100. return;
  9101. }
  9102. if (rc == -2) {
  9103. /* put_dir returns -2 if the directory can not be created */
  9104. mg_send_http_error(conn,
  9105. 500,
  9106. "Error: Can not create directory\nput_dir(%s): %s",
  9107. path,
  9108. strerror(ERRNO));
  9109. return;
  9110. }
  9111. /* A file should be created or overwritten. */
  9112. /* Currently CivetWeb does not nead read+write access. */
  9113. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9114. || file.access.fp == NULL) {
  9115. (void)mg_fclose(&file.access);
  9116. mg_send_http_error(conn,
  9117. 500,
  9118. "Error: Can not create file\nfopen(%s): %s",
  9119. path,
  9120. strerror(ERRNO));
  9121. return;
  9122. }
  9123. fclose_on_exec(&file.access, conn);
  9124. range = mg_get_header(conn, "Content-Range");
  9125. r1 = r2 = 0;
  9126. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9127. conn->status_code = 206; /* Partial content */
  9128. fseeko(file.access.fp, r1, SEEK_SET);
  9129. }
  9130. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9131. /* forward_body_data failed.
  9132. * The error code has already been sent to the client,
  9133. * and conn->status_code is already set. */
  9134. (void)mg_fclose(&file.access);
  9135. return;
  9136. }
  9137. if (mg_fclose(&file.access) != 0) {
  9138. /* fclose failed. This might have different reasons, but a likely
  9139. * one is "no space on disk", http 507. */
  9140. conn->status_code = 507;
  9141. }
  9142. gmt_time_string(date, sizeof(date), &curtime);
  9143. mg_printf(conn,
  9144. "HTTP/1.1 %d %s\r\n",
  9145. conn->status_code,
  9146. mg_get_response_code_text(NULL, conn->status_code));
  9147. send_no_cache_header(conn);
  9148. send_additional_header(conn);
  9149. mg_printf(conn,
  9150. "Date: %s\r\n"
  9151. "Content-Length: 0\r\n"
  9152. "Connection: %s\r\n\r\n",
  9153. date,
  9154. suggest_connection_header(conn));
  9155. }
  9156. static void
  9157. delete_file(struct mg_connection *conn, const char *path)
  9158. {
  9159. struct de de;
  9160. memset(&de.file, 0, sizeof(de.file));
  9161. if (!mg_stat(conn, path, &de.file)) {
  9162. /* mg_stat returns 0 if the file does not exist */
  9163. mg_send_http_error(conn,
  9164. 404,
  9165. "Error: Cannot delete file\nFile %s not found",
  9166. path);
  9167. return;
  9168. }
  9169. #if 0 /* Ignore if a file in memory is inside a folder */
  9170. if (de.access.membuf != NULL) {
  9171. /* the file is cached in memory */
  9172. mg_send_http_error(
  9173. conn,
  9174. 405,
  9175. "Error: Delete not possible\nDeleting %s is not supported",
  9176. path);
  9177. return;
  9178. }
  9179. #endif
  9180. if (de.file.is_directory) {
  9181. if (remove_directory(conn, path)) {
  9182. /* Delete is successful: Return 204 without content. */
  9183. mg_send_http_error(conn, 204, "%s", "");
  9184. } else {
  9185. /* Delete is not successful: Return 500 (Server error). */
  9186. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9187. }
  9188. return;
  9189. }
  9190. /* This is an existing file (not a directory).
  9191. * Check if write permission is granted. */
  9192. if (access(path, W_OK) != 0) {
  9193. /* File is read only */
  9194. mg_send_http_error(
  9195. conn,
  9196. 403,
  9197. "Error: Delete not possible\nDeleting %s is not allowed",
  9198. path);
  9199. return;
  9200. }
  9201. /* Try to delete it. */
  9202. if (mg_remove(conn, path) == 0) {
  9203. /* Delete was successful: Return 204 without content. */
  9204. mg_send_http_error(conn, 204, "%s", "");
  9205. } else {
  9206. /* Delete not successful (file locked). */
  9207. mg_send_http_error(conn,
  9208. 423,
  9209. "Error: Cannot delete file\nremove(%s): %s",
  9210. path,
  9211. strerror(ERRNO));
  9212. }
  9213. }
  9214. #endif /* !NO_FILES */
  9215. static void
  9216. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9217. static void
  9218. do_ssi_include(struct mg_connection *conn,
  9219. const char *ssi,
  9220. char *tag,
  9221. int include_level)
  9222. {
  9223. char file_name[MG_BUF_LEN], path[512], *p;
  9224. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9225. size_t len;
  9226. int truncated = 0;
  9227. if (conn == NULL) {
  9228. return;
  9229. }
  9230. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9231. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9232. * always < MG_BUF_LEN. */
  9233. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9234. /* File name is relative to the webserver root */
  9235. file_name[511] = 0;
  9236. (void)mg_snprintf(conn,
  9237. &truncated,
  9238. path,
  9239. sizeof(path),
  9240. "%s/%s",
  9241. conn->ctx->config[DOCUMENT_ROOT],
  9242. file_name);
  9243. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9244. /* File name is relative to the webserver working directory
  9245. * or it is absolute system path */
  9246. file_name[511] = 0;
  9247. (void)
  9248. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9249. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9250. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9251. /* File name is relative to the currect document */
  9252. file_name[511] = 0;
  9253. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9254. if (!truncated) {
  9255. if ((p = strrchr(path, '/')) != NULL) {
  9256. p[1] = '\0';
  9257. }
  9258. len = strlen(path);
  9259. (void)mg_snprintf(conn,
  9260. &truncated,
  9261. path + len,
  9262. sizeof(path) - len,
  9263. "%s",
  9264. file_name);
  9265. }
  9266. } else {
  9267. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  9268. return;
  9269. }
  9270. if (truncated) {
  9271. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  9272. return;
  9273. }
  9274. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9275. mg_cry(conn,
  9276. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9277. tag,
  9278. path,
  9279. strerror(ERRNO));
  9280. } else {
  9281. fclose_on_exec(&file.access, conn);
  9282. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9283. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9284. path) > 0) {
  9285. send_ssi_file(conn, path, &file, include_level + 1);
  9286. } else {
  9287. send_file_data(conn, &file, 0, INT64_MAX);
  9288. }
  9289. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9290. }
  9291. }
  9292. #if !defined(NO_POPEN)
  9293. static void
  9294. do_ssi_exec(struct mg_connection *conn, char *tag)
  9295. {
  9296. char cmd[1024] = "";
  9297. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9298. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9299. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  9300. } else {
  9301. cmd[1023] = 0;
  9302. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9303. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  9304. } else {
  9305. send_file_data(conn, &file, 0, INT64_MAX);
  9306. pclose(file.access.fp);
  9307. }
  9308. }
  9309. }
  9310. #endif /* !NO_POPEN */
  9311. static int
  9312. mg_fgetc(struct mg_file *filep, int offset)
  9313. {
  9314. if (filep == NULL) {
  9315. return EOF;
  9316. }
  9317. if ((filep->access.membuf != NULL) && (offset >= 0)
  9318. && (((unsigned int)(offset)) < filep->stat.size)) {
  9319. return ((const unsigned char *)filep->access.membuf)[offset];
  9320. } else if (filep->access.fp != NULL) {
  9321. return fgetc(filep->access.fp);
  9322. } else {
  9323. return EOF;
  9324. }
  9325. }
  9326. static void
  9327. send_ssi_file(struct mg_connection *conn,
  9328. const char *path,
  9329. struct mg_file *filep,
  9330. int include_level)
  9331. {
  9332. char buf[MG_BUF_LEN];
  9333. int ch, offset, len, in_tag, in_ssi_tag;
  9334. if (include_level > 10) {
  9335. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  9336. return;
  9337. }
  9338. in_tag = in_ssi_tag = len = offset = 0;
  9339. /* Read file, byte by byte, and look for SSI include tags */
  9340. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9341. if (in_tag) {
  9342. /* We are in a tag, either SSI tag or html tag */
  9343. if (ch == '>') {
  9344. /* Tag is closing */
  9345. buf[len++] = '>';
  9346. if (in_ssi_tag) {
  9347. /* Handle SSI tag */
  9348. buf[len] = 0;
  9349. if (!memcmp(buf + 5, "include", 7)) {
  9350. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9351. #if !defined(NO_POPEN)
  9352. } else if (!memcmp(buf + 5, "exec", 4)) {
  9353. do_ssi_exec(conn, buf + 9);
  9354. #endif /* !NO_POPEN */
  9355. } else {
  9356. mg_cry(conn,
  9357. "%s: unknown SSI "
  9358. "command: \"%s\"",
  9359. path,
  9360. buf);
  9361. }
  9362. len = 0;
  9363. in_ssi_tag = in_tag = 0;
  9364. } else {
  9365. /* Not an SSI tag */
  9366. /* Flush buffer */
  9367. (void)mg_write(conn, buf, (size_t)len);
  9368. len = 0;
  9369. in_tag = 0;
  9370. }
  9371. } else {
  9372. /* Tag is still open */
  9373. buf[len++] = (char)(ch & 0xff);
  9374. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9375. /* All SSI tags start with <!--# */
  9376. in_ssi_tag = 1;
  9377. }
  9378. if ((len + 2) > (int)sizeof(buf)) {
  9379. /* Tag to long for buffer */
  9380. mg_cry(conn, "%s: tag is too large", path);
  9381. return;
  9382. }
  9383. }
  9384. } else {
  9385. /* We are not in a tag yet. */
  9386. if (ch == '<') {
  9387. /* Tag is opening */
  9388. in_tag = 1;
  9389. /* Flush current buffer */
  9390. (void)mg_write(conn, buf, (size_t)len);
  9391. /* Store the < */
  9392. len = 1;
  9393. buf[0] = '<';
  9394. } else {
  9395. /* No Tag */
  9396. /* Add data to buffer */
  9397. buf[len++] = (char)(ch & 0xff);
  9398. /* Flush if buffer is full */
  9399. if (len == (int)sizeof(buf)) {
  9400. mg_write(conn, buf, (size_t)len);
  9401. len = 0;
  9402. }
  9403. }
  9404. }
  9405. }
  9406. /* Send the rest of buffered data */
  9407. if (len > 0) {
  9408. mg_write(conn, buf, (size_t)len);
  9409. }
  9410. }
  9411. static void
  9412. handle_ssi_file_request(struct mg_connection *conn,
  9413. const char *path,
  9414. struct mg_file *filep)
  9415. {
  9416. char date[64];
  9417. time_t curtime = time(NULL);
  9418. const char *cors1, *cors2, *cors3;
  9419. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9420. return;
  9421. }
  9422. if (mg_get_header(conn, "Origin")) {
  9423. /* Cross-origin resource sharing (CORS). */
  9424. cors1 = "Access-Control-Allow-Origin: ";
  9425. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9426. cors3 = "\r\n";
  9427. } else {
  9428. cors1 = cors2 = cors3 = "";
  9429. }
  9430. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9431. /* File exists (precondition for calling this function),
  9432. * but can not be opened by the server. */
  9433. mg_send_http_error(conn,
  9434. 500,
  9435. "Error: Cannot read file\nfopen(%s): %s",
  9436. path,
  9437. strerror(ERRNO));
  9438. } else {
  9439. conn->must_close = 1;
  9440. gmt_time_string(date, sizeof(date), &curtime);
  9441. fclose_on_exec(&filep->access, conn);
  9442. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9443. send_no_cache_header(conn);
  9444. send_additional_header(conn);
  9445. mg_printf(conn,
  9446. "%s%s%s"
  9447. "Date: %s\r\n"
  9448. "Content-Type: text/html\r\n"
  9449. "Connection: %s\r\n\r\n",
  9450. cors1,
  9451. cors2,
  9452. cors3,
  9453. date,
  9454. suggest_connection_header(conn));
  9455. send_ssi_file(conn, path, filep, 0);
  9456. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9457. }
  9458. }
  9459. #if !defined(NO_FILES)
  9460. static void
  9461. send_options(struct mg_connection *conn)
  9462. {
  9463. char date[64];
  9464. time_t curtime = time(NULL);
  9465. if (!conn) {
  9466. return;
  9467. }
  9468. conn->status_code = 200;
  9469. conn->must_close = 1;
  9470. gmt_time_string(date, sizeof(date), &curtime);
  9471. /* We do not set a "Cache-Control" header here, but leave the default.
  9472. * Since browsers do not send an OPTIONS request, we can not test the
  9473. * effect anyway. */
  9474. mg_printf(conn,
  9475. "HTTP/1.1 200 OK\r\n"
  9476. "Date: %s\r\n"
  9477. "Connection: %s\r\n"
  9478. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9479. "PROPFIND, MKCOL\r\n"
  9480. "DAV: 1\r\n",
  9481. date,
  9482. suggest_connection_header(conn));
  9483. send_additional_header(conn);
  9484. mg_printf(conn, "\r\n");
  9485. }
  9486. /* Writes PROPFIND properties for a collection element */
  9487. static void
  9488. print_props(struct mg_connection *conn,
  9489. const char *uri,
  9490. struct mg_file_stat *filep)
  9491. {
  9492. char mtime[64];
  9493. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9494. return;
  9495. }
  9496. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9497. mg_printf(conn,
  9498. "<d:response>"
  9499. "<d:href>%s</d:href>"
  9500. "<d:propstat>"
  9501. "<d:prop>"
  9502. "<d:resourcetype>%s</d:resourcetype>"
  9503. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9504. "<d:getlastmodified>%s</d:getlastmodified>"
  9505. "</d:prop>"
  9506. "<d:status>HTTP/1.1 200 OK</d:status>"
  9507. "</d:propstat>"
  9508. "</d:response>\n",
  9509. uri,
  9510. filep->is_directory ? "<d:collection/>" : "",
  9511. filep->size,
  9512. mtime);
  9513. }
  9514. static int
  9515. print_dav_dir_entry(struct de *de, void *data)
  9516. {
  9517. char href[PATH_MAX];
  9518. int truncated;
  9519. struct mg_connection *conn = (struct mg_connection *)data;
  9520. if (!de || !conn) {
  9521. return -1;
  9522. }
  9523. mg_snprintf(conn,
  9524. &truncated,
  9525. href,
  9526. sizeof(href),
  9527. "%s%s",
  9528. conn->request_info.local_uri,
  9529. de->file_name);
  9530. if (!truncated) {
  9531. size_t href_encoded_size;
  9532. char *href_encoded;
  9533. href_encoded_size = PATH_MAX * 3; /* worst case */
  9534. href_encoded = (char *)mg_malloc(href_encoded_size);
  9535. if (href_encoded == NULL) {
  9536. return -1;
  9537. }
  9538. mg_url_encode(href, href_encoded, href_encoded_size);
  9539. print_props(conn, href_encoded, &de->file);
  9540. mg_free(href_encoded);
  9541. }
  9542. return 0;
  9543. }
  9544. static void
  9545. handle_propfind(struct mg_connection *conn,
  9546. const char *path,
  9547. struct mg_file_stat *filep)
  9548. {
  9549. const char *depth = mg_get_header(conn, "Depth");
  9550. char date[64];
  9551. time_t curtime = time(NULL);
  9552. gmt_time_string(date, sizeof(date), &curtime);
  9553. if (!conn || !path || !filep || !conn->ctx) {
  9554. return;
  9555. }
  9556. conn->must_close = 1;
  9557. conn->status_code = 207;
  9558. mg_printf(conn,
  9559. "HTTP/1.1 207 Multi-Status\r\n"
  9560. "Date: %s\r\n",
  9561. date);
  9562. send_static_cache_header(conn);
  9563. send_additional_header(conn);
  9564. mg_printf(conn,
  9565. "Connection: %s\r\n"
  9566. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9567. suggest_connection_header(conn));
  9568. mg_printf(conn,
  9569. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9570. "<d:multistatus xmlns:d='DAV:'>\n");
  9571. /* Print properties for the requested resource itself */
  9572. print_props(conn, conn->request_info.local_uri, filep);
  9573. /* If it is a directory, print directory entries too if Depth is not 0
  9574. */
  9575. if (filep && filep->is_directory
  9576. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  9577. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9578. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9579. }
  9580. mg_printf(conn, "%s\n", "</d:multistatus>");
  9581. }
  9582. #endif
  9583. void
  9584. mg_lock_connection(struct mg_connection *conn)
  9585. {
  9586. if (conn) {
  9587. (void)pthread_mutex_lock(&conn->mutex);
  9588. }
  9589. }
  9590. void
  9591. mg_unlock_connection(struct mg_connection *conn)
  9592. {
  9593. if (conn) {
  9594. (void)pthread_mutex_unlock(&conn->mutex);
  9595. }
  9596. }
  9597. void
  9598. mg_lock_context(struct mg_context *ctx)
  9599. {
  9600. if (ctx) {
  9601. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9602. }
  9603. }
  9604. void
  9605. mg_unlock_context(struct mg_context *ctx)
  9606. {
  9607. if (ctx) {
  9608. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9609. }
  9610. }
  9611. #if defined(USE_TIMERS)
  9612. #define TIMER_API static
  9613. #include "timer.inl"
  9614. #endif /* USE_TIMERS */
  9615. #ifdef USE_LUA
  9616. #include "mod_lua.inl"
  9617. #endif /* USE_LUA */
  9618. #ifdef USE_DUKTAPE
  9619. #include "mod_duktape.inl"
  9620. #endif /* USE_DUKTAPE */
  9621. #if defined(USE_WEBSOCKET)
  9622. #if !defined(NO_SSL_DL)
  9623. #define SHA_API static
  9624. #include "sha1.inl"
  9625. #endif
  9626. static int
  9627. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9628. {
  9629. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9630. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9631. SHA_CTX sha_ctx;
  9632. int truncated;
  9633. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9634. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9635. if (truncated) {
  9636. conn->must_close = 1;
  9637. return 0;
  9638. }
  9639. SHA1_Init(&sha_ctx);
  9640. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9641. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9642. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9643. mg_printf(conn,
  9644. "HTTP/1.1 101 Switching Protocols\r\n"
  9645. "Upgrade: websocket\r\n"
  9646. "Connection: Upgrade\r\n"
  9647. "Sec-WebSocket-Accept: %s\r\n",
  9648. b64_sha);
  9649. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9650. mg_printf(conn,
  9651. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9652. conn->request_info.acceptedWebSocketSubprotocol);
  9653. } else {
  9654. mg_printf(conn, "%s", "\r\n");
  9655. }
  9656. return 1;
  9657. }
  9658. static void
  9659. read_websocket(struct mg_connection *conn,
  9660. mg_websocket_data_handler ws_data_handler,
  9661. void *callback_data)
  9662. {
  9663. /* Pointer to the beginning of the portion of the incoming websocket
  9664. * message queue.
  9665. * The original websocket upgrade request is never removed, so the queue
  9666. * begins after it. */
  9667. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9668. int n, error, exit_by_callback;
  9669. /* body_len is the length of the entire queue in bytes
  9670. * len is the length of the current message
  9671. * data_len is the length of the current message's data payload
  9672. * header_len is the length of the current message's header */
  9673. size_t i, len, mask_len = 0, header_len, body_len;
  9674. uint64_t data_len = 0;
  9675. /* "The masking key is a 32-bit value chosen at random by the client."
  9676. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9677. */
  9678. unsigned char mask[4];
  9679. /* data points to the place where the message is stored when passed to
  9680. * the
  9681. * websocket_data callback. This is either mem on the stack, or a
  9682. * dynamically allocated buffer if it is too large. */
  9683. unsigned char mem[4096];
  9684. unsigned char mop; /* mask flag and opcode */
  9685. double timeout = -1.0;
  9686. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  9687. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9688. }
  9689. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  9690. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9691. }
  9692. conn->in_websocket_handling = 1;
  9693. mg_set_thread_name("wsock");
  9694. /* Loop continuously, reading messages from the socket, invoking the
  9695. * callback, and waiting repeatedly until an error occurs. */
  9696. while (!conn->ctx->stop_flag && !conn->must_close) {
  9697. header_len = 0;
  9698. assert(conn->data_len >= conn->request_len);
  9699. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9700. len = buf[1] & 127;
  9701. mask_len = (buf[1] & 128) ? 4 : 0;
  9702. if ((len < 126) && (body_len >= mask_len)) {
  9703. /* inline 7-bit length field */
  9704. data_len = len;
  9705. header_len = 2 + mask_len;
  9706. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9707. /* 16-bit length field */
  9708. header_len = 4 + mask_len;
  9709. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9710. } else if (body_len >= (10 + mask_len)) {
  9711. /* 64-bit length field */
  9712. uint32_t l1, l2;
  9713. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9714. memcpy(&l2, &buf[6], 4);
  9715. header_len = 10 + mask_len;
  9716. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9717. if (data_len > (uint64_t)0x7FFF0000ul) {
  9718. /* no can do */
  9719. mg_cry(conn, "websocket out of memory; closing connection");
  9720. break;
  9721. }
  9722. }
  9723. }
  9724. if ((header_len > 0) && (body_len >= header_len)) {
  9725. /* Allocate space to hold websocket payload */
  9726. unsigned char *data = mem;
  9727. if ((size_t)data_len > (size_t)sizeof(mem)) {
  9728. data =
  9729. (unsigned char *)mg_malloc_ctx((size_t)data_len, conn->ctx);
  9730. if (data == NULL) {
  9731. /* Allocation failed, exit the loop and then close the
  9732. * connection */
  9733. mg_cry(conn, "websocket out of memory; closing connection");
  9734. break;
  9735. }
  9736. }
  9737. /* Copy the mask before we shift the queue and destroy it */
  9738. if (mask_len > 0) {
  9739. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9740. } else {
  9741. memset(mask, 0, sizeof(mask));
  9742. }
  9743. /* Read frame payload from the first message in the queue into
  9744. * data and advance the queue by moving the memory in place. */
  9745. assert(body_len >= header_len);
  9746. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  9747. mop = buf[0]; /* current mask and opcode */
  9748. /* Overflow case */
  9749. len = body_len - header_len;
  9750. memcpy(data, buf + header_len, len);
  9751. error = 0;
  9752. while ((uint64_t)len < data_len) {
  9753. n = pull_inner(NULL,
  9754. conn,
  9755. (char *)(data + len),
  9756. (int)(data_len - len),
  9757. timeout);
  9758. if (n <= -2) {
  9759. error = 1;
  9760. break;
  9761. } else if (n > 0) {
  9762. len += (size_t)n;
  9763. } else {
  9764. /* Timeout: should retry */
  9765. /* TODO: retry condition */
  9766. }
  9767. }
  9768. if (error) {
  9769. mg_cry(conn, "Websocket pull failed; closing connection");
  9770. if (data != mem) {
  9771. mg_free(data);
  9772. }
  9773. break;
  9774. }
  9775. conn->data_len = conn->request_len;
  9776. } else {
  9777. mop = buf[0]; /* current mask and opcode, overwritten by
  9778. * memmove() */
  9779. /* Length of the message being read at the front of the
  9780. * queue. Cast to 31 bit is OK, since we limited
  9781. * data_len before. */
  9782. len = (size_t)data_len + header_len;
  9783. /* Copy the data payload into the data pointer for the
  9784. * callback. Cast to 31 bit is OK, since we
  9785. * limited data_len */
  9786. memcpy(data, buf + header_len, (size_t)data_len);
  9787. /* Move the queue forward len bytes */
  9788. memmove(buf, buf + len, body_len - len);
  9789. /* Mark the queue as advanced */
  9790. conn->data_len -= (int)len;
  9791. }
  9792. /* Apply mask if necessary */
  9793. if (mask_len > 0) {
  9794. for (i = 0; i < (size_t)data_len; i++) {
  9795. data[i] ^= mask[i & 3];
  9796. }
  9797. }
  9798. /* Exit the loop if callback signals to exit (server side),
  9799. * or "connection close" opcode received (client side). */
  9800. exit_by_callback = 0;
  9801. if ((ws_data_handler != NULL)
  9802. && !ws_data_handler(conn,
  9803. mop,
  9804. (char *)data,
  9805. (size_t)data_len,
  9806. callback_data)) {
  9807. exit_by_callback = 1;
  9808. }
  9809. if (data != mem) {
  9810. mg_free(data);
  9811. }
  9812. if (exit_by_callback
  9813. || ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9814. /* Opcode == 8, connection close */
  9815. break;
  9816. }
  9817. /* Not breaking the loop, process next websocket frame. */
  9818. } else {
  9819. /* Read from the socket into the next available location in the
  9820. * message queue. */
  9821. n = pull_inner(NULL,
  9822. conn,
  9823. conn->buf + conn->data_len,
  9824. conn->buf_size - conn->data_len,
  9825. timeout);
  9826. if (n <= -2) {
  9827. /* Error, no bytes read */
  9828. break;
  9829. }
  9830. if (n > 0) {
  9831. conn->data_len += n;
  9832. } else {
  9833. /* Timeout: should retry */
  9834. /* TODO: get timeout def */
  9835. }
  9836. }
  9837. }
  9838. mg_set_thread_name("worker");
  9839. conn->in_websocket_handling = 0;
  9840. }
  9841. static int
  9842. mg_websocket_write_exec(struct mg_connection *conn,
  9843. int opcode,
  9844. const char *data,
  9845. size_t dataLen,
  9846. uint32_t masking_key)
  9847. {
  9848. unsigned char header[14];
  9849. size_t headerLen = 1;
  9850. int retval = -1;
  9851. #if defined(__GNUC__) || defined(__MINGW32__)
  9852. /* Disable spurious conversion warning for GCC */
  9853. #pragma GCC diagnostic push
  9854. #pragma GCC diagnostic ignored "-Wconversion"
  9855. #endif
  9856. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  9857. #if defined(__GNUC__) || defined(__MINGW32__)
  9858. #pragma GCC diagnostic pop
  9859. #endif
  9860. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  9861. if (dataLen < 126) {
  9862. /* inline 7-bit length field */
  9863. header[1] = (unsigned char)dataLen;
  9864. headerLen = 2;
  9865. } else if (dataLen <= 0xFFFF) {
  9866. /* 16-bit length field */
  9867. uint16_t len = htons((uint16_t)dataLen);
  9868. header[1] = 126;
  9869. memcpy(header + 2, &len, 2);
  9870. headerLen = 4;
  9871. } else {
  9872. /* 64-bit length field */
  9873. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  9874. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  9875. header[1] = 127;
  9876. memcpy(header + 2, &len1, 4);
  9877. memcpy(header + 6, &len2, 4);
  9878. headerLen = 10;
  9879. }
  9880. if (masking_key) {
  9881. /* add mask */
  9882. header[1] |= 0x80;
  9883. memcpy(header + headerLen, &masking_key, 4);
  9884. headerLen += 4;
  9885. }
  9886. /* Note that POSIX/Winsock's send() is threadsafe
  9887. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  9888. * but mongoose's mg_printf/mg_write is not (because of the loop in
  9889. * push(), although that is only a problem if the packet is large or
  9890. * outgoing buffer is full). */
  9891. /* TODO: Check if this lock should be moved to user land.
  9892. * Currently the server sets this lock for websockets, but
  9893. * not for any other connection. It must be set for every
  9894. * conn read/written by more than one thread, no matter if
  9895. * it is a websocket or regular connection. */
  9896. (void)mg_lock_connection(conn);
  9897. retval = mg_write(conn, header, headerLen);
  9898. if (dataLen > 0) {
  9899. retval = mg_write(conn, data, dataLen);
  9900. }
  9901. /* TODO: Remove this unlock as well, when lock is moved. */
  9902. mg_unlock_connection(conn);
  9903. return retval;
  9904. }
  9905. int
  9906. mg_websocket_write(struct mg_connection *conn,
  9907. int opcode,
  9908. const char *data,
  9909. size_t dataLen)
  9910. {
  9911. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  9912. }
  9913. static void
  9914. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  9915. {
  9916. size_t i = 0;
  9917. i = 0;
  9918. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  9919. /* Convert in 32 bit words, if data is 4 byte aligned */
  9920. while (i < (in_len - 3)) {
  9921. *(uint32_t *)(void *)(out + i) =
  9922. *(uint32_t *)(void *)(in + i) ^ masking_key;
  9923. i += 4;
  9924. }
  9925. }
  9926. if (i != in_len) {
  9927. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  9928. while (i < in_len) {
  9929. *(uint8_t *)(void *)(out + i) =
  9930. *(uint8_t *)(void *)(in + i)
  9931. ^ *(((uint8_t *)&masking_key) + (i % 4));
  9932. i++;
  9933. }
  9934. }
  9935. }
  9936. int
  9937. mg_websocket_client_write(struct mg_connection *conn,
  9938. int opcode,
  9939. const char *data,
  9940. size_t dataLen)
  9941. {
  9942. int retval = -1;
  9943. char *masked_data =
  9944. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  9945. uint32_t masking_key = (uint32_t)get_random();
  9946. if (masked_data == NULL) {
  9947. /* Return -1 in an error case */
  9948. mg_cry(conn,
  9949. "Cannot allocate buffer for masked websocket response: "
  9950. "Out of memory");
  9951. return -1;
  9952. }
  9953. mask_data(data, dataLen, masking_key, masked_data);
  9954. retval = mg_websocket_write_exec(
  9955. conn, opcode, masked_data, dataLen, masking_key);
  9956. mg_free(masked_data);
  9957. return retval;
  9958. }
  9959. static void
  9960. handle_websocket_request(struct mg_connection *conn,
  9961. const char *path,
  9962. int is_callback_resource,
  9963. struct mg_websocket_subprotocols *subprotocols,
  9964. mg_websocket_connect_handler ws_connect_handler,
  9965. mg_websocket_ready_handler ws_ready_handler,
  9966. mg_websocket_data_handler ws_data_handler,
  9967. mg_websocket_close_handler ws_close_handler,
  9968. void *cbData)
  9969. {
  9970. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  9971. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  9972. int lua_websock = 0;
  9973. #if !defined(USE_LUA)
  9974. (void)path;
  9975. #endif
  9976. /* Step 1: Check websocket protocol version. */
  9977. /* Step 1.1: Check Sec-WebSocket-Key. */
  9978. if (!websock_key) {
  9979. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  9980. * requires a Sec-WebSocket-Key header.
  9981. */
  9982. /* It could be the hixie draft version
  9983. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  9984. */
  9985. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  9986. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  9987. char key3[8];
  9988. if ((key1 != NULL) && (key2 != NULL)) {
  9989. /* This version uses 8 byte body data in a GET request */
  9990. conn->content_len = 8;
  9991. if (8 == mg_read(conn, key3, 8)) {
  9992. /* This is the hixie version */
  9993. mg_send_http_error(conn,
  9994. 426,
  9995. "%s",
  9996. "Protocol upgrade to RFC 6455 required");
  9997. return;
  9998. }
  9999. }
  10000. /* This is an unknown version */
  10001. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10002. return;
  10003. }
  10004. /* Step 1.2: Check websocket protocol version. */
  10005. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10006. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10007. /* Reject wrong versions */
  10008. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10009. return;
  10010. }
  10011. /* Step 1.3: Could check for "Host", but we do not really nead this
  10012. * value for anything, so just ignore it. */
  10013. /* Step 2: If a callback is responsible, call it. */
  10014. if (is_callback_resource) {
  10015. /* Step 2.1 check and select subprotocol */
  10016. const char *protocols[64]; // max 64 headers
  10017. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10018. "Sec-WebSocket-Protocol",
  10019. protocols,
  10020. 64);
  10021. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10022. int cnt = 0;
  10023. int idx;
  10024. unsigned long len;
  10025. const char *sep, *curSubProtocol,
  10026. *acceptedWebSocketSubprotocol = NULL;
  10027. /* look for matching subprotocol */
  10028. do {
  10029. const char *protocol = protocols[cnt];
  10030. do {
  10031. sep = strchr(protocol, ',');
  10032. curSubProtocol = protocol;
  10033. len = sep ? (unsigned long)(sep - protocol)
  10034. : (unsigned long)strlen(protocol);
  10035. while (sep && isspace(*++sep))
  10036. ; // ignore leading whitespaces
  10037. protocol = sep;
  10038. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10039. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10040. && (strncmp(curSubProtocol,
  10041. subprotocols->subprotocols[idx],
  10042. len) == 0)) {
  10043. acceptedWebSocketSubprotocol =
  10044. subprotocols->subprotocols[idx];
  10045. break;
  10046. }
  10047. }
  10048. } while (sep && !acceptedWebSocketSubprotocol);
  10049. } while (++cnt < nbSubprotocolHeader
  10050. && !acceptedWebSocketSubprotocol);
  10051. conn->request_info.acceptedWebSocketSubprotocol =
  10052. acceptedWebSocketSubprotocol;
  10053. } else if (nbSubprotocolHeader > 0) {
  10054. /* keep legacy behavior */
  10055. const char *protocol = protocols[0];
  10056. /* The protocol is a comma separated list of names. */
  10057. /* The server must only return one value from this list. */
  10058. /* First check if it is a list or just a single value. */
  10059. const char *sep = strrchr(protocol, ',');
  10060. if (sep == NULL) {
  10061. /* Just a single protocol -> accept it. */
  10062. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10063. } else {
  10064. /* Multiple protocols -> accept the last one. */
  10065. /* This is just a quick fix if the client offers multiple
  10066. * protocols. The handler should have a list of accepted
  10067. * protocols on his own
  10068. * and use it to select one protocol among those the client
  10069. * has
  10070. * offered.
  10071. */
  10072. while (isspace(*++sep)) {
  10073. ; /* ignore leading whitespaces */
  10074. }
  10075. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10076. }
  10077. }
  10078. if ((ws_connect_handler != NULL)
  10079. && (ws_connect_handler(conn, cbData) != 0)) {
  10080. /* C callback has returned non-zero, do not proceed with
  10081. * handshake.
  10082. */
  10083. /* Note that C callbacks are no longer called when Lua is
  10084. * responsible, so C can no longer filter callbacks for Lua. */
  10085. return;
  10086. }
  10087. }
  10088. #if defined(USE_LUA)
  10089. /* Step 3: No callback. Check if Lua is responsible. */
  10090. else {
  10091. /* Step 3.1: Check if Lua is responsible. */
  10092. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10093. lua_websock =
  10094. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10095. strlen(
  10096. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10097. path);
  10098. }
  10099. if (lua_websock) {
  10100. /* Step 3.2: Lua is responsible: call it. */
  10101. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10102. if (!conn->lua_websocket_state) {
  10103. /* Lua rejected the new client */
  10104. return;
  10105. }
  10106. }
  10107. }
  10108. #endif
  10109. /* Step 4: Check if there is a responsible websocket handler. */
  10110. if (!is_callback_resource && !lua_websock) {
  10111. /* There is no callback, and Lua is not responsible either. */
  10112. /* Reply with a 404 Not Found. We are still at a standard
  10113. * HTTP request here, before the websocket handshake, so
  10114. * we can still send standard HTTP error replies. */
  10115. mg_send_http_error(conn, 404, "%s", "Not found");
  10116. return;
  10117. }
  10118. /* Step 5: The websocket connection has been accepted */
  10119. if (!send_websocket_handshake(conn, websock_key)) {
  10120. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10121. return;
  10122. }
  10123. /* Step 6: Call the ready handler */
  10124. if (is_callback_resource) {
  10125. if (ws_ready_handler != NULL) {
  10126. ws_ready_handler(conn, cbData);
  10127. }
  10128. #if defined(USE_LUA)
  10129. } else if (lua_websock) {
  10130. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10131. /* the ready handler returned false */
  10132. return;
  10133. }
  10134. #endif
  10135. }
  10136. /* Step 7: Enter the read loop */
  10137. if (is_callback_resource) {
  10138. read_websocket(conn, ws_data_handler, cbData);
  10139. #if defined(USE_LUA)
  10140. } else if (lua_websock) {
  10141. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10142. #endif
  10143. }
  10144. /* Step 8: Call the close handler */
  10145. if (ws_close_handler) {
  10146. ws_close_handler(conn, cbData);
  10147. }
  10148. }
  10149. static int
  10150. is_websocket_protocol(const struct mg_connection *conn)
  10151. {
  10152. const char *upgrade, *connection;
  10153. /* A websocket protocoll has the following HTTP headers:
  10154. *
  10155. * Connection: Upgrade
  10156. * Upgrade: Websocket
  10157. */
  10158. upgrade = mg_get_header(conn, "Upgrade");
  10159. if (upgrade == NULL) {
  10160. return 0; /* fail early, don't waste time checking other header
  10161. * fields
  10162. */
  10163. }
  10164. if (!mg_strcasestr(upgrade, "websocket")) {
  10165. return 0;
  10166. }
  10167. connection = mg_get_header(conn, "Connection");
  10168. if (connection == NULL) {
  10169. return 0;
  10170. }
  10171. if (!mg_strcasestr(connection, "upgrade")) {
  10172. return 0;
  10173. }
  10174. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10175. * "Sec-WebSocket-Version" are also required.
  10176. * Don't check them here, since even an unsupported websocket protocol
  10177. * request still IS a websocket request (in contrast to a standard HTTP
  10178. * request). It will fail later in handle_websocket_request.
  10179. */
  10180. return 1;
  10181. }
  10182. #endif /* !USE_WEBSOCKET */
  10183. static int
  10184. isbyte(int n)
  10185. {
  10186. return (n >= 0) && (n <= 255);
  10187. }
  10188. static int
  10189. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10190. {
  10191. int n, a, b, c, d, slash = 32, len = 0;
  10192. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10193. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10194. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10195. && (slash < 33)) {
  10196. len = n;
  10197. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10198. | (uint32_t)d;
  10199. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10200. }
  10201. return len;
  10202. }
  10203. static int
  10204. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10205. {
  10206. int throttle = 0;
  10207. struct vec vec, val;
  10208. uint32_t net, mask;
  10209. char mult;
  10210. double v;
  10211. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10212. mult = ',';
  10213. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10214. || (v < 0) || ((lowercase(&mult) != 'k')
  10215. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10216. continue;
  10217. }
  10218. v *= (lowercase(&mult) == 'k')
  10219. ? 1024
  10220. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10221. if (vec.len == 1 && vec.ptr[0] == '*') {
  10222. throttle = (int)v;
  10223. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10224. if ((remote_ip & mask) == net) {
  10225. throttle = (int)v;
  10226. }
  10227. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10228. throttle = (int)v;
  10229. }
  10230. }
  10231. return throttle;
  10232. }
  10233. static uint32_t
  10234. get_remote_ip(const struct mg_connection *conn)
  10235. {
  10236. if (!conn) {
  10237. return 0;
  10238. }
  10239. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10240. }
  10241. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10242. #include "handle_form.inl"
  10243. #if defined(MG_LEGACY_INTERFACE)
  10244. /* Implement the deprecated mg_upload function by calling the new
  10245. * mg_handle_form_request function. While mg_upload could only handle
  10246. * HTML forms sent as POST request in multipart/form-data format
  10247. * containing only file input elements, mg_handle_form_request can
  10248. * handle all form input elements and all standard request methods. */
  10249. struct mg_upload_user_data {
  10250. struct mg_connection *conn;
  10251. const char *destination_dir;
  10252. int num_uploaded_files;
  10253. };
  10254. /* Helper function for deprecated mg_upload. */
  10255. static int
  10256. mg_upload_field_found(const char *key,
  10257. const char *filename,
  10258. char *path,
  10259. size_t pathlen,
  10260. void *user_data)
  10261. {
  10262. int truncated = 0;
  10263. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10264. (void)key;
  10265. if (!filename) {
  10266. mg_cry(fud->conn, "%s: No filename set", __func__);
  10267. return FORM_FIELD_STORAGE_ABORT;
  10268. }
  10269. mg_snprintf(fud->conn,
  10270. &truncated,
  10271. path,
  10272. pathlen - 1,
  10273. "%s/%s",
  10274. fud->destination_dir,
  10275. filename);
  10276. if (!truncated) {
  10277. mg_cry(fud->conn, "%s: File path too long", __func__);
  10278. return FORM_FIELD_STORAGE_ABORT;
  10279. }
  10280. return FORM_FIELD_STORAGE_STORE;
  10281. }
  10282. /* Helper function for deprecated mg_upload. */
  10283. static int
  10284. mg_upload_field_get(const char *key,
  10285. const char *value,
  10286. size_t value_size,
  10287. void *user_data)
  10288. {
  10289. /* Function should never be called */
  10290. (void)key;
  10291. (void)value;
  10292. (void)value_size;
  10293. (void)user_data;
  10294. return 0;
  10295. }
  10296. /* Helper function for deprecated mg_upload. */
  10297. static int
  10298. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10299. {
  10300. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10301. (void)file_size;
  10302. fud->num_uploaded_files++;
  10303. fud->conn->ctx->callbacks.upload(fud->conn, path);
  10304. return 0;
  10305. }
  10306. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10307. int
  10308. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10309. {
  10310. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10311. struct mg_form_data_handler fdh = {mg_upload_field_found,
  10312. mg_upload_field_get,
  10313. mg_upload_field_stored,
  10314. 0};
  10315. int ret;
  10316. fdh.user_data = (void *)&fud;
  10317. ret = mg_handle_form_request(conn, &fdh);
  10318. if (ret < 0) {
  10319. mg_cry(conn, "%s: Error while parsing the request", __func__);
  10320. }
  10321. return fud.num_uploaded_files;
  10322. }
  10323. #endif
  10324. static int
  10325. get_first_ssl_listener_index(const struct mg_context *ctx)
  10326. {
  10327. unsigned int i;
  10328. int idx = -1;
  10329. if (ctx) {
  10330. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  10331. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  10332. }
  10333. }
  10334. return idx;
  10335. }
  10336. static void
  10337. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  10338. {
  10339. char host[1025];
  10340. const char *host_header;
  10341. size_t hostlen;
  10342. host_header = mg_get_header(conn, "Host");
  10343. hostlen = sizeof(host);
  10344. if (host_header != NULL) {
  10345. char *pos;
  10346. mg_strlcpy(host, host_header, hostlen);
  10347. host[hostlen - 1] = '\0';
  10348. pos = strchr(host, ':');
  10349. if (pos != NULL) {
  10350. *pos = '\0';
  10351. }
  10352. } else {
  10353. /* Cannot get host from the Host: header.
  10354. * Fallback to our IP address. */
  10355. if (conn) {
  10356. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  10357. }
  10358. }
  10359. /* Send host, port, uri and (if it exists) ?query_string */
  10360. if (conn) {
  10361. mg_printf(conn,
  10362. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  10363. host,
  10364. #if defined(USE_IPV6)
  10365. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  10366. == AF_INET6)
  10367. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  10368. .lsa.sin6.sin6_port)
  10369. :
  10370. #endif
  10371. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  10372. .lsa.sin.sin_port),
  10373. conn->request_info.local_uri,
  10374. (conn->request_info.query_string == NULL) ? "" : "?",
  10375. (conn->request_info.query_string == NULL)
  10376. ? ""
  10377. : conn->request_info.query_string);
  10378. }
  10379. }
  10380. static void
  10381. mg_set_handler_type(struct mg_context *ctx,
  10382. const char *uri,
  10383. int handler_type,
  10384. int is_delete_request,
  10385. mg_request_handler handler,
  10386. struct mg_websocket_subprotocols *subprotocols,
  10387. mg_websocket_connect_handler connect_handler,
  10388. mg_websocket_ready_handler ready_handler,
  10389. mg_websocket_data_handler data_handler,
  10390. mg_websocket_close_handler close_handler,
  10391. mg_authorization_handler auth_handler,
  10392. void *cbdata)
  10393. {
  10394. struct mg_handler_info *tmp_rh, **lastref;
  10395. size_t urilen = strlen(uri);
  10396. if (handler_type == WEBSOCKET_HANDLER) {
  10397. /* assert(handler == NULL); */
  10398. /* assert(is_delete_request || connect_handler!=NULL ||
  10399. * ready_handler!=NULL || data_handler!=NULL ||
  10400. * close_handler!=NULL);
  10401. */
  10402. /* assert(auth_handler == NULL); */
  10403. if (handler != NULL) {
  10404. return;
  10405. }
  10406. if (!is_delete_request && (connect_handler == NULL)
  10407. && (ready_handler == NULL) && (data_handler == NULL)
  10408. && (close_handler == NULL)) {
  10409. return;
  10410. }
  10411. if (auth_handler != NULL) {
  10412. return;
  10413. }
  10414. } else if (handler_type == REQUEST_HANDLER) {
  10415. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10416. * data_handler==NULL && close_handler==NULL); */
  10417. /* assert(is_delete_request || (handler!=NULL));
  10418. */
  10419. /* assert(auth_handler == NULL); */
  10420. if ((connect_handler != NULL) || (ready_handler != NULL)
  10421. || (data_handler != NULL) || (close_handler != NULL)) {
  10422. return;
  10423. }
  10424. if (!is_delete_request && (handler == NULL)) {
  10425. return;
  10426. }
  10427. if (auth_handler != NULL) {
  10428. return;
  10429. }
  10430. } else { /* AUTH_HANDLER */
  10431. /* assert(handler == NULL); */
  10432. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10433. * data_handler==NULL && close_handler==NULL); */
  10434. /* assert(auth_handler != NULL); */
  10435. if (handler != NULL) {
  10436. return;
  10437. }
  10438. if ((connect_handler != NULL) || (ready_handler != NULL)
  10439. || (data_handler != NULL) || (close_handler != NULL)) {
  10440. return;
  10441. }
  10442. if (!is_delete_request && (auth_handler == NULL)) {
  10443. return;
  10444. }
  10445. }
  10446. if (!ctx) {
  10447. return;
  10448. }
  10449. mg_lock_context(ctx);
  10450. /* first try to find an existing handler */
  10451. lastref = &(ctx->handlers);
  10452. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10453. if (tmp_rh->handler_type == handler_type) {
  10454. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10455. if (!is_delete_request) {
  10456. /* update existing handler */
  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. } else {
  10470. /* remove existing handler */
  10471. *lastref = tmp_rh->next;
  10472. mg_free(tmp_rh->uri);
  10473. mg_free(tmp_rh);
  10474. }
  10475. mg_unlock_context(ctx);
  10476. return;
  10477. }
  10478. }
  10479. lastref = &(tmp_rh->next);
  10480. }
  10481. if (is_delete_request) {
  10482. /* no handler to set, this was a remove request to a non-existing
  10483. * handler */
  10484. mg_unlock_context(ctx);
  10485. return;
  10486. }
  10487. tmp_rh =
  10488. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  10489. 1,
  10490. ctx);
  10491. if (tmp_rh == NULL) {
  10492. mg_unlock_context(ctx);
  10493. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  10494. return;
  10495. }
  10496. tmp_rh->uri = mg_strdup(uri);
  10497. if (!tmp_rh->uri) {
  10498. mg_unlock_context(ctx);
  10499. mg_free(tmp_rh);
  10500. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  10501. return;
  10502. }
  10503. tmp_rh->uri_len = urilen;
  10504. if (handler_type == REQUEST_HANDLER) {
  10505. tmp_rh->handler = handler;
  10506. } else if (handler_type == WEBSOCKET_HANDLER) {
  10507. tmp_rh->subprotocols = subprotocols;
  10508. tmp_rh->connect_handler = connect_handler;
  10509. tmp_rh->ready_handler = ready_handler;
  10510. tmp_rh->data_handler = data_handler;
  10511. tmp_rh->close_handler = close_handler;
  10512. } else { /* AUTH_HANDLER */
  10513. tmp_rh->auth_handler = auth_handler;
  10514. }
  10515. tmp_rh->cbdata = cbdata;
  10516. tmp_rh->handler_type = handler_type;
  10517. tmp_rh->next = NULL;
  10518. *lastref = tmp_rh;
  10519. mg_unlock_context(ctx);
  10520. }
  10521. void
  10522. mg_set_request_handler(struct mg_context *ctx,
  10523. const char *uri,
  10524. mg_request_handler handler,
  10525. void *cbdata)
  10526. {
  10527. mg_set_handler_type(ctx,
  10528. uri,
  10529. REQUEST_HANDLER,
  10530. handler == NULL,
  10531. handler,
  10532. NULL,
  10533. NULL,
  10534. NULL,
  10535. NULL,
  10536. NULL,
  10537. NULL,
  10538. cbdata);
  10539. }
  10540. void
  10541. mg_set_websocket_handler(struct mg_context *ctx,
  10542. const char *uri,
  10543. mg_websocket_connect_handler connect_handler,
  10544. mg_websocket_ready_handler ready_handler,
  10545. mg_websocket_data_handler data_handler,
  10546. mg_websocket_close_handler close_handler,
  10547. void *cbdata)
  10548. {
  10549. mg_set_websocket_handler_with_subprotocols(ctx,
  10550. uri,
  10551. NULL,
  10552. connect_handler,
  10553. ready_handler,
  10554. data_handler,
  10555. close_handler,
  10556. cbdata);
  10557. }
  10558. void
  10559. mg_set_websocket_handler_with_subprotocols(
  10560. struct mg_context *ctx,
  10561. const char *uri,
  10562. struct mg_websocket_subprotocols *subprotocols,
  10563. mg_websocket_connect_handler connect_handler,
  10564. mg_websocket_ready_handler ready_handler,
  10565. mg_websocket_data_handler data_handler,
  10566. mg_websocket_close_handler close_handler,
  10567. void *cbdata)
  10568. {
  10569. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  10570. && (data_handler == NULL)
  10571. && (close_handler == NULL);
  10572. mg_set_handler_type(ctx,
  10573. uri,
  10574. WEBSOCKET_HANDLER,
  10575. is_delete_request,
  10576. NULL,
  10577. subprotocols,
  10578. connect_handler,
  10579. ready_handler,
  10580. data_handler,
  10581. close_handler,
  10582. NULL,
  10583. cbdata);
  10584. }
  10585. void
  10586. mg_set_auth_handler(struct mg_context *ctx,
  10587. const char *uri,
  10588. mg_request_handler handler,
  10589. void *cbdata)
  10590. {
  10591. mg_set_handler_type(ctx,
  10592. uri,
  10593. AUTH_HANDLER,
  10594. handler == NULL,
  10595. NULL,
  10596. NULL,
  10597. NULL,
  10598. NULL,
  10599. NULL,
  10600. NULL,
  10601. handler,
  10602. cbdata);
  10603. }
  10604. static int
  10605. get_request_handler(struct mg_connection *conn,
  10606. int handler_type,
  10607. mg_request_handler *handler,
  10608. struct mg_websocket_subprotocols **subprotocols,
  10609. mg_websocket_connect_handler *connect_handler,
  10610. mg_websocket_ready_handler *ready_handler,
  10611. mg_websocket_data_handler *data_handler,
  10612. mg_websocket_close_handler *close_handler,
  10613. mg_authorization_handler *auth_handler,
  10614. void **cbdata)
  10615. {
  10616. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10617. if (request_info) {
  10618. const char *uri = request_info->local_uri;
  10619. size_t urilen = strlen(uri);
  10620. struct mg_handler_info *tmp_rh;
  10621. if (!conn || !conn->ctx) {
  10622. return 0;
  10623. }
  10624. mg_lock_context(conn->ctx);
  10625. /* first try for an exact match */
  10626. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10627. tmp_rh = tmp_rh->next) {
  10628. if (tmp_rh->handler_type == handler_type) {
  10629. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10630. if (handler_type == WEBSOCKET_HANDLER) {
  10631. *subprotocols = tmp_rh->subprotocols;
  10632. *connect_handler = tmp_rh->connect_handler;
  10633. *ready_handler = tmp_rh->ready_handler;
  10634. *data_handler = tmp_rh->data_handler;
  10635. *close_handler = tmp_rh->close_handler;
  10636. } else if (handler_type == REQUEST_HANDLER) {
  10637. *handler = tmp_rh->handler;
  10638. } else { /* AUTH_HANDLER */
  10639. *auth_handler = tmp_rh->auth_handler;
  10640. }
  10641. *cbdata = tmp_rh->cbdata;
  10642. mg_unlock_context(conn->ctx);
  10643. return 1;
  10644. }
  10645. }
  10646. }
  10647. /* next try for a partial match, we will accept uri/something */
  10648. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10649. tmp_rh = tmp_rh->next) {
  10650. if (tmp_rh->handler_type == handler_type) {
  10651. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10652. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  10653. if (handler_type == WEBSOCKET_HANDLER) {
  10654. *subprotocols = tmp_rh->subprotocols;
  10655. *connect_handler = tmp_rh->connect_handler;
  10656. *ready_handler = tmp_rh->ready_handler;
  10657. *data_handler = tmp_rh->data_handler;
  10658. *close_handler = tmp_rh->close_handler;
  10659. } else if (handler_type == REQUEST_HANDLER) {
  10660. *handler = tmp_rh->handler;
  10661. } else { /* AUTH_HANDLER */
  10662. *auth_handler = tmp_rh->auth_handler;
  10663. }
  10664. *cbdata = tmp_rh->cbdata;
  10665. mg_unlock_context(conn->ctx);
  10666. return 1;
  10667. }
  10668. }
  10669. }
  10670. /* finally try for pattern match */
  10671. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10672. tmp_rh = tmp_rh->next) {
  10673. if (tmp_rh->handler_type == handler_type) {
  10674. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10675. if (handler_type == WEBSOCKET_HANDLER) {
  10676. *subprotocols = tmp_rh->subprotocols;
  10677. *connect_handler = tmp_rh->connect_handler;
  10678. *ready_handler = tmp_rh->ready_handler;
  10679. *data_handler = tmp_rh->data_handler;
  10680. *close_handler = tmp_rh->close_handler;
  10681. } else if (handler_type == REQUEST_HANDLER) {
  10682. *handler = tmp_rh->handler;
  10683. } else { /* AUTH_HANDLER */
  10684. *auth_handler = tmp_rh->auth_handler;
  10685. }
  10686. *cbdata = tmp_rh->cbdata;
  10687. mg_unlock_context(conn->ctx);
  10688. return 1;
  10689. }
  10690. }
  10691. }
  10692. mg_unlock_context(conn->ctx);
  10693. }
  10694. return 0; /* none found */
  10695. }
  10696. /* Check if the script file is in a path, allowed for script files.
  10697. * This can be used if uploading files is possible not only for the server
  10698. * admin, and the upload mechanism does not check the file extension.
  10699. */
  10700. static int
  10701. is_in_script_path(const struct mg_connection *conn, const char *path)
  10702. {
  10703. /* TODO (Feature): Add config value for allowed script path.
  10704. * Default: All allowed. */
  10705. (void)conn;
  10706. (void)path;
  10707. return 1;
  10708. }
  10709. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10710. static int
  10711. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10712. void *cbdata)
  10713. {
  10714. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10715. if (pcallbacks->websocket_connect) {
  10716. return pcallbacks->websocket_connect(conn);
  10717. }
  10718. /* No handler set - assume "OK" */
  10719. return 0;
  10720. }
  10721. static void
  10722. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10723. {
  10724. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10725. if (pcallbacks->websocket_ready) {
  10726. pcallbacks->websocket_ready(conn);
  10727. }
  10728. }
  10729. static int
  10730. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10731. int bits,
  10732. char *data,
  10733. size_t len,
  10734. void *cbdata)
  10735. {
  10736. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10737. if (pcallbacks->websocket_data) {
  10738. return pcallbacks->websocket_data(conn, bits, data, len);
  10739. }
  10740. /* No handler set - assume "OK" */
  10741. return 1;
  10742. }
  10743. #endif
  10744. /* This is the heart of the Civetweb's logic.
  10745. * This function is called when the request is read, parsed and validated,
  10746. * and Civetweb must decide what action to take: serve a file, or
  10747. * a directory, or call embedded function, etcetera. */
  10748. static void
  10749. handle_request(struct mg_connection *conn)
  10750. {
  10751. struct mg_request_info *ri = &conn->request_info;
  10752. char path[PATH_MAX];
  10753. int uri_len, ssl_index;
  10754. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  10755. is_put_or_delete_request = 0, is_callback_resource = 0;
  10756. int i;
  10757. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10758. mg_request_handler callback_handler = NULL;
  10759. struct mg_websocket_subprotocols *subprotocols;
  10760. mg_websocket_connect_handler ws_connect_handler = NULL;
  10761. mg_websocket_ready_handler ws_ready_handler = NULL;
  10762. mg_websocket_data_handler ws_data_handler = NULL;
  10763. mg_websocket_close_handler ws_close_handler = NULL;
  10764. void *callback_data = NULL;
  10765. mg_authorization_handler auth_handler = NULL;
  10766. void *auth_callback_data = NULL;
  10767. int handler_type;
  10768. time_t curtime = time(NULL);
  10769. char date[64];
  10770. path[0] = 0;
  10771. /* 1. get the request url */
  10772. /* 1.1. split into url and query string */
  10773. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  10774. != NULL) {
  10775. *((char *)conn->request_info.query_string++) = '\0';
  10776. }
  10777. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  10778. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  10779. ssl_index = get_first_ssl_listener_index(conn->ctx);
  10780. if (ssl_index >= 0) {
  10781. redirect_to_https_port(conn, ssl_index);
  10782. } else {
  10783. /* A http to https forward port has been specified,
  10784. * but no https port to forward to. */
  10785. mg_send_http_error(conn,
  10786. 503,
  10787. "%s",
  10788. "Error: SSL forward not configured properly");
  10789. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  10790. }
  10791. return;
  10792. }
  10793. uri_len = (int)strlen(ri->local_uri);
  10794. /* 1.3. decode url (if config says so) */
  10795. if (should_decode_url(conn)) {
  10796. mg_url_decode(
  10797. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  10798. }
  10799. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  10800. * not possible */
  10801. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  10802. /* step 1. completed, the url is known now */
  10803. uri_len = (int)strlen(ri->local_uri);
  10804. DEBUG_TRACE("URL: %s", ri->local_uri);
  10805. /* 2. if this ip has limited speed, set it for this connection */
  10806. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  10807. get_remote_ip(conn),
  10808. ri->local_uri);
  10809. /* 3. call a "handle everything" callback, if registered */
  10810. if (conn->ctx->callbacks.begin_request != NULL) {
  10811. /* Note that since V1.7 the "begin_request" function is called
  10812. * before an authorization check. If an authorization check is
  10813. * required, use a request_handler instead. */
  10814. i = conn->ctx->callbacks.begin_request(conn);
  10815. if (i > 0) {
  10816. /* callback already processed the request. Store the
  10817. return value as a status code for the access log. */
  10818. conn->status_code = i;
  10819. discard_unread_request_data(conn);
  10820. return;
  10821. } else if (i == 0) {
  10822. /* civetweb should process the request */
  10823. } else {
  10824. /* unspecified - may change with the next version */
  10825. return;
  10826. }
  10827. }
  10828. /* request not yet handled by a handler or redirect, so the request
  10829. * is processed here */
  10830. /* 4. Check for CORS preflight requests and handle them (if configured).
  10831. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  10832. */
  10833. if (!strcmp(ri->request_method, "OPTIONS")) {
  10834. /* Send a response to CORS preflights only if
  10835. * access_control_allow_methods is not NULL and not an empty string.
  10836. * In this case, scripts can still handle CORS. */
  10837. const char *cors_meth_cfg =
  10838. conn->ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  10839. const char *cors_orig_cfg =
  10840. conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10841. const char *cors_origin =
  10842. get_header(ri->http_headers, ri->num_headers, "Origin");
  10843. const char *cors_acrm = get_header(ri->http_headers,
  10844. ri->num_headers,
  10845. "Access-Control-Request-Method");
  10846. /* Todo: check if cors_origin is in cors_orig_cfg.
  10847. * Or, let the client check this. */
  10848. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  10849. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  10850. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  10851. /* This is a valid CORS preflight, and the server is configured
  10852. * to
  10853. * handle it automatically. */
  10854. const char *cors_acrh =
  10855. get_header(ri->http_headers,
  10856. ri->num_headers,
  10857. "Access-Control-Request-Headers");
  10858. gmt_time_string(date, sizeof(date), &curtime);
  10859. mg_printf(conn,
  10860. "HTTP/1.1 200 OK\r\n"
  10861. "Date: %s\r\n"
  10862. "Access-Control-Allow-Origin: %s\r\n"
  10863. "Access-Control-Allow-Methods: %s\r\n"
  10864. "Content-Length: 0\r\n"
  10865. "Connection: %s\r\n",
  10866. date,
  10867. cors_orig_cfg,
  10868. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  10869. suggest_connection_header(conn));
  10870. if (cors_acrh != NULL) {
  10871. /* CORS request is asking for additional headers */
  10872. const char *cors_hdr_cfg =
  10873. conn->ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  10874. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  10875. /* Allow only if access_control_allow_headers is
  10876. * not NULL and not an empty string. If this
  10877. * configuration is set to *, allow everything.
  10878. * Otherwise this configuration must be a list
  10879. * of allowed HTTP header names. */
  10880. mg_printf(conn,
  10881. "Access-Control-Allow-Headers: %s\r\n",
  10882. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  10883. : cors_hdr_cfg));
  10884. }
  10885. }
  10886. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  10887. mg_printf(conn, "\r\n");
  10888. return;
  10889. }
  10890. }
  10891. /* 5. interpret the url to find out how the request must be handled
  10892. */
  10893. /* 5.1. first test, if the request targets the regular http(s)://
  10894. * protocol namespace or the websocket ws(s):// protocol namespace.
  10895. */
  10896. is_websocket_request = is_websocket_protocol(conn);
  10897. #if defined(USE_WEBSOCKET)
  10898. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  10899. #else
  10900. handler_type = REQUEST_HANDLER;
  10901. #endif /* defined(USE_WEBSOCKET) */
  10902. /* 5.2. check if the request will be handled by a callback */
  10903. if (get_request_handler(conn,
  10904. handler_type,
  10905. &callback_handler,
  10906. &subprotocols,
  10907. &ws_connect_handler,
  10908. &ws_ready_handler,
  10909. &ws_data_handler,
  10910. &ws_close_handler,
  10911. NULL,
  10912. &callback_data)) {
  10913. /* 5.2.1. A callback will handle this request. All requests
  10914. * handled
  10915. * by a callback have to be considered as requests to a script
  10916. * resource. */
  10917. is_callback_resource = 1;
  10918. is_script_resource = 1;
  10919. is_put_or_delete_request = is_put_or_delete_method(conn);
  10920. } else {
  10921. no_callback_resource:
  10922. /* 5.2.2. No callback is responsible for this request. The URI
  10923. * addresses a file based resource (static content or Lua/cgi
  10924. * scripts in the file system). */
  10925. is_callback_resource = 0;
  10926. interpret_uri(conn,
  10927. path,
  10928. sizeof(path),
  10929. &file.stat,
  10930. &is_found,
  10931. &is_script_resource,
  10932. &is_websocket_request,
  10933. &is_put_or_delete_request);
  10934. }
  10935. /* 6. authorization check */
  10936. /* 6.1. a custom authorization handler is installed */
  10937. if (get_request_handler(conn,
  10938. AUTH_HANDLER,
  10939. NULL,
  10940. NULL,
  10941. NULL,
  10942. NULL,
  10943. NULL,
  10944. NULL,
  10945. &auth_handler,
  10946. &auth_callback_data)) {
  10947. if (!auth_handler(conn, auth_callback_data)) {
  10948. return;
  10949. }
  10950. } else if (is_put_or_delete_request && !is_script_resource
  10951. && !is_callback_resource) {
  10952. /* 6.2. this request is a PUT/DELETE to a real file */
  10953. /* 6.2.1. thus, the server must have real files */
  10954. #if defined(NO_FILES)
  10955. if (1) {
  10956. #else
  10957. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10958. #endif
  10959. /* This server does not have any real files, thus the
  10960. * PUT/DELETE methods are not valid. */
  10961. mg_send_http_error(conn,
  10962. 405,
  10963. "%s method not allowed",
  10964. conn->request_info.request_method);
  10965. return;
  10966. }
  10967. #if !defined(NO_FILES)
  10968. /* 6.2.2. Check if put authorization for static files is
  10969. * available.
  10970. */
  10971. if (!is_authorized_for_put(conn)) {
  10972. send_authorization_request(conn, NULL);
  10973. return;
  10974. }
  10975. #endif
  10976. } else {
  10977. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  10978. * or it is a PUT or DELETE request to a resource that does not
  10979. * correspond to a file. Check authorization. */
  10980. if (!check_authorization(conn, path)) {
  10981. send_authorization_request(conn, NULL);
  10982. return;
  10983. }
  10984. }
  10985. /* request is authorized or does not need authorization */
  10986. /* 7. check if there are request handlers for this uri */
  10987. if (is_callback_resource) {
  10988. if (!is_websocket_request) {
  10989. i = callback_handler(conn, callback_data);
  10990. if (i > 0) {
  10991. /* Do nothing, callback has served the request. Store
  10992. * then return value as status code for the log and discard
  10993. * all data from the client not used by the callback. */
  10994. conn->status_code = i;
  10995. discard_unread_request_data(conn);
  10996. } else {
  10997. /* The handler did NOT handle the request. */
  10998. /* Some proper reactions would be:
  10999. * a) close the connections without sending anything
  11000. * b) send a 404 not found
  11001. * c) try if there is a file matching the URI
  11002. * It would be possible to do a, b or c in the callback
  11003. * implementation, and return 1 - we cannot do anything
  11004. * here, that is not possible in the callback.
  11005. *
  11006. * TODO: What would be the best reaction here?
  11007. * (Note: The reaction may change, if there is a better
  11008. *idea.)
  11009. */
  11010. /* For the moment, use option c: We look for a proper file,
  11011. * but since a file request is not always a script resource,
  11012. * the authorization check might be different. */
  11013. interpret_uri(conn,
  11014. path,
  11015. sizeof(path),
  11016. &file.stat,
  11017. &is_found,
  11018. &is_script_resource,
  11019. &is_websocket_request,
  11020. &is_put_or_delete_request);
  11021. callback_handler = NULL;
  11022. /* Here we are at a dead end:
  11023. * According to URI matching, a callback should be
  11024. * responsible for handling the request,
  11025. * we called it, but the callback declared itself
  11026. * not responsible.
  11027. * We use a goto here, to get out of this dead end,
  11028. * and continue with the default handling.
  11029. * A goto here is simpler and better to understand
  11030. * than some curious loop. */
  11031. goto no_callback_resource;
  11032. }
  11033. } else {
  11034. #if defined(USE_WEBSOCKET)
  11035. handle_websocket_request(conn,
  11036. path,
  11037. is_callback_resource,
  11038. subprotocols,
  11039. ws_connect_handler,
  11040. ws_ready_handler,
  11041. ws_data_handler,
  11042. ws_close_handler,
  11043. callback_data);
  11044. #endif
  11045. }
  11046. return;
  11047. }
  11048. /* 8. handle websocket requests */
  11049. #if defined(USE_WEBSOCKET)
  11050. if (is_websocket_request) {
  11051. if (is_script_resource) {
  11052. if (is_in_script_path(conn, path)) {
  11053. /* Websocket Lua script */
  11054. handle_websocket_request(conn,
  11055. path,
  11056. 0 /* Lua Script */,
  11057. NULL,
  11058. NULL,
  11059. NULL,
  11060. NULL,
  11061. NULL,
  11062. &conn->ctx->callbacks);
  11063. } else {
  11064. /* Script was in an illegal path */
  11065. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11066. }
  11067. } else {
  11068. #if defined(MG_LEGACY_INTERFACE)
  11069. handle_websocket_request(
  11070. conn,
  11071. path,
  11072. !is_script_resource /* could be deprecated global callback */,
  11073. NULL,
  11074. deprecated_websocket_connect_wrapper,
  11075. deprecated_websocket_ready_wrapper,
  11076. deprecated_websocket_data_wrapper,
  11077. NULL,
  11078. &conn->ctx->callbacks);
  11079. #else
  11080. mg_send_http_error(conn, 404, "%s", "Not found");
  11081. #endif
  11082. }
  11083. return;
  11084. } else
  11085. #endif
  11086. #if defined(NO_FILES)
  11087. /* 9a. In case the server uses only callbacks, this uri is
  11088. * unknown.
  11089. * Then, all request handling ends here. */
  11090. mg_send_http_error(conn, 404, "%s", "Not Found");
  11091. #else
  11092. /* 9b. This request is either for a static file or resource handled
  11093. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11094. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  11095. mg_send_http_error(conn, 404, "%s", "Not Found");
  11096. return;
  11097. }
  11098. /* 10. Request is handled by a script */
  11099. if (is_script_resource) {
  11100. handle_file_based_request(conn, path, &file);
  11101. return;
  11102. }
  11103. /* 11. Handle put/delete/mkcol requests */
  11104. if (is_put_or_delete_request) {
  11105. /* 11.1. PUT method */
  11106. if (!strcmp(ri->request_method, "PUT")) {
  11107. put_file(conn, path);
  11108. return;
  11109. }
  11110. /* 11.2. DELETE method */
  11111. if (!strcmp(ri->request_method, "DELETE")) {
  11112. delete_file(conn, path);
  11113. return;
  11114. }
  11115. /* 11.3. MKCOL method */
  11116. if (!strcmp(ri->request_method, "MKCOL")) {
  11117. mkcol(conn, path);
  11118. return;
  11119. }
  11120. /* 11.4. PATCH method
  11121. * This method is not supported for static resources,
  11122. * only for scripts (Lua, CGI) and callbacks. */
  11123. mg_send_http_error(conn,
  11124. 405,
  11125. "%s method not allowed",
  11126. conn->request_info.request_method);
  11127. return;
  11128. }
  11129. /* 11. File does not exist, or it was configured that it should be
  11130. * hidden */
  11131. if (!is_found || (must_hide_file(conn, path))) {
  11132. mg_send_http_error(conn, 404, "%s", "Not found");
  11133. return;
  11134. }
  11135. /* 12. Directory uris should end with a slash */
  11136. if (file.stat.is_directory && (uri_len > 0)
  11137. && (ri->local_uri[uri_len - 1] != '/')) {
  11138. gmt_time_string(date, sizeof(date), &curtime);
  11139. mg_printf(conn,
  11140. "HTTP/1.1 301 Moved Permanently\r\n"
  11141. "Location: %s/\r\n"
  11142. "Date: %s\r\n"
  11143. /* "Cache-Control: private\r\n" (= default) */
  11144. "Content-Length: 0\r\n"
  11145. "Connection: %s\r\n",
  11146. ri->request_uri,
  11147. date,
  11148. suggest_connection_header(conn));
  11149. send_additional_header(conn);
  11150. mg_printf(conn, "\r\n");
  11151. return;
  11152. }
  11153. /* 13. Handle other methods than GET/HEAD */
  11154. /* 13.1. Handle PROPFIND */
  11155. if (!strcmp(ri->request_method, "PROPFIND")) {
  11156. handle_propfind(conn, path, &file.stat);
  11157. return;
  11158. }
  11159. /* 13.2. Handle OPTIONS for files */
  11160. if (!strcmp(ri->request_method, "OPTIONS")) {
  11161. /* This standard handler is only used for real files.
  11162. * Scripts should support the OPTIONS method themselves, to allow a
  11163. * maximum flexibility.
  11164. * Lua and CGI scripts may fully support CORS this way (including
  11165. * preflights). */
  11166. send_options(conn);
  11167. return;
  11168. }
  11169. /* 13.3. everything but GET and HEAD (e.g. POST) */
  11170. if ((0 != strcmp(ri->request_method, "GET"))
  11171. && (0 != strcmp(ri->request_method, "HEAD"))) {
  11172. mg_send_http_error(conn,
  11173. 405,
  11174. "%s method not allowed",
  11175. conn->request_info.request_method);
  11176. return;
  11177. }
  11178. /* 14. directories */
  11179. if (file.stat.is_directory) {
  11180. /* Substitute files have already been handled above. */
  11181. /* Here we can either generate and send a directory listing,
  11182. * or send an "access denied" error. */
  11183. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  11184. "yes")) {
  11185. handle_directory_request(conn, path);
  11186. } else {
  11187. mg_send_http_error(conn,
  11188. 403,
  11189. "%s",
  11190. "Error: Directory listing denied");
  11191. }
  11192. return;
  11193. }
  11194. handle_file_based_request(conn, path, &file);
  11195. #endif /* !defined(NO_FILES) */
  11196. #if 0
  11197. /* Perform redirect and auth checks before calling begin_request()
  11198. * handler.
  11199. * Otherwise, begin_request() would need to perform auth checks and
  11200. * redirects. */
  11201. #endif
  11202. }
  11203. static void
  11204. handle_file_based_request(struct mg_connection *conn,
  11205. const char *path,
  11206. struct mg_file *file)
  11207. {
  11208. if (!conn || !conn->ctx) {
  11209. return;
  11210. }
  11211. if (0) {
  11212. #ifdef USE_LUA
  11213. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  11214. strlen(
  11215. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  11216. path) > 0) {
  11217. if (is_in_script_path(conn, path)) {
  11218. /* Lua server page: an SSI like page containing mostly plain
  11219. * html
  11220. * code
  11221. * plus some tags with server generated contents. */
  11222. handle_lsp_request(conn, path, file, NULL);
  11223. } else {
  11224. /* Script was in an illegal path */
  11225. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11226. }
  11227. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  11228. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  11229. path) > 0) {
  11230. if (is_in_script_path(conn, path)) {
  11231. /* Lua in-server module script: a CGI like script used to
  11232. * generate
  11233. * the
  11234. * entire reply. */
  11235. mg_exec_lua_script(conn, path, NULL);
  11236. } else {
  11237. /* Script was in an illegal path */
  11238. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11239. }
  11240. #endif
  11241. #if defined(USE_DUKTAPE)
  11242. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  11243. strlen(
  11244. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  11245. path) > 0) {
  11246. if (is_in_script_path(conn, path)) {
  11247. /* Call duktape to generate the page */
  11248. mg_exec_duktape_script(conn, path);
  11249. } else {
  11250. /* Script was in an illegal path */
  11251. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11252. }
  11253. #endif
  11254. #if !defined(NO_CGI)
  11255. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  11256. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  11257. path) > 0) {
  11258. if (is_in_script_path(conn, path)) {
  11259. /* CGI scripts may support all HTTP methods */
  11260. handle_cgi_request(conn, path);
  11261. } else {
  11262. /* Script was in an illegal path */
  11263. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11264. }
  11265. #endif /* !NO_CGI */
  11266. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  11267. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  11268. path) > 0) {
  11269. if (is_in_script_path(conn, path)) {
  11270. handle_ssi_file_request(conn, path, file);
  11271. } else {
  11272. /* Script was in an illegal path */
  11273. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11274. }
  11275. #if !defined(NO_CACHING)
  11276. } else if ((!conn->in_error_handler)
  11277. && is_not_modified(conn, &file->stat)) {
  11278. /* Send 304 "Not Modified" - this must not send any body data */
  11279. handle_not_modified_static_file_request(conn, file);
  11280. #endif /* !NO_CACHING */
  11281. } else {
  11282. handle_static_file_request(conn, path, file, NULL, NULL);
  11283. }
  11284. }
  11285. static void
  11286. close_all_listening_sockets(struct mg_context *ctx)
  11287. {
  11288. unsigned int i;
  11289. if (!ctx) {
  11290. return;
  11291. }
  11292. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11293. closesocket(ctx->listening_sockets[i].sock);
  11294. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  11295. }
  11296. mg_free(ctx->listening_sockets);
  11297. ctx->listening_sockets = NULL;
  11298. mg_free(ctx->listening_socket_fds);
  11299. ctx->listening_socket_fds = NULL;
  11300. }
  11301. /* Valid listening port specification is: [ip_address:]port[s]
  11302. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  11303. * Examples for IPv6: [::]:80, [::1]:80,
  11304. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  11305. * see https://tools.ietf.org/html/rfc3513#section-2.2
  11306. * In order to bind to both, IPv4 and IPv6, you can either add
  11307. * both ports using 8080,[::]:8080, or the short form +8080.
  11308. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  11309. * one only accepting IPv4 the other only IPv6. +8080 creates
  11310. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  11311. * environment, they might work differently, or might not work
  11312. * at all - it must be tested what options work best in the
  11313. * relevant network environment.
  11314. */
  11315. static int
  11316. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  11317. {
  11318. unsigned int a, b, c, d, port;
  11319. int ch, len;
  11320. const char *cb;
  11321. #if defined(USE_IPV6)
  11322. char buf[100] = {0};
  11323. #endif
  11324. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  11325. * Also, all-zeroes in the socket address means binding to all addresses
  11326. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  11327. memset(so, 0, sizeof(*so));
  11328. so->lsa.sin.sin_family = AF_INET;
  11329. *ip_version = 0;
  11330. /* Initialize port and len as invalid. */
  11331. port = 0;
  11332. len = 0;
  11333. /* Test for different ways to format this string */
  11334. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  11335. == 5) {
  11336. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  11337. so->lsa.sin.sin_addr.s_addr =
  11338. htonl((a << 24) | (b << 16) | (c << 8) | d);
  11339. so->lsa.sin.sin_port = htons((uint16_t)port);
  11340. *ip_version = 4;
  11341. #if defined(USE_IPV6)
  11342. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  11343. && mg_inet_pton(
  11344. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  11345. /* IPv6 address, examples: see above */
  11346. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  11347. */
  11348. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11349. *ip_version = 6;
  11350. #endif
  11351. } else if ((vec->ptr[0] == '+')
  11352. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  11353. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  11354. /* Add 1 to len for the + character we skipped before */
  11355. len++;
  11356. #if defined(USE_IPV6)
  11357. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  11358. so->lsa.sin6.sin6_family = AF_INET6;
  11359. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11360. *ip_version = 4 + 6;
  11361. #else
  11362. /* Bind to IPv4 only, since IPv6 is not built in. */
  11363. so->lsa.sin.sin_port = htons((uint16_t)port);
  11364. *ip_version = 4;
  11365. #endif
  11366. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  11367. /* If only port is specified, bind to IPv4, INADDR_ANY */
  11368. so->lsa.sin.sin_port = htons((uint16_t)port);
  11369. *ip_version = 4;
  11370. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  11371. /* Could be a hostname */
  11372. /* Will only work for RFC 952 compliant hostnames,
  11373. * starting with a letter, containing only letters,
  11374. * digits and hyphen ('-'). Newer specs may allow
  11375. * more, but this is not guaranteed here, since it
  11376. * may interfere with rules for port option lists. */
  11377. *(char *)cb = 0; /* Use a const cast here and modify the string.
  11378. * We are going to restore the string later. */
  11379. if (mg_inet_pton(
  11380. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  11381. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11382. *ip_version = 4;
  11383. so->lsa.sin.sin_family = AF_INET;
  11384. so->lsa.sin.sin_port = htons((uint16_t)port);
  11385. len += (int)(cb - vec->ptr) + 1;
  11386. } else {
  11387. port = 0;
  11388. len = 0;
  11389. }
  11390. #if defined(USE_IPV6)
  11391. } else if (mg_inet_pton(AF_INET6,
  11392. vec->ptr,
  11393. &so->lsa.sin6,
  11394. sizeof(so->lsa.sin6))) {
  11395. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11396. *ip_version = 6;
  11397. so->lsa.sin6.sin6_family = AF_INET6;
  11398. so->lsa.sin.sin_port = htons((uint16_t)port);
  11399. len += (int)(cb - vec->ptr) + 1;
  11400. } else {
  11401. port = 0;
  11402. len = 0;
  11403. }
  11404. #endif
  11405. }
  11406. *(char *)cb = ':'; /* restore the string */
  11407. } else {
  11408. /* Parsing failure. */
  11409. }
  11410. /* sscanf and the option splitting code ensure the following condition
  11411. */
  11412. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11413. *ip_version = 0;
  11414. return 0;
  11415. }
  11416. ch = vec->ptr[len]; /* Next character after the port number */
  11417. so->is_ssl = (ch == 's');
  11418. so->ssl_redir = (ch == 'r');
  11419. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11420. if (is_valid_port(port)
  11421. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  11422. return 1;
  11423. }
  11424. /* Reset ip_version to 0 of there is an error */
  11425. *ip_version = 0;
  11426. return 0;
  11427. }
  11428. /* Is there any SSL port in use? */
  11429. static int
  11430. is_ssl_port_used(const char *ports)
  11431. {
  11432. if (ports) {
  11433. if (strchr(ports, 's')) {
  11434. return 1;
  11435. }
  11436. if (strchr(ports, 'r')) {
  11437. return 1;
  11438. }
  11439. }
  11440. return 0;
  11441. }
  11442. static int
  11443. set_ports_option(struct mg_context *ctx)
  11444. {
  11445. const char *list;
  11446. int on = 1;
  11447. #if defined(USE_IPV6)
  11448. int off = 0;
  11449. #endif
  11450. struct vec vec;
  11451. struct socket so, *ptr;
  11452. struct pollfd *pfd;
  11453. union usa usa;
  11454. socklen_t len;
  11455. int ip_version;
  11456. int portsTotal = 0;
  11457. int portsOk = 0;
  11458. if (!ctx) {
  11459. return 0;
  11460. }
  11461. memset(&so, 0, sizeof(so));
  11462. memset(&usa, 0, sizeof(usa));
  11463. len = sizeof(usa);
  11464. list = ctx->config[LISTENING_PORTS];
  11465. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11466. portsTotal++;
  11467. if (!parse_port_string(&vec, &so, &ip_version)) {
  11468. mg_cry(fc(ctx),
  11469. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  11470. (int)vec.len,
  11471. vec.ptr,
  11472. portsTotal,
  11473. "[IP_ADDRESS:]PORT[s|r]");
  11474. continue;
  11475. }
  11476. #if !defined(NO_SSL)
  11477. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  11478. mg_cry(fc(ctx), "Cannot add SSL socket (entry %i)", portsTotal);
  11479. continue;
  11480. }
  11481. #endif
  11482. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  11483. == INVALID_SOCKET) {
  11484. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  11485. continue;
  11486. }
  11487. #ifdef _WIN32
  11488. /* Windows SO_REUSEADDR lets many procs binds to a
  11489. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  11490. * if someone already has the socket -- DTL */
  11491. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  11492. * Windows might need a few seconds before
  11493. * the same port can be used again in the
  11494. * same process, so a short Sleep may be
  11495. * required between mg_stop and mg_start.
  11496. */
  11497. if (setsockopt(so.sock,
  11498. SOL_SOCKET,
  11499. SO_EXCLUSIVEADDRUSE,
  11500. (SOCK_OPT_TYPE)&on,
  11501. sizeof(on)) != 0) {
  11502. /* Set reuse option, but don't abort on errors. */
  11503. mg_cry(fc(ctx),
  11504. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  11505. portsTotal);
  11506. }
  11507. #else
  11508. if (setsockopt(so.sock,
  11509. SOL_SOCKET,
  11510. SO_REUSEADDR,
  11511. (SOCK_OPT_TYPE)&on,
  11512. sizeof(on)) != 0) {
  11513. /* Set reuse option, but don't abort on errors. */
  11514. mg_cry(fc(ctx),
  11515. "cannot set socket option SO_REUSEADDR (entry %i)",
  11516. portsTotal);
  11517. }
  11518. #endif
  11519. if (ip_version > 4) {
  11520. #if defined(USE_IPV6)
  11521. if (ip_version == 6) {
  11522. if (so.lsa.sa.sa_family == AF_INET6
  11523. && setsockopt(so.sock,
  11524. IPPROTO_IPV6,
  11525. IPV6_V6ONLY,
  11526. (void *)&off,
  11527. sizeof(off)) != 0) {
  11528. /* Set IPv6 only option, but don't abort on errors. */
  11529. mg_cry(fc(ctx),
  11530. "cannot set socket option IPV6_V6ONLY (entry %i)",
  11531. portsTotal);
  11532. }
  11533. }
  11534. #else
  11535. mg_cry(fc(ctx), "IPv6 not available");
  11536. closesocket(so.sock);
  11537. so.sock = INVALID_SOCKET;
  11538. continue;
  11539. #endif
  11540. }
  11541. if (so.lsa.sa.sa_family == AF_INET) {
  11542. len = sizeof(so.lsa.sin);
  11543. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11544. mg_cry(fc(ctx),
  11545. "cannot bind to %.*s: %d (%s)",
  11546. (int)vec.len,
  11547. vec.ptr,
  11548. (int)ERRNO,
  11549. strerror(errno));
  11550. closesocket(so.sock);
  11551. so.sock = INVALID_SOCKET;
  11552. continue;
  11553. }
  11554. }
  11555. #if defined(USE_IPV6)
  11556. else if (so.lsa.sa.sa_family == AF_INET6) {
  11557. len = sizeof(so.lsa.sin6);
  11558. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11559. mg_cry(fc(ctx),
  11560. "cannot bind to IPv6 %.*s: %d (%s)",
  11561. (int)vec.len,
  11562. vec.ptr,
  11563. (int)ERRNO,
  11564. strerror(errno));
  11565. closesocket(so.sock);
  11566. so.sock = INVALID_SOCKET;
  11567. continue;
  11568. }
  11569. }
  11570. #endif
  11571. else {
  11572. mg_cry(fc(ctx),
  11573. "cannot bind: address family not supported (entry %i)",
  11574. portsTotal);
  11575. closesocket(so.sock);
  11576. so.sock = INVALID_SOCKET;
  11577. continue;
  11578. }
  11579. if (listen(so.sock, SOMAXCONN) != 0) {
  11580. mg_cry(fc(ctx),
  11581. "cannot listen to %.*s: %d (%s)",
  11582. (int)vec.len,
  11583. vec.ptr,
  11584. (int)ERRNO,
  11585. strerror(errno));
  11586. closesocket(so.sock);
  11587. so.sock = INVALID_SOCKET;
  11588. continue;
  11589. }
  11590. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  11591. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  11592. int err = (int)ERRNO;
  11593. mg_cry(fc(ctx),
  11594. "call to getsockname failed %.*s: %d (%s)",
  11595. (int)vec.len,
  11596. vec.ptr,
  11597. err,
  11598. strerror(errno));
  11599. closesocket(so.sock);
  11600. so.sock = INVALID_SOCKET;
  11601. continue;
  11602. }
  11603. /* Update lsa port in case of random free ports */
  11604. #if defined(USE_IPV6)
  11605. if (so.lsa.sa.sa_family == AF_INET6) {
  11606. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  11607. } else
  11608. #endif
  11609. {
  11610. so.lsa.sin.sin_port = usa.sin.sin_port;
  11611. }
  11612. if ((ptr = (struct socket *)
  11613. mg_realloc_ctx(ctx->listening_sockets,
  11614. (ctx->num_listening_sockets + 1)
  11615. * sizeof(ctx->listening_sockets[0]),
  11616. ctx)) == NULL) {
  11617. mg_cry(fc(ctx), "%s", "Out of memory");
  11618. closesocket(so.sock);
  11619. so.sock = INVALID_SOCKET;
  11620. continue;
  11621. }
  11622. if ((pfd = (struct pollfd *)
  11623. mg_realloc_ctx(ctx->listening_socket_fds,
  11624. (ctx->num_listening_sockets + 1)
  11625. * sizeof(ctx->listening_socket_fds[0]),
  11626. ctx)) == NULL) {
  11627. mg_cry(fc(ctx), "%s", "Out of memory");
  11628. closesocket(so.sock);
  11629. so.sock = INVALID_SOCKET;
  11630. mg_free(ptr);
  11631. continue;
  11632. }
  11633. set_close_on_exec(so.sock, fc(ctx));
  11634. ctx->listening_sockets = ptr;
  11635. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  11636. ctx->listening_socket_fds = pfd;
  11637. ctx->num_listening_sockets++;
  11638. portsOk++;
  11639. }
  11640. if (portsOk != portsTotal) {
  11641. close_all_listening_sockets(ctx);
  11642. portsOk = 0;
  11643. }
  11644. return portsOk;
  11645. }
  11646. static const char *
  11647. header_val(const struct mg_connection *conn, const char *header)
  11648. {
  11649. const char *header_value;
  11650. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11651. return "-";
  11652. } else {
  11653. return header_value;
  11654. }
  11655. }
  11656. static void
  11657. log_access(const struct mg_connection *conn)
  11658. {
  11659. const struct mg_request_info *ri;
  11660. struct mg_file fi;
  11661. char date[64], src_addr[IP_ADDR_STR_LEN];
  11662. struct tm *tm;
  11663. const char *referer;
  11664. const char *user_agent;
  11665. char buf[4096];
  11666. if (!conn || !conn->ctx) {
  11667. return;
  11668. }
  11669. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  11670. if (mg_fopen(conn,
  11671. conn->ctx->config[ACCESS_LOG_FILE],
  11672. MG_FOPEN_MODE_APPEND,
  11673. &fi) == 0) {
  11674. fi.access.fp = NULL;
  11675. }
  11676. } else {
  11677. fi.access.fp = NULL;
  11678. }
  11679. /* Log is written to a file and/or a callback. If both are not set,
  11680. * executing the rest of the function is pointless. */
  11681. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  11682. return;
  11683. }
  11684. tm = localtime(&conn->conn_birth_time);
  11685. if (tm != NULL) {
  11686. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11687. } else {
  11688. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11689. date[sizeof(date) - 1] = '\0';
  11690. }
  11691. ri = &conn->request_info;
  11692. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11693. referer = header_val(conn, "Referer");
  11694. user_agent = header_val(conn, "User-Agent");
  11695. mg_snprintf(conn,
  11696. NULL, /* Ignore truncation in access log */
  11697. buf,
  11698. sizeof(buf),
  11699. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11700. src_addr,
  11701. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11702. date,
  11703. ri->request_method ? ri->request_method : "-",
  11704. ri->request_uri ? ri->request_uri : "-",
  11705. ri->query_string ? "?" : "",
  11706. ri->query_string ? ri->query_string : "",
  11707. ri->http_version,
  11708. conn->status_code,
  11709. conn->num_bytes_sent,
  11710. referer,
  11711. user_agent);
  11712. if (conn->ctx->callbacks.log_access) {
  11713. conn->ctx->callbacks.log_access(conn, buf);
  11714. }
  11715. if (fi.access.fp) {
  11716. int ok = 1;
  11717. flockfile(fi.access.fp);
  11718. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11719. ok = 0;
  11720. }
  11721. if (fflush(fi.access.fp) != 0) {
  11722. ok = 0;
  11723. }
  11724. funlockfile(fi.access.fp);
  11725. if (mg_fclose(&fi.access) != 0) {
  11726. ok = 0;
  11727. }
  11728. if (!ok) {
  11729. mg_cry(conn,
  11730. "Error writing log file %s",
  11731. conn->ctx->config[ACCESS_LOG_FILE]);
  11732. }
  11733. }
  11734. }
  11735. /* Verify given socket address against the ACL.
  11736. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  11737. */
  11738. static int
  11739. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  11740. {
  11741. int allowed, flag;
  11742. uint32_t net, mask;
  11743. struct vec vec;
  11744. if (ctx) {
  11745. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  11746. /* If any ACL is set, deny by default */
  11747. allowed = (list == NULL) ? '+' : '-';
  11748. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11749. flag = vec.ptr[0];
  11750. if ((flag != '+' && flag != '-')
  11751. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  11752. mg_cry(fc(ctx),
  11753. "%s: subnet must be [+|-]x.x.x.x[/x]",
  11754. __func__);
  11755. return -1;
  11756. }
  11757. if (net == (remote_ip & mask)) {
  11758. allowed = flag;
  11759. }
  11760. }
  11761. return allowed == '+';
  11762. }
  11763. return -1;
  11764. }
  11765. #if !defined(_WIN32)
  11766. static int
  11767. set_uid_option(struct mg_context *ctx)
  11768. {
  11769. int success = 0;
  11770. if (ctx) {
  11771. /* We are currently running as curr_uid. */
  11772. const uid_t curr_uid = getuid();
  11773. /* If set, we want to run as run_as_user. */
  11774. const char *run_as_user = ctx->config[RUN_AS_USER];
  11775. const struct passwd *to_pw = NULL;
  11776. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  11777. /* run_as_user does not exist on the system. We can't proceed
  11778. * further. */
  11779. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, run_as_user);
  11780. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  11781. /* There was either no request to change user, or we're already
  11782. * running as run_as_user. Nothing else to do.
  11783. */
  11784. success = 1;
  11785. } else {
  11786. /* Valid change request. */
  11787. if (setgid(to_pw->pw_gid) == -1) {
  11788. mg_cry(fc(ctx),
  11789. "%s: setgid(%s): %s",
  11790. __func__,
  11791. run_as_user,
  11792. strerror(errno));
  11793. } else if (setgroups(0, NULL) == -1) {
  11794. mg_cry(fc(ctx),
  11795. "%s: setgroups(): %s",
  11796. __func__,
  11797. strerror(errno));
  11798. } else if (setuid(to_pw->pw_uid) == -1) {
  11799. mg_cry(fc(ctx),
  11800. "%s: setuid(%s): %s",
  11801. __func__,
  11802. run_as_user,
  11803. strerror(errno));
  11804. } else {
  11805. success = 1;
  11806. }
  11807. }
  11808. }
  11809. return success;
  11810. }
  11811. #endif /* !_WIN32 */
  11812. static void
  11813. tls_dtor(void *key)
  11814. {
  11815. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  11816. /* key == pthread_getspecific(sTlsKey); */
  11817. if (tls) {
  11818. if (tls->is_master == 2) {
  11819. tls->is_master = -3; /* Mark memory as dead */
  11820. mg_free(tls);
  11821. }
  11822. }
  11823. pthread_setspecific(sTlsKey, NULL);
  11824. }
  11825. #if !defined(NO_SSL)
  11826. static int
  11827. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  11828. static const char *ssl_error(void);
  11829. static int
  11830. refresh_trust(struct mg_connection *conn)
  11831. {
  11832. static int reload_lock = 0;
  11833. static long int data_check = 0;
  11834. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  11835. struct stat cert_buf;
  11836. long int t;
  11837. const char *pem;
  11838. const char *chain;
  11839. int should_verify_peer;
  11840. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  11841. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  11842. * refresh_trust still can not work. */
  11843. return 0;
  11844. }
  11845. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  11846. if (chain == NULL) {
  11847. /* pem is not NULL here */
  11848. chain = pem;
  11849. }
  11850. if (*chain == 0) {
  11851. chain = NULL;
  11852. }
  11853. t = data_check;
  11854. if (stat(pem, &cert_buf) != -1) {
  11855. t = (long int)cert_buf.st_mtime;
  11856. }
  11857. if (data_check != t) {
  11858. data_check = t;
  11859. should_verify_peer = 0;
  11860. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11861. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  11862. == 0) {
  11863. should_verify_peer = 1;
  11864. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  11865. "optional") == 0) {
  11866. should_verify_peer = 1;
  11867. }
  11868. }
  11869. if (should_verify_peer) {
  11870. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  11871. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  11872. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  11873. ca_file,
  11874. ca_path) != 1) {
  11875. mg_cry(fc(conn->ctx),
  11876. "SSL_CTX_load_verify_locations error: %s "
  11877. "ssl_verify_peer requires setting "
  11878. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11879. "present in "
  11880. "the .conf file?",
  11881. ssl_error());
  11882. return 0;
  11883. }
  11884. }
  11885. if (1 == mg_atomic_inc(p_reload_lock)) {
  11886. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  11887. return 0;
  11888. }
  11889. *p_reload_lock = 0;
  11890. }
  11891. }
  11892. /* lock while cert is reloading */
  11893. while (*p_reload_lock) {
  11894. sleep(1);
  11895. }
  11896. return 1;
  11897. }
  11898. #ifdef OPENSSL_API_1_1
  11899. #else
  11900. static pthread_mutex_t *ssl_mutexes;
  11901. #endif /* OPENSSL_API_1_1 */
  11902. static int
  11903. sslize(struct mg_connection *conn,
  11904. SSL_CTX *s,
  11905. int (*func)(SSL *),
  11906. volatile int *stop_server)
  11907. {
  11908. int ret, err;
  11909. int short_trust;
  11910. unsigned i;
  11911. if (!conn) {
  11912. return 0;
  11913. }
  11914. short_trust =
  11915. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  11916. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  11917. if (short_trust) {
  11918. int trust_ret = refresh_trust(conn);
  11919. if (!trust_ret) {
  11920. return trust_ret;
  11921. }
  11922. }
  11923. conn->ssl = SSL_new(s);
  11924. if (conn->ssl == NULL) {
  11925. return 0;
  11926. }
  11927. SSL_set_app_data(conn->ssl, (char *)conn);
  11928. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  11929. if (ret != 1) {
  11930. err = SSL_get_error(conn->ssl, ret);
  11931. (void)err; /* TODO: set some error message */
  11932. SSL_free(conn->ssl);
  11933. conn->ssl = NULL;
  11934. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11935. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11936. #ifndef OPENSSL_API_1_1
  11937. ERR_remove_state(0);
  11938. #endif
  11939. return 0;
  11940. }
  11941. /* SSL functions may fail and require to be called again:
  11942. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  11943. * Here "func" could be SSL_connect or SSL_accept. */
  11944. for (i = 16; i <= 1024; i *= 2) {
  11945. ret = func(conn->ssl);
  11946. if (ret != 1) {
  11947. err = SSL_get_error(conn->ssl, ret);
  11948. if ((err == SSL_ERROR_WANT_CONNECT)
  11949. || (err == SSL_ERROR_WANT_ACCEPT)
  11950. || (err == SSL_ERROR_WANT_READ)
  11951. || (err == SSL_ERROR_WANT_WRITE)) {
  11952. /* Need to retry the function call "later".
  11953. * See https://linux.die.net/man/3/ssl_get_error
  11954. * This is typical for non-blocking sockets. */
  11955. if (*stop_server) {
  11956. /* Don't wait if the server is going to be stopped. */
  11957. break;
  11958. }
  11959. mg_sleep(i);
  11960. } else if (err == SSL_ERROR_SYSCALL) {
  11961. /* This is an IO error. Look at errno. */
  11962. err = errno;
  11963. /* TODO: set some error message */
  11964. (void)err;
  11965. break;
  11966. } else {
  11967. /* This is an SSL specific error */
  11968. /* TODO: set some error message */
  11969. break;
  11970. }
  11971. } else {
  11972. /* success */
  11973. break;
  11974. }
  11975. }
  11976. if (ret != 1) {
  11977. SSL_free(conn->ssl);
  11978. conn->ssl = NULL;
  11979. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11980. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11981. #ifndef OPENSSL_API_1_1
  11982. ERR_remove_state(0);
  11983. #endif
  11984. return 0;
  11985. }
  11986. return 1;
  11987. }
  11988. /* Return OpenSSL error message (from CRYPTO lib) */
  11989. static const char *
  11990. ssl_error(void)
  11991. {
  11992. unsigned long err;
  11993. err = ERR_get_error();
  11994. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  11995. }
  11996. static int
  11997. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  11998. {
  11999. int i;
  12000. const char hexdigit[] = "0123456789abcdef";
  12001. if ((memlen <= 0) || (buflen <= 0)) {
  12002. return 0;
  12003. }
  12004. if (buflen < (3 * memlen)) {
  12005. return 0;
  12006. }
  12007. for (i = 0; i < memlen; i++) {
  12008. if (i > 0) {
  12009. buf[3 * i - 1] = ' ';
  12010. }
  12011. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  12012. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  12013. }
  12014. buf[3 * memlen - 1] = 0;
  12015. return 1;
  12016. }
  12017. static void
  12018. ssl_get_client_cert_info(struct mg_connection *conn)
  12019. {
  12020. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  12021. if (cert) {
  12022. char str_subject[1024];
  12023. char str_issuer[1024];
  12024. char str_finger[1024];
  12025. unsigned char buf[256];
  12026. char *str_serial = NULL;
  12027. unsigned int ulen;
  12028. int ilen;
  12029. unsigned char *tmp_buf;
  12030. unsigned char *tmp_p;
  12031. /* Handle to algorithm used for fingerprint */
  12032. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  12033. /* Get Subject and issuer */
  12034. X509_NAME *subj = X509_get_subject_name(cert);
  12035. X509_NAME *iss = X509_get_issuer_name(cert);
  12036. /* Get serial number */
  12037. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  12038. /* Translate serial number to a hex string */
  12039. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12040. str_serial = BN_bn2hex(serial_bn);
  12041. BN_free(serial_bn);
  12042. /* Translate subject and issuer to a string */
  12043. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12044. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12045. /* Calculate SHA1 fingerprint and store as a hex string */
  12046. ulen = 0;
  12047. /* ASN1_digest is deprecated. Do the calculation manually,
  12048. * using EVP_Digest. */
  12049. ilen = i2d_X509(cert, NULL);
  12050. tmp_buf =
  12051. (ilen > 0)
  12052. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  12053. : NULL;
  12054. if (tmp_buf) {
  12055. tmp_p = tmp_buf;
  12056. (void)i2d_X509(cert, &tmp_p);
  12057. if (!EVP_Digest(
  12058. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12059. ulen = 0;
  12060. }
  12061. mg_free(tmp_buf);
  12062. }
  12063. if (!hexdump2string(
  12064. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12065. *str_finger = 0;
  12066. }
  12067. conn->request_info.client_cert = (struct mg_client_cert *)
  12068. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->ctx);
  12069. if (conn->request_info.client_cert) {
  12070. conn->request_info.client_cert->peer_cert = (void *)cert;
  12071. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  12072. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  12073. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  12074. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  12075. } else {
  12076. mg_cry(conn,
  12077. "Out of memory: Cannot allocate memory for client "
  12078. "certificate");
  12079. }
  12080. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  12081. * see https://linux.die.net/man/3/bn_bn2hex */
  12082. OPENSSL_free(str_serial);
  12083. }
  12084. }
  12085. #ifdef OPENSSL_API_1_1
  12086. #else
  12087. static void
  12088. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  12089. {
  12090. (void)line;
  12091. (void)file;
  12092. if (mode & 1) {
  12093. /* 1 is CRYPTO_LOCK */
  12094. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  12095. } else {
  12096. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  12097. }
  12098. }
  12099. #endif /* OPENSSL_API_1_1 */
  12100. #if !defined(NO_SSL_DL)
  12101. static void *
  12102. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  12103. {
  12104. union {
  12105. void *p;
  12106. void (*fp)(void);
  12107. } u;
  12108. void *dll_handle;
  12109. struct ssl_func *fp;
  12110. int ok;
  12111. int truncated = 0;
  12112. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  12113. mg_snprintf(NULL,
  12114. NULL, /* No truncation check for ebuf */
  12115. ebuf,
  12116. ebuf_len,
  12117. "%s: cannot load %s",
  12118. __func__,
  12119. dll_name);
  12120. return NULL;
  12121. }
  12122. ok = 1;
  12123. for (fp = sw; fp->name != NULL; fp++) {
  12124. #ifdef _WIN32
  12125. /* GetProcAddress() returns pointer to function */
  12126. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  12127. #else
  12128. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  12129. * pointers to function pointers. We need to use a union to make a
  12130. * cast. */
  12131. u.p = dlsym(dll_handle, fp->name);
  12132. #endif /* _WIN32 */
  12133. if (u.fp == NULL) {
  12134. if (ok) {
  12135. mg_snprintf(NULL,
  12136. &truncated,
  12137. ebuf,
  12138. ebuf_len,
  12139. "%s: %s: cannot find %s",
  12140. __func__,
  12141. dll_name,
  12142. fp->name);
  12143. ok = 0;
  12144. } else {
  12145. size_t cur_len = strlen(ebuf);
  12146. if (!truncated) {
  12147. mg_snprintf(NULL,
  12148. &truncated,
  12149. ebuf + cur_len,
  12150. ebuf_len - cur_len - 3,
  12151. ", %s",
  12152. fp->name);
  12153. if (truncated) {
  12154. /* If truncated, add "..." */
  12155. strcat(ebuf, "...");
  12156. }
  12157. }
  12158. }
  12159. /* Debug:
  12160. * printf("Missing function: %s\n", fp->name); */
  12161. } else {
  12162. fp->ptr = u.fp;
  12163. }
  12164. }
  12165. if (!ok) {
  12166. (void)dlclose(dll_handle);
  12167. return NULL;
  12168. }
  12169. return dll_handle;
  12170. }
  12171. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  12172. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  12173. #endif /* NO_SSL_DL */
  12174. #if defined(SSL_ALREADY_INITIALIZED)
  12175. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  12176. #else
  12177. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  12178. #endif
  12179. static int
  12180. initialize_ssl(char *ebuf, size_t ebuf_len)
  12181. {
  12182. #ifdef OPENSSL_API_1_1
  12183. if (ebuf_len > 0) {
  12184. ebuf[0] = 0;
  12185. }
  12186. #if !defined(NO_SSL_DL)
  12187. if (!cryptolib_dll_handle) {
  12188. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12189. if (!cryptolib_dll_handle) {
  12190. mg_snprintf(NULL,
  12191. NULL, /* No truncation check for ebuf */
  12192. ebuf,
  12193. ebuf_len,
  12194. "%s: error loading library %s",
  12195. __func__,
  12196. CRYPTO_LIB);
  12197. DEBUG_TRACE("%s", ebuf);
  12198. return 0;
  12199. }
  12200. }
  12201. #endif /* NO_SSL_DL */
  12202. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12203. return 1;
  12204. }
  12205. #else /* not OPENSSL_API_1_1 */
  12206. int i;
  12207. size_t size;
  12208. if (ebuf_len > 0) {
  12209. ebuf[0] = 0;
  12210. }
  12211. #if !defined(NO_SSL_DL)
  12212. if (!cryptolib_dll_handle) {
  12213. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12214. if (!cryptolib_dll_handle) {
  12215. mg_snprintf(NULL,
  12216. NULL, /* No truncation check for ebuf */
  12217. ebuf,
  12218. ebuf_len,
  12219. "%s: error loading library %s",
  12220. __func__,
  12221. CRYPTO_LIB);
  12222. DEBUG_TRACE("%s", ebuf);
  12223. return 0;
  12224. }
  12225. }
  12226. #endif /* NO_SSL_DL */
  12227. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12228. return 1;
  12229. }
  12230. /* Initialize locking callbacks, needed for thread safety.
  12231. * http://www.openssl.org/support/faq.html#PROG1
  12232. */
  12233. i = CRYPTO_num_locks();
  12234. if (i < 0) {
  12235. i = 0;
  12236. }
  12237. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  12238. if (size == 0) {
  12239. ssl_mutexes = NULL;
  12240. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  12241. mg_snprintf(NULL,
  12242. NULL, /* No truncation check for ebuf */
  12243. ebuf,
  12244. ebuf_len,
  12245. "%s: cannot allocate mutexes: %s",
  12246. __func__,
  12247. ssl_error());
  12248. DEBUG_TRACE("%s", ebuf);
  12249. return 0;
  12250. }
  12251. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12252. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  12253. }
  12254. CRYPTO_set_locking_callback(&ssl_locking_callback);
  12255. CRYPTO_set_id_callback(&mg_current_thread_id);
  12256. #endif /* OPENSSL_API_1_1 */
  12257. #if !defined(NO_SSL_DL)
  12258. if (!ssllib_dll_handle) {
  12259. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  12260. if (!ssllib_dll_handle) {
  12261. DEBUG_TRACE("%s", ebuf);
  12262. return 0;
  12263. }
  12264. }
  12265. #endif /* NO_SSL_DL */
  12266. #ifdef OPENSSL_API_1_1
  12267. /* Initialize SSL library */
  12268. OPENSSL_init_ssl(0, NULL);
  12269. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  12270. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  12271. NULL);
  12272. #else
  12273. /* Initialize SSL library */
  12274. SSL_library_init();
  12275. SSL_load_error_strings();
  12276. #endif
  12277. return 1;
  12278. }
  12279. static int
  12280. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  12281. {
  12282. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  12283. mg_cry(fc(ctx),
  12284. "%s: cannot open certificate file %s: %s",
  12285. __func__,
  12286. pem,
  12287. ssl_error());
  12288. return 0;
  12289. }
  12290. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  12291. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  12292. mg_cry(fc(ctx),
  12293. "%s: cannot open private key file %s: %s",
  12294. __func__,
  12295. pem,
  12296. ssl_error());
  12297. return 0;
  12298. }
  12299. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  12300. mg_cry(fc(ctx),
  12301. "%s: certificate and private key do not match: %s",
  12302. __func__,
  12303. pem);
  12304. return 0;
  12305. }
  12306. /* In contrast to OpenSSL, wolfSSL does not support certificate
  12307. * chain files that contain private keys and certificates in
  12308. * SSL_CTX_use_certificate_chain_file.
  12309. * The CivetWeb-Server used pem-Files that contained both information.
  12310. * In order to make wolfSSL work, it is split in two files.
  12311. * One file that contains key and certificate used by the server and
  12312. * an optional chain file for the ssl stack.
  12313. */
  12314. if (chain) {
  12315. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  12316. mg_cry(fc(ctx),
  12317. "%s: cannot use certificate chain file %s: %s",
  12318. __func__,
  12319. pem,
  12320. ssl_error());
  12321. return 0;
  12322. }
  12323. }
  12324. return 1;
  12325. }
  12326. #ifdef OPENSSL_API_1_1
  12327. static unsigned long
  12328. ssl_get_protocol(int version_id)
  12329. {
  12330. long unsigned ret = SSL_OP_ALL;
  12331. if (version_id > 0)
  12332. ret |= SSL_OP_NO_SSLv2;
  12333. if (version_id > 1)
  12334. ret |= SSL_OP_NO_SSLv3;
  12335. if (version_id > 2)
  12336. ret |= SSL_OP_NO_TLSv1;
  12337. if (version_id > 3)
  12338. ret |= SSL_OP_NO_TLSv1_1;
  12339. return ret;
  12340. }
  12341. #else
  12342. static long
  12343. ssl_get_protocol(int version_id)
  12344. {
  12345. long ret = SSL_OP_ALL;
  12346. if (version_id > 0)
  12347. ret |= SSL_OP_NO_SSLv2;
  12348. if (version_id > 1)
  12349. ret |= SSL_OP_NO_SSLv3;
  12350. if (version_id > 2)
  12351. ret |= SSL_OP_NO_TLSv1;
  12352. if (version_id > 3)
  12353. ret |= SSL_OP_NO_TLSv1_1;
  12354. return ret;
  12355. }
  12356. #endif /* OPENSSL_API_1_1 */
  12357. /* SSL callback documentation:
  12358. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  12359. * https://linux.die.net/man/3/ssl_set_info_callback */
  12360. static void
  12361. ssl_info_callback(SSL *ssl, int what, int ret)
  12362. {
  12363. (void)ret;
  12364. if (what & SSL_CB_HANDSHAKE_START) {
  12365. SSL_get_app_data(ssl);
  12366. }
  12367. if (what & SSL_CB_HANDSHAKE_DONE) {
  12368. /* TODO: check for openSSL 1.1 */
  12369. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  12370. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  12371. }
  12372. }
  12373. static int
  12374. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  12375. {
  12376. struct mg_context *ctx = (struct mg_context *)arg;
  12377. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  12378. (void)ad;
  12379. /* Old clients (Win XP) will not support SNI. Then, there
  12380. * is no server name available in the request - we can
  12381. * only work with the default certificate.
  12382. * Multiple HTTPS hosts on one IP+port are only possible
  12383. * with a certificate containing all alternative names.
  12384. */
  12385. if ((servername == NULL) || (*servername = 0)) {
  12386. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  12387. return SSL_TLSEXT_ERR_NOACK;
  12388. }
  12389. DEBUG_TRACE("TLS connection to host %s", servername);
  12390. (void)ctx;
  12391. /* TODO for SNI: check all available server names.
  12392. * For the matching server name get the matching_ssl_ctx
  12393. * and call
  12394. * SSL_set_SSL_CTX(ssl, matching_ssl_ctx);
  12395. * to use this certificate. A different document_root
  12396. * may be required as well.
  12397. */
  12398. return SSL_TLSEXT_ERR_OK;
  12399. }
  12400. /* Setup SSL CTX as required by CivetWeb */
  12401. static int
  12402. init_ssl_ctx_impl(struct mg_context *ctx)
  12403. {
  12404. const char *pem;
  12405. const char *chain;
  12406. int callback_ret;
  12407. int should_verify_peer;
  12408. int peer_certificate_optional;
  12409. const char *ca_path;
  12410. const char *ca_file;
  12411. int use_default_verify_paths;
  12412. int verify_depth;
  12413. time_t now_rt = time(NULL);
  12414. struct timespec now_mt;
  12415. md5_byte_t ssl_context_id[16];
  12416. md5_state_t md5state;
  12417. int protocol_ver;
  12418. char ebuf[128];
  12419. /* If PEM file is not specified and the init_ssl callback
  12420. * is not specified, setup will fail. */
  12421. if (((pem = ctx->config[SSL_CERTIFICATE]) == NULL)
  12422. && (ctx->callbacks.init_ssl == NULL)) {
  12423. /* No certificate and no callback:
  12424. * Essential data to set up TLS is missing.
  12425. */
  12426. mg_cry(fc(ctx),
  12427. "Initializing SSL failed: -%s is not set",
  12428. config_options[SSL_CERTIFICATE].name);
  12429. return 0;
  12430. }
  12431. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  12432. if (chain == NULL) {
  12433. chain = pem;
  12434. }
  12435. if ((chain != NULL) && (*chain == 0)) {
  12436. chain = NULL;
  12437. }
  12438. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12439. mg_cry(fc(ctx), "%s", ebuf);
  12440. return 0;
  12441. }
  12442. #ifdef OPENSSL_API_1_1
  12443. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  12444. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  12445. return 0;
  12446. }
  12447. #else
  12448. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  12449. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  12450. return 0;
  12451. }
  12452. #endif /* OPENSSL_API_1_1 */
  12453. SSL_CTX_clear_options(ctx->ssl_ctx,
  12454. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  12455. | SSL_OP_NO_TLSv1_1);
  12456. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  12457. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  12458. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  12459. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  12460. SSL_CTX_set_options(ctx->ssl_ctx,
  12461. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12462. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  12463. #if !defined(NO_SSL_DL)
  12464. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  12465. #endif /* NO_SSL_DL */
  12466. #ifdef __clang__
  12467. #pragma clang diagnostic push
  12468. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  12469. #endif
  12470. /* Depending on the OpenSSL version, the callback may be
  12471. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  12472. * yielding in an "incompatible-pointer-type" warning for the other
  12473. * version. It seems to be "unclear" what is correct:
  12474. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  12475. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  12476. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  12477. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  12478. * Disable this warning here.
  12479. * Alternative would be a version dependent ssl_info_callback and
  12480. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  12481. */
  12482. SSL_CTX_set_info_callback(ctx->ssl_ctx, ssl_info_callback);
  12483. SSL_CTX_set_tlsext_servername_callback(ctx->ssl_ctx,
  12484. ssl_servername_callback);
  12485. SSL_CTX_set_tlsext_servername_arg(ctx->ssl_ctx, &ctx);
  12486. #ifdef __clang__
  12487. #pragma clang diagnostic pop
  12488. #endif
  12489. /* If a callback has been specified, call it. */
  12490. callback_ret =
  12491. (ctx->callbacks.init_ssl == NULL)
  12492. ? 0
  12493. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  12494. /* If callback returns 0, civetweb sets up the SSL certificate.
  12495. * If it returns 1, civetweb assumes the calback already did this.
  12496. * If it returns -1, initializing ssl fails. */
  12497. if (callback_ret < 0) {
  12498. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  12499. return 0;
  12500. }
  12501. if (callback_ret > 0) {
  12502. /* Callback did everything. */
  12503. return 1;
  12504. }
  12505. /* Use some UID as session context ID. */
  12506. md5_init(&md5state);
  12507. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  12508. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  12509. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  12510. md5_append(&md5state,
  12511. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  12512. strlen(ctx->config[LISTENING_PORTS]));
  12513. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  12514. md5_finish(&md5state, ssl_context_id);
  12515. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  12516. (const unsigned char *)&ssl_context_id,
  12517. sizeof(ssl_context_id));
  12518. if (pem != NULL) {
  12519. if (!ssl_use_pem_file(ctx, pem, chain)) {
  12520. return 0;
  12521. }
  12522. }
  12523. /* Should we support client certificates? */
  12524. /* Default is "no". */
  12525. should_verify_peer = 0;
  12526. peer_certificate_optional = 0;
  12527. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12528. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  12529. /* Yes, they are mandatory */
  12530. should_verify_peer = 1;
  12531. peer_certificate_optional = 0;
  12532. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  12533. == 0) {
  12534. /* Yes, they are optional */
  12535. should_verify_peer = 1;
  12536. peer_certificate_optional = 1;
  12537. }
  12538. }
  12539. use_default_verify_paths =
  12540. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  12541. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  12542. if (should_verify_peer) {
  12543. ca_path = ctx->config[SSL_CA_PATH];
  12544. ca_file = ctx->config[SSL_CA_FILE];
  12545. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  12546. != 1) {
  12547. mg_cry(fc(ctx),
  12548. "SSL_CTX_load_verify_locations error: %s "
  12549. "ssl_verify_peer requires setting "
  12550. "either ssl_ca_path or ssl_ca_file. "
  12551. "Is any of them present in the "
  12552. ".conf file?",
  12553. ssl_error());
  12554. return 0;
  12555. }
  12556. if (peer_certificate_optional) {
  12557. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  12558. } else {
  12559. SSL_CTX_set_verify(ctx->ssl_ctx,
  12560. SSL_VERIFY_PEER
  12561. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  12562. NULL);
  12563. }
  12564. if (use_default_verify_paths
  12565. && (SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1)) {
  12566. mg_cry(fc(ctx),
  12567. "SSL_CTX_set_default_verify_paths error: %s",
  12568. ssl_error());
  12569. return 0;
  12570. }
  12571. if (ctx->config[SSL_VERIFY_DEPTH]) {
  12572. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  12573. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  12574. }
  12575. }
  12576. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  12577. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  12578. != 1) {
  12579. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  12580. }
  12581. }
  12582. return 1;
  12583. }
  12584. /* Check if SSL is required.
  12585. * If so, dynamically load SSL library
  12586. * and set up ctx->ssl_ctx pointer. */
  12587. static int
  12588. init_ssl_ctx(struct mg_context *ctx)
  12589. {
  12590. void *ssl_ctx = 0;
  12591. int callback_ret;
  12592. if (!ctx) {
  12593. return 0;
  12594. }
  12595. if (!is_ssl_port_used(ctx->config[LISTENING_PORTS])) {
  12596. /* No SSL port is set. No need to setup SSL. */
  12597. return 1;
  12598. }
  12599. /* Check for external SSL_CTX */
  12600. callback_ret =
  12601. (ctx->callbacks.external_ssl_ctx == NULL)
  12602. ? 0
  12603. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  12604. if (callback_ret < 0) {
  12605. mg_cry(fc(ctx),
  12606. "external_ssl_ctx callback returned error: %i",
  12607. callback_ret);
  12608. return 0;
  12609. } else if (callback_ret > 0) {
  12610. char ebuf[128];
  12611. ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  12612. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12613. mg_cry(fc(ctx), "%s", ebuf);
  12614. return 0;
  12615. }
  12616. return 1;
  12617. }
  12618. /* else continue */
  12619. return init_ssl_ctx_impl(ctx);
  12620. }
  12621. static void
  12622. uninitialize_ssl(void)
  12623. {
  12624. #ifdef OPENSSL_API_1_1
  12625. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12626. /* Shutdown according to
  12627. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12628. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12629. */
  12630. CONF_modules_unload(1);
  12631. #else
  12632. int i;
  12633. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12634. /* Shutdown according to
  12635. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12636. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12637. */
  12638. CRYPTO_set_locking_callback(NULL);
  12639. CRYPTO_set_id_callback(NULL);
  12640. ENGINE_cleanup();
  12641. CONF_modules_unload(1);
  12642. ERR_free_strings();
  12643. EVP_cleanup();
  12644. CRYPTO_cleanup_all_ex_data();
  12645. ERR_remove_state(0);
  12646. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12647. pthread_mutex_destroy(&ssl_mutexes[i]);
  12648. }
  12649. mg_free(ssl_mutexes);
  12650. ssl_mutexes = NULL;
  12651. #endif /* OPENSSL_API_1_1 */
  12652. }
  12653. }
  12654. #endif /* !NO_SSL */
  12655. static int
  12656. set_gpass_option(struct mg_context *ctx)
  12657. {
  12658. if (ctx) {
  12659. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12660. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  12661. if ((path != NULL) && !mg_stat(fc(ctx), path, &file.stat)) {
  12662. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  12663. return 0;
  12664. }
  12665. return 1;
  12666. }
  12667. return 0;
  12668. }
  12669. static int
  12670. set_acl_option(struct mg_context *ctx)
  12671. {
  12672. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  12673. }
  12674. static void
  12675. reset_per_request_attributes(struct mg_connection *conn)
  12676. {
  12677. if (!conn) {
  12678. return;
  12679. }
  12680. conn->connection_type =
  12681. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  12682. conn->num_bytes_sent = conn->consumed_content = 0;
  12683. conn->path_info = NULL;
  12684. conn->status_code = -1;
  12685. conn->content_len = -1;
  12686. conn->is_chunked = 0;
  12687. conn->must_close = 0;
  12688. conn->request_len = 0;
  12689. conn->throttle = 0;
  12690. conn->data_len = 0;
  12691. conn->chunk_remainder = 0;
  12692. conn->accept_gzip = 0;
  12693. conn->response_info.content_length = conn->request_info.content_length = -1;
  12694. conn->response_info.http_version = conn->request_info.http_version = NULL;
  12695. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  12696. conn->response_info.status_text = NULL;
  12697. conn->response_info.status_code = 0;
  12698. conn->request_info.remote_user = NULL;
  12699. conn->request_info.request_method = NULL;
  12700. conn->request_info.request_uri = NULL;
  12701. conn->request_info.local_uri = NULL;
  12702. #if defined(MG_LEGACY_INTERFACE)
  12703. /* Legacy before split into local_uri and request_uri */
  12704. conn->request_info.uri = NULL;
  12705. #endif
  12706. }
  12707. #if 0
  12708. /* Note: set_sock_timeout is not required for non-blocking sockets.
  12709. * Leave this function here (commented out) for reference until
  12710. * CivetWeb 1.9 is tested, and the tests confirme this function is
  12711. * no longer required.
  12712. */
  12713. static int
  12714. set_sock_timeout(SOCKET sock, int milliseconds)
  12715. {
  12716. int r0 = 0, r1, r2;
  12717. #ifdef _WIN32
  12718. /* Windows specific */
  12719. DWORD tv = (DWORD)milliseconds;
  12720. #else
  12721. /* Linux, ... (not Windows) */
  12722. struct timeval tv;
  12723. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  12724. * max. time waiting for the acknowledged of TCP data before the connection
  12725. * will be forcefully closed and ETIMEDOUT is returned to the application.
  12726. * If this option is not set, the default timeout of 20-30 minutes is used.
  12727. */
  12728. /* #define TCP_USER_TIMEOUT (18) */
  12729. #if defined(TCP_USER_TIMEOUT)
  12730. unsigned int uto = (unsigned int)milliseconds;
  12731. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  12732. #endif
  12733. memset(&tv, 0, sizeof(tv));
  12734. tv.tv_sec = milliseconds / 1000;
  12735. tv.tv_usec = (milliseconds * 1000) % 1000000;
  12736. #endif /* _WIN32 */
  12737. r1 = setsockopt(
  12738. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12739. r2 = setsockopt(
  12740. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12741. return r0 || r1 || r2;
  12742. }
  12743. #endif
  12744. static int
  12745. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  12746. {
  12747. if (setsockopt(sock,
  12748. IPPROTO_TCP,
  12749. TCP_NODELAY,
  12750. (SOCK_OPT_TYPE)&nodelay_on,
  12751. sizeof(nodelay_on)) != 0) {
  12752. /* Error */
  12753. return 1;
  12754. }
  12755. /* OK */
  12756. return 0;
  12757. }
  12758. static void
  12759. close_socket_gracefully(struct mg_connection *conn)
  12760. {
  12761. #if defined(_WIN32)
  12762. char buf[MG_BUF_LEN];
  12763. int n;
  12764. #endif
  12765. struct linger linger;
  12766. int error_code = 0;
  12767. int linger_timeout = -2;
  12768. socklen_t opt_len = sizeof(error_code);
  12769. if (!conn) {
  12770. return;
  12771. }
  12772. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  12773. * "Note that enabling a nonzero timeout on a nonblocking socket
  12774. * is not recommended.", so set it to blocking now */
  12775. set_blocking_mode(conn->client.sock);
  12776. /* Send FIN to the client */
  12777. shutdown(conn->client.sock, SHUTDOWN_WR);
  12778. #if defined(_WIN32)
  12779. /* Read and discard pending incoming data. If we do not do that and
  12780. * close
  12781. * the socket, the data in the send buffer may be discarded. This
  12782. * behaviour is seen on Windows, when client keeps sending data
  12783. * when server decides to close the connection; then when client
  12784. * does recv() it gets no data back. */
  12785. do {
  12786. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  12787. } while (n > 0);
  12788. #endif
  12789. if (conn->ctx->config[LINGER_TIMEOUT]) {
  12790. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  12791. }
  12792. /* Set linger option according to configuration */
  12793. if (linger_timeout >= 0) {
  12794. /* Set linger option to avoid socket hanging out after close. This
  12795. * prevent ephemeral port exhaust problem under high QPS. */
  12796. linger.l_onoff = 1;
  12797. #if defined(_MSC_VER)
  12798. #pragma warning(push)
  12799. #pragma warning(disable : 4244)
  12800. #endif
  12801. #if defined(__GNUC__) || defined(__MINGW32__)
  12802. #pragma GCC diagnostic push
  12803. #pragma GCC diagnostic ignored "-Wconversion"
  12804. #endif
  12805. /* Data type of linger structure elements may differ,
  12806. * so we don't know what cast we need here.
  12807. * Disable type conversion warnings. */
  12808. linger.l_linger = (linger_timeout + 999) / 1000;
  12809. #if defined(__GNUC__) || defined(__MINGW32__)
  12810. #pragma GCC diagnostic pop
  12811. #endif
  12812. #if defined(_MSC_VER)
  12813. #pragma warning(pop)
  12814. #endif
  12815. } else {
  12816. linger.l_onoff = 0;
  12817. linger.l_linger = 0;
  12818. }
  12819. if (linger_timeout < -1) {
  12820. /* Default: don't configure any linger */
  12821. } else if (getsockopt(conn->client.sock,
  12822. SOL_SOCKET,
  12823. SO_ERROR,
  12824. (char *)&error_code,
  12825. &opt_len) != 0) {
  12826. /* Cannot determine if socket is already closed. This should
  12827. * not occur and never did in a test. Log an error message
  12828. * and continue. */
  12829. mg_cry(conn,
  12830. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  12831. __func__,
  12832. strerror(ERRNO));
  12833. } else if (error_code == ECONNRESET) {
  12834. /* Socket already closed by client/peer, close socket without linger
  12835. */
  12836. } else {
  12837. /* Set linger timeout */
  12838. if (setsockopt(conn->client.sock,
  12839. SOL_SOCKET,
  12840. SO_LINGER,
  12841. (char *)&linger,
  12842. sizeof(linger)) != 0) {
  12843. mg_cry(conn,
  12844. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  12845. __func__,
  12846. linger.l_onoff,
  12847. linger.l_linger,
  12848. strerror(ERRNO));
  12849. }
  12850. }
  12851. /* Now we know that our FIN is ACK-ed, safe to close */
  12852. closesocket(conn->client.sock);
  12853. conn->client.sock = INVALID_SOCKET;
  12854. }
  12855. static void
  12856. close_connection(struct mg_connection *conn)
  12857. {
  12858. #if defined(USE_SERVER_STATS)
  12859. conn->conn_state = 6; /* to close */
  12860. #endif
  12861. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12862. if (conn->lua_websocket_state) {
  12863. lua_websocket_close(conn, conn->lua_websocket_state);
  12864. conn->lua_websocket_state = NULL;
  12865. }
  12866. #endif
  12867. mg_lock_connection(conn);
  12868. /* Set close flag, so keep-alive loops will stop */
  12869. conn->must_close = 1;
  12870. /* call the connection_close callback if assigned */
  12871. if (conn->ctx->callbacks.connection_close != NULL) {
  12872. if (conn->ctx->context_type == CONTEXT_SERVER) {
  12873. conn->ctx->callbacks.connection_close(conn);
  12874. }
  12875. }
  12876. /* Reset user data, after close callback is called.
  12877. * Do not reuse it. If the user needs a destructor,
  12878. * it must be done in the connection_close callback. */
  12879. mg_set_user_connection_data(conn, NULL);
  12880. #if defined(USE_SERVER_STATS)
  12881. conn->conn_state = 7; /* closing */
  12882. #endif
  12883. #ifndef NO_SSL
  12884. if (conn->ssl != NULL) {
  12885. /* Run SSL_shutdown twice to ensure completly close SSL connection
  12886. */
  12887. SSL_shutdown(conn->ssl);
  12888. SSL_free(conn->ssl);
  12889. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12890. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12891. #ifndef OPENSSL_API_1_1
  12892. ERR_remove_state(0);
  12893. #endif
  12894. conn->ssl = NULL;
  12895. }
  12896. #endif
  12897. if (conn->client.sock != INVALID_SOCKET) {
  12898. close_socket_gracefully(conn);
  12899. conn->client.sock = INVALID_SOCKET;
  12900. }
  12901. mg_unlock_connection(conn);
  12902. #if defined(USE_SERVER_STATS)
  12903. conn->conn_state = 8; /* closed */
  12904. #endif
  12905. }
  12906. void
  12907. mg_close_connection(struct mg_connection *conn)
  12908. {
  12909. #if defined(USE_WEBSOCKET)
  12910. struct mg_context *client_ctx = NULL;
  12911. #endif /* defined(USE_WEBSOCKET) */
  12912. if ((conn == NULL) || (conn->ctx == NULL)) {
  12913. return;
  12914. }
  12915. #if defined(USE_WEBSOCKET)
  12916. if (conn->ctx->context_type == CONTEXT_SERVER) {
  12917. if (conn->in_websocket_handling) {
  12918. /* Set close flag, so the server thread can exit. */
  12919. conn->must_close = 1;
  12920. return;
  12921. }
  12922. }
  12923. if (conn->ctx->context_type == CONTEXT_WS_CLIENT) {
  12924. unsigned int i;
  12925. /* ws/wss client */
  12926. client_ctx = conn->ctx;
  12927. /* client context: loops must end */
  12928. conn->ctx->stop_flag = 1;
  12929. conn->must_close = 1;
  12930. /* We need to get the client thread out of the select/recv call
  12931. * here. */
  12932. /* Since we use a sleep quantum of some seconds to check for recv
  12933. * timeouts, we will just wait a few seconds in mg_join_thread. */
  12934. /* join worker thread */
  12935. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  12936. if (client_ctx->worker_threadids[i] != 0) {
  12937. mg_join_thread(client_ctx->worker_threadids[i]);
  12938. }
  12939. }
  12940. }
  12941. #endif /* defined(USE_WEBSOCKET) */
  12942. close_connection(conn);
  12943. #ifndef NO_SSL
  12944. if (conn->client_ssl_ctx != NULL) {
  12945. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  12946. }
  12947. #endif
  12948. #if defined(USE_WEBSOCKET)
  12949. if (client_ctx != NULL) {
  12950. /* free context */
  12951. mg_free(client_ctx->worker_threadids);
  12952. mg_free(client_ctx);
  12953. (void)pthread_mutex_destroy(&conn->mutex);
  12954. mg_free(conn);
  12955. } else if (conn->ctx->context_type == CONTEXT_HTTP_CLIENT) {
  12956. mg_free(conn);
  12957. }
  12958. #else
  12959. if (conn->ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  12960. mg_free(conn);
  12961. }
  12962. #endif /* defined(USE_WEBSOCKET) */
  12963. }
  12964. /* Only for memory statistics */
  12965. static struct mg_context common_client_context;
  12966. static struct mg_connection *
  12967. mg_connect_client_impl(const struct mg_client_options *client_options,
  12968. int use_ssl,
  12969. char *ebuf,
  12970. size_t ebuf_len)
  12971. {
  12972. struct mg_connection *conn = NULL;
  12973. SOCKET sock;
  12974. union usa sa;
  12975. struct sockaddr *psa;
  12976. socklen_t len;
  12977. unsigned max_req_size =
  12978. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  12979. /* Size of structures, aligned to 8 bytes */
  12980. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  12981. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  12982. conn = (struct mg_connection *)mg_calloc_ctx(1,
  12983. conn_size + ctx_size
  12984. + max_req_size,
  12985. &common_client_context);
  12986. if (conn == NULL) {
  12987. mg_snprintf(NULL,
  12988. NULL, /* No truncation check for ebuf */
  12989. ebuf,
  12990. ebuf_len,
  12991. "calloc(): %s",
  12992. strerror(ERRNO));
  12993. return NULL;
  12994. }
  12995. conn->ctx = (struct mg_context *)(((char *)conn) + conn_size);
  12996. conn->buf = (((char *)conn) + conn_size + ctx_size);
  12997. conn->buf_size = (int)max_req_size;
  12998. conn->ctx->context_type = CONTEXT_HTTP_CLIENT;
  12999. if (!connect_socket(&common_client_context,
  13000. client_options->host,
  13001. client_options->port,
  13002. use_ssl,
  13003. ebuf,
  13004. ebuf_len,
  13005. &sock,
  13006. &sa)) {
  13007. /* ebuf is set by connect_socket,
  13008. * free all memory and return NULL; */
  13009. mg_free(conn);
  13010. return NULL;
  13011. }
  13012. #ifndef NO_SSL
  13013. #ifdef OPENSSL_API_1_1
  13014. if (use_ssl
  13015. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  13016. mg_snprintf(NULL,
  13017. NULL, /* No truncation check for ebuf */
  13018. ebuf,
  13019. ebuf_len,
  13020. "SSL_CTX_new error");
  13021. closesocket(sock);
  13022. mg_free(conn);
  13023. return NULL;
  13024. }
  13025. #else
  13026. if (use_ssl
  13027. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  13028. == NULL) {
  13029. mg_snprintf(NULL,
  13030. NULL, /* No truncation check for ebuf */
  13031. ebuf,
  13032. ebuf_len,
  13033. "SSL_CTX_new error");
  13034. closesocket(sock);
  13035. mg_free(conn);
  13036. return NULL;
  13037. }
  13038. #endif /* OPENSSL_API_1_1 */
  13039. #endif /* NO_SSL */
  13040. #ifdef USE_IPV6
  13041. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  13042. : sizeof(conn->client.rsa.sin6);
  13043. psa = (sa.sa.sa_family == AF_INET)
  13044. ? (struct sockaddr *)&(conn->client.rsa.sin)
  13045. : (struct sockaddr *)&(conn->client.rsa.sin6);
  13046. #else
  13047. len = sizeof(conn->client.rsa.sin);
  13048. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  13049. #endif
  13050. conn->client.sock = sock;
  13051. conn->client.lsa = sa;
  13052. if (getsockname(sock, psa, &len) != 0) {
  13053. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  13054. }
  13055. conn->client.is_ssl = use_ssl ? 1 : 0;
  13056. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13057. #ifndef NO_SSL
  13058. if (use_ssl) {
  13059. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  13060. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  13061. * SSL_CTX_set_verify call is needed to switch off server
  13062. * certificate checking, which is off by default in OpenSSL and
  13063. * on in yaSSL. */
  13064. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  13065. * SSL_VERIFY_PEER, verify_ssl_server); */
  13066. if (client_options->client_cert) {
  13067. if (!ssl_use_pem_file(&common_client_context,
  13068. client_options->client_cert,
  13069. NULL)) {
  13070. mg_snprintf(NULL,
  13071. NULL, /* No truncation check for ebuf */
  13072. ebuf,
  13073. ebuf_len,
  13074. "Can not use SSL client certificate");
  13075. SSL_CTX_free(conn->client_ssl_ctx);
  13076. closesocket(sock);
  13077. mg_free(conn);
  13078. return NULL;
  13079. }
  13080. }
  13081. if (client_options->server_cert) {
  13082. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  13083. client_options->server_cert,
  13084. NULL);
  13085. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  13086. } else {
  13087. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  13088. }
  13089. if (!sslize(conn,
  13090. conn->client_ssl_ctx,
  13091. SSL_connect,
  13092. &(conn->ctx->stop_flag))) {
  13093. mg_snprintf(NULL,
  13094. NULL, /* No truncation check for ebuf */
  13095. ebuf,
  13096. ebuf_len,
  13097. "SSL connection error");
  13098. SSL_CTX_free(conn->client_ssl_ctx);
  13099. closesocket(sock);
  13100. mg_free(conn);
  13101. return NULL;
  13102. }
  13103. }
  13104. #endif
  13105. if (0 != set_non_blocking_mode(sock)) {
  13106. /* TODO: handle error */
  13107. ;
  13108. }
  13109. return conn;
  13110. }
  13111. CIVETWEB_API struct mg_connection *
  13112. mg_connect_client_secure(const struct mg_client_options *client_options,
  13113. char *error_buffer,
  13114. size_t error_buffer_size)
  13115. {
  13116. return mg_connect_client_impl(client_options,
  13117. 1,
  13118. error_buffer,
  13119. error_buffer_size);
  13120. }
  13121. struct mg_connection *
  13122. mg_connect_client(const char *host,
  13123. int port,
  13124. int use_ssl,
  13125. char *error_buffer,
  13126. size_t error_buffer_size)
  13127. {
  13128. struct mg_client_options opts;
  13129. memset(&opts, 0, sizeof(opts));
  13130. opts.host = host;
  13131. opts.port = port;
  13132. return mg_connect_client_impl(&opts,
  13133. use_ssl,
  13134. error_buffer,
  13135. error_buffer_size);
  13136. }
  13137. static const struct {
  13138. const char *proto;
  13139. size_t proto_len;
  13140. unsigned default_port;
  13141. } abs_uri_protocols[] = {{"http://", 7, 80},
  13142. {"https://", 8, 443},
  13143. {"ws://", 5, 80},
  13144. {"wss://", 6, 443},
  13145. {NULL, 0, 0}};
  13146. /* Check if the uri is valid.
  13147. * return 0 for invalid uri,
  13148. * return 1 for *,
  13149. * return 2 for relative uri,
  13150. * return 3 for absolute uri without port,
  13151. * return 4 for absolute uri with port */
  13152. static int
  13153. get_uri_type(const char *uri)
  13154. {
  13155. int i;
  13156. const char *hostend, *portbegin;
  13157. char *portend;
  13158. unsigned long port;
  13159. /* According to the HTTP standard
  13160. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  13161. * URI can be an asterisk (*) or should start with slash (relative uri),
  13162. * or it should start with the protocol (absolute uri). */
  13163. if ((uri[0] == '*') && (uri[1] == '\0')) {
  13164. /* asterisk */
  13165. return 1;
  13166. }
  13167. /* Valid URIs according to RFC 3986
  13168. * (https://www.ietf.org/rfc/rfc3986.txt)
  13169. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  13170. * and unreserved characters A-Z a-z 0-9 and -._~
  13171. * and % encoded symbols.
  13172. */
  13173. for (i = 0; uri[i] != 0; i++) {
  13174. if (uri[i] < 33) {
  13175. /* control characters and spaces are invalid */
  13176. return 0;
  13177. }
  13178. if (uri[i] > 126) {
  13179. /* non-ascii characters must be % encoded */
  13180. return 0;
  13181. } else {
  13182. switch (uri[i]) {
  13183. case '"': /* 34 */
  13184. case '<': /* 60 */
  13185. case '>': /* 62 */
  13186. case '\\': /* 92 */
  13187. case '^': /* 94 */
  13188. case '`': /* 96 */
  13189. case '{': /* 123 */
  13190. case '|': /* 124 */
  13191. case '}': /* 125 */
  13192. return 0;
  13193. default:
  13194. /* character is ok */
  13195. break;
  13196. }
  13197. }
  13198. }
  13199. /* A relative uri starts with a / character */
  13200. if (uri[0] == '/') {
  13201. /* relative uri */
  13202. return 2;
  13203. }
  13204. /* It could be an absolute uri: */
  13205. /* This function only checks if the uri is valid, not if it is
  13206. * addressing the current server. So civetweb can also be used
  13207. * as a proxy server. */
  13208. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13209. if (mg_strncasecmp(uri,
  13210. abs_uri_protocols[i].proto,
  13211. abs_uri_protocols[i].proto_len) == 0) {
  13212. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  13213. if (!hostend) {
  13214. return 0;
  13215. }
  13216. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  13217. if (!portbegin) {
  13218. return 3;
  13219. }
  13220. port = strtoul(portbegin + 1, &portend, 10);
  13221. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  13222. return 0;
  13223. }
  13224. return 4;
  13225. }
  13226. }
  13227. return 0;
  13228. }
  13229. /* Return NULL or the relative uri at the current server */
  13230. static const char *
  13231. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  13232. {
  13233. const char *server_domain;
  13234. size_t server_domain_len;
  13235. size_t request_domain_len = 0;
  13236. unsigned long port = 0;
  13237. int i, auth_domain_check_enabled;
  13238. const char *hostbegin = NULL;
  13239. const char *hostend = NULL;
  13240. const char *portbegin;
  13241. char *portend;
  13242. auth_domain_check_enabled =
  13243. !mg_strcasecmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  13244. if (!auth_domain_check_enabled) {
  13245. return 0;
  13246. }
  13247. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  13248. if (!server_domain) {
  13249. return 0;
  13250. }
  13251. server_domain_len = strlen(server_domain);
  13252. if (!server_domain_len) {
  13253. return 0;
  13254. }
  13255. /* DNS is case insensitive, so use case insensitive string compare here
  13256. */
  13257. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13258. if (mg_strncasecmp(uri,
  13259. abs_uri_protocols[i].proto,
  13260. abs_uri_protocols[i].proto_len) == 0) {
  13261. hostbegin = uri + abs_uri_protocols[i].proto_len;
  13262. hostend = strchr(hostbegin, '/');
  13263. if (!hostend) {
  13264. return 0;
  13265. }
  13266. portbegin = strchr(hostbegin, ':');
  13267. if ((!portbegin) || (portbegin > hostend)) {
  13268. port = abs_uri_protocols[i].default_port;
  13269. request_domain_len = (size_t)(hostend - hostbegin);
  13270. } else {
  13271. port = strtoul(portbegin + 1, &portend, 10);
  13272. if ((portend != hostend) || (port <= 0)
  13273. || !is_valid_port(port)) {
  13274. return 0;
  13275. }
  13276. request_domain_len = (size_t)(portbegin - hostbegin);
  13277. }
  13278. /* protocol found, port set */
  13279. break;
  13280. }
  13281. }
  13282. if (!port) {
  13283. /* port remains 0 if the protocol is not found */
  13284. return 0;
  13285. }
  13286. /* Check if the request is directed to a different server. */
  13287. /* First check if the port is the same (IPv4 and IPv6). */
  13288. #if defined(USE_IPV6)
  13289. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  13290. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  13291. /* Request is directed to a different port */
  13292. return 0;
  13293. }
  13294. } else
  13295. #endif
  13296. {
  13297. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  13298. /* Request is directed to a different port */
  13299. return 0;
  13300. }
  13301. }
  13302. /* Finally check if the server corresponds to the authentication
  13303. * domain of the server (the server domain).
  13304. * Allow full matches (like http://mydomain.com/path/file.ext), and
  13305. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  13306. * but do not allow substrings (like
  13307. * http://notmydomain.com/path/file.ext
  13308. * or http://mydomain.com.fake/path/file.ext).
  13309. */
  13310. if (auth_domain_check_enabled) {
  13311. if ((request_domain_len == server_domain_len)
  13312. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  13313. /* Request is directed to this server - full name match. */
  13314. } else {
  13315. if (request_domain_len < (server_domain_len + 2)) {
  13316. /* Request is directed to another server: The server name is
  13317. * longer
  13318. * than
  13319. * the request name. Drop this case here to avoid overflows
  13320. * in
  13321. * the
  13322. * following checks. */
  13323. return 0;
  13324. }
  13325. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  13326. /* Request is directed to another server: It could be a
  13327. * substring
  13328. * like notmyserver.com */
  13329. return 0;
  13330. }
  13331. if (0 != memcmp(server_domain,
  13332. hostbegin + request_domain_len - server_domain_len,
  13333. server_domain_len)) {
  13334. /* Request is directed to another server:
  13335. * The server name is different. */
  13336. return 0;
  13337. }
  13338. }
  13339. }
  13340. return hostend;
  13341. }
  13342. static int
  13343. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13344. {
  13345. if (ebuf_len > 0) {
  13346. ebuf[0] = '\0';
  13347. }
  13348. *err = 0;
  13349. reset_per_request_attributes(conn);
  13350. if (!conn) {
  13351. mg_snprintf(conn,
  13352. NULL, /* No truncation check for ebuf */
  13353. ebuf,
  13354. ebuf_len,
  13355. "%s",
  13356. "Internal error");
  13357. *err = 500;
  13358. return 0;
  13359. }
  13360. /* Set the time the request was received. This value should be used for
  13361. * timeouts. */
  13362. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  13363. conn->request_len =
  13364. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  13365. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  13366. */
  13367. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  13368. mg_snprintf(conn,
  13369. NULL, /* No truncation check for ebuf */
  13370. ebuf,
  13371. ebuf_len,
  13372. "%s",
  13373. "Invalid message size");
  13374. *err = 500;
  13375. return 0;
  13376. }
  13377. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  13378. mg_snprintf(conn,
  13379. NULL, /* No truncation check for ebuf */
  13380. ebuf,
  13381. ebuf_len,
  13382. "%s",
  13383. "Message too large");
  13384. *err = 413;
  13385. return 0;
  13386. }
  13387. if (conn->request_len <= 0) {
  13388. if (conn->data_len > 0) {
  13389. mg_snprintf(conn,
  13390. NULL, /* No truncation check for ebuf */
  13391. ebuf,
  13392. ebuf_len,
  13393. "%s",
  13394. "Malformed message");
  13395. *err = 400;
  13396. } else {
  13397. /* Server did not recv anything -> just close the connection */
  13398. conn->must_close = 1;
  13399. mg_snprintf(conn,
  13400. NULL, /* No truncation check for ebuf */
  13401. ebuf,
  13402. ebuf_len,
  13403. "%s",
  13404. "No data received");
  13405. *err = 0;
  13406. }
  13407. return 0;
  13408. }
  13409. return 1;
  13410. }
  13411. static int
  13412. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13413. {
  13414. const char *cl;
  13415. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13416. return 0;
  13417. }
  13418. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  13419. <= 0) {
  13420. mg_snprintf(conn,
  13421. NULL, /* No truncation check for ebuf */
  13422. ebuf,
  13423. ebuf_len,
  13424. "%s",
  13425. "Bad request");
  13426. *err = 400;
  13427. return 0;
  13428. }
  13429. /* Message is a valid request */
  13430. if ((cl = get_header(conn->request_info.http_headers,
  13431. conn->request_info.num_headers,
  13432. "Content-Length")) != NULL) {
  13433. /* Request/response has content length set */
  13434. char *endptr = NULL;
  13435. conn->content_len = strtoll(cl, &endptr, 10);
  13436. if (endptr == cl) {
  13437. mg_snprintf(conn,
  13438. NULL, /* No truncation check for ebuf */
  13439. ebuf,
  13440. ebuf_len,
  13441. "%s",
  13442. "Bad request");
  13443. *err = 411;
  13444. return 0;
  13445. }
  13446. /* Publish the content length back to the request info. */
  13447. conn->request_info.content_length = conn->content_len;
  13448. } else if ((cl = get_header(conn->request_info.http_headers,
  13449. conn->request_info.num_headers,
  13450. "Transfer-Encoding")) != NULL
  13451. && !mg_strcasecmp(cl, "chunked")) {
  13452. conn->is_chunked = 1;
  13453. conn->content_len = -1; /* unknown content length */
  13454. } else if (get_http_method_info(conn->request_info.request_method)
  13455. ->request_has_body) {
  13456. /* POST or PUT request without content length set */
  13457. conn->content_len = -1; /* unknown content length */
  13458. } else {
  13459. /* Other request */
  13460. conn->content_len = 0; /* No content */
  13461. }
  13462. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  13463. return 1;
  13464. }
  13465. /* conn is assumed to be valid in this internal function */
  13466. static int
  13467. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13468. {
  13469. const char *cl;
  13470. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13471. return 0;
  13472. }
  13473. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  13474. <= 0) {
  13475. mg_snprintf(conn,
  13476. NULL, /* No truncation check for ebuf */
  13477. ebuf,
  13478. ebuf_len,
  13479. "%s",
  13480. "Bad response");
  13481. *err = 400;
  13482. return 0;
  13483. }
  13484. /* Message is a valid response */
  13485. if ((cl = get_header(conn->response_info.http_headers,
  13486. conn->response_info.num_headers,
  13487. "Content-Length")) != NULL) {
  13488. /* Request/response has content length set */
  13489. char *endptr = NULL;
  13490. conn->content_len = strtoll(cl, &endptr, 10);
  13491. if (endptr == cl) {
  13492. mg_snprintf(conn,
  13493. NULL, /* No truncation check for ebuf */
  13494. ebuf,
  13495. ebuf_len,
  13496. "%s",
  13497. "Bad request");
  13498. *err = 411;
  13499. return 0;
  13500. }
  13501. /* Publish the content length back to the response info. */
  13502. conn->response_info.content_length = conn->content_len;
  13503. /* TODO: check if it is still used in response_info */
  13504. conn->request_info.content_length = conn->content_len;
  13505. } else if ((cl = get_header(conn->response_info.http_headers,
  13506. conn->response_info.num_headers,
  13507. "Transfer-Encoding")) != NULL
  13508. && !mg_strcasecmp(cl, "chunked")) {
  13509. conn->is_chunked = 1;
  13510. conn->content_len = -1; /* unknown content length */
  13511. } else {
  13512. conn->content_len = -1; /* unknown content length */
  13513. }
  13514. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  13515. return 1;
  13516. }
  13517. int
  13518. mg_get_response(struct mg_connection *conn,
  13519. char *ebuf,
  13520. size_t ebuf_len,
  13521. int timeout)
  13522. {
  13523. int err, ret;
  13524. char txt[32]; /* will not overflow */
  13525. struct mg_context *octx;
  13526. struct mg_context rctx;
  13527. if (ebuf_len > 0) {
  13528. ebuf[0] = '\0';
  13529. }
  13530. if (!conn) {
  13531. mg_snprintf(conn,
  13532. NULL, /* No truncation check for ebuf */
  13533. ebuf,
  13534. ebuf_len,
  13535. "%s",
  13536. "Parameter error");
  13537. return -1;
  13538. }
  13539. /* Implementation of API function for HTTP clients */
  13540. octx = conn->ctx;
  13541. rctx = *(conn->ctx);
  13542. if (timeout >= 0) {
  13543. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  13544. rctx.config[REQUEST_TIMEOUT] = txt;
  13545. /* Not required for non-blocking sockets.
  13546. set_sock_timeout(conn->client.sock, timeout);
  13547. */
  13548. } else {
  13549. rctx.config[REQUEST_TIMEOUT] = NULL;
  13550. }
  13551. conn->ctx = &rctx;
  13552. ret = get_response(conn, ebuf, ebuf_len, &err);
  13553. conn->ctx = octx;
  13554. #if defined(MG_LEGACY_INTERFACE)
  13555. /* TODO: 1) uri is deprecated;
  13556. * 2) here, ri.uri is the http response code */
  13557. conn->request_info.uri = conn->request_info.request_uri;
  13558. #endif
  13559. conn->request_info.local_uri = conn->request_info.request_uri;
  13560. /* TODO (mid): Define proper return values - maybe return length?
  13561. * For the first test use <0 for error and >0 for OK */
  13562. return (ret == 0) ? -1 : +1;
  13563. }
  13564. struct mg_connection *
  13565. mg_download(const char *host,
  13566. int port,
  13567. int use_ssl,
  13568. char *ebuf,
  13569. size_t ebuf_len,
  13570. const char *fmt,
  13571. ...)
  13572. {
  13573. struct mg_connection *conn;
  13574. va_list ap;
  13575. int i;
  13576. int reqerr;
  13577. if (ebuf_len > 0) {
  13578. ebuf[0] = '\0';
  13579. }
  13580. va_start(ap, fmt);
  13581. /* open a connection */
  13582. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  13583. if (conn != NULL) {
  13584. i = mg_vprintf(conn, fmt, ap);
  13585. if (i <= 0) {
  13586. mg_snprintf(conn,
  13587. NULL, /* No truncation check for ebuf */
  13588. ebuf,
  13589. ebuf_len,
  13590. "%s",
  13591. "Error sending request");
  13592. } else {
  13593. get_response(conn, ebuf, ebuf_len, &reqerr);
  13594. #if defined(MG_LEGACY_INTERFACE)
  13595. /* TODO: 1) uri is deprecated;
  13596. * 2) here, ri.uri is the http response code */
  13597. conn->request_info.uri = conn->request_info.request_uri;
  13598. #endif
  13599. conn->request_info.local_uri = conn->request_info.request_uri;
  13600. }
  13601. }
  13602. /* if an error occured, close the connection */
  13603. if ((ebuf[0] != '\0') && (conn != NULL)) {
  13604. mg_close_connection(conn);
  13605. conn = NULL;
  13606. }
  13607. va_end(ap);
  13608. return conn;
  13609. }
  13610. struct websocket_client_thread_data {
  13611. struct mg_connection *conn;
  13612. mg_websocket_data_handler data_handler;
  13613. mg_websocket_close_handler close_handler;
  13614. void *callback_data;
  13615. };
  13616. #if defined(USE_WEBSOCKET)
  13617. #ifdef _WIN32
  13618. static unsigned __stdcall websocket_client_thread(void *data)
  13619. #else
  13620. static void *
  13621. websocket_client_thread(void *data)
  13622. #endif
  13623. {
  13624. struct websocket_client_thread_data *cdata =
  13625. (struct websocket_client_thread_data *)data;
  13626. mg_set_thread_name("ws-clnt");
  13627. if (cdata->conn->ctx) {
  13628. if (cdata->conn->ctx->callbacks.init_thread) {
  13629. /* 3 indicates a websocket client thread */
  13630. /* TODO: check if conn->ctx can be set */
  13631. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  13632. }
  13633. }
  13634. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  13635. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  13636. if (cdata->close_handler != NULL) {
  13637. cdata->close_handler(cdata->conn, cdata->callback_data);
  13638. }
  13639. /* The websocket_client context has only this thread. If it runs out,
  13640. set the stop_flag to 2 (= "stopped"). */
  13641. cdata->conn->ctx->stop_flag = 2;
  13642. mg_free((void *)cdata);
  13643. #ifdef _WIN32
  13644. return 0;
  13645. #else
  13646. return NULL;
  13647. #endif
  13648. }
  13649. #endif
  13650. struct mg_connection *
  13651. mg_connect_websocket_client(const char *host,
  13652. int port,
  13653. int use_ssl,
  13654. char *error_buffer,
  13655. size_t error_buffer_size,
  13656. const char *path,
  13657. const char *origin,
  13658. mg_websocket_data_handler data_func,
  13659. mg_websocket_close_handler close_func,
  13660. void *user_data)
  13661. {
  13662. struct mg_connection *conn = NULL;
  13663. #if defined(USE_WEBSOCKET)
  13664. struct mg_context *newctx = NULL;
  13665. struct websocket_client_thread_data *thread_data;
  13666. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  13667. static const char *handshake_req;
  13668. if (origin != NULL) {
  13669. handshake_req = "GET %s HTTP/1.1\r\n"
  13670. "Host: %s\r\n"
  13671. "Upgrade: websocket\r\n"
  13672. "Connection: Upgrade\r\n"
  13673. "Sec-WebSocket-Key: %s\r\n"
  13674. "Sec-WebSocket-Version: 13\r\n"
  13675. "Origin: %s\r\n"
  13676. "\r\n";
  13677. } else {
  13678. handshake_req = "GET %s HTTP/1.1\r\n"
  13679. "Host: %s\r\n"
  13680. "Upgrade: websocket\r\n"
  13681. "Connection: Upgrade\r\n"
  13682. "Sec-WebSocket-Key: %s\r\n"
  13683. "Sec-WebSocket-Version: 13\r\n"
  13684. "\r\n";
  13685. }
  13686. /* Establish the client connection and request upgrade */
  13687. conn = mg_download(host,
  13688. port,
  13689. use_ssl,
  13690. error_buffer,
  13691. error_buffer_size,
  13692. handshake_req,
  13693. path,
  13694. host,
  13695. magic,
  13696. origin);
  13697. /* Connection object will be null if something goes wrong */
  13698. if (conn == NULL) {
  13699. if (!*error_buffer) {
  13700. /* There should be already an error message */
  13701. mg_snprintf(conn,
  13702. NULL, /* No truncation check for ebuf */
  13703. error_buffer,
  13704. error_buffer_size,
  13705. "Unexpected error");
  13706. }
  13707. return NULL;
  13708. }
  13709. if (conn->response_info.status_code != 101) {
  13710. /* We sent an "upgrade" request. For a correct websocket
  13711. * protocol handshake, we expect a "101 Continue" response.
  13712. * Otherwise it is a protocol violation. Maybe the HTTP
  13713. * Server does not know websockets. */
  13714. if (!*error_buffer) {
  13715. /* set an error, if not yet set */
  13716. mg_snprintf(conn,
  13717. NULL, /* No truncation check for ebuf */
  13718. error_buffer,
  13719. error_buffer_size,
  13720. "Unexpected server reply");
  13721. }
  13722. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  13723. mg_free(conn);
  13724. return NULL;
  13725. }
  13726. /* For client connections, mg_context is fake. Since we need to set a
  13727. * callback function, we need to create a copy and modify it. */
  13728. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  13729. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  13730. newctx->user_data = user_data;
  13731. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  13732. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  13733. newctx->worker_threadids =
  13734. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  13735. sizeof(pthread_t),
  13736. newctx);
  13737. conn->ctx = newctx;
  13738. thread_data = (struct websocket_client_thread_data *)
  13739. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  13740. thread_data->conn = conn;
  13741. thread_data->data_handler = data_func;
  13742. thread_data->close_handler = close_func;
  13743. thread_data->callback_data = user_data;
  13744. /* Start a thread to read the websocket client connection
  13745. * This thread will automatically stop when mg_disconnect is
  13746. * called on the client connection */
  13747. if (mg_start_thread_with_id(websocket_client_thread,
  13748. (void *)thread_data,
  13749. newctx->worker_threadids) != 0) {
  13750. mg_free((void *)thread_data);
  13751. mg_free((void *)newctx->worker_threadids);
  13752. mg_free((void *)newctx);
  13753. mg_free((void *)conn);
  13754. conn = NULL;
  13755. DEBUG_TRACE("%s",
  13756. "Websocket client connect thread could not be started\r\n");
  13757. }
  13758. #else
  13759. /* Appease "unused parameter" warnings */
  13760. (void)host;
  13761. (void)port;
  13762. (void)use_ssl;
  13763. (void)error_buffer;
  13764. (void)error_buffer_size;
  13765. (void)path;
  13766. (void)origin;
  13767. (void)user_data;
  13768. (void)data_func;
  13769. (void)close_func;
  13770. #endif
  13771. return conn;
  13772. }
  13773. /* Prepare connection data structure */
  13774. static void
  13775. init_connection(struct mg_connection *conn)
  13776. {
  13777. /* Is keep alive allowed by the server */
  13778. int keep_alive_enabled =
  13779. !mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  13780. if (!keep_alive_enabled) {
  13781. conn->must_close = 1;
  13782. }
  13783. /* Important: on new connection, reset the receiving buffer. Credit
  13784. * goes to crule42. */
  13785. conn->data_len = 0;
  13786. conn->handled_requests = 0;
  13787. mg_set_user_connection_data(conn, NULL);
  13788. #if defined(USE_SERVER_STATS)
  13789. conn->conn_state = 2; /* init */
  13790. #endif
  13791. /* call the init_connection callback if assigned */
  13792. if (conn->ctx->callbacks.init_connection != NULL) {
  13793. if (conn->ctx->context_type == CONTEXT_SERVER) {
  13794. void *conn_data = NULL;
  13795. conn->ctx->callbacks.init_connection(conn, &conn_data);
  13796. mg_set_user_connection_data(conn, conn_data);
  13797. }
  13798. }
  13799. }
  13800. /* Process a connection - may handle multiple requests
  13801. * using the same connection.
  13802. * Must be called with a valid connection (conn and
  13803. * conn->ctx must be valid).
  13804. */
  13805. static void
  13806. process_new_connection(struct mg_connection *conn)
  13807. {
  13808. struct mg_request_info *ri = &conn->request_info;
  13809. int keep_alive, discard_len;
  13810. char ebuf[100];
  13811. const char *hostend;
  13812. int reqerr, uri_type;
  13813. #if defined(USE_SERVER_STATS)
  13814. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  13815. mg_atomic_add(&(conn->ctx->total_connections), 1);
  13816. if (mcon > (conn->ctx->max_connections)) {
  13817. /* could use atomic compare exchange, but this
  13818. * seems overkill for statistics data */
  13819. conn->ctx->max_connections = mcon;
  13820. }
  13821. #endif
  13822. init_connection(conn);
  13823. DEBUG_TRACE("Start processing connection from %s",
  13824. conn->request_info.remote_addr);
  13825. /* Loop over multiple requests sent using the same connection
  13826. * (while "keep alive"). */
  13827. do {
  13828. DEBUG_TRACE("calling get_request (%i times for this connection)",
  13829. conn->handled_requests + 1);
  13830. #if defined(USE_SERVER_STATS)
  13831. conn->conn_state = 3; /* ready */
  13832. #endif
  13833. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  13834. /* The request sent by the client could not be understood by
  13835. * the server, or it was incomplete or a timeout. Send an
  13836. * error message and close the connection. */
  13837. if (reqerr > 0) {
  13838. /*assert(ebuf[0] != '\0');*/
  13839. mg_send_http_error(conn, reqerr, "%s", ebuf);
  13840. }
  13841. } else if (strcmp(ri->http_version, "1.0")
  13842. && strcmp(ri->http_version, "1.1")) {
  13843. mg_snprintf(conn,
  13844. NULL, /* No truncation check for ebuf */
  13845. ebuf,
  13846. sizeof(ebuf),
  13847. "Bad HTTP version: [%s]",
  13848. ri->http_version);
  13849. mg_send_http_error(conn, 505, "%s", ebuf);
  13850. }
  13851. if (ebuf[0] == '\0') {
  13852. uri_type = get_uri_type(conn->request_info.request_uri);
  13853. switch (uri_type) {
  13854. case 1:
  13855. /* Asterisk */
  13856. conn->request_info.local_uri = NULL;
  13857. break;
  13858. case 2:
  13859. /* relative uri */
  13860. conn->request_info.local_uri = conn->request_info.request_uri;
  13861. break;
  13862. case 3:
  13863. case 4:
  13864. /* absolute uri (with/without port) */
  13865. hostend = get_rel_url_at_current_server(
  13866. conn->request_info.request_uri, conn);
  13867. if (hostend) {
  13868. conn->request_info.local_uri = hostend;
  13869. } else {
  13870. conn->request_info.local_uri = NULL;
  13871. }
  13872. break;
  13873. default:
  13874. mg_snprintf(conn,
  13875. NULL, /* No truncation check for ebuf */
  13876. ebuf,
  13877. sizeof(ebuf),
  13878. "Invalid URI");
  13879. mg_send_http_error(conn, 400, "%s", ebuf);
  13880. conn->request_info.local_uri = NULL;
  13881. break;
  13882. }
  13883. #if defined(MG_LEGACY_INTERFACE)
  13884. /* Legacy before split into local_uri and request_uri */
  13885. conn->request_info.uri = conn->request_info.local_uri;
  13886. #endif
  13887. }
  13888. DEBUG_TRACE("http: %s, error: %s",
  13889. (ri->http_version ? ri->http_version : "none"),
  13890. (ebuf[0] ? ebuf : "none"));
  13891. if (ebuf[0] == '\0') {
  13892. if (conn->request_info.local_uri) {
  13893. /* handle request to local server */
  13894. #if defined(USE_SERVER_STATS)
  13895. conn->conn_state = 4; /* processing */
  13896. #endif
  13897. handle_request(conn);
  13898. #if defined(USE_SERVER_STATS)
  13899. conn->conn_state = 5; /* processed */
  13900. mg_atomic_add(&(conn->ctx->total_data_read),
  13901. conn->consumed_content);
  13902. mg_atomic_add(&(conn->ctx->total_data_written),
  13903. conn->num_bytes_sent);
  13904. #endif
  13905. DEBUG_TRACE("%s", "handle_request done");
  13906. if (conn->ctx->callbacks.end_request != NULL) {
  13907. conn->ctx->callbacks.end_request(conn, conn->status_code);
  13908. DEBUG_TRACE("%s", "end_request callback done");
  13909. }
  13910. log_access(conn);
  13911. } else {
  13912. /* TODO: handle non-local request (PROXY) */
  13913. conn->must_close = 1;
  13914. }
  13915. } else {
  13916. conn->must_close = 1;
  13917. }
  13918. if (ri->remote_user != NULL) {
  13919. mg_free((void *)ri->remote_user);
  13920. /* Important! When having connections with and without auth
  13921. * would cause double free and then crash */
  13922. ri->remote_user = NULL;
  13923. }
  13924. /* NOTE(lsm): order is important here. should_keep_alive() call
  13925. * is using parsed request, which will be invalid after
  13926. * memmove's below.
  13927. * Therefore, memorize should_keep_alive() result now for later
  13928. * use in loop exit condition. */
  13929. keep_alive = (conn->ctx->stop_flag == 0) && should_keep_alive(conn)
  13930. && (conn->content_len >= 0);
  13931. /* Discard all buffered data for this request */
  13932. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  13933. && ((conn->request_len + conn->content_len)
  13934. < (int64_t)conn->data_len))
  13935. ? (int)(conn->request_len + conn->content_len)
  13936. : conn->data_len;
  13937. /*assert(discard_len >= 0);*/
  13938. if (discard_len < 0) {
  13939. DEBUG_TRACE("internal error: discard_len = %li",
  13940. (long int)discard_len);
  13941. break;
  13942. }
  13943. conn->data_len -= discard_len;
  13944. if (conn->data_len > 0) {
  13945. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  13946. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  13947. }
  13948. /* assert(conn->data_len >= 0); */
  13949. /* assert(conn->data_len <= conn->buf_size); */
  13950. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  13951. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  13952. (long int)conn->data_len,
  13953. (long int)conn->buf_size);
  13954. break;
  13955. }
  13956. conn->handled_requests++;
  13957. } while (keep_alive);
  13958. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  13959. conn->request_info.remote_addr,
  13960. difftime(time(NULL), conn->conn_birth_time));
  13961. close_connection(conn);
  13962. #if defined(USE_SERVER_STATS)
  13963. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  13964. mg_atomic_dec(&(conn->ctx->active_connections));
  13965. #endif
  13966. }
  13967. #if defined(ALTERNATIVE_QUEUE)
  13968. static void
  13969. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13970. {
  13971. unsigned int i;
  13972. for (;;) {
  13973. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13974. /* find a free worker slot and signal it */
  13975. if (ctx->client_socks[i].in_use == 0) {
  13976. ctx->client_socks[i] = *sp;
  13977. ctx->client_socks[i].in_use = 1;
  13978. event_signal(ctx->client_wait_events[i]);
  13979. return;
  13980. }
  13981. }
  13982. /* queue is full */
  13983. mg_sleep(1);
  13984. }
  13985. }
  13986. static int
  13987. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13988. {
  13989. DEBUG_TRACE("%s", "going idle");
  13990. ctx->client_socks[thread_index].in_use = 0;
  13991. event_wait(ctx->client_wait_events[thread_index]);
  13992. *sp = ctx->client_socks[thread_index];
  13993. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13994. return !ctx->stop_flag;
  13995. }
  13996. #else /* ALTERNATIVE_QUEUE */
  13997. /* Worker threads take accepted socket from the queue */
  13998. static int
  13999. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14000. {
  14001. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14002. (void)thread_index;
  14003. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14004. DEBUG_TRACE("%s", "going idle");
  14005. /* If the queue is empty, wait. We're idle at this point. */
  14006. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  14007. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  14008. }
  14009. /* If we're stopping, sq_head may be equal to sq_tail. */
  14010. if (ctx->sq_head > ctx->sq_tail) {
  14011. /* Copy socket from the queue and increment tail */
  14012. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  14013. ctx->sq_tail++;
  14014. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14015. /* Wrap pointers if needed */
  14016. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  14017. ctx->sq_tail -= QUEUE_SIZE(ctx);
  14018. ctx->sq_head -= QUEUE_SIZE(ctx);
  14019. }
  14020. }
  14021. (void)pthread_cond_signal(&ctx->sq_empty);
  14022. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14023. return !ctx->stop_flag;
  14024. #undef QUEUE_SIZE
  14025. }
  14026. /* Master thread adds accepted socket to a queue */
  14027. static void
  14028. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14029. {
  14030. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14031. if (!ctx) {
  14032. return;
  14033. }
  14034. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14035. /* If the queue is full, wait */
  14036. while ((ctx->stop_flag == 0)
  14037. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  14038. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  14039. }
  14040. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  14041. /* Copy socket to the queue and increment head */
  14042. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  14043. ctx->sq_head++;
  14044. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  14045. }
  14046. (void)pthread_cond_signal(&ctx->sq_full);
  14047. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14048. #undef QUEUE_SIZE
  14049. }
  14050. #endif /* ALTERNATIVE_QUEUE */
  14051. struct worker_thread_args {
  14052. struct mg_context *ctx;
  14053. int index;
  14054. };
  14055. static void *
  14056. worker_thread_run(struct worker_thread_args *thread_args)
  14057. {
  14058. struct mg_context *ctx = thread_args->ctx;
  14059. struct mg_connection *conn;
  14060. struct mg_workerTLS tls;
  14061. #if defined(MG_LEGACY_INTERFACE)
  14062. uint32_t addr;
  14063. #endif
  14064. mg_set_thread_name("worker");
  14065. tls.is_master = 0;
  14066. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14067. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14068. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14069. #endif
  14070. /* Initialize thread local storage before calling any callback */
  14071. pthread_setspecific(sTlsKey, &tls);
  14072. if (ctx->callbacks.init_thread) {
  14073. /* call init_thread for a worker thread (type 1) */
  14074. ctx->callbacks.init_thread(ctx, 1);
  14075. }
  14076. /* Connection structure has been pre-allocated */
  14077. if (((int)thread_args->index < 0)
  14078. || ((unsigned)thread_args->index
  14079. >= (unsigned)ctx->cfg_worker_threads)) {
  14080. mg_cry(fc(ctx),
  14081. "Internal error: Invalid worker index %i",
  14082. (int)thread_args->index);
  14083. return NULL;
  14084. }
  14085. conn = ctx->worker_connections + thread_args->index;
  14086. /* Request buffers are not pre-allocated. They are private to the
  14087. * request and do not contain any state information that might be
  14088. * of interest to anyone observing a server status. */
  14089. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->ctx);
  14090. if (conn->buf == NULL) {
  14091. mg_cry(fc(ctx),
  14092. "Out of memory: Cannot allocate buffer for worker %i",
  14093. (int)thread_args->index);
  14094. return NULL;
  14095. }
  14096. conn->buf_size = (int)ctx->max_request_size;
  14097. conn->ctx = ctx;
  14098. conn->thread_index = thread_args->index;
  14099. conn->request_info.user_data = ctx->user_data;
  14100. /* Allocate a mutex for this connection to allow communication both
  14101. * within the request handler and from elsewhere in the application
  14102. */
  14103. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  14104. #if defined(USE_SERVER_STATS)
  14105. conn->conn_state = 1; /* not consumed */
  14106. #endif
  14107. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  14108. * signal sq_empty condvar to wake up the master waiting in
  14109. * produce_socket() */
  14110. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  14111. conn->conn_birth_time = time(NULL);
  14112. /* Fill in IP, port info early so even if SSL setup below fails,
  14113. * error handler would have the corresponding info.
  14114. * Thanks to Johannes Winkelmann for the patch.
  14115. */
  14116. #if defined(USE_IPV6)
  14117. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  14118. conn->request_info.remote_port =
  14119. ntohs(conn->client.rsa.sin6.sin6_port);
  14120. } else
  14121. #endif
  14122. {
  14123. conn->request_info.remote_port =
  14124. ntohs(conn->client.rsa.sin.sin_port);
  14125. }
  14126. sockaddr_to_string(conn->request_info.remote_addr,
  14127. sizeof(conn->request_info.remote_addr),
  14128. &conn->client.rsa);
  14129. DEBUG_TRACE("Start processing connection from %s",
  14130. conn->request_info.remote_addr);
  14131. #if defined(MG_LEGACY_INTERFACE)
  14132. /* This legacy interface only works for the IPv4 case */
  14133. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  14134. memcpy(&conn->request_info.remote_ip, &addr, 4);
  14135. #endif
  14136. conn->request_info.is_ssl = conn->client.is_ssl;
  14137. if (conn->client.is_ssl) {
  14138. #ifndef NO_SSL
  14139. /* HTTPS connection */
  14140. if (sslize(conn,
  14141. conn->ctx->ssl_ctx,
  14142. SSL_accept,
  14143. &(conn->ctx->stop_flag))) {
  14144. /* Get SSL client certificate information (if set) */
  14145. ssl_get_client_cert_info(conn);
  14146. /* process HTTPS connection */
  14147. process_new_connection(conn);
  14148. /* Free client certificate info */
  14149. if (conn->request_info.client_cert) {
  14150. mg_free((void *)(conn->request_info.client_cert->subject));
  14151. mg_free((void *)(conn->request_info.client_cert->issuer));
  14152. mg_free((void *)(conn->request_info.client_cert->serial));
  14153. mg_free((void *)(conn->request_info.client_cert->finger));
  14154. /* Free certificate memory */
  14155. X509_free(
  14156. (X509 *)conn->request_info.client_cert->peer_cert);
  14157. conn->request_info.client_cert->peer_cert = 0;
  14158. conn->request_info.client_cert->subject = 0;
  14159. conn->request_info.client_cert->issuer = 0;
  14160. conn->request_info.client_cert->serial = 0;
  14161. conn->request_info.client_cert->finger = 0;
  14162. mg_free(conn->request_info.client_cert);
  14163. conn->request_info.client_cert = 0;
  14164. }
  14165. }
  14166. #endif
  14167. } else {
  14168. /* process HTTP connection */
  14169. process_new_connection(conn);
  14170. }
  14171. DEBUG_TRACE("%s", "Connection closed");
  14172. }
  14173. pthread_setspecific(sTlsKey, NULL);
  14174. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14175. CloseHandle(tls.pthread_cond_helper_mutex);
  14176. #endif
  14177. pthread_mutex_destroy(&conn->mutex);
  14178. /* Free the request buffer. */
  14179. conn->buf_size = 0;
  14180. mg_free(conn->buf);
  14181. conn->buf = NULL;
  14182. #if defined(USE_SERVER_STATS)
  14183. conn->conn_state = 9; /* done */
  14184. #endif
  14185. DEBUG_TRACE("%s", "exiting");
  14186. return NULL;
  14187. }
  14188. /* Threads have different return types on Windows and Unix. */
  14189. #ifdef _WIN32
  14190. static unsigned __stdcall worker_thread(void *thread_func_param)
  14191. {
  14192. struct worker_thread_args *pwta =
  14193. (struct worker_thread_args *)thread_func_param;
  14194. worker_thread_run(pwta);
  14195. mg_free(thread_func_param);
  14196. return 0;
  14197. }
  14198. #else
  14199. static void *
  14200. worker_thread(void *thread_func_param)
  14201. {
  14202. struct worker_thread_args *pwta =
  14203. (struct worker_thread_args *)thread_func_param;
  14204. worker_thread_run(pwta);
  14205. mg_free(thread_func_param);
  14206. return NULL;
  14207. }
  14208. #endif /* _WIN32 */
  14209. static void
  14210. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  14211. {
  14212. struct socket so;
  14213. char src_addr[IP_ADDR_STR_LEN];
  14214. socklen_t len = sizeof(so.rsa);
  14215. int on = 1;
  14216. if (!listener) {
  14217. return;
  14218. }
  14219. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  14220. == INVALID_SOCKET) {
  14221. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  14222. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  14223. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  14224. closesocket(so.sock);
  14225. } else {
  14226. /* Put so socket structure into the queue */
  14227. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  14228. set_close_on_exec(so.sock, fc(ctx));
  14229. so.is_ssl = listener->is_ssl;
  14230. so.ssl_redir = listener->ssl_redir;
  14231. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  14232. mg_cry(fc(ctx),
  14233. "%s: getsockname() failed: %s",
  14234. __func__,
  14235. strerror(ERRNO));
  14236. }
  14237. /* Set TCP keep-alive. This is needed because if HTTP-level
  14238. * keep-alive
  14239. * is enabled, and client resets the connection, server won't get
  14240. * TCP FIN or RST and will keep the connection open forever. With
  14241. * TCP keep-alive, next keep-alive handshake will figure out that
  14242. * the client is down and will close the server end.
  14243. * Thanks to Igor Klopov who suggested the patch. */
  14244. if (setsockopt(so.sock,
  14245. SOL_SOCKET,
  14246. SO_KEEPALIVE,
  14247. (SOCK_OPT_TYPE)&on,
  14248. sizeof(on)) != 0) {
  14249. mg_cry(fc(ctx),
  14250. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  14251. __func__,
  14252. strerror(ERRNO));
  14253. }
  14254. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  14255. * to effectively fill up the underlying IP packet payload and
  14256. * reduce the overhead of sending lots of small buffers. However
  14257. * this hurts the server's throughput (ie. operations per second)
  14258. * when HTTP 1.1 persistent connections are used and the responses
  14259. * are relatively small (eg. less than 1400 bytes).
  14260. */
  14261. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  14262. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  14263. if (set_tcp_nodelay(so.sock, 1) != 0) {
  14264. mg_cry(fc(ctx),
  14265. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  14266. __func__,
  14267. strerror(ERRNO));
  14268. }
  14269. }
  14270. /* We are using non-blocking sockets. Thus, the
  14271. * set_sock_timeout(so.sock, timeout);
  14272. * call is no longer required. */
  14273. /* The "non blocking" property should already be
  14274. * inherited from the parent socket. Set it for
  14275. * non-compliant socket implementations. */
  14276. set_non_blocking_mode(so.sock);
  14277. so.in_use = 0;
  14278. produce_socket(ctx, &so);
  14279. }
  14280. }
  14281. static void
  14282. master_thread_run(void *thread_func_param)
  14283. {
  14284. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  14285. struct mg_workerTLS tls;
  14286. struct pollfd *pfd;
  14287. unsigned int i;
  14288. unsigned int workerthreadcount;
  14289. if (!ctx) {
  14290. return;
  14291. }
  14292. mg_set_thread_name("master");
  14293. /* Increase priority of the master thread */
  14294. #if defined(_WIN32)
  14295. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  14296. #elif defined(USE_MASTER_THREAD_PRIORITY)
  14297. int min_prio = sched_get_priority_min(SCHED_RR);
  14298. int max_prio = sched_get_priority_max(SCHED_RR);
  14299. if ((min_prio >= 0) && (max_prio >= 0)
  14300. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  14301. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  14302. struct sched_param sched_param = {0};
  14303. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  14304. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  14305. }
  14306. #endif
  14307. /* Initialize thread local storage */
  14308. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14309. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14310. #endif
  14311. tls.is_master = 1;
  14312. pthread_setspecific(sTlsKey, &tls);
  14313. if (ctx->callbacks.init_thread) {
  14314. /* Callback for the master thread (type 0) */
  14315. ctx->callbacks.init_thread(ctx, 0);
  14316. }
  14317. /* Server starts *now* */
  14318. ctx->start_time = time(NULL);
  14319. /* Start the server */
  14320. pfd = ctx->listening_socket_fds;
  14321. while (ctx->stop_flag == 0) {
  14322. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14323. pfd[i].fd = ctx->listening_sockets[i].sock;
  14324. pfd[i].events = POLLIN;
  14325. }
  14326. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  14327. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14328. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  14329. * successful poll, and POLLIN is defined as
  14330. * (POLLRDNORM | POLLRDBAND)
  14331. * Therefore, we're checking pfd[i].revents & POLLIN, not
  14332. * pfd[i].revents == POLLIN. */
  14333. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  14334. accept_new_connection(&ctx->listening_sockets[i], ctx);
  14335. }
  14336. }
  14337. }
  14338. }
  14339. /* Here stop_flag is 1 - Initiate shutdown. */
  14340. DEBUG_TRACE("%s", "stopping workers");
  14341. /* Stop signal received: somebody called mg_stop. Quit. */
  14342. close_all_listening_sockets(ctx);
  14343. /* Wakeup workers that are waiting for connections to handle. */
  14344. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14345. #if defined(ALTERNATIVE_QUEUE)
  14346. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14347. event_signal(ctx->client_wait_events[i]);
  14348. /* Since we know all sockets, we can shutdown the connections. */
  14349. if (ctx->client_socks[i].in_use) {
  14350. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  14351. }
  14352. }
  14353. #else
  14354. pthread_cond_broadcast(&ctx->sq_full);
  14355. #endif
  14356. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14357. /* Join all worker threads to avoid leaking threads. */
  14358. workerthreadcount = ctx->cfg_worker_threads;
  14359. for (i = 0; i < workerthreadcount; i++) {
  14360. if (ctx->worker_threadids[i] != 0) {
  14361. mg_join_thread(ctx->worker_threadids[i]);
  14362. }
  14363. }
  14364. #if defined(USE_LUA)
  14365. /* Free Lua state of lua background task */
  14366. if (ctx->lua_background_state) {
  14367. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14368. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  14369. if (lua_istable(lstate, -1)) {
  14370. reg_boolean(lstate, "shutdown", 1);
  14371. lua_pop(lstate, 1);
  14372. mg_sleep(2);
  14373. }
  14374. lua_close(lstate);
  14375. ctx->lua_background_state = 0;
  14376. }
  14377. #endif
  14378. DEBUG_TRACE("%s", "exiting");
  14379. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14380. CloseHandle(tls.pthread_cond_helper_mutex);
  14381. #endif
  14382. pthread_setspecific(sTlsKey, NULL);
  14383. /* Signal mg_stop() that we're done.
  14384. * WARNING: This must be the very last thing this
  14385. * thread does, as ctx becomes invalid after this line. */
  14386. ctx->stop_flag = 2;
  14387. }
  14388. /* Threads have different return types on Windows and Unix. */
  14389. #ifdef _WIN32
  14390. static unsigned __stdcall master_thread(void *thread_func_param)
  14391. {
  14392. master_thread_run(thread_func_param);
  14393. return 0;
  14394. }
  14395. #else
  14396. static void *
  14397. master_thread(void *thread_func_param)
  14398. {
  14399. master_thread_run(thread_func_param);
  14400. return NULL;
  14401. }
  14402. #endif /* _WIN32 */
  14403. static void
  14404. free_context(struct mg_context *ctx)
  14405. {
  14406. int i;
  14407. struct mg_handler_info *tmp_rh;
  14408. if (ctx == NULL) {
  14409. return;
  14410. }
  14411. if (ctx->callbacks.exit_context) {
  14412. ctx->callbacks.exit_context(ctx);
  14413. }
  14414. /* All threads exited, no sync is needed. Destroy thread mutex and
  14415. * condvars
  14416. */
  14417. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  14418. #if defined(ALTERNATIVE_QUEUE)
  14419. mg_free(ctx->client_socks);
  14420. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14421. event_destroy(ctx->client_wait_events[i]);
  14422. }
  14423. mg_free(ctx->client_wait_events);
  14424. #else
  14425. (void)pthread_cond_destroy(&ctx->sq_empty);
  14426. (void)pthread_cond_destroy(&ctx->sq_full);
  14427. #endif
  14428. /* Destroy other context global data structures mutex */
  14429. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  14430. #if defined(USE_TIMERS)
  14431. timers_exit(ctx);
  14432. #endif
  14433. /* Deallocate config parameters */
  14434. for (i = 0; i < NUM_OPTIONS; i++) {
  14435. if (ctx->config[i] != NULL) {
  14436. #if defined(_MSC_VER)
  14437. #pragma warning(suppress : 6001)
  14438. #endif
  14439. mg_free(ctx->config[i]);
  14440. }
  14441. }
  14442. /* Deallocate request handlers */
  14443. while (ctx->handlers) {
  14444. tmp_rh = ctx->handlers;
  14445. ctx->handlers = tmp_rh->next;
  14446. mg_free(tmp_rh->uri);
  14447. mg_free(tmp_rh);
  14448. }
  14449. #ifndef NO_SSL
  14450. /* Deallocate SSL context */
  14451. if (ctx->ssl_ctx != NULL) {
  14452. void *ssl_ctx = (void *)ctx->ssl_ctx;
  14453. int callback_ret =
  14454. (ctx->callbacks.external_ssl_ctx == NULL)
  14455. ? 0
  14456. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  14457. if (callback_ret == 0) {
  14458. SSL_CTX_free(ctx->ssl_ctx);
  14459. }
  14460. // else ignore error and ommit SSL_CTX_free in case callback_ret is 1
  14461. }
  14462. #endif /* !NO_SSL */
  14463. /* Deallocate worker thread ID array */
  14464. if (ctx->worker_threadids != NULL) {
  14465. mg_free(ctx->worker_threadids);
  14466. }
  14467. /* Deallocate worker thread ID array */
  14468. if (ctx->worker_connections != NULL) {
  14469. mg_free(ctx->worker_connections);
  14470. }
  14471. /* deallocate system name string */
  14472. mg_free(ctx->systemName);
  14473. /* Deallocate context itself */
  14474. mg_free(ctx);
  14475. }
  14476. void
  14477. mg_stop(struct mg_context *ctx)
  14478. {
  14479. pthread_t mt;
  14480. if (!ctx) {
  14481. return;
  14482. }
  14483. /* We don't use a lock here. Calling mg_stop with the same ctx from
  14484. * two threads is not allowed. */
  14485. mt = ctx->masterthreadid;
  14486. if (mt == 0) {
  14487. return;
  14488. }
  14489. ctx->masterthreadid = 0;
  14490. /* Set stop flag, so all threads know they have to exit. */
  14491. ctx->stop_flag = 1;
  14492. /* Wait until everything has stopped. */
  14493. while (ctx->stop_flag != 2) {
  14494. (void)mg_sleep(10);
  14495. }
  14496. mg_join_thread(mt);
  14497. free_context(ctx);
  14498. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14499. (void)WSACleanup();
  14500. #endif /* _WIN32 && !__SYMBIAN32__ */
  14501. }
  14502. static void
  14503. get_system_name(char **sysName)
  14504. {
  14505. #if defined(_WIN32)
  14506. #if !defined(__SYMBIAN32__)
  14507. #if defined(_WIN32_WCE)
  14508. *sysName = mg_strdup("WinCE");
  14509. #else
  14510. char name[128];
  14511. DWORD dwVersion = 0;
  14512. DWORD dwMajorVersion = 0;
  14513. DWORD dwMinorVersion = 0;
  14514. DWORD dwBuild = 0;
  14515. BOOL wowRet, isWoW = FALSE;
  14516. #ifdef _MSC_VER
  14517. #pragma warning(push)
  14518. /* GetVersion was declared deprecated */
  14519. #pragma warning(disable : 4996)
  14520. #endif
  14521. dwVersion = GetVersion();
  14522. #ifdef _MSC_VER
  14523. #pragma warning(pop)
  14524. #endif
  14525. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14526. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14527. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  14528. (void)dwBuild;
  14529. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  14530. sprintf(name,
  14531. "Windows %u.%u%s",
  14532. (unsigned)dwMajorVersion,
  14533. (unsigned)dwMinorVersion,
  14534. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  14535. *sysName = mg_strdup(name);
  14536. #endif
  14537. #else
  14538. *sysName = mg_strdup("Symbian");
  14539. #endif
  14540. #else
  14541. struct utsname name;
  14542. memset(&name, 0, sizeof(name));
  14543. uname(&name);
  14544. *sysName = mg_strdup(name.sysname);
  14545. #endif
  14546. }
  14547. struct mg_context *
  14548. mg_start(const struct mg_callbacks *callbacks,
  14549. void *user_data,
  14550. const char **options)
  14551. {
  14552. struct mg_context *ctx;
  14553. const char *name, *value, *default_value;
  14554. int idx, ok, workerthreadcount;
  14555. unsigned int i;
  14556. int itmp;
  14557. void (*exit_callback)(const struct mg_context *ctx) = 0;
  14558. struct mg_workerTLS tls;
  14559. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14560. WSADATA data;
  14561. WSAStartup(MAKEWORD(2, 2), &data);
  14562. #endif /* _WIN32 && !__SYMBIAN32__ */
  14563. /* Allocate context and initialize reasonable general case defaults. */
  14564. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  14565. return NULL;
  14566. }
  14567. /* Random number generator will initialize at the first call */
  14568. ctx->auth_nonce_mask =
  14569. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  14570. if (mg_init_library_called == 0) {
  14571. /* Legacy INIT, if mg_start is called without mg_init_library.
  14572. * Note: This may cause a memory leak */
  14573. const char *ports_option =
  14574. config_options[LISTENING_PORTS].default_value;
  14575. if (options) {
  14576. const char **run_options = options;
  14577. const char *optname = config_options[LISTENING_PORTS].name;
  14578. /* Try to find the "listening_ports" option */
  14579. while (*run_options) {
  14580. if (!strcmp(*run_options, optname)) {
  14581. ports_option = run_options[1];
  14582. }
  14583. run_options += 2;
  14584. }
  14585. }
  14586. if (is_ssl_port_used(ports_option)) {
  14587. /* Initialize with SSL support */
  14588. mg_init_library(MG_FEATURES_TLS);
  14589. } else {
  14590. /* Initialize without SSL support */
  14591. mg_init_library(MG_FEATURES_DEFAULT);
  14592. }
  14593. }
  14594. tls.is_master = -1;
  14595. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14596. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14597. tls.pthread_cond_helper_mutex = NULL;
  14598. #endif
  14599. pthread_setspecific(sTlsKey, &tls);
  14600. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  14601. #if !defined(ALTERNATIVE_QUEUE)
  14602. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  14603. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  14604. #endif
  14605. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  14606. if (!ok) {
  14607. /* Fatal error - abort start. However, this situation should never
  14608. * occur in practice. */
  14609. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  14610. mg_free(ctx);
  14611. pthread_setspecific(sTlsKey, NULL);
  14612. return NULL;
  14613. }
  14614. if (callbacks) {
  14615. ctx->callbacks = *callbacks;
  14616. exit_callback = callbacks->exit_context;
  14617. ctx->callbacks.exit_context = 0;
  14618. }
  14619. ctx->user_data = user_data;
  14620. ctx->handlers = NULL;
  14621. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14622. ctx->shared_lua_websockets = 0;
  14623. #endif
  14624. while (options && (name = *options++) != NULL) {
  14625. if ((idx = get_option_index(name)) == -1) {
  14626. mg_cry(fc(ctx), "Invalid option: %s", name);
  14627. free_context(ctx);
  14628. pthread_setspecific(sTlsKey, NULL);
  14629. return NULL;
  14630. } else if ((value = *options++) == NULL) {
  14631. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  14632. free_context(ctx);
  14633. pthread_setspecific(sTlsKey, NULL);
  14634. return NULL;
  14635. }
  14636. if (ctx->config[idx] != NULL) {
  14637. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  14638. mg_free(ctx->config[idx]);
  14639. }
  14640. ctx->config[idx] = mg_strdup(value);
  14641. DEBUG_TRACE("[%s] -> [%s]", name, value);
  14642. }
  14643. /* Set default value if needed */
  14644. for (i = 0; config_options[i].name != NULL; i++) {
  14645. default_value = config_options[i].default_value;
  14646. if ((ctx->config[i] == NULL) && (default_value != NULL)) {
  14647. ctx->config[i] = mg_strdup(default_value);
  14648. }
  14649. }
  14650. itmp = atoi(ctx->config[MAX_REQUEST_SIZE]);
  14651. if (itmp < 1024) {
  14652. mg_cry(fc(ctx), "max_request_size too small");
  14653. free_context(ctx);
  14654. pthread_setspecific(sTlsKey, NULL);
  14655. return NULL;
  14656. }
  14657. ctx->max_request_size = (unsigned)itmp;
  14658. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  14659. if (workerthreadcount > MAX_WORKER_THREADS) {
  14660. mg_cry(fc(ctx), "Too many worker threads");
  14661. free_context(ctx);
  14662. pthread_setspecific(sTlsKey, NULL);
  14663. return NULL;
  14664. }
  14665. if (workerthreadcount <= 0) {
  14666. mg_cry(fc(ctx), "Invalid number of worker threads");
  14667. free_context(ctx);
  14668. pthread_setspecific(sTlsKey, NULL);
  14669. return NULL;
  14670. }
  14671. #if defined(NO_FILES)
  14672. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  14673. mg_cry(fc(ctx), "%s", "Document root must not be set");
  14674. free_context(ctx);
  14675. pthread_setspecific(sTlsKey, NULL);
  14676. return NULL;
  14677. }
  14678. #endif
  14679. get_system_name(&ctx->systemName);
  14680. #if defined(USE_LUA)
  14681. /* If a Lua background script has been configured, start it. */
  14682. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  14683. char ebuf[256];
  14684. lua_State *state = (void *)mg_prepare_lua_context_script(
  14685. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  14686. if (!state) {
  14687. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  14688. free_context(ctx);
  14689. pthread_setspecific(sTlsKey, NULL);
  14690. return NULL;
  14691. }
  14692. ctx->lua_background_state = (void *)state;
  14693. lua_newtable(state);
  14694. reg_boolean(state, "shutdown", 0);
  14695. struct vec opt_vec;
  14696. struct vec eq_vec;
  14697. const char *sparams = ctx->config[LUA_BACKGROUND_SCRIPT_PARAMS];
  14698. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  14699. reg_llstring(
  14700. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  14701. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  14702. break;
  14703. }
  14704. lua_setglobal(state, LUABACKGROUNDPARAMS);
  14705. } else {
  14706. ctx->lua_background_state = 0;
  14707. }
  14708. #endif
  14709. /* NOTE(lsm): order is important here. SSL certificates must
  14710. * be initialized before listening ports. UID must be set last. */
  14711. if (!set_gpass_option(ctx) ||
  14712. #if !defined(NO_SSL)
  14713. !init_ssl_ctx(ctx) ||
  14714. #endif
  14715. !set_ports_option(ctx) ||
  14716. #if !defined(_WIN32)
  14717. !set_uid_option(ctx) ||
  14718. #endif
  14719. !set_acl_option(ctx)) {
  14720. free_context(ctx);
  14721. pthread_setspecific(sTlsKey, NULL);
  14722. return NULL;
  14723. }
  14724. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  14725. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  14726. * won't kill the whole process. */
  14727. (void)signal(SIGPIPE, SIG_IGN);
  14728. #endif /* !_WIN32 && !__SYMBIAN32__ */
  14729. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  14730. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14731. sizeof(pthread_t),
  14732. ctx);
  14733. if (ctx->worker_threadids == NULL) {
  14734. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  14735. free_context(ctx);
  14736. pthread_setspecific(sTlsKey, NULL);
  14737. return NULL;
  14738. }
  14739. ctx->worker_connections =
  14740. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14741. sizeof(struct mg_connection),
  14742. ctx);
  14743. if (ctx->worker_connections == NULL) {
  14744. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  14745. free_context(ctx);
  14746. pthread_setspecific(sTlsKey, NULL);
  14747. return NULL;
  14748. }
  14749. #if defined(ALTERNATIVE_QUEUE)
  14750. ctx->client_wait_events =
  14751. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  14752. ctx->cfg_worker_threads,
  14753. ctx);
  14754. if (ctx->client_wait_events == NULL) {
  14755. mg_cry(fc(ctx), "Not enough memory for worker event array");
  14756. mg_free(ctx->worker_threadids);
  14757. free_context(ctx);
  14758. pthread_setspecific(sTlsKey, NULL);
  14759. return NULL;
  14760. }
  14761. ctx->client_socks =
  14762. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  14763. ctx->cfg_worker_threads,
  14764. ctx);
  14765. if (ctx->client_wait_events == NULL) {
  14766. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  14767. mg_free(ctx->client_socks);
  14768. mg_free(ctx->worker_threadids);
  14769. free_context(ctx);
  14770. pthread_setspecific(sTlsKey, NULL);
  14771. return NULL;
  14772. }
  14773. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14774. ctx->client_wait_events[i] = event_create();
  14775. if (ctx->client_wait_events[i] == 0) {
  14776. mg_cry(fc(ctx), "Error creating worker event %i", i);
  14777. while (i > 0) {
  14778. i--;
  14779. event_destroy(ctx->client_wait_events[i]);
  14780. }
  14781. mg_free(ctx->client_socks);
  14782. mg_free(ctx->worker_threadids);
  14783. free_context(ctx);
  14784. pthread_setspecific(sTlsKey, NULL);
  14785. return NULL;
  14786. }
  14787. }
  14788. #endif
  14789. #if defined(USE_TIMERS)
  14790. if (timers_init(ctx) != 0) {
  14791. mg_cry(fc(ctx), "Error creating timers");
  14792. free_context(ctx);
  14793. pthread_setspecific(sTlsKey, NULL);
  14794. return NULL;
  14795. }
  14796. #endif
  14797. /* Context has been created - init user libraries */
  14798. if (ctx->callbacks.init_context) {
  14799. ctx->callbacks.init_context(ctx);
  14800. }
  14801. ctx->callbacks.exit_context = exit_callback;
  14802. ctx->context_type = CONTEXT_SERVER; /* server context */
  14803. /* Start master (listening) thread */
  14804. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  14805. /* Start worker threads */
  14806. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14807. struct worker_thread_args *wta = (struct worker_thread_args *)
  14808. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  14809. if (wta) {
  14810. wta->ctx = ctx;
  14811. wta->index = (int)i;
  14812. }
  14813. if ((wta == NULL)
  14814. || (mg_start_thread_with_id(worker_thread,
  14815. wta,
  14816. &ctx->worker_threadids[i]) != 0)) {
  14817. /* thread was not created */
  14818. if (wta != NULL) {
  14819. mg_free(wta);
  14820. }
  14821. if (i > 0) {
  14822. mg_cry(fc(ctx),
  14823. "Cannot start worker thread %i: error %ld",
  14824. i + 1,
  14825. (long)ERRNO);
  14826. } else {
  14827. mg_cry(fc(ctx),
  14828. "Cannot create threads: error %ld",
  14829. (long)ERRNO);
  14830. free_context(ctx);
  14831. pthread_setspecific(sTlsKey, NULL);
  14832. return NULL;
  14833. }
  14834. break;
  14835. }
  14836. }
  14837. pthread_setspecific(sTlsKey, NULL);
  14838. return ctx;
  14839. }
  14840. /* Feature check API function */
  14841. unsigned
  14842. mg_check_feature(unsigned feature)
  14843. {
  14844. static const unsigned feature_set = 0
  14845. /* Set bits for available features according to API documentation.
  14846. * This bit mask is created at compile time, according to the active
  14847. * preprocessor defines. It is a single const value at runtime. */
  14848. #if !defined(NO_FILES)
  14849. | 0x0001u
  14850. #endif
  14851. #if !defined(NO_SSL)
  14852. | 0x0002u
  14853. #endif
  14854. #if !defined(NO_CGI)
  14855. | 0x0004u
  14856. #endif
  14857. #if defined(USE_IPV6)
  14858. | 0x0008u
  14859. #endif
  14860. #if defined(USE_WEBSOCKET)
  14861. | 0x0010u
  14862. #endif
  14863. #if defined(USE_LUA)
  14864. | 0x0020u
  14865. #endif
  14866. #if defined(USE_DUKTAPE)
  14867. | 0x0040u
  14868. #endif
  14869. #if !defined(NO_CACHING)
  14870. | 0x0080u
  14871. #endif
  14872. #if defined(USE_SERVER_STATS)
  14873. | 0x0100u
  14874. #endif
  14875. /* Set some extra bits not defined in the API documentation.
  14876. * These bits may change without further notice. */
  14877. #if defined(MG_LEGACY_INTERFACE)
  14878. | 0x8000u
  14879. #endif
  14880. #if defined(MEMORY_DEBUGGING)
  14881. | 0x0100u
  14882. #endif
  14883. #if defined(USE_TIMERS)
  14884. | 0x0200u
  14885. #endif
  14886. #if !defined(NO_NONCE_CHECK)
  14887. | 0x0400u
  14888. #endif
  14889. #if !defined(NO_POPEN)
  14890. | 0x0800u
  14891. #endif
  14892. ;
  14893. return (feature & feature_set);
  14894. }
  14895. /* strcat with additional NULL check to avoid clang scan-build warning. */
  14896. #define strcat0(a, b) \
  14897. { \
  14898. if ((a != NULL) && (b != NULL)) { \
  14899. strcat(a, b); \
  14900. } \
  14901. }
  14902. /* Get system information. It can be printed or stored by the caller.
  14903. * Return the size of available information. */
  14904. static int
  14905. mg_get_system_info_impl(char *buffer, int buflen)
  14906. {
  14907. char block[256];
  14908. int system_info_length = 0;
  14909. #if defined(_WIN32)
  14910. const char *eol = "\r\n";
  14911. #else
  14912. const char *eol = "\n";
  14913. #endif
  14914. const char *eoobj = "}";
  14915. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  14916. if ((buffer == NULL) || (buflen < 1)) {
  14917. buflen = 0;
  14918. } else {
  14919. *buffer = 0;
  14920. }
  14921. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  14922. system_info_length += (int)strlen(block);
  14923. if (system_info_length < buflen) {
  14924. strcat0(buffer, block);
  14925. }
  14926. /* Server version */
  14927. {
  14928. const char *version = mg_version();
  14929. mg_snprintf(NULL,
  14930. NULL,
  14931. block,
  14932. sizeof(block),
  14933. "\"version\" : \"%s\",%s",
  14934. version,
  14935. eol);
  14936. system_info_length += (int)strlen(block);
  14937. if (system_info_length < buflen) {
  14938. strcat0(buffer, block);
  14939. }
  14940. }
  14941. /* System info */
  14942. {
  14943. #if defined(_WIN32)
  14944. #if !defined(__SYMBIAN32__)
  14945. DWORD dwVersion = 0;
  14946. DWORD dwMajorVersion = 0;
  14947. DWORD dwMinorVersion = 0;
  14948. SYSTEM_INFO si;
  14949. GetSystemInfo(&si);
  14950. #ifdef _MSC_VER
  14951. #pragma warning(push)
  14952. /* GetVersion was declared deprecated */
  14953. #pragma warning(disable : 4996)
  14954. #endif
  14955. dwVersion = GetVersion();
  14956. #ifdef _MSC_VER
  14957. #pragma warning(pop)
  14958. #endif
  14959. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14960. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14961. mg_snprintf(NULL,
  14962. NULL,
  14963. block,
  14964. sizeof(block),
  14965. "\"os\" : \"Windows %u.%u\",%s",
  14966. (unsigned)dwMajorVersion,
  14967. (unsigned)dwMinorVersion,
  14968. eol);
  14969. system_info_length += (int)strlen(block);
  14970. if (system_info_length < buflen) {
  14971. strcat0(buffer, block);
  14972. }
  14973. mg_snprintf(NULL,
  14974. NULL,
  14975. block,
  14976. sizeof(block),
  14977. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  14978. (unsigned)si.wProcessorArchitecture,
  14979. (unsigned)si.dwNumberOfProcessors,
  14980. (unsigned)si.dwActiveProcessorMask,
  14981. eol);
  14982. system_info_length += (int)strlen(block);
  14983. if (system_info_length < buflen) {
  14984. strcat0(buffer, block);
  14985. }
  14986. #else
  14987. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  14988. system_info_length += (int)strlen(block);
  14989. if (system_info_length < buflen) {
  14990. strcat0(buffer, block);
  14991. }
  14992. #endif
  14993. #else
  14994. struct utsname name;
  14995. memset(&name, 0, sizeof(name));
  14996. uname(&name);
  14997. mg_snprintf(NULL,
  14998. NULL,
  14999. block,
  15000. sizeof(block),
  15001. "\"os\" : \"%s %s (%s) - %s\",%s",
  15002. name.sysname,
  15003. name.version,
  15004. name.release,
  15005. name.machine,
  15006. eol);
  15007. system_info_length += (int)strlen(block);
  15008. if (system_info_length < buflen) {
  15009. strcat0(buffer, block);
  15010. }
  15011. #endif
  15012. }
  15013. /* Features */
  15014. {
  15015. mg_snprintf(NULL,
  15016. NULL,
  15017. block,
  15018. sizeof(block),
  15019. "\"features\" : %lu,%s"
  15020. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  15021. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  15022. eol,
  15023. mg_check_feature(1) ? " Files" : "",
  15024. mg_check_feature(2) ? " HTTPS" : "",
  15025. mg_check_feature(4) ? " CGI" : "",
  15026. mg_check_feature(8) ? " IPv6" : "",
  15027. mg_check_feature(16) ? " WebSockets" : "",
  15028. mg_check_feature(32) ? " Lua" : "",
  15029. mg_check_feature(64) ? " JavaScript" : "",
  15030. mg_check_feature(128) ? " Cache" : "",
  15031. mg_check_feature(256) ? " Stats" : "",
  15032. eol);
  15033. system_info_length += (int)strlen(block);
  15034. if (system_info_length < buflen) {
  15035. strcat0(buffer, block);
  15036. }
  15037. #ifdef USE_LUA
  15038. mg_snprintf(NULL,
  15039. NULL,
  15040. block,
  15041. sizeof(block),
  15042. "\"lua_version\" : \"%u (%s)\",%s",
  15043. (unsigned)LUA_VERSION_NUM,
  15044. LUA_RELEASE,
  15045. eol);
  15046. system_info_length += (int)strlen(block);
  15047. if (system_info_length < buflen) {
  15048. strcat0(buffer, block);
  15049. }
  15050. #endif
  15051. #if defined(USE_DUKTAPE)
  15052. mg_snprintf(NULL,
  15053. NULL,
  15054. block,
  15055. sizeof(block),
  15056. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  15057. (unsigned)DUK_VERSION / 10000,
  15058. ((unsigned)DUK_VERSION / 100) % 100,
  15059. (unsigned)DUK_VERSION % 100,
  15060. eol);
  15061. system_info_length += (int)strlen(block);
  15062. if (system_info_length < buflen) {
  15063. strcat0(buffer, block);
  15064. }
  15065. #endif
  15066. }
  15067. /* Build date */
  15068. {
  15069. #if defined(__GNUC__)
  15070. #pragma GCC diagnostic push
  15071. /* Disable bogus compiler warning -Wdate-time */
  15072. #pragma GCC diagnostic ignored "-Wall"
  15073. #pragma GCC diagnostic ignored "-Werror"
  15074. #endif
  15075. mg_snprintf(NULL,
  15076. NULL,
  15077. block,
  15078. sizeof(block),
  15079. "\"build\" : \"%s\",%s",
  15080. __DATE__,
  15081. eol);
  15082. #if defined(__GNUC__)
  15083. #pragma GCC diagnostic pop
  15084. #endif
  15085. system_info_length += (int)strlen(block);
  15086. if (system_info_length < buflen) {
  15087. strcat0(buffer, block);
  15088. }
  15089. }
  15090. /* Compiler information */
  15091. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  15092. {
  15093. #if defined(_MSC_VER)
  15094. mg_snprintf(NULL,
  15095. NULL,
  15096. block,
  15097. sizeof(block),
  15098. "\"compiler\" : \"MSC: %u (%u)\",%s",
  15099. (unsigned)_MSC_VER,
  15100. (unsigned)_MSC_FULL_VER,
  15101. eol);
  15102. system_info_length += (int)strlen(block);
  15103. if (system_info_length < buflen) {
  15104. strcat0(buffer, block);
  15105. }
  15106. #elif defined(__MINGW64__)
  15107. mg_snprintf(NULL,
  15108. NULL,
  15109. block,
  15110. sizeof(block),
  15111. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  15112. (unsigned)__MINGW64_VERSION_MAJOR,
  15113. (unsigned)__MINGW64_VERSION_MINOR,
  15114. eol);
  15115. system_info_length += (int)strlen(block);
  15116. if (system_info_length < buflen) {
  15117. strcat0(buffer, block);
  15118. }
  15119. mg_snprintf(NULL,
  15120. NULL,
  15121. block,
  15122. sizeof(block),
  15123. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15124. (unsigned)__MINGW32_MAJOR_VERSION,
  15125. (unsigned)__MINGW32_MINOR_VERSION,
  15126. eol);
  15127. system_info_length += (int)strlen(block);
  15128. if (system_info_length < buflen) {
  15129. strcat0(buffer, block);
  15130. }
  15131. #elif defined(__MINGW32__)
  15132. mg_snprintf(NULL,
  15133. NULL,
  15134. block,
  15135. sizeof(block),
  15136. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15137. (unsigned)__MINGW32_MAJOR_VERSION,
  15138. (unsigned)__MINGW32_MINOR_VERSION,
  15139. eol);
  15140. system_info_length += (int)strlen(block);
  15141. if (system_info_length < buflen) {
  15142. strcat0(buffer, block);
  15143. }
  15144. #elif defined(__clang__)
  15145. mg_snprintf(NULL,
  15146. NULL,
  15147. block,
  15148. sizeof(block),
  15149. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  15150. __clang_major__,
  15151. __clang_minor__,
  15152. __clang_patchlevel__,
  15153. __clang_version__,
  15154. eol);
  15155. system_info_length += (int)strlen(block);
  15156. if (system_info_length < buflen) {
  15157. strcat0(buffer, block);
  15158. }
  15159. #elif defined(__GNUC__)
  15160. mg_snprintf(NULL,
  15161. NULL,
  15162. block,
  15163. sizeof(block),
  15164. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  15165. (unsigned)__GNUC__,
  15166. (unsigned)__GNUC_MINOR__,
  15167. (unsigned)__GNUC_PATCHLEVEL__,
  15168. eol);
  15169. system_info_length += (int)strlen(block);
  15170. if (system_info_length < buflen) {
  15171. strcat0(buffer, block);
  15172. }
  15173. #elif defined(__INTEL_COMPILER)
  15174. mg_snprintf(NULL,
  15175. NULL,
  15176. block,
  15177. sizeof(block),
  15178. "\"compiler\" : \"Intel C/C++: %u\",%s",
  15179. (unsigned)__INTEL_COMPILER,
  15180. eol);
  15181. system_info_length += (int)strlen(block);
  15182. if (system_info_length < buflen) {
  15183. strcat0(buffer, block);
  15184. }
  15185. #elif defined(__BORLANDC__)
  15186. mg_snprintf(NULL,
  15187. NULL,
  15188. block,
  15189. sizeof(block),
  15190. "\"compiler\" : \"Borland C: 0x%x\",%s",
  15191. (unsigned)__BORLANDC__,
  15192. eol);
  15193. system_info_length += (int)strlen(block);
  15194. if (system_info_length < buflen) {
  15195. strcat0(buffer, block);
  15196. }
  15197. #elif defined(__SUNPRO_C)
  15198. mg_snprintf(NULL,
  15199. NULL,
  15200. block,
  15201. sizeof(block),
  15202. "\"compiler\" : \"Solaris: 0x%x\",%s",
  15203. (unsigned)__SUNPRO_C,
  15204. eol);
  15205. system_info_length += (int)strlen(block);
  15206. if (system_info_length < buflen) {
  15207. strcat0(buffer, block);
  15208. }
  15209. #else
  15210. mg_snprintf(NULL,
  15211. NULL,
  15212. block,
  15213. sizeof(block),
  15214. "\"compiler\" : \"other\",%s",
  15215. eol);
  15216. system_info_length += (int)strlen(block);
  15217. if (system_info_length < buflen) {
  15218. strcat0(buffer, block);
  15219. }
  15220. #endif
  15221. }
  15222. /* Determine 32/64 bit data mode.
  15223. * see https://en.wikipedia.org/wiki/64-bit_computing */
  15224. {
  15225. mg_snprintf(
  15226. NULL,
  15227. NULL,
  15228. block,
  15229. sizeof(block),
  15230. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  15231. "ptr:%u, size:%u, time:%u\"%s",
  15232. (unsigned)sizeof(short),
  15233. (unsigned)sizeof(int),
  15234. (unsigned)sizeof(long),
  15235. (unsigned)sizeof(long long),
  15236. (unsigned)sizeof(float),
  15237. (unsigned)sizeof(double),
  15238. (unsigned)sizeof(long double),
  15239. (unsigned)sizeof(char),
  15240. (unsigned)sizeof(wchar_t),
  15241. (unsigned)sizeof(void *),
  15242. (unsigned)sizeof(size_t),
  15243. (unsigned)sizeof(time_t),
  15244. eol);
  15245. system_info_length += (int)strlen(block);
  15246. if (system_info_length < buflen) {
  15247. strcat0(buffer, block);
  15248. }
  15249. }
  15250. /* Terminate string */
  15251. if ((buflen > 0) && buffer && buffer[0]) {
  15252. if (system_info_length < buflen) {
  15253. strcat0(buffer, eoobj);
  15254. strcat0(buffer, eol);
  15255. }
  15256. }
  15257. system_info_length += reserved_len;
  15258. return system_info_length;
  15259. }
  15260. #if defined(USE_SERVER_STATS)
  15261. /* Get context information. It can be printed or stored by the caller.
  15262. * Return the size of available information. */
  15263. static int
  15264. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  15265. {
  15266. char block[256];
  15267. int context_info_length = 0;
  15268. #if defined(_WIN32)
  15269. const char *eol = "\r\n";
  15270. #else
  15271. const char *eol = "\n";
  15272. #endif
  15273. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  15274. const char *eoobj = "}";
  15275. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15276. if ((buffer == NULL) || (buflen < 1)) {
  15277. buflen = 0;
  15278. } else {
  15279. *buffer = 0;
  15280. }
  15281. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15282. context_info_length += (int)strlen(block);
  15283. if (context_info_length < buflen) {
  15284. strcat0(buffer, block);
  15285. }
  15286. /* Memory information */
  15287. if (ms) {
  15288. mg_snprintf(NULL,
  15289. NULL,
  15290. block,
  15291. sizeof(block),
  15292. "\"memory\" : {%s"
  15293. "\"blocks\" : %i,%s"
  15294. "\"used\" : %" INT64_FMT ",%s"
  15295. "\"maxUsed\" : %" INT64_FMT "%s"
  15296. "}%s%s",
  15297. eol,
  15298. ms->blockCount,
  15299. eol,
  15300. ms->totalMemUsed,
  15301. eol,
  15302. ms->maxMemUsed,
  15303. eol,
  15304. (ctx ? "," : ""),
  15305. eol);
  15306. context_info_length += (int)strlen(block);
  15307. if (context_info_length + reserved_len < buflen) {
  15308. strcat0(buffer, block);
  15309. }
  15310. }
  15311. /* Connections information */
  15312. if (ctx) {
  15313. mg_snprintf(NULL,
  15314. NULL,
  15315. block,
  15316. sizeof(block),
  15317. "\"connections\" : {%s"
  15318. "\"active\" : %i,%s"
  15319. "\"maxActive\" : %i,%s"
  15320. "\"total\" : %" INT64_FMT "%s"
  15321. "},%s",
  15322. eol,
  15323. ctx->active_connections,
  15324. eol,
  15325. ctx->max_connections,
  15326. eol,
  15327. ctx->total_connections,
  15328. eol,
  15329. eol);
  15330. context_info_length += (int)strlen(block);
  15331. if (context_info_length + reserved_len < buflen) {
  15332. strcat0(buffer, block);
  15333. }
  15334. }
  15335. /* Requests information */
  15336. if (ctx) {
  15337. mg_snprintf(NULL,
  15338. NULL,
  15339. block,
  15340. sizeof(block),
  15341. "\"requests\" : {%s"
  15342. "\"total\" : %" INT64_FMT "%s"
  15343. "},%s",
  15344. eol,
  15345. ctx->total_requests,
  15346. eol,
  15347. eol);
  15348. context_info_length += (int)strlen(block);
  15349. if (context_info_length + reserved_len < buflen) {
  15350. strcat0(buffer, block);
  15351. }
  15352. }
  15353. /* Data information */
  15354. if (ctx) {
  15355. mg_snprintf(NULL,
  15356. NULL,
  15357. block,
  15358. sizeof(block),
  15359. "\"data\" : {%s"
  15360. "\"read\" : %" INT64_FMT "%s,"
  15361. "\"written\" : %" INT64_FMT "%s"
  15362. "},%s",
  15363. eol,
  15364. ctx->total_data_read,
  15365. eol,
  15366. ctx->total_data_written,
  15367. eol,
  15368. eol);
  15369. context_info_length += (int)strlen(block);
  15370. if (context_info_length + reserved_len < buflen) {
  15371. strcat0(buffer, block);
  15372. }
  15373. }
  15374. /* Execution time information */
  15375. if (ctx) {
  15376. char start_time_str[64] = {0};
  15377. char now_str[64] = {0};
  15378. time_t start_time = ctx->start_time;
  15379. time_t now = time(NULL);
  15380. gmt_time_string(start_time_str,
  15381. sizeof(start_time_str) - 1,
  15382. &start_time);
  15383. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15384. mg_snprintf(NULL,
  15385. NULL,
  15386. block,
  15387. sizeof(block),
  15388. "\"time\" : {%s"
  15389. "\"uptime\" : %.0f,%s"
  15390. "\"start\" : \"%s\",%s"
  15391. "\"now\" : \"%s\"%s"
  15392. "}%s",
  15393. eol,
  15394. difftime(now, start_time),
  15395. eol,
  15396. start_time_str,
  15397. eol,
  15398. now_str,
  15399. eol,
  15400. eol);
  15401. context_info_length += (int)strlen(block);
  15402. if (context_info_length + reserved_len < buflen) {
  15403. strcat0(buffer, block);
  15404. }
  15405. }
  15406. /* Terminate string */
  15407. if ((buflen > 0) && buffer && buffer[0]) {
  15408. if (context_info_length < buflen) {
  15409. strcat0(buffer, eoobj);
  15410. strcat0(buffer, eol);
  15411. }
  15412. }
  15413. context_info_length += reserved_len;
  15414. return context_info_length;
  15415. }
  15416. #endif
  15417. #ifdef MG_EXPERIMENTAL_INTERFACES
  15418. /* Get connection information. It can be printed or stored by the caller.
  15419. * Return the size of available information. */
  15420. static int
  15421. mg_get_connection_info_impl(const struct mg_context *ctx,
  15422. int idx,
  15423. char *buffer,
  15424. int buflen)
  15425. {
  15426. const struct mg_connection *conn;
  15427. const struct mg_request_info *ri;
  15428. char block[256];
  15429. int connection_info_length = 0;
  15430. int state = 0;
  15431. const char *state_str = "unknown";
  15432. #if defined(_WIN32)
  15433. const char *eol = "\r\n";
  15434. #else
  15435. const char *eol = "\n";
  15436. #endif
  15437. const char *eoobj = "}";
  15438. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15439. if ((buffer == NULL) || (buflen < 1)) {
  15440. buflen = 0;
  15441. } else {
  15442. *buffer = 0;
  15443. }
  15444. if ((ctx == NULL) || (idx < 0)) {
  15445. /* Parameter error */
  15446. return 0;
  15447. }
  15448. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  15449. /* Out of range */
  15450. return 0;
  15451. }
  15452. /* Take connection [idx]. This connection is not locked in
  15453. * any way, so some other thread might use it. */
  15454. conn = (ctx->worker_connections) + idx;
  15455. /* Initialize output string */
  15456. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15457. connection_info_length += (int)strlen(block);
  15458. if (connection_info_length < buflen) {
  15459. strcat0(buffer, block);
  15460. }
  15461. /* Init variables */
  15462. ri = &(conn->request_info);
  15463. #if defined(USE_SERVER_STATS)
  15464. state = conn->conn_state;
  15465. /* State as string */
  15466. switch (state) {
  15467. case 0:
  15468. state_str = "undefined";
  15469. break;
  15470. case 1:
  15471. state_str = "not used";
  15472. break;
  15473. case 2:
  15474. state_str = "init";
  15475. break;
  15476. case 3:
  15477. state_str = "ready";
  15478. break;
  15479. case 4:
  15480. state_str = "processing";
  15481. break;
  15482. case 5:
  15483. state_str = "processed";
  15484. break;
  15485. case 6:
  15486. state_str = "to close";
  15487. break;
  15488. case 7:
  15489. state_str = "closing";
  15490. break;
  15491. case 8:
  15492. state_str = "closed";
  15493. break;
  15494. case 9:
  15495. state_str = "done";
  15496. break;
  15497. }
  15498. #endif
  15499. /* Connection info */
  15500. if ((state >= 3) && (state < 9)) {
  15501. mg_snprintf(NULL,
  15502. NULL,
  15503. block,
  15504. sizeof(block),
  15505. "\"connection\" : {%s"
  15506. "\"remote\" : {%s"
  15507. "\"protocol\" : \"%s\",%s"
  15508. "\"addr\" : \"%s\",%s"
  15509. "\"port\" : %u%s"
  15510. "},%s"
  15511. "\"handled_requests\" : %u%s"
  15512. "},%s",
  15513. eol,
  15514. eol,
  15515. get_proto_name(conn),
  15516. eol,
  15517. ri->remote_addr,
  15518. eol,
  15519. ri->remote_port,
  15520. eol,
  15521. eol,
  15522. conn->handled_requests,
  15523. eol,
  15524. eol);
  15525. connection_info_length += (int)strlen(block);
  15526. if (connection_info_length + reserved_len < buflen) {
  15527. strcat0(buffer, block);
  15528. }
  15529. }
  15530. /* Request info */
  15531. if ((state >= 4) && (state < 6)) {
  15532. mg_snprintf(NULL,
  15533. NULL,
  15534. block,
  15535. sizeof(block),
  15536. "\"request_info\" : {%s"
  15537. "\"method\" : \"%s\",%s"
  15538. "\"uri\" : \"%s\",%s"
  15539. "\"query\" : %s%s%s%s"
  15540. "},%s",
  15541. eol,
  15542. ri->request_method,
  15543. eol,
  15544. ri->request_uri,
  15545. eol,
  15546. ri->query_string ? "\"" : "",
  15547. ri->query_string ? ri->query_string : "null",
  15548. ri->query_string ? "\"" : "",
  15549. eol,
  15550. eol);
  15551. connection_info_length += (int)strlen(block);
  15552. if (connection_info_length + reserved_len < buflen) {
  15553. strcat0(buffer, block);
  15554. }
  15555. }
  15556. /* Execution time information */
  15557. if ((state >= 2) && (state < 9)) {
  15558. char start_time_str[64] = {0};
  15559. char now_str[64] = {0};
  15560. time_t start_time = conn->conn_birth_time;
  15561. time_t now = time(NULL);
  15562. gmt_time_string(start_time_str,
  15563. sizeof(start_time_str) - 1,
  15564. &start_time);
  15565. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15566. mg_snprintf(NULL,
  15567. NULL,
  15568. block,
  15569. sizeof(block),
  15570. "\"time\" : {%s"
  15571. "\"uptime\" : %.0f,%s"
  15572. "\"start\" : \"%s\",%s"
  15573. "\"now\" : \"%s\"%s"
  15574. "},%s",
  15575. eol,
  15576. difftime(now, start_time),
  15577. eol,
  15578. start_time_str,
  15579. eol,
  15580. now_str,
  15581. eol,
  15582. eol);
  15583. connection_info_length += (int)strlen(block);
  15584. if (connection_info_length + reserved_len < buflen) {
  15585. strcat0(buffer, block);
  15586. }
  15587. }
  15588. /* Remote user name */
  15589. if ((ri->remote_user) && (state < 9)) {
  15590. mg_snprintf(NULL,
  15591. NULL,
  15592. block,
  15593. sizeof(block),
  15594. "\"user\" : {%s"
  15595. "\"name\" : \"%s\",%s"
  15596. "},%s",
  15597. eol,
  15598. ri->remote_user,
  15599. eol,
  15600. eol);
  15601. connection_info_length += (int)strlen(block);
  15602. if (connection_info_length + reserved_len < buflen) {
  15603. strcat0(buffer, block);
  15604. }
  15605. }
  15606. /* Data block */
  15607. if (state >= 3) {
  15608. mg_snprintf(NULL,
  15609. NULL,
  15610. block,
  15611. sizeof(block),
  15612. "\"data\" : {%s"
  15613. "\"read\" : %" INT64_FMT ",%s"
  15614. "\"written\" : %" INT64_FMT "%s"
  15615. "},%s",
  15616. eol,
  15617. conn->consumed_content,
  15618. eol,
  15619. conn->num_bytes_sent,
  15620. eol,
  15621. eol);
  15622. connection_info_length += (int)strlen(block);
  15623. if (connection_info_length + reserved_len < buflen) {
  15624. strcat0(buffer, block);
  15625. }
  15626. }
  15627. /* State */
  15628. mg_snprintf(NULL,
  15629. NULL,
  15630. block,
  15631. sizeof(block),
  15632. "\"state\" : \"%s\"%s",
  15633. state_str,
  15634. eol);
  15635. connection_info_length += (int)strlen(block);
  15636. if (connection_info_length + reserved_len < buflen) {
  15637. strcat0(buffer, block);
  15638. }
  15639. /* Terminate string */
  15640. if ((buflen > 0) && buffer && buffer[0]) {
  15641. if (connection_info_length < buflen) {
  15642. strcat0(buffer, eoobj);
  15643. strcat0(buffer, eol);
  15644. }
  15645. }
  15646. connection_info_length += reserved_len;
  15647. return connection_info_length;
  15648. }
  15649. #endif
  15650. /* Get system information. It can be printed or stored by the caller.
  15651. * Return the size of available information. */
  15652. int
  15653. mg_get_system_info(char *buffer, int buflen)
  15654. {
  15655. if ((buffer == NULL) || (buflen < 1)) {
  15656. return mg_get_system_info_impl(NULL, 0);
  15657. } else {
  15658. /* Reset buffer, so we can always use strcat. */
  15659. buffer[0] = 0;
  15660. return mg_get_system_info_impl(buffer, buflen);
  15661. }
  15662. }
  15663. /* Get context information. It can be printed or stored by the caller.
  15664. * Return the size of available information. */
  15665. int
  15666. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  15667. {
  15668. #if defined(USE_SERVER_STATS)
  15669. if ((buffer == NULL) || (buflen < 1)) {
  15670. return mg_get_context_info_impl(ctx, NULL, 0);
  15671. } else {
  15672. /* Reset buffer, so we can always use strcat. */
  15673. buffer[0] = 0;
  15674. return mg_get_context_info_impl(ctx, buffer, buflen);
  15675. }
  15676. #else
  15677. (void)ctx;
  15678. if ((buffer != NULL) && (buflen > 0)) {
  15679. buffer[0] = 0;
  15680. }
  15681. return 0;
  15682. #endif
  15683. }
  15684. #ifdef MG_EXPERIMENTAL_INTERFACES
  15685. int
  15686. mg_get_connection_info(const struct mg_context *ctx,
  15687. int idx,
  15688. char *buffer,
  15689. int buflen)
  15690. {
  15691. if ((buffer == NULL) || (buflen < 1)) {
  15692. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  15693. } else {
  15694. /* Reset buffer, so we can always use strcat. */
  15695. buffer[0] = 0;
  15696. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  15697. }
  15698. }
  15699. #endif
  15700. /* Initialize this library. This function does not need to be thread safe.
  15701. */
  15702. unsigned
  15703. mg_init_library(unsigned features)
  15704. {
  15705. #if !defined(NO_SSL)
  15706. char ebuf[128];
  15707. #endif
  15708. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  15709. unsigned features_inited = features_to_init;
  15710. if (mg_init_library_called <= 0) {
  15711. /* Not initialized yet */
  15712. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  15713. return 0;
  15714. }
  15715. }
  15716. mg_global_lock();
  15717. if (mg_init_library_called <= 0) {
  15718. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  15719. /* Fatal error - abort start. However, this situation should
  15720. * never occur in practice. */
  15721. return 0;
  15722. }
  15723. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15724. InitializeCriticalSection(&global_log_file_lock);
  15725. #endif /* _WIN32 && !__SYMBIAN32__ */
  15726. #if !defined(_WIN32)
  15727. pthread_mutexattr_init(&pthread_mutex_attr);
  15728. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  15729. #endif
  15730. #if defined(USE_LUA)
  15731. lua_init_optional_libraries();
  15732. #endif
  15733. }
  15734. #if !defined(NO_SSL)
  15735. if (features_to_init & 2) {
  15736. if (!mg_ssl_initialized) {
  15737. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  15738. mg_ssl_initialized = 1;
  15739. } else {
  15740. (void)ebuf;
  15741. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  15742. features_inited &= ~(2u);
  15743. }
  15744. } else {
  15745. /* ssl already initialized */
  15746. }
  15747. }
  15748. #endif
  15749. /* Start WinSock for Windows */
  15750. if (mg_init_library_called <= 0) {
  15751. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15752. WSADATA data;
  15753. WSAStartup(MAKEWORD(2, 2), &data);
  15754. #endif /* _WIN32 && !__SYMBIAN32__ */
  15755. mg_init_library_called = 1;
  15756. } else {
  15757. mg_init_library_called++;
  15758. }
  15759. mg_global_unlock();
  15760. return features_inited;
  15761. }
  15762. /* Un-initialize this library. */
  15763. unsigned
  15764. mg_exit_library(void)
  15765. {
  15766. if (mg_init_library_called <= 0) {
  15767. return 0;
  15768. }
  15769. mg_global_lock();
  15770. mg_init_library_called--;
  15771. if (mg_init_library_called == 0) {
  15772. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15773. (void)WSACleanup();
  15774. #endif /* _WIN32 && !__SYMBIAN32__ */
  15775. #if !defined(NO_SSL)
  15776. if (mg_ssl_initialized) {
  15777. uninitialize_ssl();
  15778. mg_ssl_initialized = 0;
  15779. }
  15780. #endif
  15781. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15782. (void)DeleteCriticalSection(&global_log_file_lock);
  15783. #endif /* _WIN32 && !__SYMBIAN32__ */
  15784. #if !defined(_WIN32)
  15785. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  15786. #endif
  15787. (void)pthread_key_delete(sTlsKey);
  15788. #if defined(USE_LUA)
  15789. lua_exit_optional_libraries();
  15790. #endif
  15791. mg_global_unlock();
  15792. (void)pthread_mutex_destroy(&global_lock_mutex);
  15793. return 1;
  15794. }
  15795. mg_global_unlock();
  15796. return 1;
  15797. }
  15798. /* End of civetweb.c */