civetweb.c 402 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182
  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. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __clang__
  114. /* When using -Weverything, clang does not accept it's own headers
  115. * in a release build configuration. Disable what is too much in
  116. * -Weverything. */
  117. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  118. #endif
  119. #ifdef __MACH__ /* Apple OSX section */
  120. #ifdef __clang__
  121. /* Avoid warnings for Xopen 7.00 and higher */
  122. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  123. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  124. #endif
  125. #define CLOCK_MONOTONIC (1)
  126. #define CLOCK_REALTIME (2)
  127. #include <sys/errno.h>
  128. #include <sys/time.h>
  129. #include <mach/clock.h>
  130. #include <mach/mach.h>
  131. #include <mach/mach_time.h>
  132. #include <assert.h>
  133. /* clock_gettime is not implemented on OSX prior to 10.12 */
  134. static int
  135. _civet_clock_gettime(int clk_id, struct timespec *t)
  136. {
  137. memset(t, 0, sizeof(*t));
  138. if (clk_id == CLOCK_REALTIME) {
  139. struct timeval now;
  140. int rv = gettimeofday(&now, NULL);
  141. if (rv) {
  142. return rv;
  143. }
  144. t->tv_sec = now.tv_sec;
  145. t->tv_nsec = now.tv_usec * 1000;
  146. return 0;
  147. } else if (clk_id == CLOCK_MONOTONIC) {
  148. static uint64_t clock_start_time = 0;
  149. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  150. uint64_t now = mach_absolute_time();
  151. if (clock_start_time == 0) {
  152. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  153. #if defined(DEBUG)
  154. assert(mach_status == KERN_SUCCESS);
  155. #else
  156. /* appease "unused variable" warning for release builds */
  157. (void)mach_status;
  158. #endif
  159. clock_start_time = now;
  160. }
  161. now = (uint64_t)((double)(now - clock_start_time)
  162. * (double)timebase_ifo.numer
  163. / (double)timebase_ifo.denom);
  164. t->tv_sec = now / 1000000000;
  165. t->tv_nsec = now % 1000000000;
  166. return 0;
  167. }
  168. return -1; /* EINVAL - Clock ID is unknown */
  169. }
  170. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  171. #ifdef __CLOCK_AVAILABILITY
  172. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  173. * declared but it may be NULL at runtime. So we need to check before using
  174. * it. */
  175. static int
  176. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  177. {
  178. if (clock_gettime) {
  179. return clock_gettime(clk_id, t);
  180. }
  181. return _civet_clock_gettime(clk_id, t);
  182. }
  183. #define clock_gettime _civet_safe_clock_gettime
  184. #else
  185. #define clock_gettime _civet_clock_gettime
  186. #endif
  187. #endif
  188. #include <time.h>
  189. #include <stdlib.h>
  190. #include <stdarg.h>
  191. #include <assert.h>
  192. #include <string.h>
  193. #include <ctype.h>
  194. #include <limits.h>
  195. #include <stddef.h>
  196. #include <stdio.h>
  197. #include <stdint.h>
  198. #ifndef INT64_MAX
  199. #define INT64_MAX (9223372036854775807)
  200. #endif
  201. #ifndef MAX_WORKER_THREADS
  202. #define MAX_WORKER_THREADS (1024 * 64)
  203. #endif
  204. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  205. #define SOCKET_TIMEOUT_QUANTUM (2000)
  206. #endif
  207. #define SHUTDOWN_RD (0)
  208. #define SHUTDOWN_WR (1)
  209. #define SHUTDOWN_BOTH (2)
  210. mg_static_assert(MAX_WORKER_THREADS >= 1,
  211. "worker threads must be a positive number");
  212. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  213. "size_t data type size check");
  214. #if defined(_WIN32) \
  215. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  216. #include <windows.h>
  217. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  218. #include <ws2tcpip.h>
  219. typedef const char *SOCK_OPT_TYPE;
  220. #if !defined(PATH_MAX)
  221. #define PATH_MAX (MAX_PATH)
  222. #endif
  223. #if !defined(PATH_MAX)
  224. #define PATH_MAX (4096)
  225. #endif
  226. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  227. #ifndef _IN_PORT_T
  228. #ifndef in_port_t
  229. #define in_port_t u_short
  230. #endif
  231. #endif
  232. #ifndef _WIN32_WCE
  233. #include <process.h>
  234. #include <direct.h>
  235. #include <io.h>
  236. #else /* _WIN32_WCE */
  237. #define NO_CGI /* WinCE has no pipes */
  238. #define NO_POPEN /* WinCE has no popen */
  239. typedef long off_t;
  240. #define errno ((int)(GetLastError()))
  241. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  242. #endif /* _WIN32_WCE */
  243. #define MAKEUQUAD(lo, hi) \
  244. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  245. #define RATE_DIFF (10000000) /* 100 nsecs */
  246. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  247. #define SYS2UNIX_TIME(lo, hi) \
  248. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  249. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  250. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  251. * Also use _strtoui64 on modern M$ compilers */
  252. #if defined(_MSC_VER)
  253. #if (_MSC_VER < 1300)
  254. #define STRX(x) #x
  255. #define STR(x) STRX(x)
  256. #define __func__ __FILE__ ":" STR(__LINE__)
  257. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  258. #define strtoll(x, y, z) (_atoi64(x))
  259. #else
  260. #define __func__ __FUNCTION__
  261. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  262. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  263. #endif
  264. #endif /* _MSC_VER */
  265. #define ERRNO ((int)(GetLastError()))
  266. #define NO_SOCKLEN_T
  267. #if defined(_WIN64) || defined(__MINGW64__)
  268. #define SSL_LIB "ssleay64.dll"
  269. #define CRYPTO_LIB "libeay64.dll"
  270. #else
  271. #define SSL_LIB "ssleay32.dll"
  272. #define CRYPTO_LIB "libeay32.dll"
  273. #endif
  274. #define O_NONBLOCK (0)
  275. #ifndef W_OK
  276. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  277. #endif
  278. #if !defined(EWOULDBLOCK)
  279. #define EWOULDBLOCK WSAEWOULDBLOCK
  280. #endif /* !EWOULDBLOCK */
  281. #define _POSIX_
  282. #define INT64_FMT "I64d"
  283. #define UINT64_FMT "I64u"
  284. #define WINCDECL __cdecl
  285. #define vsnprintf_impl _vsnprintf
  286. #define access _access
  287. #define mg_sleep(x) (Sleep(x))
  288. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  289. #ifndef popen
  290. #define popen(x, y) (_popen(x, y))
  291. #endif
  292. #ifndef pclose
  293. #define pclose(x) (_pclose(x))
  294. #endif
  295. #define close(x) (_close(x))
  296. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  297. #define RTLD_LAZY (0)
  298. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  299. #define fdopen(x, y) (_fdopen((x), (y)))
  300. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  301. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  302. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  303. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  304. #define sleep(x) (Sleep((x)*1000))
  305. #define rmdir(x) (_rmdir(x))
  306. #define timegm(x) (_mkgmtime(x))
  307. #if !defined(fileno)
  308. #define fileno(x) (_fileno(x))
  309. #endif /* !fileno MINGW #defines fileno */
  310. typedef HANDLE pthread_mutex_t;
  311. typedef DWORD pthread_key_t;
  312. typedef HANDLE pthread_t;
  313. typedef struct {
  314. CRITICAL_SECTION threadIdSec;
  315. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  316. } pthread_cond_t;
  317. #ifndef __clockid_t_defined
  318. typedef DWORD clockid_t;
  319. #endif
  320. #ifndef CLOCK_MONOTONIC
  321. #define CLOCK_MONOTONIC (1)
  322. #endif
  323. #ifndef CLOCK_REALTIME
  324. #define CLOCK_REALTIME (2)
  325. #endif
  326. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  327. #define _TIMESPEC_DEFINED
  328. #endif
  329. #ifndef _TIMESPEC_DEFINED
  330. struct timespec {
  331. time_t tv_sec; /* seconds */
  332. long tv_nsec; /* nanoseconds */
  333. };
  334. #endif
  335. #if !defined(WIN_PTHREADS_TIME_H)
  336. #define MUST_IMPLEMENT_CLOCK_GETTIME
  337. #endif
  338. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  339. #define clock_gettime mg_clock_gettime
  340. static int
  341. clock_gettime(clockid_t clk_id, struct timespec *tp)
  342. {
  343. FILETIME ft;
  344. ULARGE_INTEGER li;
  345. BOOL ok = FALSE;
  346. double d;
  347. static double perfcnt_per_sec = 0.0;
  348. if (tp) {
  349. memset(tp, 0, sizeof(*tp));
  350. if (clk_id == CLOCK_REALTIME) {
  351. GetSystemTimeAsFileTime(&ft);
  352. li.LowPart = ft.dwLowDateTime;
  353. li.HighPart = ft.dwHighDateTime;
  354. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  355. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  356. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  357. ok = TRUE;
  358. } else if (clk_id == CLOCK_MONOTONIC) {
  359. if (perfcnt_per_sec == 0.0) {
  360. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  361. perfcnt_per_sec = 1.0 / li.QuadPart;
  362. }
  363. if (perfcnt_per_sec != 0.0) {
  364. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  365. d = li.QuadPart * perfcnt_per_sec;
  366. tp->tv_sec = (time_t)d;
  367. d -= tp->tv_sec;
  368. tp->tv_nsec = (long)(d * 1.0E9);
  369. ok = TRUE;
  370. }
  371. }
  372. }
  373. return ok ? 0 : -1;
  374. }
  375. #endif
  376. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  377. static int pthread_mutex_lock(pthread_mutex_t *);
  378. static int pthread_mutex_unlock(pthread_mutex_t *);
  379. static void path_to_unicode(const struct mg_connection *conn,
  380. const char *path,
  381. wchar_t *wbuf,
  382. size_t wbuf_len);
  383. /* All file operations need to be rewritten to solve #246. */
  384. #include "file_ops.inl"
  385. struct mg_file;
  386. static const char *
  387. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  388. /* POSIX dirent interface */
  389. struct dirent {
  390. char d_name[PATH_MAX];
  391. };
  392. typedef struct DIR {
  393. HANDLE handle;
  394. WIN32_FIND_DATAW info;
  395. struct dirent result;
  396. } DIR;
  397. #if defined(_WIN32) && !defined(POLLIN)
  398. #ifndef HAVE_POLL
  399. struct pollfd {
  400. SOCKET fd;
  401. short events;
  402. short revents;
  403. };
  404. #define POLLIN (0x0300)
  405. #endif
  406. #endif
  407. /* Mark required libraries */
  408. #if defined(_MSC_VER)
  409. #pragma comment(lib, "Ws2_32.lib")
  410. #endif
  411. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  412. WINDOWS / UNIX include block */
  413. #include <sys/wait.h>
  414. #include <sys/socket.h>
  415. #include <sys/poll.h>
  416. #include <netinet/in.h>
  417. #include <arpa/inet.h>
  418. #include <sys/time.h>
  419. #include <sys/utsname.h>
  420. #include <stdint.h>
  421. #include <inttypes.h>
  422. #include <netdb.h>
  423. #include <netinet/tcp.h>
  424. typedef const void *SOCK_OPT_TYPE;
  425. #if defined(ANDROID)
  426. typedef unsigned short int in_port_t;
  427. #endif
  428. #include <pwd.h>
  429. #include <unistd.h>
  430. #include <grp.h>
  431. #include <dirent.h>
  432. #define vsnprintf_impl vsnprintf
  433. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  434. #include <dlfcn.h>
  435. #endif
  436. #include <pthread.h>
  437. #if defined(__MACH__)
  438. #define SSL_LIB "libssl.dylib"
  439. #define CRYPTO_LIB "libcrypto.dylib"
  440. #else
  441. #if !defined(SSL_LIB)
  442. #define SSL_LIB "libssl.so"
  443. #endif
  444. #if !defined(CRYPTO_LIB)
  445. #define CRYPTO_LIB "libcrypto.so"
  446. #endif
  447. #endif
  448. #ifndef O_BINARY
  449. #define O_BINARY (0)
  450. #endif /* O_BINARY */
  451. #define closesocket(a) (close(a))
  452. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  453. #define mg_remove(conn, x) (remove(x))
  454. #define mg_sleep(x) (usleep((x)*1000))
  455. #define mg_opendir(conn, x) (opendir(x))
  456. #define mg_closedir(x) (closedir(x))
  457. #define mg_readdir(x) (readdir(x))
  458. #define ERRNO (errno)
  459. #define INVALID_SOCKET (-1)
  460. #define INT64_FMT PRId64
  461. #define UINT64_FMT PRIu64
  462. typedef int SOCKET;
  463. #define WINCDECL
  464. #if defined(__hpux)
  465. /* HPUX 11 does not have monotonic, fall back to realtime */
  466. #ifndef CLOCK_MONOTONIC
  467. #define CLOCK_MONOTONIC CLOCK_REALTIME
  468. #endif
  469. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  470. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  471. * the prototypes use int* rather than socklen_t* which matches the
  472. * actual library expectation. When called with the wrong size arg
  473. * accept() returns a zero client inet addr and check_acl() always
  474. * fails. Since socklen_t is widely used below, just force replace
  475. * their typedef with int. - DTL
  476. */
  477. #define socklen_t int
  478. #endif /* hpux */
  479. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  480. WINDOWS / UNIX include block */
  481. /* va_copy should always be a macro, C99 and C++11 - DTL */
  482. #ifndef va_copy
  483. #define va_copy(x, y) ((x) = (y))
  484. #endif
  485. #ifdef _WIN32
  486. /* Create substitutes for POSIX functions in Win32. */
  487. #if defined(__MINGW32__)
  488. /* Show no warning in case system functions are not used. */
  489. #pragma GCC diagnostic push
  490. #pragma GCC diagnostic ignored "-Wunused-function"
  491. #endif
  492. static CRITICAL_SECTION global_log_file_lock;
  493. static DWORD
  494. pthread_self(void)
  495. {
  496. return GetCurrentThreadId();
  497. }
  498. static int
  499. pthread_key_create(
  500. pthread_key_t *key,
  501. void (*_ignored)(void *) /* destructor not supported for Windows */
  502. )
  503. {
  504. (void)_ignored;
  505. if ((key != 0)) {
  506. *key = TlsAlloc();
  507. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  508. }
  509. return -2;
  510. }
  511. static int
  512. pthread_key_delete(pthread_key_t key)
  513. {
  514. return TlsFree(key) ? 0 : 1;
  515. }
  516. static int
  517. pthread_setspecific(pthread_key_t key, void *value)
  518. {
  519. return TlsSetValue(key, value) ? 0 : 1;
  520. }
  521. static void *
  522. pthread_getspecific(pthread_key_t key)
  523. {
  524. return TlsGetValue(key);
  525. }
  526. #if defined(__MINGW32__)
  527. /* Enable unused function warning again */
  528. #pragma GCC diagnostic pop
  529. #endif
  530. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  531. #else
  532. static pthread_mutexattr_t pthread_mutex_attr;
  533. #endif /* _WIN32 */
  534. #define PASSWORDS_FILE_NAME ".htpasswd"
  535. #define CGI_ENVIRONMENT_SIZE (4096)
  536. #define MAX_CGI_ENVIR_VARS (256)
  537. #define MG_BUF_LEN (8192)
  538. #ifndef MAX_REQUEST_SIZE
  539. #define MAX_REQUEST_SIZE (16384)
  540. #endif
  541. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  542. "request size length must be a positive number");
  543. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  544. #if defined(_WIN32_WCE)
  545. /* Create substitutes for POSIX functions in Win32. */
  546. #if defined(__MINGW32__)
  547. /* Show no warning in case system functions are not used. */
  548. #pragma GCC diagnostic push
  549. #pragma GCC diagnostic ignored "-Wunused-function"
  550. #endif
  551. static time_t
  552. time(time_t *ptime)
  553. {
  554. time_t t;
  555. SYSTEMTIME st;
  556. FILETIME ft;
  557. GetSystemTime(&st);
  558. SystemTimeToFileTime(&st, &ft);
  559. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  560. if (ptime != NULL) {
  561. *ptime = t;
  562. }
  563. return t;
  564. }
  565. static struct tm *
  566. localtime_s(const time_t *ptime, struct tm *ptm)
  567. {
  568. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  569. FILETIME ft, lft;
  570. SYSTEMTIME st;
  571. TIME_ZONE_INFORMATION tzinfo;
  572. if (ptm == NULL) {
  573. return NULL;
  574. }
  575. *(int64_t *)&ft = t;
  576. FileTimeToLocalFileTime(&ft, &lft);
  577. FileTimeToSystemTime(&lft, &st);
  578. ptm->tm_year = st.wYear - 1900;
  579. ptm->tm_mon = st.wMonth - 1;
  580. ptm->tm_wday = st.wDayOfWeek;
  581. ptm->tm_mday = st.wDay;
  582. ptm->tm_hour = st.wHour;
  583. ptm->tm_min = st.wMinute;
  584. ptm->tm_sec = st.wSecond;
  585. ptm->tm_yday = 0; /* hope nobody uses this */
  586. ptm->tm_isdst =
  587. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  588. return ptm;
  589. }
  590. static struct tm *
  591. gmtime_s(const time_t *ptime, struct tm *ptm)
  592. {
  593. /* FIXME(lsm): fix this. */
  594. return localtime_s(ptime, ptm);
  595. }
  596. static int mg_atomic_inc(volatile int *addr);
  597. static struct tm tm_array[MAX_WORKER_THREADS];
  598. static int tm_index = 0;
  599. static struct tm *
  600. localtime(const time_t *ptime)
  601. {
  602. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  603. return localtime_s(ptime, tm_array + i);
  604. }
  605. static struct tm *
  606. gmtime(const time_t *ptime)
  607. {
  608. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  609. return gmtime_s(ptime, tm_array + i);
  610. }
  611. static size_t
  612. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  613. {
  614. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  615. * for WinCE"); */
  616. return 0;
  617. }
  618. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  619. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  620. #define remove(f) mg_remove(NULL, f)
  621. static int
  622. rename(const char *a, const char *b)
  623. {
  624. wchar_t wa[PATH_MAX];
  625. wchar_t wb[PATH_MAX];
  626. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  627. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  628. return MoveFileW(wa, wb) ? 0 : -1;
  629. }
  630. struct stat {
  631. int64_t st_size;
  632. time_t st_mtime;
  633. };
  634. static int
  635. stat(const char *name, struct stat *st)
  636. {
  637. wchar_t wbuf[PATH_MAX];
  638. WIN32_FILE_ATTRIBUTE_DATA attr;
  639. time_t creation_time, write_time;
  640. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  641. memset(&attr, 0, sizeof(attr));
  642. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  643. st->st_size =
  644. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  645. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  646. attr.ftLastWriteTime.dwHighDateTime);
  647. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  648. attr.ftCreationTime.dwHighDateTime);
  649. if (creation_time > write_time) {
  650. st->st_mtime = creation_time;
  651. } else {
  652. st->st_mtime = write_time;
  653. }
  654. return 0;
  655. }
  656. #define access(x, a) 1 /* not required anyway */
  657. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  658. /* Values from errno.h in Windows SDK (Visual Studio). */
  659. #define EEXIST 17
  660. #define EACCES 13
  661. #define ENOENT 2
  662. #if defined(__MINGW32__)
  663. /* Enable unused function warning again */
  664. #pragma GCC diagnostic pop
  665. #endif
  666. #endif /* defined(_WIN32_WCE) */
  667. static int
  668. mg_atomic_inc(volatile int *addr)
  669. {
  670. int ret;
  671. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  672. /* Depending on the SDK, this function uses either
  673. * (volatile unsigned int *) or (volatile LONG *),
  674. * so whatever you use, the other SDK is likely to raise a warning. */
  675. ret = InterlockedIncrement((volatile long *)addr);
  676. #elif defined(__GNUC__) \
  677. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  678. ret = __sync_add_and_fetch(addr, 1);
  679. #else
  680. ret = (++(*addr));
  681. #endif
  682. return ret;
  683. }
  684. static int
  685. mg_atomic_dec(volatile int *addr)
  686. {
  687. int ret;
  688. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  689. /* Depending on the SDK, this function uses either
  690. * (volatile unsigned int *) or (volatile LONG *),
  691. * so whatever you use, the other SDK is likely to raise a warning. */
  692. ret = InterlockedDecrement((volatile long *)addr);
  693. #elif defined(__GNUC__) \
  694. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  695. ret = __sync_sub_and_fetch(addr, 1);
  696. #else
  697. ret = (--(*addr));
  698. #endif
  699. return ret;
  700. }
  701. #if defined(MEMORY_DEBUGGING)
  702. static unsigned long mg_memory_debug_blockCount = 0;
  703. static unsigned long mg_memory_debug_totalMemUsed = 0;
  704. static void *
  705. mg_malloc_ex(size_t size, const char *file, unsigned line)
  706. {
  707. void *data = malloc(size + sizeof(size_t));
  708. void *memory = 0;
  709. char mallocStr[256];
  710. if (data) {
  711. *(size_t *)data = size;
  712. mg_memory_debug_totalMemUsed += size;
  713. mg_memory_debug_blockCount++;
  714. memory = (void *)(((char *)data) + sizeof(size_t));
  715. }
  716. sprintf(mallocStr,
  717. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  718. memory,
  719. (unsigned long)size,
  720. mg_memory_debug_totalMemUsed,
  721. mg_memory_debug_blockCount,
  722. file,
  723. line);
  724. #if defined(_WIN32)
  725. OutputDebugStringA(mallocStr);
  726. #else
  727. DEBUG_TRACE("%s", mallocStr);
  728. #endif
  729. return memory;
  730. }
  731. static void *
  732. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  733. {
  734. void *data = mg_malloc_ex(size * count, file, line);
  735. if (data) {
  736. memset(data, 0, size * count);
  737. }
  738. return data;
  739. }
  740. static void
  741. mg_free_ex(void *memory, const char *file, unsigned line)
  742. {
  743. char mallocStr[256];
  744. void *data = (void *)(((char *)memory) - sizeof(size_t));
  745. size_t size;
  746. if (memory) {
  747. size = *(size_t *)data;
  748. mg_memory_debug_totalMemUsed -= size;
  749. mg_memory_debug_blockCount--;
  750. sprintf(mallocStr,
  751. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  752. memory,
  753. (unsigned long)size,
  754. mg_memory_debug_totalMemUsed,
  755. mg_memory_debug_blockCount,
  756. file,
  757. line);
  758. #if defined(_WIN32)
  759. OutputDebugStringA(mallocStr);
  760. #else
  761. DEBUG_TRACE("%s", mallocStr);
  762. #endif
  763. free(data);
  764. }
  765. }
  766. static void *
  767. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  768. {
  769. char mallocStr[256];
  770. void *data;
  771. void *_realloc;
  772. size_t oldsize;
  773. if (newsize) {
  774. if (memory) {
  775. data = (void *)(((char *)memory) - sizeof(size_t));
  776. oldsize = *(size_t *)data;
  777. _realloc = realloc(data, newsize + sizeof(size_t));
  778. if (_realloc) {
  779. data = _realloc;
  780. mg_memory_debug_totalMemUsed -= oldsize;
  781. sprintf(mallocStr,
  782. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  783. memory,
  784. (unsigned long)oldsize,
  785. mg_memory_debug_totalMemUsed,
  786. mg_memory_debug_blockCount,
  787. file,
  788. line);
  789. #if defined(_WIN32)
  790. OutputDebugStringA(mallocStr);
  791. #else
  792. DEBUG_TRACE("%s", mallocStr);
  793. #endif
  794. mg_memory_debug_totalMemUsed += newsize;
  795. sprintf(mallocStr,
  796. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  797. memory,
  798. (unsigned long)newsize,
  799. mg_memory_debug_totalMemUsed,
  800. mg_memory_debug_blockCount,
  801. file,
  802. line);
  803. #if defined(_WIN32)
  804. OutputDebugStringA(mallocStr);
  805. #else
  806. DEBUG_TRACE("%s", mallocStr);
  807. #endif
  808. *(size_t *)data = newsize;
  809. data = (void *)(((char *)data) + sizeof(size_t));
  810. } else {
  811. #if defined(_WIN32)
  812. OutputDebugStringA("MEM: realloc failed\n");
  813. #else
  814. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  815. #endif
  816. return _realloc;
  817. }
  818. } else {
  819. data = mg_malloc_ex(newsize, file, line);
  820. }
  821. } else {
  822. data = 0;
  823. mg_free_ex(memory, file, line);
  824. }
  825. return data;
  826. }
  827. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  828. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  829. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  830. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  831. #else
  832. static __inline void *
  833. mg_malloc(size_t a)
  834. {
  835. return malloc(a);
  836. }
  837. static __inline void *
  838. mg_calloc(size_t a, size_t b)
  839. {
  840. return calloc(a, b);
  841. }
  842. static __inline void *
  843. mg_realloc(void *a, size_t b)
  844. {
  845. return realloc(a, b);
  846. }
  847. static __inline void
  848. mg_free(void *a)
  849. {
  850. free(a);
  851. }
  852. #endif
  853. static void mg_vsnprintf(const struct mg_connection *conn,
  854. int *truncated,
  855. char *buf,
  856. size_t buflen,
  857. const char *fmt,
  858. va_list ap);
  859. static void mg_snprintf(const struct mg_connection *conn,
  860. int *truncated,
  861. char *buf,
  862. size_t buflen,
  863. PRINTF_FORMAT_STRING(const char *fmt),
  864. ...) PRINTF_ARGS(5, 6);
  865. /* This following lines are just meant as a reminder to use the mg-functions
  866. * for memory management */
  867. #ifdef malloc
  868. #undef malloc
  869. #endif
  870. #ifdef calloc
  871. #undef calloc
  872. #endif
  873. #ifdef realloc
  874. #undef realloc
  875. #endif
  876. #ifdef free
  877. #undef free
  878. #endif
  879. #ifdef snprintf
  880. #undef snprintf
  881. #endif
  882. #ifdef vsnprintf
  883. #undef vsnprintf
  884. #endif
  885. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  886. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  887. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  888. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  889. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  890. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  891. * but this define only works well for Windows. */
  892. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  893. #endif
  894. static pthread_key_t sTlsKey; /* Thread local storage index */
  895. static int sTlsInit = 0;
  896. static int thread_idx_max = 0;
  897. struct mg_workerTLS {
  898. int is_master;
  899. unsigned long thread_idx;
  900. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  901. HANDLE pthread_cond_helper_mutex;
  902. struct mg_workerTLS *next_waiting_thread;
  903. #endif
  904. };
  905. #if defined(__GNUC__) || defined(__MINGW32__)
  906. /* Show no warning in case system functions are not used. */
  907. #pragma GCC diagnostic push
  908. #pragma GCC diagnostic ignored "-Wunused-function"
  909. #endif
  910. #if defined(__clang__)
  911. /* Show no warning in case system functions are not used. */
  912. #pragma clang diagnostic push
  913. #pragma clang diagnostic ignored "-Wunused-function"
  914. #endif
  915. /* Get a unique thread ID as unsigned long, independent from the data type
  916. * of thread IDs defined by the operating system API.
  917. * If two calls to mg_current_thread_id return the same value, they calls
  918. * are done from the same thread. If they return different values, they are
  919. * done from different threads. (Provided this function is used in the same
  920. * process context and threads are not repeatedly created and deleted, but
  921. * CivetWeb does not do that).
  922. * This function must match the signature required for SSL id callbacks:
  923. * CRYPTO_set_id_callback
  924. */
  925. static unsigned long
  926. mg_current_thread_id(void)
  927. {
  928. #ifdef _WIN32
  929. return GetCurrentThreadId();
  930. #else
  931. #ifdef __clang__
  932. #pragma clang diagnostic push
  933. #pragma clang diagnostic ignored "-Wunreachable-code"
  934. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  935. * or not, so one of the two conditions will be unreachable by construction.
  936. * Unfortunately the C standard does not define a way to check this at
  937. * compile time, since the #if preprocessor conditions can not use the sizeof
  938. * operator as an argument. */
  939. #endif
  940. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  941. /* This is the problematic case for CRYPTO_set_id_callback:
  942. * The OS pthread_t can not be cast to unsigned long. */
  943. struct mg_workerTLS *tls =
  944. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  945. if (tls == NULL) {
  946. /* SSL called from an unknown thread: Create some thread index.
  947. */
  948. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  949. tls->is_master = -2; /* -2 means "3rd party thread" */
  950. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  951. pthread_setspecific(sTlsKey, tls);
  952. }
  953. return tls->thread_idx;
  954. } else {
  955. /* pthread_t may be any data type, so a simple cast to unsigned long
  956. * can rise a warning/error, depending on the platform.
  957. * Here memcpy is used as an anything-to-anything cast. */
  958. unsigned long ret = 0;
  959. pthread_t t = pthread_self();
  960. memcpy(&ret, &t, sizeof(pthread_t));
  961. return ret;
  962. }
  963. #ifdef __clang__
  964. #pragma clang diagnostic pop
  965. #endif
  966. #endif
  967. }
  968. #if defined(__GNUC__)
  969. /* Show no warning in case system functions are not used. */
  970. #pragma GCC diagnostic pop
  971. #endif
  972. #if defined(__clang__)
  973. /* Show no warning in case system functions are not used. */
  974. #pragma clang diagnostic pop
  975. #endif
  976. #if !defined(DEBUG_TRACE)
  977. #if defined(DEBUG)
  978. static void DEBUG_TRACE_FUNC(const char *func,
  979. unsigned line,
  980. PRINTF_FORMAT_STRING(const char *fmt),
  981. ...) PRINTF_ARGS(3, 4);
  982. static void
  983. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  984. {
  985. va_list args;
  986. struct timespec tsnow;
  987. uint64_t nsnow;
  988. static uint64_t nslast;
  989. /* Get some operating system independent thread id */
  990. unsigned long thread_id = mg_current_thread_id();
  991. clock_gettime(CLOCK_REALTIME, &tsnow);
  992. nsnow = (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  993. flockfile(stdout);
  994. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  995. (unsigned long)tsnow.tv_sec,
  996. (unsigned long)tsnow.tv_nsec,
  997. nsnow - nslast,
  998. thread_id,
  999. func,
  1000. line);
  1001. va_start(args, fmt);
  1002. vprintf(fmt, args);
  1003. va_end(args);
  1004. putchar('\n');
  1005. fflush(stdout);
  1006. funlockfile(stdout);
  1007. nslast = nsnow;
  1008. }
  1009. #define DEBUG_TRACE(fmt, ...) \
  1010. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1011. #else
  1012. #define DEBUG_TRACE(fmt, ...) \
  1013. do { \
  1014. } while (0)
  1015. #endif /* DEBUG */
  1016. #endif /* DEBUG_TRACE */
  1017. #define MD5_STATIC static
  1018. #include "md5.inl"
  1019. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1020. #ifdef NO_SOCKLEN_T
  1021. typedef int socklen_t;
  1022. #endif /* NO_SOCKLEN_T */
  1023. #define _DARWIN_UNLIMITED_SELECT
  1024. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1025. #if !defined(MSG_NOSIGNAL)
  1026. #define MSG_NOSIGNAL (0)
  1027. #endif
  1028. #if !defined(SOMAXCONN)
  1029. #define SOMAXCONN (100)
  1030. #endif
  1031. /* Size of the accepted socket queue */
  1032. #if !defined(MGSQLEN)
  1033. #define MGSQLEN (20)
  1034. #endif
  1035. #if defined(NO_SSL)
  1036. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1037. typedef struct SSL_CTX SSL_CTX;
  1038. #else
  1039. #if defined(NO_SSL_DL)
  1040. #include <openssl/ssl.h>
  1041. #include <openssl/err.h>
  1042. #include <openssl/crypto.h>
  1043. #include <openssl/x509.h>
  1044. #include <openssl/pem.h>
  1045. #include <openssl/engine.h>
  1046. #include <openssl/conf.h>
  1047. #include <openssl/dh.h>
  1048. #include <openssl/bn.h>
  1049. #include <openssl/opensslv.h>
  1050. #else
  1051. /* SSL loaded dynamically from DLL.
  1052. * I put the prototypes here to be independent from OpenSSL source
  1053. * installation. */
  1054. typedef struct ssl_st SSL;
  1055. typedef struct ssl_method_st SSL_METHOD;
  1056. typedef struct ssl_ctx_st SSL_CTX;
  1057. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1058. typedef struct x509_name X509_NAME;
  1059. typedef struct asn1_integer ASN1_INTEGER;
  1060. typedef struct bignum BIGNUM;
  1061. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1062. typedef struct evp_md EVP_MD;
  1063. typedef struct x509 X509;
  1064. #define SSL_CTRL_OPTIONS (32)
  1065. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1066. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1067. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1068. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1069. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1070. #define SSL_VERIFY_NONE (0)
  1071. #define SSL_VERIFY_PEER (1)
  1072. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1073. #define SSL_VERIFY_CLIENT_ONCE (4)
  1074. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1075. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1076. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1077. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1078. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1079. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1080. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1081. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1082. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1083. #define SSL_ERROR_NONE (0)
  1084. #define SSL_ERROR_SSL (1)
  1085. #define SSL_ERROR_WANT_READ (2)
  1086. #define SSL_ERROR_WANT_WRITE (3)
  1087. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1088. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1089. #define SSL_ERROR_ZERO_RETURN (6)
  1090. #define SSL_ERROR_WANT_CONNECT (7)
  1091. #define SSL_ERROR_WANT_ACCEPT (8)
  1092. struct ssl_func {
  1093. const char *name; /* SSL function name */
  1094. void (*ptr)(void); /* Function pointer */
  1095. };
  1096. #ifdef OPENSSL_API_1_1
  1097. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1098. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1099. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1100. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1101. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1102. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1103. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1104. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1105. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1106. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1107. #define OPENSSL_init_ssl \
  1108. (*(int (*)(uint64_t opts, \
  1109. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1110. #define SSL_CTX_use_PrivateKey_file \
  1111. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1112. #define SSL_CTX_use_certificate_file \
  1113. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1114. #define SSL_CTX_set_default_passwd_cb \
  1115. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1116. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1117. #define SSL_CTX_use_certificate_chain_file \
  1118. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1119. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1120. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1121. #define SSL_CTX_set_verify \
  1122. (*(void (*)(SSL_CTX *, \
  1123. int, \
  1124. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1125. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1126. #define SSL_CTX_load_verify_locations \
  1127. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1128. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1129. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1130. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1131. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1132. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1133. #define SSL_CIPHER_get_name \
  1134. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1135. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1136. #define SSL_CTX_set_session_id_context \
  1137. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1138. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1139. #define SSL_CTX_set_cipher_list \
  1140. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1141. #define SSL_CTX_set_options \
  1142. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1143. #define SSL_CTX_clear_options(ctx, op) \
  1144. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1145. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1146. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1147. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1148. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1149. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1150. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1151. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1152. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1153. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1154. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1155. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1156. #define X509_NAME_oneline \
  1157. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1158. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1159. #define EVP_get_digestbyname \
  1160. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1161. #define ASN1_digest \
  1162. (*(int (*)(int (*)(), \
  1163. const EVP_MD *, \
  1164. char *, \
  1165. unsigned char *, \
  1166. unsigned int *))crypto_sw[10].ptr)
  1167. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1168. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1169. #define ASN1_INTEGER_to_BN \
  1170. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1171. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1172. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1173. #define OPENSSL_free(a) CRYPTO_free(a)
  1174. /* set_ssl_option() function updates this array.
  1175. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1176. * of respective functions. The macros above (like SSL_connect()) are really
  1177. * just calling these functions indirectly via the pointer. */
  1178. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1179. {"SSL_accept", NULL},
  1180. {"SSL_connect", NULL},
  1181. {"SSL_read", NULL},
  1182. {"SSL_write", NULL},
  1183. {"SSL_get_error", NULL},
  1184. {"SSL_set_fd", NULL},
  1185. {"SSL_new", NULL},
  1186. {"SSL_CTX_new", NULL},
  1187. {"TLS_server_method", NULL},
  1188. {"OPENSSL_init_ssl", NULL},
  1189. {"SSL_CTX_use_PrivateKey_file", NULL},
  1190. {"SSL_CTX_use_certificate_file", NULL},
  1191. {"SSL_CTX_set_default_passwd_cb", NULL},
  1192. {"SSL_CTX_free", NULL},
  1193. {"SSL_CTX_use_certificate_chain_file", NULL},
  1194. {"TLS_client_method", NULL},
  1195. {"SSL_pending", NULL},
  1196. {"SSL_CTX_set_verify", NULL},
  1197. {"SSL_shutdown", NULL},
  1198. {"SSL_CTX_load_verify_locations", NULL},
  1199. {"SSL_CTX_set_default_verify_paths", NULL},
  1200. {"SSL_CTX_set_verify_depth", NULL},
  1201. {"SSL_get_peer_certificate", NULL},
  1202. {"SSL_get_version", NULL},
  1203. {"SSL_get_current_cipher", NULL},
  1204. {"SSL_CIPHER_get_name", NULL},
  1205. {"SSL_CTX_check_private_key", NULL},
  1206. {"SSL_CTX_set_session_id_context", NULL},
  1207. {"SSL_CTX_ctrl", NULL},
  1208. {"SSL_CTX_set_cipher_list", NULL},
  1209. {"SSL_CTX_set_options", NULL},
  1210. {NULL, NULL}};
  1211. /* Similar array as ssl_sw. These functions could be located in different
  1212. * lib. */
  1213. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1214. {"ERR_error_string", NULL},
  1215. {"ERR_remove_state", NULL},
  1216. {"CONF_modules_unload", NULL},
  1217. {"X509_free", NULL},
  1218. {"X509_get_subject_name", NULL},
  1219. {"X509_get_issuer_name", NULL},
  1220. {"X509_NAME_oneline", NULL},
  1221. {"X509_get_serialNumber", NULL},
  1222. {"EVP_get_digestbyname", NULL},
  1223. {"ASN1_digest", NULL},
  1224. {"i2d_X509", NULL},
  1225. {"BN_bn2hex", NULL},
  1226. {"ASN1_INTEGER_to_BN", NULL},
  1227. {"BN_free", NULL},
  1228. {"CRYPTO_free", NULL},
  1229. {NULL, NULL}};
  1230. #else
  1231. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1232. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1233. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1234. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1235. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1236. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1237. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1238. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1239. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1240. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1241. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1242. #define SSL_CTX_use_PrivateKey_file \
  1243. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1244. #define SSL_CTX_use_certificate_file \
  1245. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1246. #define SSL_CTX_set_default_passwd_cb \
  1247. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1248. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1249. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1250. #define SSL_CTX_use_certificate_chain_file \
  1251. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1252. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1253. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1254. #define SSL_CTX_set_verify \
  1255. (*(void (*)(SSL_CTX *, \
  1256. int, \
  1257. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1258. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1259. #define SSL_CTX_load_verify_locations \
  1260. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1261. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1262. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1263. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1264. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1265. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1266. #define SSL_CIPHER_get_name \
  1267. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1268. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1269. #define SSL_CTX_set_session_id_context \
  1270. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1271. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1272. #define SSL_CTX_set_cipher_list \
  1273. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1274. #define SSL_CTX_set_options(ctx, op) \
  1275. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1276. #define SSL_CTX_clear_options(ctx, op) \
  1277. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1278. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1279. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1280. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1281. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1282. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1283. #define CRYPTO_set_locking_callback \
  1284. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1285. #define CRYPTO_set_id_callback \
  1286. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1287. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1288. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1289. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1290. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1291. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1292. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1293. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1294. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1295. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1296. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1297. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1298. #define X509_NAME_oneline \
  1299. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1300. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1301. #define i2c_ASN1_INTEGER \
  1302. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1303. #define EVP_get_digestbyname \
  1304. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1305. #define ASN1_digest \
  1306. (*(int (*)(int (*)(), \
  1307. const EVP_MD *, \
  1308. char *, \
  1309. unsigned char *, \
  1310. unsigned int *))crypto_sw[18].ptr)
  1311. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1312. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1313. #define ASN1_INTEGER_to_BN \
  1314. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1315. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1316. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1317. #define OPENSSL_free(a) CRYPTO_free(a)
  1318. /* set_ssl_option() function updates this array.
  1319. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1320. * of respective functions. The macros above (like SSL_connect()) are really
  1321. * just calling these functions indirectly via the pointer. */
  1322. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1323. {"SSL_accept", NULL},
  1324. {"SSL_connect", NULL},
  1325. {"SSL_read", NULL},
  1326. {"SSL_write", NULL},
  1327. {"SSL_get_error", NULL},
  1328. {"SSL_set_fd", NULL},
  1329. {"SSL_new", NULL},
  1330. {"SSL_CTX_new", NULL},
  1331. {"SSLv23_server_method", NULL},
  1332. {"SSL_library_init", NULL},
  1333. {"SSL_CTX_use_PrivateKey_file", NULL},
  1334. {"SSL_CTX_use_certificate_file", NULL},
  1335. {"SSL_CTX_set_default_passwd_cb", NULL},
  1336. {"SSL_CTX_free", NULL},
  1337. {"SSL_load_error_strings", NULL},
  1338. {"SSL_CTX_use_certificate_chain_file", NULL},
  1339. {"SSLv23_client_method", NULL},
  1340. {"SSL_pending", NULL},
  1341. {"SSL_CTX_set_verify", NULL},
  1342. {"SSL_shutdown", NULL},
  1343. {"SSL_CTX_load_verify_locations", NULL},
  1344. {"SSL_CTX_set_default_verify_paths", NULL},
  1345. {"SSL_CTX_set_verify_depth", NULL},
  1346. {"SSL_get_peer_certificate", NULL},
  1347. {"SSL_get_version", NULL},
  1348. {"SSL_get_current_cipher", NULL},
  1349. {"SSL_CIPHER_get_name", NULL},
  1350. {"SSL_CTX_check_private_key", NULL},
  1351. {"SSL_CTX_set_session_id_context", NULL},
  1352. {"SSL_CTX_ctrl", NULL},
  1353. {"SSL_CTX_set_cipher_list", NULL},
  1354. {NULL, NULL}};
  1355. /* Similar array as ssl_sw. These functions could be located in different
  1356. * lib. */
  1357. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1358. {"CRYPTO_set_locking_callback", NULL},
  1359. {"CRYPTO_set_id_callback", NULL},
  1360. {"ERR_get_error", NULL},
  1361. {"ERR_error_string", NULL},
  1362. {"ERR_remove_state", NULL},
  1363. {"ERR_free_strings", NULL},
  1364. {"ENGINE_cleanup", NULL},
  1365. {"CONF_modules_unload", NULL},
  1366. {"CRYPTO_cleanup_all_ex_data", NULL},
  1367. {"EVP_cleanup", NULL},
  1368. {"X509_free", NULL},
  1369. {"X509_get_subject_name", NULL},
  1370. {"X509_get_issuer_name", NULL},
  1371. {"X509_NAME_oneline", NULL},
  1372. {"X509_get_serialNumber", NULL},
  1373. {"i2c_ASN1_INTEGER", NULL},
  1374. {"EVP_get_digestbyname", NULL},
  1375. {"ASN1_digest", NULL},
  1376. {"i2d_X509", NULL},
  1377. {"BN_bn2hex", NULL},
  1378. {"ASN1_INTEGER_to_BN", NULL},
  1379. {"BN_free", NULL},
  1380. {"CRYPTO_free", NULL},
  1381. {NULL, NULL}};
  1382. #endif /* OPENSSL_API_1_1 */
  1383. #endif /* NO_SSL_DL */
  1384. #endif /* NO_SSL */
  1385. #if !defined(NO_CACHING)
  1386. static const char *month_names[] = {"Jan",
  1387. "Feb",
  1388. "Mar",
  1389. "Apr",
  1390. "May",
  1391. "Jun",
  1392. "Jul",
  1393. "Aug",
  1394. "Sep",
  1395. "Oct",
  1396. "Nov",
  1397. "Dec"};
  1398. #endif /* !NO_CACHING */
  1399. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1400. * union u. */
  1401. union usa {
  1402. struct sockaddr sa;
  1403. struct sockaddr_in sin;
  1404. #if defined(USE_IPV6)
  1405. struct sockaddr_in6 sin6;
  1406. #endif
  1407. };
  1408. /* Describes a string (chunk of memory). */
  1409. struct vec {
  1410. const char *ptr;
  1411. size_t len;
  1412. };
  1413. struct mg_file_stat {
  1414. /* File properties filled by mg_stat: */
  1415. uint64_t size;
  1416. time_t last_modified;
  1417. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1418. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1419. * case we need a "Content-Eencoding: gzip" header */
  1420. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1421. };
  1422. struct mg_file_in_memory {
  1423. char *p;
  1424. uint32_t pos;
  1425. char mode;
  1426. };
  1427. struct mg_file_access {
  1428. /* File properties filled by mg_fopen: */
  1429. FILE *fp;
  1430. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1431. * support library. Use some struct mg_file_in_memory *mf; instead of
  1432. * membuf char pointer. */
  1433. const char *membuf;
  1434. };
  1435. struct mg_file {
  1436. struct mg_file_stat stat;
  1437. struct mg_file_access access;
  1438. };
  1439. #define STRUCT_FILE_INITIALIZER \
  1440. { \
  1441. { \
  1442. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1443. } \
  1444. , \
  1445. { \
  1446. (FILE *) NULL, (const char *)NULL \
  1447. } \
  1448. }
  1449. /* Describes listening socket, or socket which was accept()-ed by the master
  1450. * thread and queued for future handling by the worker thread. */
  1451. struct socket {
  1452. SOCKET sock; /* Listening socket */
  1453. union usa lsa; /* Local socket address */
  1454. union usa rsa; /* Remote socket address */
  1455. unsigned char is_ssl; /* Is port SSL-ed */
  1456. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1457. * port */
  1458. unsigned char in_use; /* Is valid */
  1459. };
  1460. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1461. enum {
  1462. CGI_EXTENSIONS,
  1463. CGI_ENVIRONMENT,
  1464. PUT_DELETE_PASSWORDS_FILE,
  1465. CGI_INTERPRETER,
  1466. PROTECT_URI,
  1467. AUTHENTICATION_DOMAIN,
  1468. SSI_EXTENSIONS,
  1469. THROTTLE,
  1470. ACCESS_LOG_FILE,
  1471. ENABLE_DIRECTORY_LISTING,
  1472. ERROR_LOG_FILE,
  1473. GLOBAL_PASSWORDS_FILE,
  1474. INDEX_FILES,
  1475. ENABLE_KEEP_ALIVE,
  1476. ACCESS_CONTROL_LIST,
  1477. EXTRA_MIME_TYPES,
  1478. LISTENING_PORTS,
  1479. DOCUMENT_ROOT,
  1480. SSL_CERTIFICATE,
  1481. NUM_THREADS,
  1482. RUN_AS_USER,
  1483. REWRITE,
  1484. HIDE_FILES,
  1485. REQUEST_TIMEOUT,
  1486. KEEP_ALIVE_TIMEOUT,
  1487. LINGER_TIMEOUT,
  1488. SSL_DO_VERIFY_PEER,
  1489. SSL_CA_PATH,
  1490. SSL_CA_FILE,
  1491. SSL_VERIFY_DEPTH,
  1492. SSL_DEFAULT_VERIFY_PATHS,
  1493. SSL_CIPHER_LIST,
  1494. SSL_PROTOCOL_VERSION,
  1495. SSL_SHORT_TRUST,
  1496. #if defined(USE_WEBSOCKET)
  1497. WEBSOCKET_TIMEOUT,
  1498. #endif
  1499. DECODE_URL,
  1500. #if defined(USE_LUA)
  1501. LUA_PRELOAD_FILE,
  1502. LUA_SCRIPT_EXTENSIONS,
  1503. LUA_SERVER_PAGE_EXTENSIONS,
  1504. #endif
  1505. #if defined(USE_DUKTAPE)
  1506. DUKTAPE_SCRIPT_EXTENSIONS,
  1507. #endif
  1508. #if defined(USE_WEBSOCKET)
  1509. WEBSOCKET_ROOT,
  1510. #endif
  1511. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1512. LUA_WEBSOCKET_EXTENSIONS,
  1513. #endif
  1514. ACCESS_CONTROL_ALLOW_ORIGIN,
  1515. ERROR_PAGES,
  1516. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1517. * socket option typedef TCP_NODELAY. */
  1518. #if !defined(NO_CACHING)
  1519. STATIC_FILE_MAX_AGE,
  1520. #endif
  1521. #if defined(__linux__)
  1522. ALLOW_SENDFILE_CALL,
  1523. #endif
  1524. #if defined(_WIN32)
  1525. CASE_SENSITIVE_FILES,
  1526. #endif
  1527. #if defined(USE_LUA)
  1528. LUA_BACKGROUND_SCRIPT,
  1529. #endif
  1530. NUM_OPTIONS
  1531. };
  1532. /* Config option name, config types, default value */
  1533. static struct mg_option config_options[] = {
  1534. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1535. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1536. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1537. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1538. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1539. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1540. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1541. {"throttle", CONFIG_TYPE_STRING, NULL},
  1542. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1543. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1544. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1545. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1546. {"index_files",
  1547. CONFIG_TYPE_STRING,
  1548. #ifdef USE_LUA
  1549. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1550. "index.shtml,index.php"},
  1551. #else
  1552. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1553. #endif
  1554. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1555. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1556. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1557. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1558. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1559. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1560. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1561. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1562. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1563. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1564. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1565. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1566. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1567. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1568. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1569. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1570. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1571. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1572. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1573. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1574. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1575. #if defined(USE_WEBSOCKET)
  1576. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1577. #endif
  1578. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1579. #if defined(USE_LUA)
  1580. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1581. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1582. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1583. #endif
  1584. #if defined(USE_DUKTAPE)
  1585. /* The support for duktape is still in alpha version state.
  1586. * The name of this config option might change. */
  1587. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1588. #endif
  1589. #if defined(USE_WEBSOCKET)
  1590. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1591. #endif
  1592. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1593. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1594. #endif
  1595. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1596. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1597. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1598. #if !defined(NO_CACHING)
  1599. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1600. #endif
  1601. #if defined(__linux__)
  1602. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1603. #endif
  1604. #if defined(_WIN32)
  1605. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1606. #endif
  1607. #if defined(USE_LUA)
  1608. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1609. #endif
  1610. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1611. /* Check if the config_options and the corresponding enum have compatible
  1612. * sizes. */
  1613. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1614. == (NUM_OPTIONS + 1),
  1615. "config_options and enum not sync");
  1616. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1617. struct mg_handler_info {
  1618. /* Name/Pattern of the URI. */
  1619. char *uri;
  1620. size_t uri_len;
  1621. /* handler type */
  1622. int handler_type;
  1623. /* Handler for http/https or authorization requests. */
  1624. mg_request_handler handler;
  1625. /* Handler for ws/wss (websocket) requests. */
  1626. mg_websocket_connect_handler connect_handler;
  1627. mg_websocket_ready_handler ready_handler;
  1628. mg_websocket_data_handler data_handler;
  1629. mg_websocket_close_handler close_handler;
  1630. /* accepted subprotocols for ws/wss requests. */
  1631. struct mg_websocket_subprotocols *subprotocols;
  1632. /* Handler for authorization requests */
  1633. mg_authorization_handler auth_handler;
  1634. /* User supplied argument for the handler function. */
  1635. void *cbdata;
  1636. /* next handler in a linked list */
  1637. struct mg_handler_info *next;
  1638. };
  1639. struct mg_context {
  1640. volatile int stop_flag; /* Should we stop event loop */
  1641. SSL_CTX *ssl_ctx; /* SSL context */
  1642. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1643. struct mg_callbacks callbacks; /* User-defined callback function */
  1644. void *user_data; /* User-defined data */
  1645. int context_type; /* 1 = server context,
  1646. * 2 = ws/wss client context,
  1647. */
  1648. struct socket *listening_sockets;
  1649. struct pollfd *listening_socket_fds;
  1650. unsigned int num_listening_sockets;
  1651. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1652. #ifdef ALTERNATIVE_QUEUE
  1653. struct socket *client_socks;
  1654. void **client_wait_events;
  1655. #else
  1656. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1657. volatile int sq_head; /* Head of the socket queue */
  1658. volatile int sq_tail; /* Tail of the socket queue */
  1659. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1660. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1661. #endif
  1662. pthread_t masterthreadid; /* The master thread ID */
  1663. unsigned int
  1664. cfg_worker_threads; /* The number of configured worker threads. */
  1665. pthread_t *worker_threadids; /* The worker thread IDs */
  1666. struct mg_connection *worker_connections; /* The connection struct, pre-
  1667. * allocated for each worker */
  1668. time_t start_time; /* Server start time, used for authentication */
  1669. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1670. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1671. unsigned long nonce_count; /* Used nonces, used for authentication */
  1672. char *systemName; /* What operating system is running */
  1673. /* linked list of uri handlers */
  1674. struct mg_handler_info *handlers;
  1675. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1676. /* linked list of shared lua websockets */
  1677. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1678. #endif
  1679. #if defined(USE_TIMERS)
  1680. struct ttimers *timers;
  1681. #endif
  1682. #if defined(USE_LUA)
  1683. void *lua_background_state;
  1684. #endif
  1685. };
  1686. struct mg_connection {
  1687. struct mg_request_info request_info;
  1688. struct mg_context *ctx;
  1689. SSL *ssl; /* SSL descriptor */
  1690. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1691. struct socket client; /* Connected client */
  1692. time_t conn_birth_time; /* Time (wall clock) when connection was
  1693. * established */
  1694. struct timespec req_time; /* Time (since system start) when the request
  1695. * was received */
  1696. int64_t num_bytes_sent; /* Total bytes sent to client */
  1697. int64_t content_len; /* Content-Length header value */
  1698. int64_t consumed_content; /* How many bytes of content have been read */
  1699. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1700. * data available, 2: all data read */
  1701. size_t chunk_remainder; /* Unread data from the last chunk */
  1702. char *buf; /* Buffer for received data */
  1703. char *path_info; /* PATH_INFO part of the URL */
  1704. int must_close; /* 1 if connection must be closed */
  1705. int in_error_handler; /* 1 if in handler for user defined error
  1706. * pages */
  1707. int handled_requests; /* Number of requests handled by this connection */
  1708. int buf_size; /* Buffer size */
  1709. int request_len; /* Size of the request + headers in a buffer */
  1710. int data_len; /* Total size of data in a buffer */
  1711. int status_code; /* HTTP reply status code, e.g. 200 */
  1712. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1713. * throttle */
  1714. time_t last_throttle_time; /* Last time throttled data was sent */
  1715. int64_t last_throttle_bytes; /* Bytes sent this second */
  1716. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1717. * atomic transmissions for websockets */
  1718. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1719. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1720. #endif
  1721. int thread_index; /* Thread index within ctx */
  1722. };
  1723. /* Directory entry */
  1724. struct de {
  1725. struct mg_connection *conn;
  1726. char *file_name;
  1727. struct mg_file_stat file;
  1728. };
  1729. #if defined(USE_WEBSOCKET)
  1730. static int is_websocket_protocol(const struct mg_connection *conn);
  1731. #else
  1732. #define is_websocket_protocol(conn) (0)
  1733. #endif
  1734. #if !defined(NO_THREAD_NAME)
  1735. #if defined(_WIN32) && defined(_MSC_VER)
  1736. /* Set the thread name for debugging purposes in Visual Studio
  1737. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1738. */
  1739. #pragma pack(push, 8)
  1740. typedef struct tagTHREADNAME_INFO {
  1741. DWORD dwType; /* Must be 0x1000. */
  1742. LPCSTR szName; /* Pointer to name (in user addr space). */
  1743. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1744. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1745. } THREADNAME_INFO;
  1746. #pragma pack(pop)
  1747. #elif defined(__linux__)
  1748. #include <sys/prctl.h>
  1749. #include <sys/sendfile.h>
  1750. #include <sys/eventfd.h>
  1751. #if defined(ALTERNATIVE_QUEUE)
  1752. static void *
  1753. event_create(void)
  1754. {
  1755. int ret = eventfd(0, EFD_CLOEXEC);
  1756. if (ret == -1) {
  1757. /* Linux uses -1 on error, Windows NULL. */
  1758. /* However, Linux does not return 0 on success either. */
  1759. return 0;
  1760. }
  1761. return (void *)ret;
  1762. }
  1763. static int
  1764. event_wait(void *eventhdl)
  1765. {
  1766. uint64_t u;
  1767. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1768. if (s != sizeof(uint64_t)) {
  1769. /* error */
  1770. return 0;
  1771. }
  1772. (void)u; /* the value is not required */
  1773. return 1;
  1774. }
  1775. static int
  1776. event_signal(void *eventhdl)
  1777. {
  1778. uint64_t u = 1;
  1779. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1780. if (s != sizeof(uint64_t)) {
  1781. /* error */
  1782. return 0;
  1783. }
  1784. return 1;
  1785. }
  1786. static void
  1787. event_destroy(void *eventhdl)
  1788. {
  1789. close((int)eventhdl);
  1790. }
  1791. #endif
  1792. #endif
  1793. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1794. struct posix_event {
  1795. pthread_mutex_t mutex;
  1796. pthread_cond_t cond;
  1797. };
  1798. static void *
  1799. event_create(void)
  1800. {
  1801. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1802. if (ret == 0) {
  1803. /* out of memory */
  1804. return 0;
  1805. }
  1806. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1807. /* pthread mutex not available */
  1808. mg_free(ret);
  1809. return 0;
  1810. }
  1811. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1812. /* pthread cond not available */
  1813. pthread_mutex_destroy(&(ret->mutex));
  1814. mg_free(ret);
  1815. return 0;
  1816. }
  1817. return (void *)ret;
  1818. }
  1819. static int
  1820. event_wait(void *eventhdl)
  1821. {
  1822. struct posix_event *ev = (struct posix_event *)eventhdl;
  1823. pthread_mutex_lock(&(ev->mutex));
  1824. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1825. pthread_mutex_unlock(&(ev->mutex));
  1826. return 1;
  1827. }
  1828. static int
  1829. event_signal(void *eventhdl)
  1830. {
  1831. struct posix_event *ev = (struct posix_event *)eventhdl;
  1832. pthread_mutex_lock(&(ev->mutex));
  1833. pthread_cond_signal(&(ev->cond));
  1834. pthread_mutex_unlock(&(ev->mutex));
  1835. return 1;
  1836. }
  1837. static void
  1838. event_destroy(void *eventhdl)
  1839. {
  1840. struct posix_event *ev = (struct posix_event *)eventhdl;
  1841. pthread_cond_destroy(&(ev->cond));
  1842. pthread_mutex_destroy(&(ev->mutex));
  1843. mg_free(ev);
  1844. }
  1845. #endif
  1846. static void
  1847. mg_set_thread_name(const char *name)
  1848. {
  1849. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1850. mg_snprintf(
  1851. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1852. #if defined(_WIN32)
  1853. #if defined(_MSC_VER)
  1854. /* Windows and Visual Studio Compiler */
  1855. __try
  1856. {
  1857. THREADNAME_INFO info;
  1858. info.dwType = 0x1000;
  1859. info.szName = threadName;
  1860. info.dwThreadID = ~0U;
  1861. info.dwFlags = 0;
  1862. RaiseException(0x406D1388,
  1863. 0,
  1864. sizeof(info) / sizeof(ULONG_PTR),
  1865. (ULONG_PTR *)&info);
  1866. }
  1867. __except(EXCEPTION_EXECUTE_HANDLER)
  1868. {
  1869. }
  1870. #elif defined(__MINGW32__)
  1871. /* No option known to set thread name for MinGW */
  1872. #endif
  1873. #elif defined(__GLIBC__) \
  1874. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1875. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1876. (void)pthread_setname_np(pthread_self(), threadName);
  1877. #elif defined(__linux__)
  1878. /* on linux we can use the old prctl function */
  1879. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1880. #endif
  1881. }
  1882. #else /* !defined(NO_THREAD_NAME) */
  1883. void
  1884. mg_set_thread_name(const char *threadName)
  1885. {
  1886. }
  1887. #endif
  1888. #if defined(MG_LEGACY_INTERFACE)
  1889. const char **
  1890. mg_get_valid_option_names(void)
  1891. {
  1892. /* This function is deprecated. Use mg_get_valid_options instead. */
  1893. static const char *
  1894. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1895. int i;
  1896. for (i = 0; config_options[i].name != NULL; i++) {
  1897. data[i * 2] = config_options[i].name;
  1898. data[i * 2 + 1] = config_options[i].default_value;
  1899. }
  1900. return data;
  1901. }
  1902. #endif
  1903. const struct mg_option *
  1904. mg_get_valid_options(void)
  1905. {
  1906. return config_options;
  1907. }
  1908. /* Do not open file (used in is_file_in_memory) */
  1909. #define MG_FOPEN_MODE_NONE (0)
  1910. /* Open file for read only access */
  1911. #define MG_FOPEN_MODE_READ (1)
  1912. /* Open file for writing, create and overwrite */
  1913. #define MG_FOPEN_MODE_WRITE (2)
  1914. /* Open file for writing, create and append */
  1915. #define MG_FOPEN_MODE_APPEND (4)
  1916. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1917. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1918. static int
  1919. open_file_in_memory(const struct mg_connection *conn,
  1920. const char *path,
  1921. struct mg_file *filep,
  1922. int mode)
  1923. {
  1924. size_t size = 0;
  1925. const char *buf = NULL;
  1926. if (!conn) {
  1927. return 0;
  1928. }
  1929. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1930. return 0;
  1931. }
  1932. if (conn->ctx->callbacks.open_file) {
  1933. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1934. if (buf != NULL) {
  1935. if (filep == NULL) {
  1936. /* This is a file in memory, but we cannot store the properties
  1937. * now.
  1938. * Called from "is_file_in_memory" function. */
  1939. return 1;
  1940. }
  1941. /* NOTE: override filep->size only on success. Otherwise, it might
  1942. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1943. filep->access.membuf = buf;
  1944. filep->access.fp = NULL;
  1945. /* Size was set by the callback */
  1946. filep->stat.size = size;
  1947. /* Assume the data may change during runtime by setting
  1948. * last_modified = now */
  1949. filep->stat.last_modified = time(NULL);
  1950. filep->stat.is_directory = 0;
  1951. filep->stat.is_gzipped = 0;
  1952. }
  1953. }
  1954. return (buf != NULL);
  1955. }
  1956. static int
  1957. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1958. {
  1959. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1960. }
  1961. static int
  1962. is_file_opened(const struct mg_file_access *fileacc)
  1963. {
  1964. if (!fileacc) {
  1965. return 0;
  1966. }
  1967. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1968. }
  1969. static int mg_stat(const struct mg_connection *conn,
  1970. const char *path,
  1971. struct mg_file_stat *filep);
  1972. /* mg_fopen will open a file either in memory or on the disk.
  1973. * The input parameter path is a string in UTF-8 encoding.
  1974. * The input parameter mode is MG_FOPEN_MODE_*
  1975. * On success, either fp or membuf will be set in the output
  1976. * struct file. All status members will also be set.
  1977. * The function returns 1 on success, 0 on error. */
  1978. static int
  1979. mg_fopen(const struct mg_connection *conn,
  1980. const char *path,
  1981. int mode,
  1982. struct mg_file *filep)
  1983. {
  1984. int found;
  1985. if (!filep) {
  1986. return 0;
  1987. }
  1988. filep->access.fp = NULL;
  1989. filep->access.membuf = NULL;
  1990. if (!is_file_in_memory(conn, path)) {
  1991. /* filep is initialized in mg_stat: all fields with memset to,
  1992. * some fields like size and modification date with values */
  1993. found = mg_stat(conn, path, &(filep->stat));
  1994. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  1995. /* file does not exist and will not be created */
  1996. return 0;
  1997. }
  1998. #ifdef _WIN32
  1999. {
  2000. wchar_t wbuf[PATH_MAX];
  2001. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2002. switch (mode) {
  2003. case MG_FOPEN_MODE_READ:
  2004. filep->access.fp = _wfopen(wbuf, L"rb");
  2005. break;
  2006. case MG_FOPEN_MODE_WRITE:
  2007. filep->access.fp = _wfopen(wbuf, L"wb");
  2008. break;
  2009. case MG_FOPEN_MODE_APPEND:
  2010. filep->access.fp = _wfopen(wbuf, L"ab");
  2011. break;
  2012. }
  2013. }
  2014. #else
  2015. /* Linux et al already use unicode. No need to convert. */
  2016. switch (mode) {
  2017. case MG_FOPEN_MODE_READ:
  2018. filep->access.fp = fopen(path, "r");
  2019. break;
  2020. case MG_FOPEN_MODE_WRITE:
  2021. filep->access.fp = fopen(path, "w");
  2022. break;
  2023. case MG_FOPEN_MODE_APPEND:
  2024. filep->access.fp = fopen(path, "a");
  2025. break;
  2026. }
  2027. #endif
  2028. if (!found) {
  2029. /* File did not exist before fopen was called.
  2030. * Maybe it has been created now. Get stat info
  2031. * like creation time now. */
  2032. found = mg_stat(conn, path, &(filep->stat));
  2033. (void)found;
  2034. }
  2035. /* file is on disk */
  2036. return (filep->access.fp != NULL);
  2037. } else {
  2038. /* is_file_in_memory returned true */
  2039. if (open_file_in_memory(conn, path, filep, mode)) {
  2040. /* file is in memory */
  2041. return (filep->access.membuf != NULL);
  2042. }
  2043. }
  2044. /* Open failed */
  2045. return 0;
  2046. }
  2047. /* return 0 on success, just like fclose */
  2048. static int
  2049. mg_fclose(struct mg_file_access *fileacc)
  2050. {
  2051. int ret = -1;
  2052. if (fileacc != NULL) {
  2053. if (fileacc->fp != NULL) {
  2054. ret = fclose(fileacc->fp);
  2055. } else if (fileacc->membuf != NULL) {
  2056. ret = 0;
  2057. }
  2058. /* reset all members of fileacc */
  2059. memset(fileacc, 0, sizeof(*fileacc));
  2060. }
  2061. return ret;
  2062. }
  2063. static void
  2064. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2065. {
  2066. for (; *src != '\0' && n > 1; n--) {
  2067. *dst++ = *src++;
  2068. }
  2069. *dst = '\0';
  2070. }
  2071. static int
  2072. lowercase(const char *s)
  2073. {
  2074. return tolower(*(const unsigned char *)s);
  2075. }
  2076. int
  2077. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2078. {
  2079. int diff = 0;
  2080. if (len > 0) {
  2081. do {
  2082. diff = lowercase(s1++) - lowercase(s2++);
  2083. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2084. }
  2085. return diff;
  2086. }
  2087. int
  2088. mg_strcasecmp(const char *s1, const char *s2)
  2089. {
  2090. int diff;
  2091. do {
  2092. diff = lowercase(s1++) - lowercase(s2++);
  2093. } while (diff == 0 && s1[-1] != '\0');
  2094. return diff;
  2095. }
  2096. static char *
  2097. mg_strndup(const char *ptr, size_t len)
  2098. {
  2099. char *p;
  2100. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2101. mg_strlcpy(p, ptr, len + 1);
  2102. }
  2103. return p;
  2104. }
  2105. static char *
  2106. mg_strdup(const char *str)
  2107. {
  2108. return mg_strndup(str, strlen(str));
  2109. }
  2110. static const char *
  2111. mg_strcasestr(const char *big_str, const char *small_str)
  2112. {
  2113. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2114. if (big_len >= small_len) {
  2115. for (i = 0; i <= (big_len - small_len); i++) {
  2116. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2117. return big_str + i;
  2118. }
  2119. }
  2120. }
  2121. return NULL;
  2122. }
  2123. /* Return null terminated string of given maximum length.
  2124. * Report errors if length is exceeded. */
  2125. static void
  2126. mg_vsnprintf(const struct mg_connection *conn,
  2127. int *truncated,
  2128. char *buf,
  2129. size_t buflen,
  2130. const char *fmt,
  2131. va_list ap)
  2132. {
  2133. int n, ok;
  2134. if (buflen == 0) {
  2135. return;
  2136. }
  2137. #ifdef __clang__
  2138. #pragma clang diagnostic push
  2139. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2140. /* Using fmt as a non-literal is intended here, since it is mostly called
  2141. * indirectly by mg_snprintf */
  2142. #endif
  2143. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2144. ok = (n >= 0) && ((size_t)n < buflen);
  2145. #ifdef __clang__
  2146. #pragma clang diagnostic pop
  2147. #endif
  2148. if (ok) {
  2149. if (truncated) {
  2150. *truncated = 0;
  2151. }
  2152. } else {
  2153. if (truncated) {
  2154. *truncated = 1;
  2155. }
  2156. mg_cry(conn,
  2157. "truncating vsnprintf buffer: [%.*s]",
  2158. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2159. buf);
  2160. n = (int)buflen - 1;
  2161. }
  2162. buf[n] = '\0';
  2163. }
  2164. static void
  2165. mg_snprintf(const struct mg_connection *conn,
  2166. int *truncated,
  2167. char *buf,
  2168. size_t buflen,
  2169. const char *fmt,
  2170. ...)
  2171. {
  2172. va_list ap;
  2173. va_start(ap, fmt);
  2174. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2175. va_end(ap);
  2176. }
  2177. static int
  2178. get_option_index(const char *name)
  2179. {
  2180. int i;
  2181. for (i = 0; config_options[i].name != NULL; i++) {
  2182. if (strcmp(config_options[i].name, name) == 0) {
  2183. return i;
  2184. }
  2185. }
  2186. return -1;
  2187. }
  2188. const char *
  2189. mg_get_option(const struct mg_context *ctx, const char *name)
  2190. {
  2191. int i;
  2192. if ((i = get_option_index(name)) == -1) {
  2193. return NULL;
  2194. } else if (!ctx || ctx->config[i] == NULL) {
  2195. return "";
  2196. } else {
  2197. return ctx->config[i];
  2198. }
  2199. }
  2200. struct mg_context *
  2201. mg_get_context(const struct mg_connection *conn)
  2202. {
  2203. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2204. }
  2205. void *
  2206. mg_get_user_data(const struct mg_context *ctx)
  2207. {
  2208. return (ctx == NULL) ? NULL : ctx->user_data;
  2209. }
  2210. void
  2211. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2212. {
  2213. if (conn != NULL) {
  2214. conn->request_info.conn_data = data;
  2215. }
  2216. }
  2217. void *
  2218. mg_get_user_connection_data(const struct mg_connection *conn)
  2219. {
  2220. if (conn != NULL) {
  2221. return conn->request_info.conn_data;
  2222. }
  2223. return NULL;
  2224. }
  2225. size_t
  2226. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2227. {
  2228. size_t i;
  2229. if (!ctx) {
  2230. return 0;
  2231. }
  2232. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2233. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2234. ports[i] =
  2235. #if defined(USE_IPV6)
  2236. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2237. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2238. :
  2239. #endif
  2240. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2241. }
  2242. return i;
  2243. }
  2244. int
  2245. mg_get_server_ports(const struct mg_context *ctx,
  2246. int size,
  2247. struct mg_server_ports *ports)
  2248. {
  2249. int i, cnt = 0;
  2250. if (size <= 0) {
  2251. return -1;
  2252. }
  2253. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2254. if (!ctx) {
  2255. return -1;
  2256. }
  2257. if (!ctx->listening_sockets) {
  2258. return -1;
  2259. }
  2260. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2261. ports[cnt].port =
  2262. #if defined(USE_IPV6)
  2263. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2264. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2265. :
  2266. #endif
  2267. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2268. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2269. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2270. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2271. /* IPv4 */
  2272. ports[cnt].protocol = 1;
  2273. cnt++;
  2274. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2275. /* IPv6 */
  2276. ports[cnt].protocol = 3;
  2277. cnt++;
  2278. }
  2279. }
  2280. return cnt;
  2281. }
  2282. static void
  2283. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2284. {
  2285. buf[0] = '\0';
  2286. if (!usa) {
  2287. return;
  2288. }
  2289. if (usa->sa.sa_family == AF_INET) {
  2290. getnameinfo(&usa->sa,
  2291. sizeof(usa->sin),
  2292. buf,
  2293. (unsigned)len,
  2294. NULL,
  2295. 0,
  2296. NI_NUMERICHOST);
  2297. }
  2298. #if defined(USE_IPV6)
  2299. else if (usa->sa.sa_family == AF_INET6) {
  2300. getnameinfo(&usa->sa,
  2301. sizeof(usa->sin6),
  2302. buf,
  2303. (unsigned)len,
  2304. NULL,
  2305. 0,
  2306. NI_NUMERICHOST);
  2307. }
  2308. #endif
  2309. }
  2310. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2311. * included in all responses other than 100, 101, 5xx. */
  2312. static void
  2313. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2314. {
  2315. struct tm *tm;
  2316. tm = ((t != NULL) ? gmtime(t) : NULL);
  2317. if (tm != NULL) {
  2318. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2319. } else {
  2320. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2321. buf[buf_len - 1] = '\0';
  2322. }
  2323. }
  2324. /* difftime for struct timespec. Return value is in seconds. */
  2325. static double
  2326. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2327. {
  2328. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2329. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2330. }
  2331. /* Print error message to the opened error log stream. */
  2332. void
  2333. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2334. {
  2335. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2336. va_list ap;
  2337. struct mg_file fi;
  2338. time_t timestamp;
  2339. va_start(ap, fmt);
  2340. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2341. va_end(ap);
  2342. buf[sizeof(buf) - 1] = 0;
  2343. if (!conn) {
  2344. puts(buf);
  2345. return;
  2346. }
  2347. /* Do not lock when getting the callback value, here and below.
  2348. * I suppose this is fine, since function cannot disappear in the
  2349. * same way string option can. */
  2350. if ((conn->ctx->callbacks.log_message == NULL)
  2351. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2352. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2353. if (mg_fopen(conn,
  2354. conn->ctx->config[ERROR_LOG_FILE],
  2355. MG_FOPEN_MODE_APPEND,
  2356. &fi) == 0) {
  2357. fi.access.fp = NULL;
  2358. }
  2359. } else {
  2360. fi.access.fp = NULL;
  2361. }
  2362. if (fi.access.fp != NULL) {
  2363. flockfile(fi.access.fp);
  2364. timestamp = time(NULL);
  2365. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2366. fprintf(fi.access.fp,
  2367. "[%010lu] [error] [client %s] ",
  2368. (unsigned long)timestamp,
  2369. src_addr);
  2370. if (conn->request_info.request_method != NULL) {
  2371. fprintf(fi.access.fp,
  2372. "%s %s: ",
  2373. conn->request_info.request_method,
  2374. conn->request_info.request_uri);
  2375. }
  2376. fprintf(fi.access.fp, "%s", buf);
  2377. fputc('\n', fi.access.fp);
  2378. fflush(fi.access.fp);
  2379. funlockfile(fi.access.fp);
  2380. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2381. * mg_cry here anyway ;-) */
  2382. }
  2383. }
  2384. }
  2385. /* Return fake connection structure. Used for logging, if connection
  2386. * is not applicable at the moment of logging. */
  2387. static struct mg_connection *
  2388. fc(struct mg_context *ctx)
  2389. {
  2390. static struct mg_connection fake_connection;
  2391. fake_connection.ctx = ctx;
  2392. return &fake_connection;
  2393. }
  2394. const char *
  2395. mg_version(void)
  2396. {
  2397. return CIVETWEB_VERSION;
  2398. }
  2399. const struct mg_request_info *
  2400. mg_get_request_info(const struct mg_connection *conn)
  2401. {
  2402. if (!conn) {
  2403. return NULL;
  2404. }
  2405. return &conn->request_info;
  2406. }
  2407. /* Skip the characters until one of the delimiters characters found.
  2408. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2409. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2410. * Delimiters can be quoted with quotechar. */
  2411. static char *
  2412. skip_quoted(char **buf,
  2413. const char *delimiters,
  2414. const char *whitespace,
  2415. char quotechar)
  2416. {
  2417. char *p, *begin_word, *end_word, *end_whitespace;
  2418. begin_word = *buf;
  2419. end_word = begin_word + strcspn(begin_word, delimiters);
  2420. /* Check for quotechar */
  2421. if (end_word > begin_word) {
  2422. p = end_word - 1;
  2423. while (*p == quotechar) {
  2424. /* While the delimiter is quoted, look for the next delimiter. */
  2425. /* This happens, e.g., in calls from parse_auth_header,
  2426. * if the user name contains a " character. */
  2427. /* If there is anything beyond end_word, copy it. */
  2428. if (*end_word != '\0') {
  2429. size_t end_off = strcspn(end_word + 1, delimiters);
  2430. memmove(p, end_word, end_off + 1);
  2431. p += end_off; /* p must correspond to end_word - 1 */
  2432. end_word += end_off + 1;
  2433. } else {
  2434. *p = '\0';
  2435. break;
  2436. }
  2437. }
  2438. for (p++; p < end_word; p++) {
  2439. *p = '\0';
  2440. }
  2441. }
  2442. if (*end_word == '\0') {
  2443. *buf = end_word;
  2444. } else {
  2445. #if defined(__GNUC__) || defined(__MINGW32__)
  2446. /* Disable spurious conversion warning for GCC */
  2447. #pragma GCC diagnostic push
  2448. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2449. #endif
  2450. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2451. #if defined(__GNUC__) || defined(__MINGW32__)
  2452. #pragma GCC diagnostic pop
  2453. #endif
  2454. for (p = end_word; p < end_whitespace; p++) {
  2455. *p = '\0';
  2456. }
  2457. *buf = end_whitespace;
  2458. }
  2459. return begin_word;
  2460. }
  2461. /* Simplified version of skip_quoted without quote char
  2462. * and whitespace == delimiters */
  2463. static char *
  2464. skip(char **buf, const char *delimiters)
  2465. {
  2466. return skip_quoted(buf, delimiters, delimiters, 0);
  2467. }
  2468. /* Return HTTP header value, or NULL if not found. */
  2469. static const char *
  2470. get_header(const struct mg_request_info *ri, const char *name)
  2471. {
  2472. int i;
  2473. if (ri) {
  2474. for (i = 0; i < ri->num_headers; i++) {
  2475. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2476. return ri->http_headers[i].value;
  2477. }
  2478. }
  2479. }
  2480. return NULL;
  2481. }
  2482. const char *
  2483. mg_get_header(const struct mg_connection *conn, const char *name)
  2484. {
  2485. if (!conn) {
  2486. return NULL;
  2487. }
  2488. return get_header(&conn->request_info, name);
  2489. }
  2490. /* A helper function for traversing a comma separated list of values.
  2491. * It returns a list pointer shifted to the next value, or NULL if the end
  2492. * of the list found.
  2493. * Value is stored in val vector. If value has form "x=y", then eq_val
  2494. * vector is initialized to point to the "y" part, and val vector length
  2495. * is adjusted to point only to "x". */
  2496. static const char *
  2497. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2498. {
  2499. int end;
  2500. reparse:
  2501. if (val == NULL || list == NULL || *list == '\0') {
  2502. /* End of the list */
  2503. list = NULL;
  2504. } else {
  2505. /* Skip over leading LWS */
  2506. while (*list == ' ' || *list == '\t')
  2507. list++;
  2508. val->ptr = list;
  2509. if ((list = strchr(val->ptr, ',')) != NULL) {
  2510. /* Comma found. Store length and shift the list ptr */
  2511. val->len = ((size_t)(list - val->ptr));
  2512. list++;
  2513. } else {
  2514. /* This value is the last one */
  2515. list = val->ptr + strlen(val->ptr);
  2516. val->len = ((size_t)(list - val->ptr));
  2517. }
  2518. /* Adjust length for trailing LWS */
  2519. end = (int)val->len - 1;
  2520. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2521. end--;
  2522. val->len = (size_t)(end + 1);
  2523. if (val->len == 0) {
  2524. /* Ignore any empty entries. */
  2525. goto reparse;
  2526. }
  2527. if (eq_val != NULL) {
  2528. /* Value has form "x=y", adjust pointers and lengths
  2529. * so that val points to "x", and eq_val points to "y". */
  2530. eq_val->len = 0;
  2531. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2532. if (eq_val->ptr != NULL) {
  2533. eq_val->ptr++; /* Skip over '=' character */
  2534. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2535. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2536. }
  2537. }
  2538. }
  2539. return list;
  2540. }
  2541. /* A helper function for checking if a comma separated list of values contains
  2542. * the given option (case insensitvely).
  2543. * 'header' can be NULL, in which case false is returned. */
  2544. static int
  2545. header_has_option(const char *header, const char *option)
  2546. {
  2547. struct vec opt_vec;
  2548. struct vec eq_vec;
  2549. assert(option != NULL);
  2550. assert(option[0] != '\0');
  2551. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2552. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2553. return 1;
  2554. }
  2555. return 0;
  2556. }
  2557. /* Perform case-insensitive match of string against pattern */
  2558. static int
  2559. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2560. {
  2561. const char *or_str;
  2562. size_t i;
  2563. int j, len, res;
  2564. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2565. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2566. return (res > 0) ? res : match_prefix(or_str + 1,
  2567. (size_t)((pattern + pattern_len)
  2568. - (or_str + 1)),
  2569. str);
  2570. }
  2571. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2572. if (pattern[i] == '?' && str[j] != '\0') {
  2573. continue;
  2574. } else if (pattern[i] == '$') {
  2575. return (str[j] == '\0') ? j : -1;
  2576. } else if (pattern[i] == '*') {
  2577. i++;
  2578. if (pattern[i] == '*') {
  2579. i++;
  2580. len = (int)strlen(str + j);
  2581. } else {
  2582. len = (int)strcspn(str + j, "/");
  2583. }
  2584. if (i == pattern_len) {
  2585. return j + len;
  2586. }
  2587. do {
  2588. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2589. } while (res == -1 && len-- > 0);
  2590. return (res == -1) ? -1 : j + res + len;
  2591. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2592. return -1;
  2593. }
  2594. }
  2595. return j;
  2596. }
  2597. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2598. * This function must tolerate situations when connection info is not
  2599. * set up, for example if request parsing failed. */
  2600. static int
  2601. should_keep_alive(const struct mg_connection *conn)
  2602. {
  2603. if (conn != NULL) {
  2604. const char *http_version = conn->request_info.http_version;
  2605. const char *header = mg_get_header(conn, "Connection");
  2606. if (conn->must_close || conn->status_code == 401
  2607. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2608. || (header != NULL && !header_has_option(header, "keep-alive"))
  2609. || (header == NULL && http_version
  2610. && 0 != strcmp(http_version, "1.1"))) {
  2611. return 0;
  2612. }
  2613. return 1;
  2614. }
  2615. return 0;
  2616. }
  2617. static int
  2618. should_decode_url(const struct mg_connection *conn)
  2619. {
  2620. if (!conn || !conn->ctx) {
  2621. return 0;
  2622. }
  2623. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2624. }
  2625. static const char *
  2626. suggest_connection_header(const struct mg_connection *conn)
  2627. {
  2628. return should_keep_alive(conn) ? "keep-alive" : "close";
  2629. }
  2630. static int
  2631. send_no_cache_header(struct mg_connection *conn)
  2632. {
  2633. /* Send all current and obsolete cache opt-out directives. */
  2634. return mg_printf(conn,
  2635. "Cache-Control: no-cache, no-store, "
  2636. "must-revalidate, private, max-age=0\r\n"
  2637. "Pragma: no-cache\r\n"
  2638. "Expires: 0\r\n");
  2639. }
  2640. static int
  2641. send_static_cache_header(struct mg_connection *conn)
  2642. {
  2643. #if !defined(NO_CACHING)
  2644. /* Read the server config to check how long a file may be cached.
  2645. * The configuration is in seconds. */
  2646. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2647. if (max_age <= 0) {
  2648. /* 0 means "do not cache". All values <0 are reserved
  2649. * and may be used differently in the future. */
  2650. /* If a file should not be cached, do not only send
  2651. * max-age=0, but also pragmas and Expires headers. */
  2652. return send_no_cache_header(conn);
  2653. }
  2654. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2655. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2656. /* See also https://www.mnot.net/cache_docs/ */
  2657. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2658. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2659. * year to 31622400 seconds. For the moment, we just send whatever has
  2660. * been configured, still the behavior for >1 year should be considered
  2661. * as undefined. */
  2662. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2663. #else /* NO_CACHING */
  2664. return send_no_cache_header(conn);
  2665. #endif /* !NO_CACHING */
  2666. }
  2667. static void handle_file_based_request(struct mg_connection *conn,
  2668. const char *path,
  2669. struct mg_file *filep);
  2670. const char *
  2671. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2672. {
  2673. /* See IANA HTTP status code assignment:
  2674. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2675. */
  2676. switch (response_code) {
  2677. /* RFC2616 Section 10.1 - Informational 1xx */
  2678. case 100:
  2679. return "Continue"; /* RFC2616 Section 10.1.1 */
  2680. case 101:
  2681. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2682. case 102:
  2683. return "Processing"; /* RFC2518 Section 10.1 */
  2684. /* RFC2616 Section 10.2 - Successful 2xx */
  2685. case 200:
  2686. return "OK"; /* RFC2616 Section 10.2.1 */
  2687. case 201:
  2688. return "Created"; /* RFC2616 Section 10.2.2 */
  2689. case 202:
  2690. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2691. case 203:
  2692. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2693. case 204:
  2694. return "No Content"; /* RFC2616 Section 10.2.5 */
  2695. case 205:
  2696. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2697. case 206:
  2698. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2699. case 207:
  2700. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2701. case 208:
  2702. return "Already Reported"; /* RFC5842 Section 7.1 */
  2703. case 226:
  2704. return "IM used"; /* RFC3229 Section 10.4.1 */
  2705. /* RFC2616 Section 10.3 - Redirection 3xx */
  2706. case 300:
  2707. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2708. case 301:
  2709. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2710. case 302:
  2711. return "Found"; /* RFC2616 Section 10.3.3 */
  2712. case 303:
  2713. return "See Other"; /* RFC2616 Section 10.3.4 */
  2714. case 304:
  2715. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2716. case 305:
  2717. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2718. case 307:
  2719. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2720. case 308:
  2721. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2722. /* RFC2616 Section 10.4 - Client Error 4xx */
  2723. case 400:
  2724. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2725. case 401:
  2726. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2727. case 402:
  2728. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2729. case 403:
  2730. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2731. case 404:
  2732. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2733. case 405:
  2734. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2735. case 406:
  2736. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2737. case 407:
  2738. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2739. case 408:
  2740. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2741. case 409:
  2742. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2743. case 410:
  2744. return "Gone"; /* RFC2616 Section 10.4.11 */
  2745. case 411:
  2746. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2747. case 412:
  2748. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2749. case 413:
  2750. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2751. case 414:
  2752. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2753. case 415:
  2754. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2755. case 416:
  2756. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2757. case 417:
  2758. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2759. case 421:
  2760. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2761. case 422:
  2762. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2763. * Section 11.2 */
  2764. case 423:
  2765. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2766. case 424:
  2767. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2768. * Section 11.4 */
  2769. case 426:
  2770. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2771. case 428:
  2772. return "Precondition Required"; /* RFC 6585, Section 3 */
  2773. case 429:
  2774. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2775. case 431:
  2776. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2777. case 451:
  2778. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2779. * Section 3 */
  2780. /* RFC2616 Section 10.5 - Server Error 5xx */
  2781. case 500:
  2782. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2783. case 501:
  2784. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2785. case 502:
  2786. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2787. case 503:
  2788. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2789. case 504:
  2790. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2791. case 505:
  2792. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2793. case 506:
  2794. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2795. case 507:
  2796. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2797. * Section 11.5 */
  2798. case 508:
  2799. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2800. case 510:
  2801. return "Not Extended"; /* RFC 2774, Section 7 */
  2802. case 511:
  2803. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2804. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2805. * E.g., "de facto" standards due to common use, ... */
  2806. case 418:
  2807. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2808. case 419:
  2809. return "Authentication Timeout"; /* common use */
  2810. case 420:
  2811. return "Enhance Your Calm"; /* common use */
  2812. case 440:
  2813. return "Login Timeout"; /* common use */
  2814. case 509:
  2815. return "Bandwidth Limit Exceeded"; /* common use */
  2816. default:
  2817. /* This error code is unknown. This should not happen. */
  2818. if (conn) {
  2819. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2820. }
  2821. /* Return at least a category according to RFC 2616 Section 10. */
  2822. if (response_code >= 100 && response_code < 200) {
  2823. /* Unknown informational status code */
  2824. return "Information";
  2825. }
  2826. if (response_code >= 200 && response_code < 300) {
  2827. /* Unknown success code */
  2828. return "Success";
  2829. }
  2830. if (response_code >= 300 && response_code < 400) {
  2831. /* Unknown redirection code */
  2832. return "Redirection";
  2833. }
  2834. if (response_code >= 400 && response_code < 500) {
  2835. /* Unknown request error code */
  2836. return "Client Error";
  2837. }
  2838. if (response_code >= 500 && response_code < 600) {
  2839. /* Unknown server error code */
  2840. return "Server Error";
  2841. }
  2842. /* Response code not even within reasonable range */
  2843. return "";
  2844. }
  2845. }
  2846. static void send_http_error(struct mg_connection *,
  2847. int,
  2848. PRINTF_FORMAT_STRING(const char *fmt),
  2849. ...) PRINTF_ARGS(3, 4);
  2850. static void
  2851. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2852. {
  2853. char buf[MG_BUF_LEN];
  2854. va_list ap;
  2855. int len, i, page_handler_found, scope, truncated, has_body;
  2856. char date[64];
  2857. time_t curtime = time(NULL);
  2858. const char *error_handler = NULL;
  2859. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2860. const char *error_page_file_ext, *tstr;
  2861. const char *status_text = mg_get_response_code_text(conn, status);
  2862. if (conn == NULL) {
  2863. return;
  2864. }
  2865. conn->status_code = status;
  2866. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2867. || conn->ctx->callbacks.http_error(conn, status)) {
  2868. if (!conn->in_error_handler) {
  2869. /* Send user defined error pages, if defined */
  2870. error_handler = conn->ctx->config[ERROR_PAGES];
  2871. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2872. page_handler_found = 0;
  2873. if (error_handler != NULL) {
  2874. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2875. switch (scope) {
  2876. case 1: /* Handler for specific error, e.g. 404 error */
  2877. mg_snprintf(conn,
  2878. &truncated,
  2879. buf,
  2880. sizeof(buf) - 32,
  2881. "%serror%03u.",
  2882. error_handler,
  2883. status);
  2884. break;
  2885. case 2: /* Handler for error group, e.g., 5xx error handler
  2886. * for all server errors (500-599) */
  2887. mg_snprintf(conn,
  2888. &truncated,
  2889. buf,
  2890. sizeof(buf) - 32,
  2891. "%serror%01uxx.",
  2892. error_handler,
  2893. status / 100);
  2894. break;
  2895. default: /* Handler for all errors */
  2896. mg_snprintf(conn,
  2897. &truncated,
  2898. buf,
  2899. sizeof(buf) - 32,
  2900. "%serror.",
  2901. error_handler);
  2902. break;
  2903. }
  2904. /* String truncation in buf may only occur if error_handler
  2905. * is too long. This string is from the config, not from a
  2906. * client. */
  2907. (void)truncated;
  2908. len = (int)strlen(buf);
  2909. tstr = strchr(error_page_file_ext, '.');
  2910. while (tstr) {
  2911. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2912. i++)
  2913. buf[len + i - 1] = tstr[i];
  2914. buf[len + i - 1] = 0;
  2915. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2916. page_handler_found = 1;
  2917. break;
  2918. }
  2919. tstr = strchr(tstr + i, '.');
  2920. }
  2921. }
  2922. }
  2923. if (page_handler_found) {
  2924. conn->in_error_handler = 1;
  2925. handle_file_based_request(conn, buf, &error_page_file);
  2926. conn->in_error_handler = 0;
  2927. return;
  2928. }
  2929. }
  2930. /* No custom error page. Send default error page. */
  2931. gmt_time_string(date, sizeof(date), &curtime);
  2932. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2933. has_body = (status > 199 && status != 204 && status != 304);
  2934. conn->must_close = 1;
  2935. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2936. send_no_cache_header(conn);
  2937. if (has_body) {
  2938. mg_printf(conn,
  2939. "%s",
  2940. "Content-Type: text/plain; charset=utf-8\r\n");
  2941. }
  2942. mg_printf(conn,
  2943. "Date: %s\r\n"
  2944. "Connection: close\r\n\r\n",
  2945. date);
  2946. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2947. if (has_body) {
  2948. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2949. if (fmt != NULL) {
  2950. va_start(ap, fmt);
  2951. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2952. va_end(ap);
  2953. mg_write(conn, buf, strlen(buf));
  2954. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2955. }
  2956. } else {
  2957. /* No body allowed. Close the connection. */
  2958. DEBUG_TRACE("Error %i", status);
  2959. }
  2960. }
  2961. }
  2962. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2963. /* Create substitutes for POSIX functions in Win32. */
  2964. #if defined(__MINGW32__)
  2965. /* Show no warning in case system functions are not used. */
  2966. #pragma GCC diagnostic push
  2967. #pragma GCC diagnostic ignored "-Wunused-function"
  2968. #endif
  2969. static int
  2970. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2971. {
  2972. (void)unused;
  2973. *mutex = CreateMutex(NULL, FALSE, NULL);
  2974. return (*mutex == NULL) ? -1 : 0;
  2975. }
  2976. static int
  2977. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2978. {
  2979. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2980. }
  2981. static int
  2982. pthread_mutex_lock(pthread_mutex_t *mutex)
  2983. {
  2984. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2985. }
  2986. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2987. static int
  2988. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2989. {
  2990. switch (WaitForSingleObject(*mutex, 0)) {
  2991. case WAIT_OBJECT_0:
  2992. return 0;
  2993. case WAIT_TIMEOUT:
  2994. return -2; /* EBUSY */
  2995. }
  2996. return -1;
  2997. }
  2998. #endif
  2999. static int
  3000. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3001. {
  3002. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3003. }
  3004. static int
  3005. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3006. {
  3007. (void)unused;
  3008. InitializeCriticalSection(&cv->threadIdSec);
  3009. cv->waiting_thread = NULL;
  3010. return 0;
  3011. }
  3012. static int
  3013. pthread_cond_timedwait(pthread_cond_t *cv,
  3014. pthread_mutex_t *mutex,
  3015. const struct timespec *abstime)
  3016. {
  3017. struct mg_workerTLS **ptls,
  3018. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3019. int ok;
  3020. struct timespec tsnow;
  3021. int64_t nsnow, nswaitabs, nswaitrel;
  3022. DWORD mswaitrel;
  3023. EnterCriticalSection(&cv->threadIdSec);
  3024. /* Add this thread to cv's waiting list */
  3025. ptls = &cv->waiting_thread;
  3026. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3027. ;
  3028. tls->next_waiting_thread = NULL;
  3029. *ptls = tls;
  3030. LeaveCriticalSection(&cv->threadIdSec);
  3031. if (abstime) {
  3032. clock_gettime(CLOCK_REALTIME, &tsnow);
  3033. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  3034. nswaitabs =
  3035. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3036. nswaitrel = nswaitabs - nsnow;
  3037. if (nswaitrel < 0) {
  3038. nswaitrel = 0;
  3039. }
  3040. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3041. } else {
  3042. mswaitrel = INFINITE;
  3043. }
  3044. pthread_mutex_unlock(mutex);
  3045. ok = (WAIT_OBJECT_0
  3046. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3047. if (!ok) {
  3048. ok = 1;
  3049. EnterCriticalSection(&cv->threadIdSec);
  3050. ptls = &cv->waiting_thread;
  3051. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3052. if (*ptls == tls) {
  3053. *ptls = tls->next_waiting_thread;
  3054. ok = 0;
  3055. break;
  3056. }
  3057. }
  3058. LeaveCriticalSection(&cv->threadIdSec);
  3059. if (ok) {
  3060. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3061. }
  3062. }
  3063. /* This thread has been removed from cv's waiting list */
  3064. pthread_mutex_lock(mutex);
  3065. return ok ? 0 : -1;
  3066. }
  3067. static int
  3068. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3069. {
  3070. return pthread_cond_timedwait(cv, mutex, NULL);
  3071. }
  3072. static int
  3073. pthread_cond_signal(pthread_cond_t *cv)
  3074. {
  3075. HANDLE wkup = NULL;
  3076. BOOL ok = FALSE;
  3077. EnterCriticalSection(&cv->threadIdSec);
  3078. if (cv->waiting_thread) {
  3079. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3080. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3081. ok = SetEvent(wkup);
  3082. assert(ok);
  3083. }
  3084. LeaveCriticalSection(&cv->threadIdSec);
  3085. return ok ? 0 : 1;
  3086. }
  3087. static int
  3088. pthread_cond_broadcast(pthread_cond_t *cv)
  3089. {
  3090. EnterCriticalSection(&cv->threadIdSec);
  3091. while (cv->waiting_thread) {
  3092. pthread_cond_signal(cv);
  3093. }
  3094. LeaveCriticalSection(&cv->threadIdSec);
  3095. return 0;
  3096. }
  3097. static int
  3098. pthread_cond_destroy(pthread_cond_t *cv)
  3099. {
  3100. EnterCriticalSection(&cv->threadIdSec);
  3101. assert(cv->waiting_thread == NULL);
  3102. LeaveCriticalSection(&cv->threadIdSec);
  3103. DeleteCriticalSection(&cv->threadIdSec);
  3104. return 0;
  3105. }
  3106. #ifdef ALTERNATIVE_QUEUE
  3107. static void *
  3108. event_create(void)
  3109. {
  3110. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3111. }
  3112. static int
  3113. event_wait(void *eventhdl)
  3114. {
  3115. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3116. return (res == WAIT_OBJECT_0);
  3117. }
  3118. static int
  3119. event_signal(void *eventhdl)
  3120. {
  3121. return (int)SetEvent((HANDLE)eventhdl);
  3122. }
  3123. static void
  3124. event_destroy(void *eventhdl)
  3125. {
  3126. CloseHandle((HANDLE)eventhdl);
  3127. }
  3128. #endif
  3129. #if defined(__MINGW32__)
  3130. /* Enable unused function warning again */
  3131. #pragma GCC diagnostic pop
  3132. #endif
  3133. /* For Windows, change all slashes to backslashes in path names. */
  3134. static void
  3135. change_slashes_to_backslashes(char *path)
  3136. {
  3137. int i;
  3138. for (i = 0; path[i] != '\0'; i++) {
  3139. if (path[i] == '/') {
  3140. path[i] = '\\';
  3141. }
  3142. /* remove double backslash (check i > 0 to preserve UNC paths,
  3143. * like \\server\file.txt) */
  3144. if ((path[i] == '\\') && (i > 0)) {
  3145. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3146. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3147. }
  3148. }
  3149. }
  3150. }
  3151. static int
  3152. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3153. {
  3154. int diff;
  3155. do {
  3156. diff = tolower(*s1) - tolower(*s2);
  3157. s1++;
  3158. s2++;
  3159. } while (diff == 0 && s1[-1] != '\0');
  3160. return diff;
  3161. }
  3162. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3163. * wbuf and wbuf_len is a target buffer and its length. */
  3164. static void
  3165. path_to_unicode(const struct mg_connection *conn,
  3166. const char *path,
  3167. wchar_t *wbuf,
  3168. size_t wbuf_len)
  3169. {
  3170. char buf[PATH_MAX], buf2[PATH_MAX];
  3171. wchar_t wbuf2[MAX_PATH + 1];
  3172. DWORD long_len, err;
  3173. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3174. mg_strlcpy(buf, path, sizeof(buf));
  3175. change_slashes_to_backslashes(buf);
  3176. /* Convert to Unicode and back. If doubly-converted string does not
  3177. * match the original, something is fishy, reject. */
  3178. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3179. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3180. WideCharToMultiByte(
  3181. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3182. if (strcmp(buf, buf2) != 0) {
  3183. wbuf[0] = L'\0';
  3184. }
  3185. /* Windows file systems are not case sensitive, but you can still use
  3186. * uppercase and lowercase letters (on all modern file systems).
  3187. * The server can check if the URI uses the same upper/lowercase
  3188. * letters an the file system, effectively making Windows servers
  3189. * case sensitive (like Linux servers are). It is still not possible
  3190. * to use two files with the same name in different cases on Windows
  3191. * (like /a and /A) - this would be possible in Linux.
  3192. * As a default, Windows is not case sensitive, but the case sensitive
  3193. * file name check can be activated by an additional configuration. */
  3194. if (conn) {
  3195. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3196. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3197. /* Use case sensitive compare function */
  3198. fcompare = wcscmp;
  3199. }
  3200. }
  3201. (void)conn; /* conn is currently unused */
  3202. #if !defined(_WIN32_WCE)
  3203. /* Only accept a full file path, not a Windows short (8.3) path. */
  3204. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3205. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3206. if (long_len == 0) {
  3207. err = GetLastError();
  3208. if (err == ERROR_FILE_NOT_FOUND) {
  3209. /* File does not exist. This is not always a problem here. */
  3210. return;
  3211. }
  3212. }
  3213. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3214. /* Short name is used. */
  3215. wbuf[0] = L'\0';
  3216. }
  3217. #else
  3218. (void)long_len;
  3219. (void)wbuf2;
  3220. (void)err;
  3221. if (strchr(path, '~')) {
  3222. wbuf[0] = L'\0';
  3223. }
  3224. #endif
  3225. }
  3226. /* Windows happily opens files with some garbage at the end of file name.
  3227. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3228. * "a.cgi", despite one would expect an error back.
  3229. * This function returns non-0 if path ends with some garbage. */
  3230. static int
  3231. path_cannot_disclose_cgi(const char *path)
  3232. {
  3233. static const char *allowed_last_characters = "_-";
  3234. int last = path[strlen(path) - 1];
  3235. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3236. }
  3237. static int
  3238. mg_stat(const struct mg_connection *conn,
  3239. const char *path,
  3240. struct mg_file_stat *filep)
  3241. {
  3242. wchar_t wbuf[PATH_MAX];
  3243. WIN32_FILE_ATTRIBUTE_DATA info;
  3244. time_t creation_time;
  3245. if (!filep) {
  3246. return 0;
  3247. }
  3248. memset(filep, 0, sizeof(*filep));
  3249. if (conn && is_file_in_memory(conn, path)) {
  3250. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3251. * memset */
  3252. /* Quick fix (for 1.9.x): */
  3253. /* mg_stat must fill all fields, also for files in memory */
  3254. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3255. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3256. filep->size = tmp_file.stat.size;
  3257. filep->location = 2;
  3258. /* TODO: for 1.10: restructure how files in memory are handled */
  3259. filep->last_modified = time(NULL); /* xxxxxxxx */
  3260. /* last_modified = now ... assumes the file may change during runtime,
  3261. * so every mg_fopen call may return different data */
  3262. /* last_modified = conn->ctx.start_time;
  3263. * May be used it the data does not change during runtime. This allows
  3264. * browser caching. Since we do not know, we have to assume the file
  3265. * in memory may change. */
  3266. return 1;
  3267. }
  3268. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3269. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3270. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3271. filep->last_modified =
  3272. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3273. info.ftLastWriteTime.dwHighDateTime);
  3274. /* On Windows, the file creation time can be higher than the
  3275. * modification time, e.g. when a file is copied.
  3276. * Since the Last-Modified timestamp is used for caching
  3277. * it should be based on the most recent timestamp. */
  3278. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3279. info.ftCreationTime.dwHighDateTime);
  3280. if (creation_time > filep->last_modified) {
  3281. filep->last_modified = creation_time;
  3282. }
  3283. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3284. /* If file name is fishy, reset the file structure and return
  3285. * error.
  3286. * Note it is important to reset, not just return the error, cause
  3287. * functions like is_file_opened() check the struct. */
  3288. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3289. memset(filep, 0, sizeof(*filep));
  3290. return 0;
  3291. }
  3292. return 1;
  3293. }
  3294. return 0;
  3295. }
  3296. static int
  3297. mg_remove(const struct mg_connection *conn, const char *path)
  3298. {
  3299. wchar_t wbuf[PATH_MAX];
  3300. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3301. return DeleteFileW(wbuf) ? 0 : -1;
  3302. }
  3303. static int
  3304. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3305. {
  3306. wchar_t wbuf[PATH_MAX];
  3307. (void)mode;
  3308. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3309. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3310. }
  3311. /* Create substitutes for POSIX functions in Win32. */
  3312. #if defined(__MINGW32__)
  3313. /* Show no warning in case system functions are not used. */
  3314. #pragma GCC diagnostic push
  3315. #pragma GCC diagnostic ignored "-Wunused-function"
  3316. #endif
  3317. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3318. static DIR *
  3319. mg_opendir(const struct mg_connection *conn, const char *name)
  3320. {
  3321. DIR *dir = NULL;
  3322. wchar_t wpath[PATH_MAX];
  3323. DWORD attrs;
  3324. if (name == NULL) {
  3325. SetLastError(ERROR_BAD_ARGUMENTS);
  3326. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3327. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3328. } else {
  3329. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3330. attrs = GetFileAttributesW(wpath);
  3331. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3332. == FILE_ATTRIBUTE_DIRECTORY)) {
  3333. (void)wcscat(wpath, L"\\*");
  3334. dir->handle = FindFirstFileW(wpath, &dir->info);
  3335. dir->result.d_name[0] = '\0';
  3336. } else {
  3337. mg_free(dir);
  3338. dir = NULL;
  3339. }
  3340. }
  3341. return dir;
  3342. }
  3343. static int
  3344. mg_closedir(DIR *dir)
  3345. {
  3346. int result = 0;
  3347. if (dir != NULL) {
  3348. if (dir->handle != INVALID_HANDLE_VALUE)
  3349. result = FindClose(dir->handle) ? 0 : -1;
  3350. mg_free(dir);
  3351. } else {
  3352. result = -1;
  3353. SetLastError(ERROR_BAD_ARGUMENTS);
  3354. }
  3355. return result;
  3356. }
  3357. static struct dirent *
  3358. mg_readdir(DIR *dir)
  3359. {
  3360. struct dirent *result = 0;
  3361. if (dir) {
  3362. if (dir->handle != INVALID_HANDLE_VALUE) {
  3363. result = &dir->result;
  3364. (void)WideCharToMultiByte(CP_UTF8,
  3365. 0,
  3366. dir->info.cFileName,
  3367. -1,
  3368. result->d_name,
  3369. sizeof(result->d_name),
  3370. NULL,
  3371. NULL);
  3372. if (!FindNextFileW(dir->handle, &dir->info)) {
  3373. (void)FindClose(dir->handle);
  3374. dir->handle = INVALID_HANDLE_VALUE;
  3375. }
  3376. } else {
  3377. SetLastError(ERROR_FILE_NOT_FOUND);
  3378. }
  3379. } else {
  3380. SetLastError(ERROR_BAD_ARGUMENTS);
  3381. }
  3382. return result;
  3383. }
  3384. #ifndef HAVE_POLL
  3385. static int
  3386. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3387. {
  3388. struct timeval tv;
  3389. fd_set set;
  3390. unsigned int i;
  3391. int result;
  3392. SOCKET maxfd = 0;
  3393. memset(&tv, 0, sizeof(tv));
  3394. tv.tv_sec = milliseconds / 1000;
  3395. tv.tv_usec = (milliseconds % 1000) * 1000;
  3396. FD_ZERO(&set);
  3397. for (i = 0; i < n; i++) {
  3398. FD_SET((SOCKET)pfd[i].fd, &set);
  3399. pfd[i].revents = 0;
  3400. if (pfd[i].fd > maxfd) {
  3401. maxfd = pfd[i].fd;
  3402. }
  3403. }
  3404. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3405. for (i = 0; i < n; i++) {
  3406. if (FD_ISSET(pfd[i].fd, &set)) {
  3407. pfd[i].revents = POLLIN;
  3408. }
  3409. }
  3410. }
  3411. /* We should subtract the time used in select from remaining
  3412. * "milliseconds", in particular if called from mg_poll with a
  3413. * timeout quantum.
  3414. * Unfortunately, the remaining time is not stored in "tv" in all
  3415. * implementations, so the result in "tv" must be considered undefined.
  3416. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3417. return result;
  3418. }
  3419. #endif /* HAVE_POLL */
  3420. #if defined(__MINGW32__)
  3421. /* Enable unused function warning again */
  3422. #pragma GCC diagnostic pop
  3423. #endif
  3424. static void
  3425. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3426. {
  3427. (void)conn; /* Unused. */
  3428. #if defined(_WIN32_WCE)
  3429. (void)sock;
  3430. #else
  3431. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3432. #endif
  3433. }
  3434. int
  3435. mg_start_thread(mg_thread_func_t f, void *p)
  3436. {
  3437. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3438. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3439. */
  3440. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3441. == ((uintptr_t)(-1L)))
  3442. ? -1
  3443. : 0);
  3444. #else
  3445. return (
  3446. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3447. ? -1
  3448. : 0);
  3449. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3450. }
  3451. /* Start a thread storing the thread context. */
  3452. static int
  3453. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3454. void *p,
  3455. pthread_t *threadidptr)
  3456. {
  3457. uintptr_t uip;
  3458. HANDLE threadhandle;
  3459. int result = -1;
  3460. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3461. threadhandle = (HANDLE)uip;
  3462. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3463. *threadidptr = threadhandle;
  3464. result = 0;
  3465. }
  3466. return result;
  3467. }
  3468. /* Wait for a thread to finish. */
  3469. static int
  3470. mg_join_thread(pthread_t threadid)
  3471. {
  3472. int result;
  3473. DWORD dwevent;
  3474. result = -1;
  3475. dwevent = WaitForSingleObject(threadid, INFINITE);
  3476. if (dwevent == WAIT_FAILED) {
  3477. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3478. } else {
  3479. if (dwevent == WAIT_OBJECT_0) {
  3480. CloseHandle(threadid);
  3481. result = 0;
  3482. }
  3483. }
  3484. return result;
  3485. }
  3486. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3487. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3488. /* Create substitutes for POSIX functions in Win32. */
  3489. #if defined(__MINGW32__)
  3490. /* Show no warning in case system functions are not used. */
  3491. #pragma GCC diagnostic push
  3492. #pragma GCC diagnostic ignored "-Wunused-function"
  3493. #endif
  3494. static HANDLE
  3495. dlopen(const char *dll_name, int flags)
  3496. {
  3497. wchar_t wbuf[PATH_MAX];
  3498. (void)flags;
  3499. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3500. return LoadLibraryW(wbuf);
  3501. }
  3502. static int
  3503. dlclose(void *handle)
  3504. {
  3505. int result;
  3506. if (FreeLibrary((HMODULE)handle) != 0) {
  3507. result = 0;
  3508. } else {
  3509. result = -1;
  3510. }
  3511. return result;
  3512. }
  3513. #if defined(__MINGW32__)
  3514. /* Enable unused function warning again */
  3515. #pragma GCC diagnostic pop
  3516. #endif
  3517. #endif
  3518. #if !defined(NO_CGI)
  3519. #define SIGKILL (0)
  3520. static int
  3521. kill(pid_t pid, int sig_num)
  3522. {
  3523. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3524. (void)CloseHandle((HANDLE)pid);
  3525. return 0;
  3526. }
  3527. static void
  3528. trim_trailing_whitespaces(char *s)
  3529. {
  3530. char *e = s + strlen(s) - 1;
  3531. while (e > s && isspace(*(unsigned char *)e)) {
  3532. *e-- = '\0';
  3533. }
  3534. }
  3535. static pid_t
  3536. spawn_process(struct mg_connection *conn,
  3537. const char *prog,
  3538. char *envblk,
  3539. char *envp[],
  3540. int fdin[2],
  3541. int fdout[2],
  3542. int fderr[2],
  3543. const char *dir)
  3544. {
  3545. HANDLE me;
  3546. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3547. cmdline[PATH_MAX], buf[PATH_MAX];
  3548. int truncated;
  3549. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3550. STARTUPINFOA si;
  3551. PROCESS_INFORMATION pi = {0};
  3552. (void)envp;
  3553. memset(&si, 0, sizeof(si));
  3554. si.cb = sizeof(si);
  3555. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3556. si.wShowWindow = SW_HIDE;
  3557. me = GetCurrentProcess();
  3558. DuplicateHandle(me,
  3559. (HANDLE)_get_osfhandle(fdin[0]),
  3560. me,
  3561. &si.hStdInput,
  3562. 0,
  3563. TRUE,
  3564. DUPLICATE_SAME_ACCESS);
  3565. DuplicateHandle(me,
  3566. (HANDLE)_get_osfhandle(fdout[1]),
  3567. me,
  3568. &si.hStdOutput,
  3569. 0,
  3570. TRUE,
  3571. DUPLICATE_SAME_ACCESS);
  3572. DuplicateHandle(me,
  3573. (HANDLE)_get_osfhandle(fderr[1]),
  3574. me,
  3575. &si.hStdError,
  3576. 0,
  3577. TRUE,
  3578. DUPLICATE_SAME_ACCESS);
  3579. /* Mark handles that should not be inherited. See
  3580. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3581. */
  3582. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3583. HANDLE_FLAG_INHERIT,
  3584. 0);
  3585. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3586. HANDLE_FLAG_INHERIT,
  3587. 0);
  3588. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3589. HANDLE_FLAG_INHERIT,
  3590. 0);
  3591. /* If CGI file is a script, try to read the interpreter line */
  3592. interp = conn->ctx->config[CGI_INTERPRETER];
  3593. if (interp == NULL) {
  3594. buf[0] = buf[1] = '\0';
  3595. /* Read the first line of the script into the buffer */
  3596. mg_snprintf(
  3597. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3598. if (truncated) {
  3599. pi.hProcess = (pid_t)-1;
  3600. goto spawn_cleanup;
  3601. }
  3602. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3603. p = (char *)file.access.membuf;
  3604. mg_fgets(buf, sizeof(buf), &file, &p);
  3605. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3606. buf[sizeof(buf) - 1] = '\0';
  3607. }
  3608. if (buf[0] == '#' && buf[1] == '!') {
  3609. trim_trailing_whitespaces(buf + 2);
  3610. } else {
  3611. buf[2] = '\0';
  3612. }
  3613. interp = buf + 2;
  3614. }
  3615. if (interp[0] != '\0') {
  3616. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3617. interp = full_interp;
  3618. }
  3619. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3620. if (interp[0] != '\0') {
  3621. mg_snprintf(conn,
  3622. &truncated,
  3623. cmdline,
  3624. sizeof(cmdline),
  3625. "\"%s\" \"%s\\%s\"",
  3626. interp,
  3627. full_dir,
  3628. prog);
  3629. } else {
  3630. mg_snprintf(conn,
  3631. &truncated,
  3632. cmdline,
  3633. sizeof(cmdline),
  3634. "\"%s\\%s\"",
  3635. full_dir,
  3636. prog);
  3637. }
  3638. if (truncated) {
  3639. pi.hProcess = (pid_t)-1;
  3640. goto spawn_cleanup;
  3641. }
  3642. DEBUG_TRACE("Running [%s]", cmdline);
  3643. if (CreateProcessA(NULL,
  3644. cmdline,
  3645. NULL,
  3646. NULL,
  3647. TRUE,
  3648. CREATE_NEW_PROCESS_GROUP,
  3649. envblk,
  3650. NULL,
  3651. &si,
  3652. &pi) == 0) {
  3653. mg_cry(
  3654. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3655. pi.hProcess = (pid_t)-1;
  3656. /* goto spawn_cleanup; */
  3657. }
  3658. spawn_cleanup:
  3659. (void)CloseHandle(si.hStdOutput);
  3660. (void)CloseHandle(si.hStdError);
  3661. (void)CloseHandle(si.hStdInput);
  3662. if (pi.hThread != NULL) {
  3663. (void)CloseHandle(pi.hThread);
  3664. }
  3665. return (pid_t)pi.hProcess;
  3666. }
  3667. #endif /* !NO_CGI */
  3668. static int
  3669. set_blocking_mode(SOCKET sock, int blocking)
  3670. {
  3671. unsigned long non_blocking = !blocking;
  3672. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3673. }
  3674. #else
  3675. static int
  3676. mg_stat(const struct mg_connection *conn,
  3677. const char *path,
  3678. struct mg_file_stat *filep)
  3679. {
  3680. struct stat st;
  3681. if (!filep) {
  3682. return 0;
  3683. }
  3684. memset(filep, 0, sizeof(*filep));
  3685. if (conn && is_file_in_memory(conn, path)) {
  3686. /* Quick fix (for 1.9.x): */
  3687. /* mg_stat must fill all fields, also for files in memory */
  3688. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3689. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3690. filep->size = tmp_file.stat.size;
  3691. filep->last_modified = time(NULL);
  3692. filep->location = 2;
  3693. /* TODO: for 1.10: restructure how files in memory are handled */
  3694. return 1;
  3695. }
  3696. if (0 == stat(path, &st)) {
  3697. filep->size = (uint64_t)(st.st_size);
  3698. filep->last_modified = st.st_mtime;
  3699. filep->is_directory = S_ISDIR(st.st_mode);
  3700. return 1;
  3701. }
  3702. return 0;
  3703. }
  3704. static void
  3705. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3706. {
  3707. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3708. if (conn) {
  3709. mg_cry(conn,
  3710. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3711. __func__,
  3712. strerror(ERRNO));
  3713. }
  3714. }
  3715. }
  3716. int
  3717. mg_start_thread(mg_thread_func_t func, void *param)
  3718. {
  3719. pthread_t thread_id;
  3720. pthread_attr_t attr;
  3721. int result;
  3722. (void)pthread_attr_init(&attr);
  3723. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3724. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3725. /* Compile-time option to control stack size,
  3726. * e.g. -DUSE_STACK_SIZE=16384 */
  3727. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3728. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3729. result = pthread_create(&thread_id, &attr, func, param);
  3730. pthread_attr_destroy(&attr);
  3731. return result;
  3732. }
  3733. /* Start a thread storing the thread context. */
  3734. static int
  3735. mg_start_thread_with_id(mg_thread_func_t func,
  3736. void *param,
  3737. pthread_t *threadidptr)
  3738. {
  3739. pthread_t thread_id;
  3740. pthread_attr_t attr;
  3741. int result;
  3742. (void)pthread_attr_init(&attr);
  3743. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3744. /* Compile-time option to control stack size,
  3745. * e.g. -DUSE_STACK_SIZE=16384 */
  3746. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3747. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3748. result = pthread_create(&thread_id, &attr, func, param);
  3749. pthread_attr_destroy(&attr);
  3750. if ((result == 0) && (threadidptr != NULL)) {
  3751. *threadidptr = thread_id;
  3752. }
  3753. return result;
  3754. }
  3755. /* Wait for a thread to finish. */
  3756. static int
  3757. mg_join_thread(pthread_t threadid)
  3758. {
  3759. int result;
  3760. result = pthread_join(threadid, NULL);
  3761. return result;
  3762. }
  3763. #ifndef NO_CGI
  3764. static pid_t
  3765. spawn_process(struct mg_connection *conn,
  3766. const char *prog,
  3767. char *envblk,
  3768. char *envp[],
  3769. int fdin[2],
  3770. int fdout[2],
  3771. int fderr[2],
  3772. const char *dir)
  3773. {
  3774. pid_t pid;
  3775. const char *interp;
  3776. (void)envblk;
  3777. if (conn == NULL) {
  3778. return 0;
  3779. }
  3780. if ((pid = fork()) == -1) {
  3781. /* Parent */
  3782. send_http_error(conn,
  3783. 500,
  3784. "Error: Creating CGI process\nfork(): %s",
  3785. strerror(ERRNO));
  3786. } else if (pid == 0) {
  3787. /* Child */
  3788. if (chdir(dir) != 0) {
  3789. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3790. } else if (dup2(fdin[0], 0) == -1) {
  3791. mg_cry(conn,
  3792. "%s: dup2(%d, 0): %s",
  3793. __func__,
  3794. fdin[0],
  3795. strerror(ERRNO));
  3796. } else if (dup2(fdout[1], 1) == -1) {
  3797. mg_cry(conn,
  3798. "%s: dup2(%d, 1): %s",
  3799. __func__,
  3800. fdout[1],
  3801. strerror(ERRNO));
  3802. } else if (dup2(fderr[1], 2) == -1) {
  3803. mg_cry(conn,
  3804. "%s: dup2(%d, 2): %s",
  3805. __func__,
  3806. fderr[1],
  3807. strerror(ERRNO));
  3808. } else {
  3809. /* Keep stderr and stdout in two different pipes.
  3810. * Stdout will be sent back to the client,
  3811. * stderr should go into a server error log. */
  3812. (void)close(fdin[0]);
  3813. (void)close(fdout[1]);
  3814. (void)close(fderr[1]);
  3815. /* Close write end fdin and read end fdout and fderr */
  3816. (void)close(fdin[1]);
  3817. (void)close(fdout[0]);
  3818. (void)close(fderr[0]);
  3819. /* After exec, all signal handlers are restored to their default
  3820. * values, with one exception of SIGCHLD. According to
  3821. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3822. * leave unchanged after exec if it was set to be ignored. Restore
  3823. * it to default action. */
  3824. signal(SIGCHLD, SIG_DFL);
  3825. interp = conn->ctx->config[CGI_INTERPRETER];
  3826. if (interp == NULL) {
  3827. (void)execle(prog, prog, NULL, envp);
  3828. mg_cry(conn,
  3829. "%s: execle(%s): %s",
  3830. __func__,
  3831. prog,
  3832. strerror(ERRNO));
  3833. } else {
  3834. (void)execle(interp, interp, prog, NULL, envp);
  3835. mg_cry(conn,
  3836. "%s: execle(%s %s): %s",
  3837. __func__,
  3838. interp,
  3839. prog,
  3840. strerror(ERRNO));
  3841. }
  3842. }
  3843. exit(EXIT_FAILURE);
  3844. }
  3845. return pid;
  3846. }
  3847. #endif /* !NO_CGI */
  3848. static int
  3849. set_blocking_mode(SOCKET sock, int blocking)
  3850. {
  3851. int flags;
  3852. flags = fcntl(sock, F_GETFL, 0);
  3853. if (blocking) {
  3854. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3855. } else {
  3856. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3857. }
  3858. return 0;
  3859. }
  3860. #endif /* _WIN32 */
  3861. /* End of initial operating system specific define block. */
  3862. /* Get a random number (independent of C rand function) */
  3863. static uint64_t
  3864. get_random(void)
  3865. {
  3866. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3867. static uint64_t lcg = 0; /* Linear congruential generator */
  3868. struct timespec now;
  3869. memset(&now, 0, sizeof(now));
  3870. clock_gettime(CLOCK_MONOTONIC, &now);
  3871. if (lfsr == 0) {
  3872. /* lfsr will be only 0 if has not been initialized,
  3873. * so this code is called only once. */
  3874. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3875. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3876. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3877. + (uint64_t)(ptrdiff_t)&now;
  3878. } else {
  3879. /* Get the next step of both random number generators. */
  3880. lfsr = (lfsr >> 1)
  3881. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3882. << 63);
  3883. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3884. }
  3885. /* Combining two pseudo-random number generators and a high resolution part
  3886. * of the current server time will make it hard (impossible?) to guess the
  3887. * next number. */
  3888. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3889. }
  3890. static int
  3891. mg_poll(struct pollfd *pfd,
  3892. unsigned int n,
  3893. int milliseconds,
  3894. volatile int *stop_server)
  3895. {
  3896. int ms_now, result;
  3897. /* Call poll, but only for a maximum time of a few seconds.
  3898. * This will allow to stop the server after some seconds, instead
  3899. * of having to wait for a long socket timeout. */
  3900. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3901. do {
  3902. if (*stop_server) {
  3903. /* Shut down signal */
  3904. return -2;
  3905. }
  3906. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3907. ms_now = milliseconds;
  3908. }
  3909. result = poll(pfd, n, ms_now);
  3910. if (result != 0) {
  3911. /* Poll returned either success (1) or error (-1).
  3912. * Forward both to the caller. */
  3913. return result;
  3914. }
  3915. /* Poll returned timeout (0). */
  3916. if (milliseconds > 0) {
  3917. milliseconds -= ms_now;
  3918. }
  3919. } while (milliseconds != 0);
  3920. return result;
  3921. }
  3922. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3923. * descriptor. Return number of bytes written. */
  3924. static int
  3925. push(struct mg_context *ctx,
  3926. FILE *fp,
  3927. SOCKET sock,
  3928. SSL *ssl,
  3929. const char *buf,
  3930. int len,
  3931. double timeout)
  3932. {
  3933. struct timespec start, now;
  3934. int n, err;
  3935. #ifdef _WIN32
  3936. typedef int len_t;
  3937. #else
  3938. typedef size_t len_t;
  3939. #endif
  3940. if (timeout > 0) {
  3941. memset(&start, 0, sizeof(start));
  3942. memset(&now, 0, sizeof(now));
  3943. clock_gettime(CLOCK_MONOTONIC, &start);
  3944. }
  3945. if (ctx == NULL) {
  3946. return -1;
  3947. }
  3948. #ifdef NO_SSL
  3949. if (ssl) {
  3950. return -1;
  3951. }
  3952. #endif
  3953. do {
  3954. #ifndef NO_SSL
  3955. if (ssl != NULL) {
  3956. n = SSL_write(ssl, buf, len);
  3957. if (n <= 0) {
  3958. err = SSL_get_error(ssl, n);
  3959. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3960. err = ERRNO;
  3961. } else if ((err == SSL_ERROR_WANT_READ)
  3962. || (err == SSL_ERROR_WANT_WRITE)) {
  3963. n = 0;
  3964. } else {
  3965. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3966. return -1;
  3967. }
  3968. } else {
  3969. err = 0;
  3970. }
  3971. } else
  3972. #endif
  3973. if (fp != NULL) {
  3974. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3975. if (ferror(fp)) {
  3976. n = -1;
  3977. err = ERRNO;
  3978. } else {
  3979. err = 0;
  3980. }
  3981. } else {
  3982. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3983. err = (n < 0) ? ERRNO : 0;
  3984. #ifdef _WIN32
  3985. if (err == WSAEWOULDBLOCK) {
  3986. err = 0;
  3987. n = 0;
  3988. }
  3989. #else
  3990. if (err == EWOULDBLOCK) {
  3991. err = 0;
  3992. n = 0;
  3993. }
  3994. #endif
  3995. if (n < 0) {
  3996. /* shutdown of the socket at client side */
  3997. return -1;
  3998. }
  3999. }
  4000. if (ctx->stop_flag) {
  4001. return -1;
  4002. }
  4003. if ((n > 0) || (n == 0 && len == 0)) {
  4004. /* some data has been read, or no data was requested */
  4005. return n;
  4006. }
  4007. if (n < 0) {
  4008. /* socket error - check errno */
  4009. DEBUG_TRACE("send() failed, error %d", err);
  4010. /* TODO (mid): error handling depending on the error code.
  4011. * These codes are different between Windows and Linux.
  4012. * Currently there is no problem with failing send calls,
  4013. * if there is a reproducible situation, it should be
  4014. * investigated in detail.
  4015. */
  4016. return -1;
  4017. }
  4018. /* Only in case n=0 (timeout), repeat calling the write function */
  4019. if (timeout > 0) {
  4020. clock_gettime(CLOCK_MONOTONIC, &now);
  4021. }
  4022. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  4023. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4024. used */
  4025. return -1;
  4026. }
  4027. static int64_t
  4028. push_all(struct mg_context *ctx,
  4029. FILE *fp,
  4030. SOCKET sock,
  4031. SSL *ssl,
  4032. const char *buf,
  4033. int64_t len)
  4034. {
  4035. double timeout = -1.0;
  4036. int64_t n, nwritten = 0;
  4037. if (ctx == NULL) {
  4038. return -1;
  4039. }
  4040. if (ctx->config[REQUEST_TIMEOUT]) {
  4041. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4042. }
  4043. while (len > 0 && ctx->stop_flag == 0) {
  4044. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4045. if (n < 0) {
  4046. if (nwritten == 0) {
  4047. nwritten = n; /* Propagate the error */
  4048. }
  4049. break;
  4050. } else if (n == 0) {
  4051. break; /* No more data to write */
  4052. } else {
  4053. nwritten += n;
  4054. len -= n;
  4055. }
  4056. }
  4057. return nwritten;
  4058. }
  4059. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4060. * Return negative value on error, or number of bytes read on success. */
  4061. static int
  4062. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  4063. {
  4064. int nread, err = 0;
  4065. #ifdef _WIN32
  4066. typedef int len_t;
  4067. #else
  4068. typedef size_t len_t;
  4069. #endif
  4070. if (fp != NULL) {
  4071. #if !defined(_WIN32_WCE)
  4072. /* Use read() instead of fread(), because if we're reading from the
  4073. * CGI pipe, fread() may block until IO buffer is filled up. We
  4074. * cannot afford to block and must pass all read bytes immediately
  4075. * to the client. */
  4076. nread = (int)read(fileno(fp), buf, (size_t)len);
  4077. #else
  4078. /* WinCE does not support CGI pipes */
  4079. nread = (int)fread(buf, 1, (size_t)len, fp);
  4080. #endif
  4081. err = (nread < 0) ? ERRNO : 0;
  4082. #ifndef NO_SSL
  4083. } else if (conn->ssl != NULL) {
  4084. struct pollfd pfd[1];
  4085. int pollres;
  4086. pfd[0].fd = conn->client.sock;
  4087. pfd[0].events = POLLIN;
  4088. pollres =
  4089. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4090. if (conn->ctx->stop_flag) {
  4091. return -1;
  4092. }
  4093. if (pollres > 0) {
  4094. nread = SSL_read(conn->ssl, buf, len);
  4095. if (nread <= 0) {
  4096. err = SSL_get_error(conn->ssl, nread);
  4097. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4098. err = ERRNO;
  4099. } else if ((err == SSL_ERROR_WANT_READ)
  4100. || (err == SSL_ERROR_WANT_WRITE)) {
  4101. nread = 0;
  4102. } else {
  4103. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4104. return -1;
  4105. }
  4106. } else {
  4107. err = 0;
  4108. }
  4109. } else if (pollres < 0) {
  4110. /* Error */
  4111. return -1;
  4112. } else {
  4113. /* pollres = 0 means timeout */
  4114. nread = 0;
  4115. }
  4116. #endif
  4117. } else {
  4118. struct pollfd pfd[1];
  4119. int pollres;
  4120. pfd[0].fd = conn->client.sock;
  4121. pfd[0].events = POLLIN;
  4122. pollres =
  4123. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4124. if (conn->ctx->stop_flag) {
  4125. return -1;
  4126. }
  4127. if (pollres > 0) {
  4128. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4129. err = (nread < 0) ? ERRNO : 0;
  4130. if (nread <= 0) {
  4131. /* shutdown of the socket at client side */
  4132. return -1;
  4133. }
  4134. } else if (pollres < 0) {
  4135. /* error callint poll */
  4136. return -1;
  4137. } else {
  4138. /* pollres = 0 means timeout */
  4139. nread = 0;
  4140. }
  4141. }
  4142. if (conn->ctx->stop_flag) {
  4143. return -1;
  4144. }
  4145. if ((nread > 0) || (nread == 0 && len == 0)) {
  4146. /* some data has been read, or no data was requested */
  4147. return nread;
  4148. }
  4149. if (nread < 0) {
  4150. /* socket error - check errno */
  4151. #ifdef _WIN32
  4152. if (err == WSAEWOULDBLOCK) {
  4153. /* TODO (low): check if this is still required */
  4154. /* standard case if called from close_socket_gracefully */
  4155. return -1;
  4156. } else if (err == WSAETIMEDOUT) {
  4157. /* TODO (low): check if this is still required */
  4158. /* timeout is handled by the while loop */
  4159. return 0;
  4160. } else if (err == WSAECONNABORTED) {
  4161. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4162. return -1;
  4163. } else {
  4164. DEBUG_TRACE("recv() failed, error %d", err);
  4165. return -1;
  4166. }
  4167. #else
  4168. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4169. * if the timeout is reached and if the socket was set to non-
  4170. * blocking in close_socket_gracefully, so we can not distinguish
  4171. * here. We have to wait for the timeout in both cases for now.
  4172. */
  4173. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4174. /* TODO (low): check if this is still required */
  4175. /* EAGAIN/EWOULDBLOCK:
  4176. * standard case if called from close_socket_gracefully
  4177. * => should return -1 */
  4178. /* or timeout occured
  4179. * => the code must stay in the while loop */
  4180. /* EINTR can be generated on a socket with a timeout set even
  4181. * when SA_RESTART is effective for all relevant signals
  4182. * (see signal(7)).
  4183. * => stay in the while loop */
  4184. } else {
  4185. DEBUG_TRACE("recv() failed, error %d", err);
  4186. return -1;
  4187. }
  4188. #endif
  4189. }
  4190. /* Timeout occured, but no data available. */
  4191. return -1;
  4192. }
  4193. static int
  4194. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4195. {
  4196. int n, nread = 0;
  4197. double timeout = -1.0;
  4198. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4199. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4200. }
  4201. while (len > 0 && conn->ctx->stop_flag == 0) {
  4202. n = pull(fp, conn, buf + nread, len, timeout);
  4203. if (n < 0) {
  4204. if (nread == 0) {
  4205. nread = n; /* Propagate the error */
  4206. }
  4207. break;
  4208. } else if (n == 0) {
  4209. break; /* No more data to read */
  4210. } else {
  4211. conn->consumed_content += n;
  4212. nread += n;
  4213. len -= n;
  4214. }
  4215. }
  4216. return nread;
  4217. }
  4218. static void
  4219. discard_unread_request_data(struct mg_connection *conn)
  4220. {
  4221. char buf[MG_BUF_LEN];
  4222. size_t to_read;
  4223. int nread;
  4224. if (conn == NULL) {
  4225. return;
  4226. }
  4227. to_read = sizeof(buf);
  4228. if (conn->is_chunked) {
  4229. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4230. * completely */
  4231. while (conn->is_chunked == 1) {
  4232. nread = mg_read(conn, buf, to_read);
  4233. if (nread <= 0) {
  4234. break;
  4235. }
  4236. }
  4237. } else {
  4238. /* Not chunked: content length is known */
  4239. while (conn->consumed_content < conn->content_len) {
  4240. if (to_read
  4241. > (size_t)(conn->content_len - conn->consumed_content)) {
  4242. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4243. }
  4244. nread = mg_read(conn, buf, to_read);
  4245. if (nread <= 0) {
  4246. break;
  4247. }
  4248. }
  4249. }
  4250. }
  4251. static int
  4252. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4253. {
  4254. int64_t n, buffered_len, nread;
  4255. int64_t len64 =
  4256. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4257. * int, we may not read more
  4258. * bytes */
  4259. const char *body;
  4260. if (conn == NULL) {
  4261. return 0;
  4262. }
  4263. /* If Content-Length is not set for a PUT or POST request, read until
  4264. * socket is closed */
  4265. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4266. conn->content_len = INT64_MAX;
  4267. conn->must_close = 1;
  4268. }
  4269. nread = 0;
  4270. if (conn->consumed_content < conn->content_len) {
  4271. /* Adjust number of bytes to read. */
  4272. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4273. if (left_to_read < len64) {
  4274. /* Do not read more than the total content length of the request.
  4275. */
  4276. len64 = left_to_read;
  4277. }
  4278. /* Return buffered data */
  4279. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4280. - conn->consumed_content;
  4281. if (buffered_len > 0) {
  4282. if (len64 < buffered_len) {
  4283. buffered_len = len64;
  4284. }
  4285. body = conn->buf + conn->request_len + conn->consumed_content;
  4286. memcpy(buf, body, (size_t)buffered_len);
  4287. len64 -= buffered_len;
  4288. conn->consumed_content += buffered_len;
  4289. nread += buffered_len;
  4290. buf = (char *)buf + buffered_len;
  4291. }
  4292. /* We have returned all buffered data. Read new data from the remote
  4293. * socket.
  4294. */
  4295. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4296. nread += n;
  4297. } else {
  4298. nread = ((nread > 0) ? nread : n);
  4299. }
  4300. }
  4301. return (int)nread;
  4302. }
  4303. static char
  4304. mg_getc(struct mg_connection *conn)
  4305. {
  4306. char c;
  4307. if (conn == NULL) {
  4308. return 0;
  4309. }
  4310. conn->content_len++;
  4311. if (mg_read_inner(conn, &c, 1) <= 0) {
  4312. return (char)0;
  4313. }
  4314. return c;
  4315. }
  4316. int
  4317. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4318. {
  4319. if (len > INT_MAX) {
  4320. len = INT_MAX;
  4321. }
  4322. if (conn == NULL) {
  4323. return 0;
  4324. }
  4325. if (conn->is_chunked) {
  4326. size_t all_read = 0;
  4327. while (len > 0) {
  4328. if (conn->is_chunked == 2) {
  4329. /* No more data left to read */
  4330. return 0;
  4331. }
  4332. if (conn->chunk_remainder) {
  4333. /* copy from the remainder of the last received chunk */
  4334. long read_ret;
  4335. size_t read_now =
  4336. ((conn->chunk_remainder > len) ? (len)
  4337. : (conn->chunk_remainder));
  4338. conn->content_len += (int)read_now;
  4339. read_ret =
  4340. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4341. if (read_ret < 1) {
  4342. /* read error */
  4343. return -1;
  4344. }
  4345. all_read += (size_t)read_ret;
  4346. conn->chunk_remainder -= (size_t)read_ret;
  4347. len -= (size_t)read_ret;
  4348. if (conn->chunk_remainder == 0) {
  4349. /* Add data bytes in the current chunk have been read,
  4350. * so we are expecting \r\n now. */
  4351. char x1 = mg_getc(conn);
  4352. char x2 = mg_getc(conn);
  4353. if ((x1 != '\r') || (x2 != '\n')) {
  4354. /* Protocol violation */
  4355. return -1;
  4356. }
  4357. }
  4358. } else {
  4359. /* fetch a new chunk */
  4360. int i = 0;
  4361. char lenbuf[64];
  4362. char *end = 0;
  4363. unsigned long chunkSize = 0;
  4364. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4365. lenbuf[i] = mg_getc(conn);
  4366. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4367. continue;
  4368. }
  4369. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4370. lenbuf[i + 1] = 0;
  4371. chunkSize = strtoul(lenbuf, &end, 16);
  4372. if (chunkSize == 0) {
  4373. /* regular end of content */
  4374. conn->is_chunked = 2;
  4375. }
  4376. break;
  4377. }
  4378. if (!isxdigit(lenbuf[i])) {
  4379. /* illegal character for chunk length */
  4380. return -1;
  4381. }
  4382. }
  4383. if ((end == NULL) || (*end != '\r')) {
  4384. /* chunksize not set correctly */
  4385. return -1;
  4386. }
  4387. if (chunkSize == 0) {
  4388. break;
  4389. }
  4390. conn->chunk_remainder = chunkSize;
  4391. }
  4392. }
  4393. return (int)all_read;
  4394. }
  4395. return mg_read_inner(conn, buf, len);
  4396. }
  4397. int
  4398. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4399. {
  4400. time_t now;
  4401. int64_t n, total, allowed;
  4402. if (conn == NULL) {
  4403. return 0;
  4404. }
  4405. if (conn->throttle > 0) {
  4406. if ((now = time(NULL)) != conn->last_throttle_time) {
  4407. conn->last_throttle_time = now;
  4408. conn->last_throttle_bytes = 0;
  4409. }
  4410. allowed = conn->throttle - conn->last_throttle_bytes;
  4411. if (allowed > (int64_t)len) {
  4412. allowed = (int64_t)len;
  4413. }
  4414. if ((total = push_all(conn->ctx,
  4415. NULL,
  4416. conn->client.sock,
  4417. conn->ssl,
  4418. (const char *)buf,
  4419. (int64_t)allowed)) == allowed) {
  4420. buf = (const char *)buf + total;
  4421. conn->last_throttle_bytes += total;
  4422. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4423. allowed = (conn->throttle > ((int64_t)len - total))
  4424. ? (int64_t)len - total
  4425. : conn->throttle;
  4426. if ((n = push_all(conn->ctx,
  4427. NULL,
  4428. conn->client.sock,
  4429. conn->ssl,
  4430. (const char *)buf,
  4431. (int64_t)allowed)) != allowed) {
  4432. break;
  4433. }
  4434. sleep(1);
  4435. conn->last_throttle_bytes = allowed;
  4436. conn->last_throttle_time = time(NULL);
  4437. buf = (const char *)buf + n;
  4438. total += n;
  4439. }
  4440. }
  4441. } else {
  4442. total = push_all(conn->ctx,
  4443. NULL,
  4444. conn->client.sock,
  4445. conn->ssl,
  4446. (const char *)buf,
  4447. (int64_t)len);
  4448. }
  4449. return (int)total;
  4450. }
  4451. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4452. static int
  4453. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4454. {
  4455. va_list ap_copy;
  4456. size_t size = MG_BUF_LEN / 4;
  4457. int len = -1;
  4458. *buf = NULL;
  4459. while (len < 0) {
  4460. if (*buf) {
  4461. mg_free(*buf);
  4462. }
  4463. size *= 4;
  4464. *buf = (char *)mg_malloc(size);
  4465. if (!*buf) {
  4466. break;
  4467. }
  4468. va_copy(ap_copy, ap);
  4469. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4470. va_end(ap_copy);
  4471. (*buf)[size - 1] = 0;
  4472. }
  4473. return len;
  4474. }
  4475. /* Print message to buffer. If buffer is large enough to hold the message,
  4476. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4477. * and return allocated buffer. */
  4478. static int
  4479. alloc_vprintf(char **out_buf,
  4480. char *prealloc_buf,
  4481. size_t prealloc_size,
  4482. const char *fmt,
  4483. va_list ap)
  4484. {
  4485. va_list ap_copy;
  4486. int len;
  4487. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4488. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4489. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4490. * Therefore, we make two passes: on first pass, get required message
  4491. * length.
  4492. * On second pass, actually print the message. */
  4493. va_copy(ap_copy, ap);
  4494. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4495. va_end(ap_copy);
  4496. if (len < 0) {
  4497. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4498. * Switch to alternative code path that uses incremental allocations.
  4499. */
  4500. va_copy(ap_copy, ap);
  4501. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4502. va_end(ap_copy);
  4503. } else if ((size_t)(len) >= prealloc_size) {
  4504. /* The pre-allocated buffer not large enough. */
  4505. /* Allocate a new buffer. */
  4506. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4507. if (!*out_buf) {
  4508. /* Allocation failed. Return -1 as "out of memory" error. */
  4509. return -1;
  4510. }
  4511. /* Buffer allocation successful. Store the string there. */
  4512. va_copy(ap_copy, ap);
  4513. IGNORE_UNUSED_RESULT(
  4514. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4515. va_end(ap_copy);
  4516. } else {
  4517. /* The pre-allocated buffer is large enough.
  4518. * Use it to store the string and return the address. */
  4519. va_copy(ap_copy, ap);
  4520. IGNORE_UNUSED_RESULT(
  4521. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4522. va_end(ap_copy);
  4523. *out_buf = prealloc_buf;
  4524. }
  4525. return len;
  4526. }
  4527. static int
  4528. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4529. {
  4530. char mem[MG_BUF_LEN];
  4531. char *buf = NULL;
  4532. int len;
  4533. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4534. len = mg_write(conn, buf, (size_t)len);
  4535. }
  4536. if (buf != mem && buf != NULL) {
  4537. mg_free(buf);
  4538. }
  4539. return len;
  4540. }
  4541. int
  4542. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4543. {
  4544. va_list ap;
  4545. int result;
  4546. va_start(ap, fmt);
  4547. result = mg_vprintf(conn, fmt, ap);
  4548. va_end(ap);
  4549. return result;
  4550. }
  4551. int
  4552. mg_url_decode(const char *src,
  4553. int src_len,
  4554. char *dst,
  4555. int dst_len,
  4556. int is_form_url_encoded)
  4557. {
  4558. int i, j, a, b;
  4559. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4560. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4561. if (i < src_len - 2 && src[i] == '%'
  4562. && isxdigit(*(const unsigned char *)(src + i + 1))
  4563. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4564. a = tolower(*(const unsigned char *)(src + i + 1));
  4565. b = tolower(*(const unsigned char *)(src + i + 2));
  4566. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4567. i += 2;
  4568. } else if (is_form_url_encoded && src[i] == '+') {
  4569. dst[j] = ' ';
  4570. } else {
  4571. dst[j] = src[i];
  4572. }
  4573. }
  4574. dst[j] = '\0'; /* Null-terminate the destination */
  4575. return (i >= src_len) ? j : -1;
  4576. }
  4577. int
  4578. mg_get_var(const char *data,
  4579. size_t data_len,
  4580. const char *name,
  4581. char *dst,
  4582. size_t dst_len)
  4583. {
  4584. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4585. }
  4586. int
  4587. mg_get_var2(const char *data,
  4588. size_t data_len,
  4589. const char *name,
  4590. char *dst,
  4591. size_t dst_len,
  4592. size_t occurrence)
  4593. {
  4594. const char *p, *e, *s;
  4595. size_t name_len;
  4596. int len;
  4597. if (dst == NULL || dst_len == 0) {
  4598. len = -2;
  4599. } else if (data == NULL || name == NULL || data_len == 0) {
  4600. len = -1;
  4601. dst[0] = '\0';
  4602. } else {
  4603. name_len = strlen(name);
  4604. e = data + data_len;
  4605. len = -1;
  4606. dst[0] = '\0';
  4607. /* data is "var1=val1&var2=val2...". Find variable first */
  4608. for (p = data; p + name_len < e; p++) {
  4609. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4610. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4611. /* Point p to variable value */
  4612. p += name_len + 1;
  4613. /* Point s to the end of the value */
  4614. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4615. if (s == NULL) {
  4616. s = e;
  4617. }
  4618. /* assert(s >= p); */
  4619. if (s < p) {
  4620. return -3;
  4621. }
  4622. /* Decode variable into destination buffer */
  4623. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4624. /* Redirect error code from -1 to -2 (destination buffer too
  4625. * small). */
  4626. if (len == -1) {
  4627. len = -2;
  4628. }
  4629. break;
  4630. }
  4631. }
  4632. }
  4633. return len;
  4634. }
  4635. /* HCP24: some changes to compare hole var_name */
  4636. int
  4637. mg_get_cookie(const char *cookie_header,
  4638. const char *var_name,
  4639. char *dst,
  4640. size_t dst_size)
  4641. {
  4642. const char *s, *p, *end;
  4643. int name_len, len = -1;
  4644. if (dst == NULL || dst_size == 0) {
  4645. return -2;
  4646. }
  4647. dst[0] = '\0';
  4648. if (var_name == NULL || (s = cookie_header) == NULL) {
  4649. return -1;
  4650. }
  4651. name_len = (int)strlen(var_name);
  4652. end = s + strlen(s);
  4653. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4654. if (s[name_len] == '=') {
  4655. /* HCP24: now check is it a substring or a full cookie name */
  4656. if ((s == cookie_header) || (s[-1] == ' ')) {
  4657. s += name_len + 1;
  4658. if ((p = strchr(s, ' ')) == NULL) {
  4659. p = end;
  4660. }
  4661. if (p[-1] == ';') {
  4662. p--;
  4663. }
  4664. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4665. s++;
  4666. p--;
  4667. }
  4668. if ((size_t)(p - s) < dst_size) {
  4669. len = (int)(p - s);
  4670. mg_strlcpy(dst, s, (size_t)len + 1);
  4671. } else {
  4672. len = -3;
  4673. }
  4674. break;
  4675. }
  4676. }
  4677. }
  4678. return len;
  4679. }
  4680. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4681. static void
  4682. base64_encode(const unsigned char *src, int src_len, char *dst)
  4683. {
  4684. static const char *b64 =
  4685. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4686. int i, j, a, b, c;
  4687. for (i = j = 0; i < src_len; i += 3) {
  4688. a = src[i];
  4689. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4690. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4691. dst[j++] = b64[a >> 2];
  4692. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4693. if (i + 1 < src_len) {
  4694. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4695. }
  4696. if (i + 2 < src_len) {
  4697. dst[j++] = b64[c & 63];
  4698. }
  4699. }
  4700. while (j % 4 != 0) {
  4701. dst[j++] = '=';
  4702. }
  4703. dst[j++] = '\0';
  4704. }
  4705. #endif
  4706. #if defined(USE_LUA)
  4707. static unsigned char
  4708. b64reverse(char letter)
  4709. {
  4710. if (letter >= 'A' && letter <= 'Z') {
  4711. return letter - 'A';
  4712. }
  4713. if (letter >= 'a' && letter <= 'z') {
  4714. return letter - 'a' + 26;
  4715. }
  4716. if (letter >= '0' && letter <= '9') {
  4717. return letter - '0' + 52;
  4718. }
  4719. if (letter == '+') {
  4720. return 62;
  4721. }
  4722. if (letter == '/') {
  4723. return 63;
  4724. }
  4725. if (letter == '=') {
  4726. return 255; /* normal end */
  4727. }
  4728. return 254; /* error */
  4729. }
  4730. static int
  4731. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4732. {
  4733. int i;
  4734. unsigned char a, b, c, d;
  4735. *dst_len = 0;
  4736. for (i = 0; i < src_len; i += 4) {
  4737. a = b64reverse(src[i]);
  4738. if (a >= 254) {
  4739. return i;
  4740. }
  4741. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4742. if (b >= 254) {
  4743. return i + 1;
  4744. }
  4745. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4746. if (c == 254) {
  4747. return i + 2;
  4748. }
  4749. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4750. if (d == 254) {
  4751. return i + 3;
  4752. }
  4753. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4754. if (c != 255) {
  4755. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4756. if (d != 255) {
  4757. dst[(*dst_len)++] = (c << 6) + d;
  4758. }
  4759. }
  4760. }
  4761. return -1;
  4762. }
  4763. #endif
  4764. static int
  4765. is_put_or_delete_method(const struct mg_connection *conn)
  4766. {
  4767. if (conn) {
  4768. const char *s = conn->request_info.request_method;
  4769. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4770. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4771. }
  4772. return 0;
  4773. }
  4774. static void
  4775. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4776. char *filename, /* out: filename */
  4777. size_t filename_buf_len, /* in: size of filename buffer */
  4778. struct mg_file_stat *filestat, /* out: file structure */
  4779. int *is_found, /* out: file found (directly) */
  4780. int *is_script_resource, /* out: handled by a script? */
  4781. int *is_websocket_request, /* out: websocket connetion? */
  4782. int *is_put_or_delete_request /* out: put/delete a file? */
  4783. )
  4784. {
  4785. /* TODO (high / maintainability issue): Restructure this function */
  4786. #if !defined(NO_FILES)
  4787. const char *uri = conn->request_info.local_uri;
  4788. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4789. const char *rewrite;
  4790. struct vec a, b;
  4791. int match_len;
  4792. char gz_path[PATH_MAX];
  4793. char const *accept_encoding;
  4794. int truncated;
  4795. #if !defined(NO_CGI) || defined(USE_LUA)
  4796. char *p;
  4797. #endif
  4798. #else
  4799. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4800. #endif
  4801. memset(filestat, 0, sizeof(*filestat));
  4802. *filename = 0;
  4803. *is_found = 0;
  4804. *is_script_resource = 0;
  4805. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4806. #if defined(USE_WEBSOCKET)
  4807. *is_websocket_request = is_websocket_protocol(conn);
  4808. #if !defined(NO_FILES)
  4809. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4810. root = conn->ctx->config[WEBSOCKET_ROOT];
  4811. }
  4812. #endif /* !NO_FILES */
  4813. #else /* USE_WEBSOCKET */
  4814. *is_websocket_request = 0;
  4815. #endif /* USE_WEBSOCKET */
  4816. #if !defined(NO_FILES)
  4817. /* Note that root == NULL is a regular use case here. This occurs,
  4818. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4819. * config is not required. */
  4820. if (root == NULL) {
  4821. /* all file related outputs have already been set to 0, just return
  4822. */
  4823. return;
  4824. }
  4825. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4826. * of the path one byte on the right.
  4827. * If document_root is NULL, leave the file empty. */
  4828. mg_snprintf(
  4829. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4830. if (truncated) {
  4831. goto interpret_cleanup;
  4832. }
  4833. rewrite = conn->ctx->config[REWRITE];
  4834. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4835. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4836. mg_snprintf(conn,
  4837. &truncated,
  4838. filename,
  4839. filename_buf_len - 1,
  4840. "%.*s%s",
  4841. (int)b.len,
  4842. b.ptr,
  4843. uri + match_len);
  4844. break;
  4845. }
  4846. }
  4847. if (truncated) {
  4848. goto interpret_cleanup;
  4849. }
  4850. /* Local file path and name, corresponding to requested URI
  4851. * is now stored in "filename" variable. */
  4852. if (mg_stat(conn, filename, filestat)) {
  4853. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4854. /* File exists. Check if it is a script type. */
  4855. if (0
  4856. #if !defined(NO_CGI)
  4857. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4858. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4859. filename) > 0
  4860. #endif
  4861. #if defined(USE_LUA)
  4862. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4863. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4864. filename) > 0
  4865. #endif
  4866. #if defined(USE_DUKTAPE)
  4867. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4868. strlen(
  4869. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4870. filename) > 0
  4871. #endif
  4872. ) {
  4873. /* The request addresses a CGI script or a Lua script. The URI
  4874. * corresponds to the script itself (like /path/script.cgi),
  4875. * and there is no additional resource path
  4876. * (like /path/script.cgi/something).
  4877. * Requests that modify (replace or delete) a resource, like
  4878. * PUT and DELETE requests, should replace/delete the script
  4879. * file.
  4880. * Requests that read or write from/to a resource, like GET and
  4881. * POST requests, should call the script and return the
  4882. * generated response. */
  4883. *is_script_resource = !*is_put_or_delete_request;
  4884. }
  4885. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4886. *is_found = 1;
  4887. return;
  4888. }
  4889. /* If we can't find the actual file, look for the file
  4890. * with the same name but a .gz extension. If we find it,
  4891. * use that and set the gzipped flag in the file struct
  4892. * to indicate that the response need to have the content-
  4893. * encoding: gzip header.
  4894. * We can only do this if the browser declares support. */
  4895. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4896. if (strstr(accept_encoding, "gzip") != NULL) {
  4897. mg_snprintf(
  4898. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4899. if (truncated) {
  4900. goto interpret_cleanup;
  4901. }
  4902. if (mg_stat(conn, gz_path, filestat)) {
  4903. if (filestat) {
  4904. filestat->is_gzipped = 1;
  4905. *is_found = 1;
  4906. }
  4907. /* Currently gz files can not be scripts. */
  4908. return;
  4909. }
  4910. }
  4911. }
  4912. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4913. /* Support PATH_INFO for CGI scripts. */
  4914. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4915. if (*p == '/') {
  4916. *p = '\0';
  4917. if ((0
  4918. #if !defined(NO_CGI)
  4919. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4920. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4921. filename) > 0
  4922. #endif
  4923. #if defined(USE_LUA)
  4924. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4925. strlen(
  4926. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4927. filename) > 0
  4928. #endif
  4929. #if defined(USE_DUKTAPE)
  4930. || match_prefix(
  4931. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4932. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4933. filename) > 0
  4934. #endif
  4935. ) && mg_stat(conn, filename, filestat)) {
  4936. /* Shift PATH_INFO block one character right, e.g.
  4937. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4938. * conn->path_info is pointing to the local variable "path"
  4939. * declared in handle_request(), so PATH_INFO is not valid
  4940. * after handle_request returns. */
  4941. conn->path_info = p + 1;
  4942. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4943. * trailing \0 */
  4944. p[1] = '/';
  4945. *is_script_resource = 1;
  4946. break;
  4947. } else {
  4948. *p = '/';
  4949. }
  4950. }
  4951. }
  4952. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4953. #endif /* !defined(NO_FILES) */
  4954. return;
  4955. #if !defined(NO_FILES)
  4956. /* Reset all outputs */
  4957. interpret_cleanup:
  4958. memset(filestat, 0, sizeof(*filestat));
  4959. *filename = 0;
  4960. *is_found = 0;
  4961. *is_script_resource = 0;
  4962. *is_websocket_request = 0;
  4963. *is_put_or_delete_request = 0;
  4964. #endif /* !defined(NO_FILES) */
  4965. }
  4966. /* Check whether full request is buffered. Return:
  4967. * -1 if request is malformed
  4968. * 0 if request is not yet fully buffered
  4969. * >0 actual request length, including last \r\n\r\n */
  4970. static int
  4971. get_request_len(const char *buf, int buflen)
  4972. {
  4973. const char *s, *e;
  4974. int len = 0;
  4975. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4976. /* Control characters are not allowed but >=128 is. */
  4977. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4978. && *(const unsigned char *)s < 128) {
  4979. len = -1;
  4980. break; /* [i_a] abort scan as soon as one malformed character is
  4981. * found; */
  4982. /* don't let subsequent \r\n\r\n win us over anyhow */
  4983. } else if (s[0] == '\n' && s[1] == '\n') {
  4984. len = (int)(s - buf) + 2;
  4985. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4986. len = (int)(s - buf) + 3;
  4987. }
  4988. return len;
  4989. }
  4990. #if !defined(NO_CACHING)
  4991. /* Convert month to the month number. Return -1 on error, or month number */
  4992. static int
  4993. get_month_index(const char *s)
  4994. {
  4995. size_t i;
  4996. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4997. if (!strcmp(s, month_names[i])) {
  4998. return (int)i;
  4999. }
  5000. }
  5001. return -1;
  5002. }
  5003. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5004. static time_t
  5005. parse_date_string(const char *datetime)
  5006. {
  5007. char month_str[32] = {0};
  5008. int second, minute, hour, day, month, year;
  5009. time_t result = (time_t)0;
  5010. struct tm tm;
  5011. if ((sscanf(datetime,
  5012. "%d/%3s/%d %d:%d:%d",
  5013. &day,
  5014. month_str,
  5015. &year,
  5016. &hour,
  5017. &minute,
  5018. &second) == 6) || (sscanf(datetime,
  5019. "%d %3s %d %d:%d:%d",
  5020. &day,
  5021. month_str,
  5022. &year,
  5023. &hour,
  5024. &minute,
  5025. &second) == 6)
  5026. || (sscanf(datetime,
  5027. "%*3s, %d %3s %d %d:%d:%d",
  5028. &day,
  5029. month_str,
  5030. &year,
  5031. &hour,
  5032. &minute,
  5033. &second) == 6) || (sscanf(datetime,
  5034. "%d-%3s-%d %d:%d:%d",
  5035. &day,
  5036. month_str,
  5037. &year,
  5038. &hour,
  5039. &minute,
  5040. &second) == 6)) {
  5041. month = get_month_index(month_str);
  5042. if ((month >= 0) && (year >= 1970)) {
  5043. memset(&tm, 0, sizeof(tm));
  5044. tm.tm_year = year - 1900;
  5045. tm.tm_mon = month;
  5046. tm.tm_mday = day;
  5047. tm.tm_hour = hour;
  5048. tm.tm_min = minute;
  5049. tm.tm_sec = second;
  5050. result = timegm(&tm);
  5051. }
  5052. }
  5053. return result;
  5054. }
  5055. #endif /* !NO_CACHING */
  5056. /* Protect against directory disclosure attack by removing '..',
  5057. * excessive '/' and '\' characters */
  5058. static void
  5059. remove_double_dots_and_double_slashes(char *s)
  5060. {
  5061. char *p = s;
  5062. while ((s[0] == '.') && (s[1] == '.')) {
  5063. s++;
  5064. }
  5065. while (*s != '\0') {
  5066. *p++ = *s++;
  5067. if (s[-1] == '/' || s[-1] == '\\') {
  5068. /* Skip all following slashes, backslashes and double-dots */
  5069. while (s[0] != '\0') {
  5070. if (s[0] == '/' || s[0] == '\\') {
  5071. s++;
  5072. } else if (s[0] == '.' && s[1] == '.') {
  5073. s += 2;
  5074. } else {
  5075. break;
  5076. }
  5077. }
  5078. }
  5079. }
  5080. *p = '\0';
  5081. }
  5082. static const struct {
  5083. const char *extension;
  5084. size_t ext_len;
  5085. const char *mime_type;
  5086. } builtin_mime_types[] = {
  5087. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5088. * application types */
  5089. {".doc", 4, "application/msword"},
  5090. {".eps", 4, "application/postscript"},
  5091. {".exe", 4, "application/octet-stream"},
  5092. {".js", 3, "application/javascript"},
  5093. {".json", 5, "application/json"},
  5094. {".pdf", 4, "application/pdf"},
  5095. {".ps", 3, "application/postscript"},
  5096. {".rtf", 4, "application/rtf"},
  5097. {".xhtml", 6, "application/xhtml+xml"},
  5098. {".xsl", 4, "application/xml"},
  5099. {".xslt", 5, "application/xml"},
  5100. /* fonts */
  5101. {".ttf", 4, "application/font-sfnt"},
  5102. {".cff", 4, "application/font-sfnt"},
  5103. {".otf", 4, "application/font-sfnt"},
  5104. {".aat", 4, "application/font-sfnt"},
  5105. {".sil", 4, "application/font-sfnt"},
  5106. {".pfr", 4, "application/font-tdpfr"},
  5107. {".woff", 5, "application/font-woff"},
  5108. /* audio */
  5109. {".mp3", 4, "audio/mpeg"},
  5110. {".oga", 4, "audio/ogg"},
  5111. {".ogg", 4, "audio/ogg"},
  5112. /* image */
  5113. {".gif", 4, "image/gif"},
  5114. {".ief", 4, "image/ief"},
  5115. {".jpeg", 5, "image/jpeg"},
  5116. {".jpg", 4, "image/jpeg"},
  5117. {".jpm", 4, "image/jpm"},
  5118. {".jpx", 4, "image/jpx"},
  5119. {".png", 4, "image/png"},
  5120. {".svg", 4, "image/svg+xml"},
  5121. {".tif", 4, "image/tiff"},
  5122. {".tiff", 5, "image/tiff"},
  5123. /* model */
  5124. {".wrl", 4, "model/vrml"},
  5125. /* text */
  5126. {".css", 4, "text/css"},
  5127. {".csv", 4, "text/csv"},
  5128. {".htm", 4, "text/html"},
  5129. {".html", 5, "text/html"},
  5130. {".sgm", 4, "text/sgml"},
  5131. {".shtm", 5, "text/html"},
  5132. {".shtml", 6, "text/html"},
  5133. {".txt", 4, "text/plain"},
  5134. {".xml", 4, "text/xml"},
  5135. /* video */
  5136. {".mov", 4, "video/quicktime"},
  5137. {".mp4", 4, "video/mp4"},
  5138. {".mpeg", 5, "video/mpeg"},
  5139. {".mpg", 4, "video/mpeg"},
  5140. {".ogv", 4, "video/ogg"},
  5141. {".qt", 3, "video/quicktime"},
  5142. /* not registered types
  5143. * (http://reference.sitepoint.com/html/mime-types-full,
  5144. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5145. {".arj", 4, "application/x-arj-compressed"},
  5146. {".gz", 3, "application/x-gunzip"},
  5147. {".rar", 4, "application/x-arj-compressed"},
  5148. {".swf", 4, "application/x-shockwave-flash"},
  5149. {".tar", 4, "application/x-tar"},
  5150. {".tgz", 4, "application/x-tar-gz"},
  5151. {".torrent", 8, "application/x-bittorrent"},
  5152. {".ppt", 4, "application/x-mspowerpoint"},
  5153. {".xls", 4, "application/x-msexcel"},
  5154. {".zip", 4, "application/x-zip-compressed"},
  5155. {".aac",
  5156. 4,
  5157. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5158. {".aif", 4, "audio/x-aif"},
  5159. {".m3u", 4, "audio/x-mpegurl"},
  5160. {".mid", 4, "audio/x-midi"},
  5161. {".ra", 3, "audio/x-pn-realaudio"},
  5162. {".ram", 4, "audio/x-pn-realaudio"},
  5163. {".wav", 4, "audio/x-wav"},
  5164. {".bmp", 4, "image/bmp"},
  5165. {".ico", 4, "image/x-icon"},
  5166. {".pct", 4, "image/x-pct"},
  5167. {".pict", 5, "image/pict"},
  5168. {".rgb", 4, "image/x-rgb"},
  5169. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5170. {".asf", 4, "video/x-ms-asf"},
  5171. {".avi", 4, "video/x-msvideo"},
  5172. {".m4v", 4, "video/x-m4v"},
  5173. {NULL, 0, NULL}};
  5174. const char *
  5175. mg_get_builtin_mime_type(const char *path)
  5176. {
  5177. const char *ext;
  5178. size_t i, path_len;
  5179. path_len = strlen(path);
  5180. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5181. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5182. if (path_len > builtin_mime_types[i].ext_len
  5183. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5184. return builtin_mime_types[i].mime_type;
  5185. }
  5186. }
  5187. return "text/plain";
  5188. }
  5189. /* Look at the "path" extension and figure what mime type it has.
  5190. * Store mime type in the vector. */
  5191. static void
  5192. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5193. {
  5194. struct vec ext_vec, mime_vec;
  5195. const char *list, *ext;
  5196. size_t path_len;
  5197. path_len = strlen(path);
  5198. if (ctx == NULL || vec == NULL) {
  5199. return;
  5200. }
  5201. /* Scan user-defined mime types first, in case user wants to
  5202. * override default mime types. */
  5203. list = ctx->config[EXTRA_MIME_TYPES];
  5204. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5205. /* ext now points to the path suffix */
  5206. ext = path + path_len - ext_vec.len;
  5207. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5208. *vec = mime_vec;
  5209. return;
  5210. }
  5211. }
  5212. vec->ptr = mg_get_builtin_mime_type(path);
  5213. vec->len = strlen(vec->ptr);
  5214. }
  5215. /* Stringify binary data. Output buffer must be twice as big as input,
  5216. * because each byte takes 2 bytes in string representation */
  5217. static void
  5218. bin2str(char *to, const unsigned char *p, size_t len)
  5219. {
  5220. static const char *hex = "0123456789abcdef";
  5221. for (; len--; p++) {
  5222. *to++ = hex[p[0] >> 4];
  5223. *to++ = hex[p[0] & 0x0f];
  5224. }
  5225. *to = '\0';
  5226. }
  5227. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5228. char *
  5229. mg_md5(char buf[33], ...)
  5230. {
  5231. md5_byte_t hash[16];
  5232. const char *p;
  5233. va_list ap;
  5234. md5_state_t ctx;
  5235. md5_init(&ctx);
  5236. va_start(ap, buf);
  5237. while ((p = va_arg(ap, const char *)) != NULL) {
  5238. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5239. }
  5240. va_end(ap);
  5241. md5_finish(&ctx, hash);
  5242. bin2str(buf, hash, sizeof(hash));
  5243. return buf;
  5244. }
  5245. /* Check the user's password, return 1 if OK */
  5246. static int
  5247. check_password(const char *method,
  5248. const char *ha1,
  5249. const char *uri,
  5250. const char *nonce,
  5251. const char *nc,
  5252. const char *cnonce,
  5253. const char *qop,
  5254. const char *response)
  5255. {
  5256. char ha2[32 + 1], expected_response[32 + 1];
  5257. /* Some of the parameters may be NULL */
  5258. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5259. || qop == NULL
  5260. || response == NULL) {
  5261. return 0;
  5262. }
  5263. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5264. if (strlen(response) != 32) {
  5265. return 0;
  5266. }
  5267. mg_md5(ha2, method, ":", uri, NULL);
  5268. mg_md5(expected_response,
  5269. ha1,
  5270. ":",
  5271. nonce,
  5272. ":",
  5273. nc,
  5274. ":",
  5275. cnonce,
  5276. ":",
  5277. qop,
  5278. ":",
  5279. ha2,
  5280. NULL);
  5281. return mg_strcasecmp(response, expected_response) == 0;
  5282. }
  5283. /* Use the global passwords file, if specified by auth_gpass option,
  5284. * or search for .htpasswd in the requested directory. */
  5285. static void
  5286. open_auth_file(struct mg_connection *conn,
  5287. const char *path,
  5288. struct mg_file *filep)
  5289. {
  5290. if (conn != NULL && conn->ctx != NULL) {
  5291. char name[PATH_MAX];
  5292. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5293. int truncated;
  5294. if (gpass != NULL) {
  5295. /* Use global passwords file */
  5296. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5297. #ifdef DEBUG
  5298. /* Use mg_cry here, since gpass has been configured. */
  5299. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5300. #endif
  5301. }
  5302. /* Important: using local struct mg_file to test path for
  5303. * is_directory flag. If filep is used, mg_stat() makes it
  5304. * appear as if auth file was opened.
  5305. * TODO(mid): Check if this is still required after rewriting
  5306. * mg_stat */
  5307. } else if (mg_stat(conn, path, &filep->stat)
  5308. && filep->stat.is_directory) {
  5309. mg_snprintf(conn,
  5310. &truncated,
  5311. name,
  5312. sizeof(name),
  5313. "%s/%s",
  5314. path,
  5315. PASSWORDS_FILE_NAME);
  5316. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5317. #ifdef DEBUG
  5318. /* Don't use mg_cry here, but only a trace, since this is
  5319. * a typical case. It will occur for every directory
  5320. * without a password file. */
  5321. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5322. #endif
  5323. }
  5324. } else {
  5325. /* Try to find .htpasswd in requested directory. */
  5326. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5327. if (e[0] == '/') {
  5328. break;
  5329. }
  5330. }
  5331. mg_snprintf(conn,
  5332. &truncated,
  5333. name,
  5334. sizeof(name),
  5335. "%.*s/%s",
  5336. (int)(e - p),
  5337. p,
  5338. PASSWORDS_FILE_NAME);
  5339. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5340. #ifdef DEBUG
  5341. /* Don't use mg_cry here, but only a trace, since this is
  5342. * a typical case. It will occur for every directory
  5343. * without a password file. */
  5344. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5345. #endif
  5346. }
  5347. }
  5348. }
  5349. }
  5350. /* Parsed Authorization header */
  5351. struct ah {
  5352. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5353. };
  5354. /* Return 1 on success. Always initializes the ah structure. */
  5355. static int
  5356. parse_auth_header(struct mg_connection *conn,
  5357. char *buf,
  5358. size_t buf_size,
  5359. struct ah *ah)
  5360. {
  5361. char *name, *value, *s;
  5362. const char *auth_header;
  5363. uint64_t nonce;
  5364. if (!ah || !conn) {
  5365. return 0;
  5366. }
  5367. (void)memset(ah, 0, sizeof(*ah));
  5368. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5369. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5370. return 0;
  5371. }
  5372. /* Make modifiable copy of the auth header */
  5373. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5374. s = buf;
  5375. /* Parse authorization header */
  5376. for (;;) {
  5377. /* Gobble initial spaces */
  5378. while (isspace(*(unsigned char *)s)) {
  5379. s++;
  5380. }
  5381. name = skip_quoted(&s, "=", " ", 0);
  5382. /* Value is either quote-delimited, or ends at first comma or space. */
  5383. if (s[0] == '\"') {
  5384. s++;
  5385. value = skip_quoted(&s, "\"", " ", '\\');
  5386. if (s[0] == ',') {
  5387. s++;
  5388. }
  5389. } else {
  5390. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5391. * spaces */
  5392. }
  5393. if (*name == '\0') {
  5394. break;
  5395. }
  5396. if (!strcmp(name, "username")) {
  5397. ah->user = value;
  5398. } else if (!strcmp(name, "cnonce")) {
  5399. ah->cnonce = value;
  5400. } else if (!strcmp(name, "response")) {
  5401. ah->response = value;
  5402. } else if (!strcmp(name, "uri")) {
  5403. ah->uri = value;
  5404. } else if (!strcmp(name, "qop")) {
  5405. ah->qop = value;
  5406. } else if (!strcmp(name, "nc")) {
  5407. ah->nc = value;
  5408. } else if (!strcmp(name, "nonce")) {
  5409. ah->nonce = value;
  5410. }
  5411. }
  5412. #ifndef NO_NONCE_CHECK
  5413. /* Read the nonce from the response. */
  5414. if (ah->nonce == NULL) {
  5415. return 0;
  5416. }
  5417. s = NULL;
  5418. nonce = strtoull(ah->nonce, &s, 10);
  5419. if ((s == NULL) || (*s != 0)) {
  5420. return 0;
  5421. }
  5422. /* Convert the nonce from the client to a number. */
  5423. nonce ^= conn->ctx->auth_nonce_mask;
  5424. /* The converted number corresponds to the time the nounce has been
  5425. * created. This should not be earlier than the server start. */
  5426. /* Server side nonce check is valuable in all situations but one:
  5427. * if the server restarts frequently, but the client should not see
  5428. * that, so the server should accept nonces from previous starts. */
  5429. /* However, the reasonable default is to not accept a nonce from a
  5430. * previous start, so if anyone changed the access rights between
  5431. * two restarts, a new login is required. */
  5432. if (nonce < (uint64_t)conn->ctx->start_time) {
  5433. /* nonce is from a previous start of the server and no longer valid
  5434. * (replay attack?) */
  5435. return 0;
  5436. }
  5437. /* Check if the nonce is too high, so it has not (yet) been used by the
  5438. * server. */
  5439. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5440. return 0;
  5441. }
  5442. #else
  5443. (void)nonce;
  5444. #endif
  5445. /* CGI needs it as REMOTE_USER */
  5446. if (ah->user != NULL) {
  5447. conn->request_info.remote_user = mg_strdup(ah->user);
  5448. } else {
  5449. return 0;
  5450. }
  5451. return 1;
  5452. }
  5453. static const char *
  5454. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5455. {
  5456. const char *eof;
  5457. size_t len;
  5458. const char *memend;
  5459. if (!filep) {
  5460. return NULL;
  5461. }
  5462. if (filep->access.membuf != NULL && *p != NULL) {
  5463. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5464. /* Search for \n from p till the end of stream */
  5465. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5466. if (eof != NULL) {
  5467. eof += 1; /* Include \n */
  5468. } else {
  5469. eof = memend; /* Copy remaining data */
  5470. }
  5471. len =
  5472. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5473. memcpy(buf, *p, len);
  5474. buf[len] = '\0';
  5475. *p += len;
  5476. return len ? eof : NULL;
  5477. } else if (filep->access.fp != NULL) {
  5478. return fgets(buf, (int)size, filep->access.fp);
  5479. } else {
  5480. return NULL;
  5481. }
  5482. }
  5483. /* Define the initial recursion depth for procesesing htpasswd files that
  5484. * include other htpasswd
  5485. * (or even the same) files. It is not difficult to provide a file or files
  5486. * s.t. they force civetweb
  5487. * to infinitely recurse and then crash.
  5488. */
  5489. #define INITIAL_DEPTH 9
  5490. #if INITIAL_DEPTH <= 0
  5491. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5492. #endif
  5493. struct read_auth_file_struct {
  5494. struct mg_connection *conn;
  5495. struct ah ah;
  5496. char *domain;
  5497. char buf[256 + 256 + 40];
  5498. char *f_user;
  5499. char *f_domain;
  5500. char *f_ha1;
  5501. };
  5502. static int
  5503. read_auth_file(struct mg_file *filep,
  5504. struct read_auth_file_struct *workdata,
  5505. int depth)
  5506. {
  5507. char *p;
  5508. int is_authorized = 0;
  5509. struct mg_file fp;
  5510. size_t l;
  5511. if (!filep || !workdata || 0 == depth) {
  5512. return 0;
  5513. }
  5514. /* Loop over passwords file */
  5515. p = (char *)filep->access.membuf;
  5516. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5517. l = strlen(workdata->buf);
  5518. while (l > 0) {
  5519. if (isspace(workdata->buf[l - 1])
  5520. || iscntrl(workdata->buf[l - 1])) {
  5521. l--;
  5522. workdata->buf[l] = 0;
  5523. } else
  5524. break;
  5525. }
  5526. if (l < 1) {
  5527. continue;
  5528. }
  5529. workdata->f_user = workdata->buf;
  5530. if (workdata->f_user[0] == ':') {
  5531. /* user names may not contain a ':' and may not be empty,
  5532. * so lines starting with ':' may be used for a special purpose */
  5533. if (workdata->f_user[1] == '#') {
  5534. /* :# is a comment */
  5535. continue;
  5536. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5537. if (mg_fopen(workdata->conn,
  5538. workdata->f_user + 9,
  5539. MG_FOPEN_MODE_READ,
  5540. &fp)) {
  5541. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5542. (void)mg_fclose(
  5543. &fp.access); /* ignore error on read only file */
  5544. /* No need to continue processing files once we have a
  5545. * match, since nothing will reset it back
  5546. * to 0.
  5547. */
  5548. if (is_authorized) {
  5549. return is_authorized;
  5550. }
  5551. } else {
  5552. mg_cry(workdata->conn,
  5553. "%s: cannot open authorization file: %s",
  5554. __func__,
  5555. workdata->buf);
  5556. }
  5557. continue;
  5558. }
  5559. /* everything is invalid for the moment (might change in the
  5560. * future) */
  5561. mg_cry(workdata->conn,
  5562. "%s: syntax error in authorization file: %s",
  5563. __func__,
  5564. workdata->buf);
  5565. continue;
  5566. }
  5567. workdata->f_domain = strchr(workdata->f_user, ':');
  5568. if (workdata->f_domain == NULL) {
  5569. mg_cry(workdata->conn,
  5570. "%s: syntax error in authorization file: %s",
  5571. __func__,
  5572. workdata->buf);
  5573. continue;
  5574. }
  5575. *(workdata->f_domain) = 0;
  5576. (workdata->f_domain)++;
  5577. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5578. if (workdata->f_ha1 == NULL) {
  5579. mg_cry(workdata->conn,
  5580. "%s: syntax error in authorization file: %s",
  5581. __func__,
  5582. workdata->buf);
  5583. continue;
  5584. }
  5585. *(workdata->f_ha1) = 0;
  5586. (workdata->f_ha1)++;
  5587. if (!strcmp(workdata->ah.user, workdata->f_user)
  5588. && !strcmp(workdata->domain, workdata->f_domain)) {
  5589. return check_password(workdata->conn->request_info.request_method,
  5590. workdata->f_ha1,
  5591. workdata->ah.uri,
  5592. workdata->ah.nonce,
  5593. workdata->ah.nc,
  5594. workdata->ah.cnonce,
  5595. workdata->ah.qop,
  5596. workdata->ah.response);
  5597. }
  5598. }
  5599. return is_authorized;
  5600. }
  5601. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5602. static int
  5603. authorize(struct mg_connection *conn, struct mg_file *filep)
  5604. {
  5605. struct read_auth_file_struct workdata;
  5606. char buf[MG_BUF_LEN];
  5607. if (!conn || !conn->ctx) {
  5608. return 0;
  5609. }
  5610. memset(&workdata, 0, sizeof(workdata));
  5611. workdata.conn = conn;
  5612. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5613. return 0;
  5614. }
  5615. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5616. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5617. }
  5618. /* Return 1 if request is authorised, 0 otherwise. */
  5619. static int
  5620. check_authorization(struct mg_connection *conn, const char *path)
  5621. {
  5622. char fname[PATH_MAX];
  5623. struct vec uri_vec, filename_vec;
  5624. const char *list;
  5625. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5626. int authorized = 1, truncated;
  5627. if (!conn || !conn->ctx) {
  5628. return 0;
  5629. }
  5630. list = conn->ctx->config[PROTECT_URI];
  5631. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5632. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5633. mg_snprintf(conn,
  5634. &truncated,
  5635. fname,
  5636. sizeof(fname),
  5637. "%.*s",
  5638. (int)filename_vec.len,
  5639. filename_vec.ptr);
  5640. if (truncated
  5641. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5642. mg_cry(conn,
  5643. "%s: cannot open %s: %s",
  5644. __func__,
  5645. fname,
  5646. strerror(errno));
  5647. }
  5648. break;
  5649. }
  5650. }
  5651. if (!is_file_opened(&file.access)) {
  5652. open_auth_file(conn, path, &file);
  5653. }
  5654. if (is_file_opened(&file.access)) {
  5655. authorized = authorize(conn, &file);
  5656. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5657. }
  5658. return authorized;
  5659. }
  5660. static void
  5661. send_authorization_request(struct mg_connection *conn)
  5662. {
  5663. char date[64];
  5664. time_t curtime = time(NULL);
  5665. if (conn && conn->ctx) {
  5666. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5667. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5668. nonce += conn->ctx->nonce_count;
  5669. ++conn->ctx->nonce_count;
  5670. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5671. nonce ^= conn->ctx->auth_nonce_mask;
  5672. conn->status_code = 401;
  5673. conn->must_close = 1;
  5674. gmt_time_string(date, sizeof(date), &curtime);
  5675. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5676. send_no_cache_header(conn);
  5677. mg_printf(conn,
  5678. "Date: %s\r\n"
  5679. "Connection: %s\r\n"
  5680. "Content-Length: 0\r\n"
  5681. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5682. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5683. date,
  5684. suggest_connection_header(conn),
  5685. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5686. nonce);
  5687. }
  5688. }
  5689. #if !defined(NO_FILES)
  5690. static int
  5691. is_authorized_for_put(struct mg_connection *conn)
  5692. {
  5693. if (conn) {
  5694. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5695. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5696. int ret = 0;
  5697. if (passfile != NULL
  5698. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5699. ret = authorize(conn, &file);
  5700. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5701. }
  5702. return ret;
  5703. }
  5704. return 0;
  5705. }
  5706. #endif
  5707. int
  5708. mg_modify_passwords_file(const char *fname,
  5709. const char *domain,
  5710. const char *user,
  5711. const char *pass)
  5712. {
  5713. int found, i;
  5714. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5715. FILE *fp, *fp2;
  5716. found = 0;
  5717. fp = fp2 = NULL;
  5718. /* Regard empty password as no password - remove user record. */
  5719. if (pass != NULL && pass[0] == '\0') {
  5720. pass = NULL;
  5721. }
  5722. /* Other arguments must not be empty */
  5723. if (fname == NULL || domain == NULL || user == NULL) {
  5724. return 0;
  5725. }
  5726. /* Using the given file format, user name and domain must not contain ':'
  5727. */
  5728. if (strchr(user, ':') != NULL) {
  5729. return 0;
  5730. }
  5731. if (strchr(domain, ':') != NULL) {
  5732. return 0;
  5733. }
  5734. /* Do not allow control characters like newline in user name and domain.
  5735. * Do not allow excessively long names either. */
  5736. for (i = 0; i < 255 && user[i] != 0; i++) {
  5737. if (iscntrl(user[i])) {
  5738. return 0;
  5739. }
  5740. }
  5741. if (user[i]) {
  5742. return 0;
  5743. }
  5744. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5745. if (iscntrl(domain[i])) {
  5746. return 0;
  5747. }
  5748. }
  5749. if (domain[i]) {
  5750. return 0;
  5751. }
  5752. /* The maximum length of the path to the password file is limited */
  5753. if ((strlen(fname) + 4) >= PATH_MAX) {
  5754. return 0;
  5755. }
  5756. /* Create a temporary file name. Length has been checked before. */
  5757. strcpy(tmp, fname);
  5758. strcat(tmp, ".tmp");
  5759. /* Create the file if does not exist */
  5760. /* Use of fopen here is OK, since fname is only ASCII */
  5761. if ((fp = fopen(fname, "a+")) != NULL) {
  5762. (void)fclose(fp);
  5763. }
  5764. /* Open the given file and temporary file */
  5765. if ((fp = fopen(fname, "r")) == NULL) {
  5766. return 0;
  5767. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5768. fclose(fp);
  5769. return 0;
  5770. }
  5771. /* Copy the stuff to temporary file */
  5772. while (fgets(line, sizeof(line), fp) != NULL) {
  5773. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5774. continue;
  5775. }
  5776. u[255] = 0;
  5777. d[255] = 0;
  5778. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5779. found++;
  5780. if (pass != NULL) {
  5781. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5782. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5783. }
  5784. } else {
  5785. fprintf(fp2, "%s", line);
  5786. }
  5787. }
  5788. /* If new user, just add it */
  5789. if (!found && pass != NULL) {
  5790. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5791. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5792. }
  5793. /* Close files */
  5794. fclose(fp);
  5795. fclose(fp2);
  5796. /* Put the temp file in place of real file */
  5797. IGNORE_UNUSED_RESULT(remove(fname));
  5798. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5799. return 1;
  5800. }
  5801. static int
  5802. is_valid_port(unsigned long port)
  5803. {
  5804. return port < 0xffff;
  5805. }
  5806. static int
  5807. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5808. {
  5809. struct addrinfo hints, *res, *ressave;
  5810. int func_ret = 0;
  5811. int gai_ret;
  5812. memset(&hints, 0, sizeof(struct addrinfo));
  5813. hints.ai_family = af;
  5814. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5815. if (gai_ret != 0) {
  5816. /* gai_strerror could be used to convert gai_ret to a string */
  5817. /* POSIX return values: see
  5818. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5819. */
  5820. /* Windows return values: see
  5821. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5822. */
  5823. return 0;
  5824. }
  5825. ressave = res;
  5826. while (res) {
  5827. if (dstlen >= res->ai_addrlen) {
  5828. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5829. func_ret = 1;
  5830. }
  5831. res = res->ai_next;
  5832. }
  5833. freeaddrinfo(ressave);
  5834. return func_ret;
  5835. }
  5836. static int
  5837. connect_socket(struct mg_context *ctx /* may be NULL */,
  5838. const char *host,
  5839. int port,
  5840. int use_ssl,
  5841. char *ebuf,
  5842. size_t ebuf_len,
  5843. SOCKET *sock /* output: socket, must not be NULL */,
  5844. union usa *sa /* output: socket address, must not be NULL */
  5845. )
  5846. {
  5847. int ip_ver = 0;
  5848. *sock = INVALID_SOCKET;
  5849. memset(sa, 0, sizeof(*sa));
  5850. if (ebuf_len > 0) {
  5851. *ebuf = 0;
  5852. }
  5853. if (host == NULL) {
  5854. mg_snprintf(NULL,
  5855. NULL, /* No truncation check for ebuf */
  5856. ebuf,
  5857. ebuf_len,
  5858. "%s",
  5859. "NULL host");
  5860. return 0;
  5861. }
  5862. if (port < 0 || !is_valid_port((unsigned)port)) {
  5863. mg_snprintf(NULL,
  5864. NULL, /* No truncation check for ebuf */
  5865. ebuf,
  5866. ebuf_len,
  5867. "%s",
  5868. "invalid port");
  5869. return 0;
  5870. }
  5871. #if !defined(NO_SSL)
  5872. #if !defined(NO_SSL_DL)
  5873. #ifdef OPENSSL_API_1_1
  5874. if (use_ssl && (TLS_client_method == NULL)) {
  5875. mg_snprintf(NULL,
  5876. NULL, /* No truncation check for ebuf */
  5877. ebuf,
  5878. ebuf_len,
  5879. "%s",
  5880. "SSL is not initialized");
  5881. return 0;
  5882. }
  5883. #else
  5884. if (use_ssl && (SSLv23_client_method == NULL)) {
  5885. mg_snprintf(NULL,
  5886. NULL, /* No truncation check for ebuf */
  5887. ebuf,
  5888. ebuf_len,
  5889. "%s",
  5890. "SSL is not initialized");
  5891. return 0;
  5892. }
  5893. #endif /* OPENSSL_API_1_1 */
  5894. #else
  5895. (void)use_ssl;
  5896. #endif /* NO_SSL_DL */
  5897. #else
  5898. (void)use_ssl;
  5899. #endif /* !defined(NO_SSL) */
  5900. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5901. sa->sin.sin_port = htons((uint16_t)port);
  5902. ip_ver = 4;
  5903. #ifdef USE_IPV6
  5904. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5905. sa->sin6.sin6_port = htons((uint16_t)port);
  5906. ip_ver = 6;
  5907. } else if (host[0] == '[') {
  5908. /* While getaddrinfo on Windows will work with [::1],
  5909. * getaddrinfo on Linux only works with ::1 (without []). */
  5910. size_t l = strlen(host + 1);
  5911. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5912. if (h) {
  5913. h[l - 1] = 0;
  5914. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5915. sa->sin6.sin6_port = htons((uint16_t)port);
  5916. ip_ver = 6;
  5917. }
  5918. mg_free(h);
  5919. }
  5920. #endif
  5921. }
  5922. if (ip_ver == 0) {
  5923. mg_snprintf(NULL,
  5924. NULL, /* No truncation check for ebuf */
  5925. ebuf,
  5926. ebuf_len,
  5927. "%s",
  5928. "host not found");
  5929. return 0;
  5930. }
  5931. if (ip_ver == 4) {
  5932. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5933. }
  5934. #ifdef USE_IPV6
  5935. else if (ip_ver == 6) {
  5936. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5937. }
  5938. #endif
  5939. if (*sock == INVALID_SOCKET) {
  5940. mg_snprintf(NULL,
  5941. NULL, /* No truncation check for ebuf */
  5942. ebuf,
  5943. ebuf_len,
  5944. "socket(): %s",
  5945. strerror(ERRNO));
  5946. return 0;
  5947. }
  5948. set_close_on_exec(*sock, fc(ctx));
  5949. if ((ip_ver == 4)
  5950. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5951. == 0)) {
  5952. /* connected with IPv4 */
  5953. set_blocking_mode(*sock, 0);
  5954. return 1;
  5955. }
  5956. #ifdef USE_IPV6
  5957. if ((ip_ver == 6)
  5958. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5959. == 0)) {
  5960. /* connected with IPv6 */
  5961. set_blocking_mode(*sock, 0);
  5962. return 1;
  5963. }
  5964. #endif
  5965. /* Not connected */
  5966. mg_snprintf(NULL,
  5967. NULL, /* No truncation check for ebuf */
  5968. ebuf,
  5969. ebuf_len,
  5970. "connect(%s:%d): %s",
  5971. host,
  5972. port,
  5973. strerror(ERRNO));
  5974. closesocket(*sock);
  5975. *sock = INVALID_SOCKET;
  5976. return 0;
  5977. }
  5978. int
  5979. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5980. {
  5981. static const char *dont_escape = "._-$,;~()";
  5982. static const char *hex = "0123456789abcdef";
  5983. char *pos = dst;
  5984. const char *end = dst + dst_len - 1;
  5985. for (; *src != '\0' && pos < end; src++, pos++) {
  5986. if (isalnum(*(const unsigned char *)src)
  5987. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5988. *pos = *src;
  5989. } else if (pos + 2 < end) {
  5990. pos[0] = '%';
  5991. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5992. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5993. pos += 2;
  5994. } else {
  5995. break;
  5996. }
  5997. }
  5998. *pos = '\0';
  5999. return (*src == '\0') ? (int)(pos - dst) : -1;
  6000. }
  6001. static void
  6002. print_dir_entry(struct de *de)
  6003. {
  6004. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6005. struct tm *tm;
  6006. if (de->file.is_directory) {
  6007. mg_snprintf(de->conn,
  6008. NULL, /* Buffer is big enough */
  6009. size,
  6010. sizeof(size),
  6011. "%s",
  6012. "[DIRECTORY]");
  6013. } else {
  6014. /* We use (signed) cast below because MSVC 6 compiler cannot
  6015. * convert unsigned __int64 to double. Sigh. */
  6016. if (de->file.size < 1024) {
  6017. mg_snprintf(de->conn,
  6018. NULL, /* Buffer is big enough */
  6019. size,
  6020. sizeof(size),
  6021. "%d",
  6022. (int)de->file.size);
  6023. } else if (de->file.size < 0x100000) {
  6024. mg_snprintf(de->conn,
  6025. NULL, /* Buffer is big enough */
  6026. size,
  6027. sizeof(size),
  6028. "%.1fk",
  6029. (double)de->file.size / 1024.0);
  6030. } else if (de->file.size < 0x40000000) {
  6031. mg_snprintf(de->conn,
  6032. NULL, /* Buffer is big enough */
  6033. size,
  6034. sizeof(size),
  6035. "%.1fM",
  6036. (double)de->file.size / 1048576);
  6037. } else {
  6038. mg_snprintf(de->conn,
  6039. NULL, /* Buffer is big enough */
  6040. size,
  6041. sizeof(size),
  6042. "%.1fG",
  6043. (double)de->file.size / 1073741824);
  6044. }
  6045. }
  6046. /* Note: mg_snprintf will not cause a buffer overflow above.
  6047. * So, string truncation checks are not required here. */
  6048. tm = localtime(&de->file.last_modified);
  6049. if (tm != NULL) {
  6050. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6051. } else {
  6052. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6053. mod[sizeof(mod) - 1] = '\0';
  6054. }
  6055. mg_url_encode(de->file_name, href, sizeof(href));
  6056. de->conn->num_bytes_sent +=
  6057. mg_printf(de->conn,
  6058. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6059. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6060. de->conn->request_info.local_uri,
  6061. href,
  6062. de->file.is_directory ? "/" : "",
  6063. de->file_name,
  6064. de->file.is_directory ? "/" : "",
  6065. mod,
  6066. size);
  6067. }
  6068. /* This function is called from send_directory() and used for
  6069. * sorting directory entries by size, or name, or modification time.
  6070. * On windows, __cdecl specification is needed in case if project is built
  6071. * with __stdcall convention. qsort always requires __cdels callback. */
  6072. static int WINCDECL
  6073. compare_dir_entries(const void *p1, const void *p2)
  6074. {
  6075. if (p1 && p2) {
  6076. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6077. const char *query_string = a->conn->request_info.query_string;
  6078. int cmp_result = 0;
  6079. if (query_string == NULL) {
  6080. query_string = "na";
  6081. }
  6082. if (a->file.is_directory && !b->file.is_directory) {
  6083. return -1; /* Always put directories on top */
  6084. } else if (!a->file.is_directory && b->file.is_directory) {
  6085. return 1; /* Always put directories on top */
  6086. } else if (*query_string == 'n') {
  6087. cmp_result = strcmp(a->file_name, b->file_name);
  6088. } else if (*query_string == 's') {
  6089. cmp_result = (a->file.size == b->file.size)
  6090. ? 0
  6091. : ((a->file.size > b->file.size) ? 1 : -1);
  6092. } else if (*query_string == 'd') {
  6093. cmp_result =
  6094. (a->file.last_modified == b->file.last_modified)
  6095. ? 0
  6096. : ((a->file.last_modified > b->file.last_modified) ? 1
  6097. : -1);
  6098. }
  6099. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6100. }
  6101. return 0;
  6102. }
  6103. static int
  6104. must_hide_file(struct mg_connection *conn, const char *path)
  6105. {
  6106. if (conn && conn->ctx) {
  6107. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6108. const char *pattern = conn->ctx->config[HIDE_FILES];
  6109. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6110. || (pattern != NULL
  6111. && match_prefix(pattern, strlen(pattern), path) > 0);
  6112. }
  6113. return 0;
  6114. }
  6115. static int
  6116. scan_directory(struct mg_connection *conn,
  6117. const char *dir,
  6118. void *data,
  6119. void (*cb)(struct de *, void *))
  6120. {
  6121. char path[PATH_MAX];
  6122. struct dirent *dp;
  6123. DIR *dirp;
  6124. struct de de;
  6125. int truncated;
  6126. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6127. return 0;
  6128. } else {
  6129. de.conn = conn;
  6130. while ((dp = mg_readdir(dirp)) != NULL) {
  6131. /* Do not show current dir and hidden files */
  6132. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6133. || must_hide_file(conn, dp->d_name)) {
  6134. continue;
  6135. }
  6136. mg_snprintf(
  6137. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6138. /* If we don't memset stat structure to zero, mtime will have
  6139. * garbage and strftime() will segfault later on in
  6140. * print_dir_entry(). memset is required only if mg_stat()
  6141. * fails. For more details, see
  6142. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6143. memset(&de.file, 0, sizeof(de.file));
  6144. if (truncated) {
  6145. /* If the path is not complete, skip processing. */
  6146. continue;
  6147. }
  6148. if (!mg_stat(conn, path, &de.file)) {
  6149. mg_cry(conn,
  6150. "%s: mg_stat(%s) failed: %s",
  6151. __func__,
  6152. path,
  6153. strerror(ERRNO));
  6154. }
  6155. de.file_name = dp->d_name;
  6156. cb(&de, data);
  6157. }
  6158. (void)mg_closedir(dirp);
  6159. }
  6160. return 1;
  6161. }
  6162. #if !defined(NO_FILES)
  6163. static int
  6164. remove_directory(struct mg_connection *conn, const char *dir)
  6165. {
  6166. char path[PATH_MAX];
  6167. struct dirent *dp;
  6168. DIR *dirp;
  6169. struct de de;
  6170. int truncated;
  6171. int ok = 1;
  6172. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6173. return 0;
  6174. } else {
  6175. de.conn = conn;
  6176. while ((dp = mg_readdir(dirp)) != NULL) {
  6177. /* Do not show current dir (but show hidden files as they will
  6178. * also be removed) */
  6179. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6180. continue;
  6181. }
  6182. mg_snprintf(
  6183. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6184. /* If we don't memset stat structure to zero, mtime will have
  6185. * garbage and strftime() will segfault later on in
  6186. * print_dir_entry(). memset is required only if mg_stat()
  6187. * fails. For more details, see
  6188. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6189. memset(&de.file, 0, sizeof(de.file));
  6190. if (truncated) {
  6191. /* Do not delete anything shorter */
  6192. ok = 0;
  6193. continue;
  6194. }
  6195. if (!mg_stat(conn, path, &de.file)) {
  6196. mg_cry(conn,
  6197. "%s: mg_stat(%s) failed: %s",
  6198. __func__,
  6199. path,
  6200. strerror(ERRNO));
  6201. ok = 0;
  6202. }
  6203. if (de.file.is_directory) {
  6204. if (remove_directory(conn, path) == 0) {
  6205. ok = 0;
  6206. }
  6207. } else {
  6208. /* This will fail file is the file is in memory */
  6209. if (mg_remove(conn, path) == 0) {
  6210. ok = 0;
  6211. }
  6212. }
  6213. }
  6214. (void)mg_closedir(dirp);
  6215. IGNORE_UNUSED_RESULT(rmdir(dir));
  6216. }
  6217. return ok;
  6218. }
  6219. #endif
  6220. struct dir_scan_data {
  6221. struct de *entries;
  6222. unsigned int num_entries;
  6223. unsigned int arr_size;
  6224. };
  6225. /* Behaves like realloc(), but frees original pointer on failure */
  6226. static void *
  6227. realloc2(void *ptr, size_t size)
  6228. {
  6229. void *new_ptr = mg_realloc(ptr, size);
  6230. if (new_ptr == NULL) {
  6231. mg_free(ptr);
  6232. }
  6233. return new_ptr;
  6234. }
  6235. static void
  6236. dir_scan_callback(struct de *de, void *data)
  6237. {
  6238. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6239. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6240. dsd->arr_size *= 2;
  6241. dsd->entries =
  6242. (struct de *)realloc2(dsd->entries,
  6243. dsd->arr_size * sizeof(dsd->entries[0]));
  6244. }
  6245. if (dsd->entries == NULL) {
  6246. /* TODO(lsm, low): propagate an error to the caller */
  6247. dsd->num_entries = 0;
  6248. } else {
  6249. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6250. dsd->entries[dsd->num_entries].file = de->file;
  6251. dsd->entries[dsd->num_entries].conn = de->conn;
  6252. dsd->num_entries++;
  6253. }
  6254. }
  6255. static void
  6256. handle_directory_request(struct mg_connection *conn, const char *dir)
  6257. {
  6258. unsigned int i;
  6259. int sort_direction;
  6260. struct dir_scan_data data = {NULL, 0, 128};
  6261. char date[64];
  6262. time_t curtime = time(NULL);
  6263. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6264. send_http_error(conn,
  6265. 500,
  6266. "Error: Cannot open directory\nopendir(%s): %s",
  6267. dir,
  6268. strerror(ERRNO));
  6269. return;
  6270. }
  6271. gmt_time_string(date, sizeof(date), &curtime);
  6272. if (!conn) {
  6273. return;
  6274. }
  6275. sort_direction = ((conn->request_info.query_string != NULL)
  6276. && (conn->request_info.query_string[1] == 'd'))
  6277. ? 'a'
  6278. : 'd';
  6279. conn->must_close = 1;
  6280. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6281. send_static_cache_header(conn);
  6282. mg_printf(conn,
  6283. "Date: %s\r\n"
  6284. "Connection: close\r\n"
  6285. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6286. date);
  6287. conn->num_bytes_sent +=
  6288. mg_printf(conn,
  6289. "<html><head><title>Index of %s</title>"
  6290. "<style>th {text-align: left;}</style></head>"
  6291. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6292. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6293. "<th><a href=\"?d%c\">Modified</a></th>"
  6294. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6295. "<tr><td colspan=\"3\"><hr></td></tr>",
  6296. conn->request_info.local_uri,
  6297. conn->request_info.local_uri,
  6298. sort_direction,
  6299. sort_direction,
  6300. sort_direction);
  6301. /* Print first entry - link to a parent directory */
  6302. conn->num_bytes_sent +=
  6303. mg_printf(conn,
  6304. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6305. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6306. conn->request_info.local_uri,
  6307. "..",
  6308. "Parent directory",
  6309. "-",
  6310. "-");
  6311. /* Sort and print directory entries */
  6312. if (data.entries != NULL) {
  6313. qsort(data.entries,
  6314. (size_t)data.num_entries,
  6315. sizeof(data.entries[0]),
  6316. compare_dir_entries);
  6317. for (i = 0; i < data.num_entries; i++) {
  6318. print_dir_entry(&data.entries[i]);
  6319. mg_free(data.entries[i].file_name);
  6320. }
  6321. mg_free(data.entries);
  6322. }
  6323. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6324. conn->status_code = 200;
  6325. }
  6326. /* Send len bytes from the opened file to the client. */
  6327. static void
  6328. send_file_data(struct mg_connection *conn,
  6329. struct mg_file *filep,
  6330. int64_t offset,
  6331. int64_t len)
  6332. {
  6333. char buf[MG_BUF_LEN];
  6334. int to_read, num_read, num_written;
  6335. int64_t size;
  6336. if (!filep || !conn) {
  6337. return;
  6338. }
  6339. /* Sanity check the offset */
  6340. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6341. : (int64_t)(filep->stat.size);
  6342. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6343. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6344. /* file stored in memory */
  6345. if (len > size - offset) {
  6346. len = size - offset;
  6347. }
  6348. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6349. } else if (len > 0 && filep->access.fp != NULL) {
  6350. /* file stored on disk */
  6351. #if defined(__linux__)
  6352. /* sendfile is only available for Linux */
  6353. if ((conn->ssl == 0) && (conn->throttle == 0)
  6354. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6355. "yes"))) {
  6356. off_t sf_offs = (off_t)offset;
  6357. ssize_t sf_sent;
  6358. int sf_file = fileno(filep->access.fp);
  6359. int loop_cnt = 0;
  6360. do {
  6361. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6362. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6363. size_t sf_tosend =
  6364. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6365. sf_sent =
  6366. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6367. if (sf_sent > 0) {
  6368. conn->num_bytes_sent += sf_sent;
  6369. len -= sf_sent;
  6370. offset += sf_sent;
  6371. } else if (loop_cnt == 0) {
  6372. /* This file can not be sent using sendfile.
  6373. * This might be the case for pseudo-files in the
  6374. * /sys/ and /proc/ file system.
  6375. * Use the regular user mode copy code instead. */
  6376. break;
  6377. } else if (sf_sent == 0) {
  6378. /* No error, but 0 bytes sent. May be EOF? */
  6379. return;
  6380. }
  6381. loop_cnt++;
  6382. } while ((len > 0) && (sf_sent >= 0));
  6383. if (sf_sent > 0) {
  6384. return; /* OK */
  6385. }
  6386. /* sf_sent<0 means error, thus fall back to the classic way */
  6387. /* This is always the case, if sf_file is not a "normal" file,
  6388. * e.g., for sending data from the output of a CGI process. */
  6389. offset = (int64_t)sf_offs;
  6390. }
  6391. #endif
  6392. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6393. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6394. send_http_error(
  6395. conn,
  6396. 500,
  6397. "%s",
  6398. "Error: Unable to access file at requested position.");
  6399. } else {
  6400. while (len > 0) {
  6401. /* Calculate how much to read from the file in the buffer */
  6402. to_read = sizeof(buf);
  6403. if ((int64_t)to_read > len) {
  6404. to_read = (int)len;
  6405. }
  6406. /* Read from file, exit the loop on error */
  6407. if ((num_read =
  6408. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6409. <= 0) {
  6410. break;
  6411. }
  6412. /* Send read bytes to the client, exit the loop on error */
  6413. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6414. != num_read) {
  6415. break;
  6416. }
  6417. /* Both read and were successful, adjust counters */
  6418. conn->num_bytes_sent += num_written;
  6419. len -= num_written;
  6420. }
  6421. }
  6422. }
  6423. }
  6424. static int
  6425. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6426. {
  6427. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6428. }
  6429. static void
  6430. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6431. {
  6432. if (filestat != NULL && buf != NULL) {
  6433. mg_snprintf(NULL,
  6434. NULL, /* All calls to construct_etag use 64 byte buffer */
  6435. buf,
  6436. buf_len,
  6437. "\"%lx.%" INT64_FMT "\"",
  6438. (unsigned long)filestat->last_modified,
  6439. filestat->size);
  6440. }
  6441. }
  6442. static void
  6443. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6444. {
  6445. if (filep != NULL && filep->fp != NULL) {
  6446. #ifdef _WIN32
  6447. (void)conn; /* Unused. */
  6448. #else
  6449. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6450. mg_cry(conn,
  6451. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6452. __func__,
  6453. strerror(ERRNO));
  6454. }
  6455. #endif
  6456. }
  6457. }
  6458. static void
  6459. handle_static_file_request(struct mg_connection *conn,
  6460. const char *path,
  6461. struct mg_file *filep,
  6462. const char *mime_type,
  6463. const char *additional_headers)
  6464. {
  6465. char date[64], lm[64], etag[64];
  6466. char range[128]; /* large enough, so there will be no overflow */
  6467. const char *msg = "OK", *hdr;
  6468. time_t curtime = time(NULL);
  6469. int64_t cl, r1, r2;
  6470. struct vec mime_vec;
  6471. int n, truncated;
  6472. char gz_path[PATH_MAX];
  6473. const char *encoding = "";
  6474. const char *cors1, *cors2, *cors3;
  6475. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6476. return;
  6477. }
  6478. if (mime_type == NULL) {
  6479. get_mime_type(conn->ctx, path, &mime_vec);
  6480. } else {
  6481. mime_vec.ptr = mime_type;
  6482. mime_vec.len = strlen(mime_type);
  6483. }
  6484. if (filep->stat.size > INT64_MAX) {
  6485. send_http_error(conn,
  6486. 500,
  6487. "Error: File size is too large to send\n%" INT64_FMT,
  6488. filep->stat.size);
  6489. }
  6490. cl = (int64_t)filep->stat.size;
  6491. conn->status_code = 200;
  6492. range[0] = '\0';
  6493. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6494. * it's important to rewrite the filename after resolving
  6495. * the mime type from it, to preserve the actual file's type */
  6496. if (filep->stat.is_gzipped) {
  6497. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6498. if (truncated) {
  6499. send_http_error(conn,
  6500. 500,
  6501. "Error: Path of zipped file too long (%s)",
  6502. path);
  6503. return;
  6504. }
  6505. path = gz_path;
  6506. encoding = "Content-Encoding: gzip\r\n";
  6507. }
  6508. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6509. send_http_error(conn,
  6510. 500,
  6511. "Error: Cannot open file\nfopen(%s): %s",
  6512. path,
  6513. strerror(ERRNO));
  6514. return;
  6515. }
  6516. fclose_on_exec(&filep->access, conn);
  6517. /* If Range: header specified, act accordingly */
  6518. r1 = r2 = 0;
  6519. hdr = mg_get_header(conn, "Range");
  6520. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6521. && r2 >= 0) {
  6522. /* actually, range requests don't play well with a pre-gzipped
  6523. * file (since the range is specified in the uncompressed space) */
  6524. if (filep->stat.is_gzipped) {
  6525. send_http_error(
  6526. conn,
  6527. 501,
  6528. "%s",
  6529. "Error: Range requests in gzipped files are not supported");
  6530. (void)mg_fclose(
  6531. &filep->access); /* ignore error on read only file */
  6532. return;
  6533. }
  6534. conn->status_code = 206;
  6535. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6536. mg_snprintf(conn,
  6537. NULL, /* range buffer is big enough */
  6538. range,
  6539. sizeof(range),
  6540. "Content-Range: bytes "
  6541. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6542. r1,
  6543. r1 + cl - 1,
  6544. filep->stat.size);
  6545. msg = "Partial Content";
  6546. }
  6547. hdr = mg_get_header(conn, "Origin");
  6548. if (hdr) {
  6549. /* Cross-origin resource sharing (CORS), see
  6550. * http://www.html5rocks.com/en/tutorials/cors/,
  6551. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6552. * preflight is not supported for files. */
  6553. cors1 = "Access-Control-Allow-Origin: ";
  6554. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6555. cors3 = "\r\n";
  6556. } else {
  6557. cors1 = cors2 = cors3 = "";
  6558. }
  6559. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6560. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6561. gmt_time_string(date, sizeof(date), &curtime);
  6562. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6563. construct_etag(etag, sizeof(etag), &filep->stat);
  6564. (void)mg_printf(conn,
  6565. "HTTP/1.1 %d %s\r\n"
  6566. "%s%s%s"
  6567. "Date: %s\r\n",
  6568. conn->status_code,
  6569. msg,
  6570. cors1,
  6571. cors2,
  6572. cors3,
  6573. date);
  6574. send_static_cache_header(conn);
  6575. (void)mg_printf(conn,
  6576. "Last-Modified: %s\r\n"
  6577. "Etag: %s\r\n"
  6578. "Content-Type: %.*s\r\n"
  6579. "Content-Length: %" INT64_FMT "\r\n"
  6580. "Connection: %s\r\n"
  6581. "Accept-Ranges: bytes\r\n"
  6582. "%s%s",
  6583. lm,
  6584. etag,
  6585. (int)mime_vec.len,
  6586. mime_vec.ptr,
  6587. cl,
  6588. suggest_connection_header(conn),
  6589. range,
  6590. encoding);
  6591. /* The previous code must not add any header starting with X- to make
  6592. * sure no one of the additional_headers is included twice */
  6593. if (additional_headers != NULL) {
  6594. (void)mg_printf(conn,
  6595. "%.*s\r\n\r\n",
  6596. (int)strlen(additional_headers),
  6597. additional_headers);
  6598. } else {
  6599. (void)mg_printf(conn, "\r\n");
  6600. }
  6601. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6602. send_file_data(conn, filep, r1, cl);
  6603. }
  6604. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6605. }
  6606. #if !defined(NO_CACHING)
  6607. static void
  6608. handle_not_modified_static_file_request(struct mg_connection *conn,
  6609. struct mg_file *filep)
  6610. {
  6611. char date[64], lm[64], etag[64];
  6612. time_t curtime = time(NULL);
  6613. if (conn == NULL || filep == NULL) {
  6614. return;
  6615. }
  6616. conn->status_code = 304;
  6617. gmt_time_string(date, sizeof(date), &curtime);
  6618. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6619. construct_etag(etag, sizeof(etag), &filep->stat);
  6620. (void)mg_printf(conn,
  6621. "HTTP/1.1 %d %s\r\n"
  6622. "Date: %s\r\n",
  6623. conn->status_code,
  6624. mg_get_response_code_text(conn, conn->status_code),
  6625. date);
  6626. send_static_cache_header(conn);
  6627. (void)mg_printf(conn,
  6628. "Last-Modified: %s\r\n"
  6629. "Etag: %s\r\n"
  6630. "Connection: %s\r\n"
  6631. "\r\n",
  6632. lm,
  6633. etag,
  6634. suggest_connection_header(conn));
  6635. }
  6636. #endif
  6637. void
  6638. mg_send_file(struct mg_connection *conn, const char *path)
  6639. {
  6640. mg_send_mime_file(conn, path, NULL);
  6641. }
  6642. void
  6643. mg_send_mime_file(struct mg_connection *conn,
  6644. const char *path,
  6645. const char *mime_type)
  6646. {
  6647. mg_send_mime_file2(conn, path, mime_type, NULL);
  6648. }
  6649. void
  6650. mg_send_mime_file2(struct mg_connection *conn,
  6651. const char *path,
  6652. const char *mime_type,
  6653. const char *additional_headers)
  6654. {
  6655. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6656. if (mg_stat(conn, path, &file.stat)) {
  6657. if (file.stat.is_directory) {
  6658. if (!conn) {
  6659. return;
  6660. }
  6661. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6662. "yes")) {
  6663. handle_directory_request(conn, path);
  6664. } else {
  6665. send_http_error(conn,
  6666. 403,
  6667. "%s",
  6668. "Error: Directory listing denied");
  6669. }
  6670. } else {
  6671. handle_static_file_request(
  6672. conn, path, &file, mime_type, additional_headers);
  6673. }
  6674. } else {
  6675. send_http_error(conn, 404, "%s", "Error: File not found");
  6676. }
  6677. }
  6678. /* For a given PUT path, create all intermediate subdirectories.
  6679. * Return 0 if the path itself is a directory.
  6680. * Return 1 if the path leads to a file.
  6681. * Return -1 for if the path is too long.
  6682. * Return -2 if path can not be created.
  6683. */
  6684. static int
  6685. put_dir(struct mg_connection *conn, const char *path)
  6686. {
  6687. char buf[PATH_MAX];
  6688. const char *s, *p;
  6689. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6690. size_t len;
  6691. int res = 1;
  6692. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6693. len = (size_t)(p - path);
  6694. if (len >= sizeof(buf)) {
  6695. /* path too long */
  6696. res = -1;
  6697. break;
  6698. }
  6699. memcpy(buf, path, len);
  6700. buf[len] = '\0';
  6701. /* Try to create intermediate directory */
  6702. DEBUG_TRACE("mkdir(%s)", buf);
  6703. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6704. /* path does not exixt and can not be created */
  6705. res = -2;
  6706. break;
  6707. }
  6708. /* Is path itself a directory? */
  6709. if (p[1] == '\0') {
  6710. res = 0;
  6711. }
  6712. }
  6713. return res;
  6714. }
  6715. static void
  6716. remove_bad_file(const struct mg_connection *conn, const char *path)
  6717. {
  6718. int r = mg_remove(conn, path);
  6719. if (r != 0) {
  6720. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6721. }
  6722. }
  6723. long long
  6724. mg_store_body(struct mg_connection *conn, const char *path)
  6725. {
  6726. char buf[MG_BUF_LEN];
  6727. long long len = 0;
  6728. int ret, n;
  6729. struct mg_file fi;
  6730. if (conn->consumed_content != 0) {
  6731. mg_cry(conn, "%s: Contents already consumed", __func__);
  6732. return -11;
  6733. }
  6734. ret = put_dir(conn, path);
  6735. if (ret < 0) {
  6736. /* -1 for path too long,
  6737. * -2 for path can not be created. */
  6738. return ret;
  6739. }
  6740. if (ret != 1) {
  6741. /* Return 0 means, path itself is a directory. */
  6742. return 0;
  6743. }
  6744. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6745. return -12;
  6746. }
  6747. ret = mg_read(conn, buf, sizeof(buf));
  6748. while (ret > 0) {
  6749. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6750. if (n != ret) {
  6751. (void)mg_fclose(
  6752. &fi.access); /* File is bad and will be removed anyway. */
  6753. remove_bad_file(conn, path);
  6754. return -13;
  6755. }
  6756. ret = mg_read(conn, buf, sizeof(buf));
  6757. }
  6758. /* File is open for writing. If fclose fails, there was probably an
  6759. * error flushing the buffer to disk, so the file on disk might be
  6760. * broken. Delete it and return an error to the caller. */
  6761. if (mg_fclose(&fi.access) != 0) {
  6762. remove_bad_file(conn, path);
  6763. return -14;
  6764. }
  6765. return len;
  6766. }
  6767. /* Parse HTTP headers from the given buffer, advance buf pointer
  6768. * to the point where parsing stopped.
  6769. * All parameters must be valid pointers (not NULL).
  6770. * Return <0 on error. */
  6771. static int
  6772. parse_http_headers(char **buf, struct mg_request_info *ri)
  6773. {
  6774. int i;
  6775. ri->num_headers = 0;
  6776. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6777. char *dp = *buf;
  6778. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6779. dp++;
  6780. }
  6781. if (dp == *buf) {
  6782. /* End of headers reached. */
  6783. break;
  6784. }
  6785. if (*dp != ':') {
  6786. /* This is not a valid field. */
  6787. return -1;
  6788. }
  6789. /* End of header key (*dp == ':') */
  6790. /* Truncate here and set the key name */
  6791. *dp = 0;
  6792. ri->http_headers[i].name = *buf;
  6793. do {
  6794. dp++;
  6795. } while (*dp == ' ');
  6796. /* The rest of the line is the value */
  6797. ri->http_headers[i].value = dp;
  6798. *buf = dp + strcspn(dp, "\r\n");
  6799. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6800. *buf = NULL;
  6801. }
  6802. ri->num_headers = i + 1;
  6803. if (*buf) {
  6804. (*buf)[0] = 0;
  6805. (*buf)[1] = 0;
  6806. *buf += 2;
  6807. } else {
  6808. *buf = dp;
  6809. break;
  6810. }
  6811. if ((*buf)[0] == '\r') {
  6812. /* This is the end of the header */
  6813. break;
  6814. }
  6815. }
  6816. return ri->num_headers;
  6817. }
  6818. static int
  6819. is_valid_http_method(const char *method)
  6820. {
  6821. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6822. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6823. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6824. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6825. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6826. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6827. /* TRACE method (RFC 2616) is not supported for security reasons */
  6828. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6829. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6830. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6831. /* Unsupported WEBDAV Methods: */
  6832. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6833. /* + 11 methods from RFC 3253 */
  6834. /* ORDERPATCH (RFC 3648) */
  6835. /* ACL (RFC 3744) */
  6836. /* SEARCH (RFC 5323) */
  6837. /* + MicroSoft extensions
  6838. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6839. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6840. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6841. }
  6842. /* Parse HTTP request, fill in mg_request_info structure.
  6843. * This function modifies the buffer by NUL-terminating
  6844. * HTTP request components, header names and header values.
  6845. * Parameters:
  6846. * buf (in/out): pointer to the HTTP header to parse and split
  6847. * len (in): length of HTTP header buffer
  6848. * re (out): parsed header as mg_request_info
  6849. * buf and ri must be valid pointers (not NULL), len>0.
  6850. * Returns <0 on error. */
  6851. static int
  6852. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6853. {
  6854. int is_request, request_length;
  6855. char *start_line;
  6856. request_length = get_request_len(buf, len);
  6857. if (request_length > 0) {
  6858. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6859. * remote_port */
  6860. ri->remote_user = ri->request_method = ri->request_uri =
  6861. ri->http_version = NULL;
  6862. ri->num_headers = 0;
  6863. buf[request_length - 1] = '\0';
  6864. /* RFC says that all initial whitespaces should be ingored */
  6865. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6866. buf++;
  6867. }
  6868. start_line = skip(&buf, "\r\n");
  6869. ri->request_method = skip(&start_line, " ");
  6870. ri->request_uri = skip(&start_line, " ");
  6871. ri->http_version = start_line;
  6872. /* HTTP message could be either HTTP request:
  6873. * "GET / HTTP/1.0 ..."
  6874. * or a HTTP response:
  6875. * "HTTP/1.0 200 OK ..."
  6876. * otherwise it is invalid.
  6877. */
  6878. is_request = is_valid_http_method(ri->request_method);
  6879. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6880. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6881. /* Not a valid request or response: invalid */
  6882. return -1;
  6883. }
  6884. if (is_request) {
  6885. ri->http_version += 5;
  6886. }
  6887. if (parse_http_headers(&buf, ri) < 0) {
  6888. /* Error while parsing headers */
  6889. return -1;
  6890. }
  6891. }
  6892. return request_length;
  6893. }
  6894. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6895. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6896. * buffer (which marks the end of HTTP request). Buffer buf may already
  6897. * have some data. The length of the data is stored in nread.
  6898. * Upon every read operation, increase nread by the number of bytes read. */
  6899. static int
  6900. read_request(FILE *fp,
  6901. struct mg_connection *conn,
  6902. char *buf,
  6903. int bufsiz,
  6904. int *nread)
  6905. {
  6906. int request_len, n = 0;
  6907. struct timespec last_action_time;
  6908. double request_timeout;
  6909. if (!conn) {
  6910. return 0;
  6911. }
  6912. memset(&last_action_time, 0, sizeof(last_action_time));
  6913. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6914. /* value of request_timeout is in seconds, config in milliseconds */
  6915. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6916. } else {
  6917. request_timeout = -1.0;
  6918. }
  6919. if (conn->handled_requests > 0) {
  6920. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  6921. request_timeout =
  6922. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  6923. }
  6924. }
  6925. request_len = get_request_len(buf, *nread);
  6926. /* first time reading from this connection */
  6927. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6928. while (request_len == 0) {
  6929. /* Full request not yet received */
  6930. if (conn->ctx->stop_flag != 0) {
  6931. /* Server is to be stopped. */
  6932. return -1;
  6933. }
  6934. if (*nread >= bufsiz) {
  6935. /* Request too long */
  6936. return -2;
  6937. }
  6938. n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6939. if (n < 0) {
  6940. /* Receive error */
  6941. return -1;
  6942. }
  6943. *nread += n;
  6944. request_len = get_request_len(buf, *nread);
  6945. if ((request_len == 0) && (request_timeout >= 0)) {
  6946. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  6947. > request_timeout) {
  6948. /* Timeout */
  6949. return -1;
  6950. }
  6951. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6952. }
  6953. }
  6954. return request_len;
  6955. }
  6956. #if !defined(NO_FILES)
  6957. /* For given directory path, substitute it to valid index file.
  6958. * Return 1 if index file has been found, 0 if not found.
  6959. * If the file is found, it's stats is returned in stp. */
  6960. static int
  6961. substitute_index_file(struct mg_connection *conn,
  6962. char *path,
  6963. size_t path_len,
  6964. struct mg_file *filep)
  6965. {
  6966. if (conn && conn->ctx) {
  6967. const char *list = conn->ctx->config[INDEX_FILES];
  6968. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6969. struct vec filename_vec;
  6970. size_t n = strlen(path);
  6971. int found = 0;
  6972. /* The 'path' given to us points to the directory. Remove all trailing
  6973. * directory separator characters from the end of the path, and
  6974. * then append single directory separator character. */
  6975. while (n > 0 && path[n - 1] == '/') {
  6976. n--;
  6977. }
  6978. path[n] = '/';
  6979. /* Traverse index files list. For each entry, append it to the given
  6980. * path and see if the file exists. If it exists, break the loop */
  6981. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6982. /* Ignore too long entries that may overflow path buffer */
  6983. if (filename_vec.len > path_len - (n + 2)) {
  6984. continue;
  6985. }
  6986. /* Prepare full path to the index file */
  6987. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6988. /* Does it exist? */
  6989. if (mg_stat(conn, path, &file.stat)) {
  6990. /* Yes it does, break the loop */
  6991. *filep = file;
  6992. found = 1;
  6993. break;
  6994. }
  6995. }
  6996. /* If no index file exists, restore directory path */
  6997. if (!found) {
  6998. path[n] = '\0';
  6999. }
  7000. return found;
  7001. }
  7002. return 0;
  7003. }
  7004. #endif
  7005. #if !defined(NO_CACHING)
  7006. /* Return True if we should reply 304 Not Modified. */
  7007. static int
  7008. is_not_modified(const struct mg_connection *conn,
  7009. const struct mg_file_stat *filestat)
  7010. {
  7011. char etag[64];
  7012. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7013. const char *inm = mg_get_header(conn, "If-None-Match");
  7014. construct_etag(etag, sizeof(etag), filestat);
  7015. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7016. || ((ims != NULL)
  7017. && (filestat->last_modified <= parse_date_string(ims)));
  7018. }
  7019. #endif /* !NO_CACHING */
  7020. #if !defined(NO_CGI) || !defined(NO_FILES)
  7021. static int
  7022. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7023. {
  7024. const char *expect, *body;
  7025. char buf[MG_BUF_LEN];
  7026. int to_read, nread, success = 0;
  7027. int64_t buffered_len;
  7028. double timeout = -1.0;
  7029. if (!conn) {
  7030. return 0;
  7031. }
  7032. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7033. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7034. }
  7035. expect = mg_get_header(conn, "Expect");
  7036. /* assert(fp != NULL); */
  7037. if (!fp) {
  7038. send_http_error(conn, 500, "%s", "Error: NULL File");
  7039. return 0;
  7040. }
  7041. if (conn->content_len == -1 && !conn->is_chunked) {
  7042. /* Content length is not specified by the client. */
  7043. send_http_error(conn,
  7044. 411,
  7045. "%s",
  7046. "Error: Client did not specify content length");
  7047. } else if ((expect != NULL)
  7048. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7049. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7050. send_http_error(conn,
  7051. 417,
  7052. "Error: Can not fulfill expectation %s",
  7053. expect);
  7054. } else {
  7055. if (expect != NULL) {
  7056. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7057. conn->status_code = 100;
  7058. } else {
  7059. conn->status_code = 200;
  7060. }
  7061. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7062. - conn->consumed_content;
  7063. /* assert(buffered_len >= 0); */
  7064. /* assert(conn->consumed_content == 0); */
  7065. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7066. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7067. return 0;
  7068. }
  7069. if (buffered_len > 0) {
  7070. if ((int64_t)buffered_len > conn->content_len) {
  7071. buffered_len = (int)conn->content_len;
  7072. }
  7073. body = conn->buf + conn->request_len + conn->consumed_content;
  7074. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7075. conn->consumed_content += buffered_len;
  7076. }
  7077. nread = 0;
  7078. while (conn->consumed_content < conn->content_len) {
  7079. to_read = sizeof(buf);
  7080. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7081. to_read = (int)(conn->content_len - conn->consumed_content);
  7082. }
  7083. nread = pull(NULL, conn, buf, to_read, timeout);
  7084. if (nread <= 0
  7085. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7086. break;
  7087. }
  7088. conn->consumed_content += nread;
  7089. }
  7090. if (conn->consumed_content == conn->content_len) {
  7091. success = (nread >= 0);
  7092. }
  7093. /* Each error code path in this function must send an error */
  7094. if (!success) {
  7095. /* NOTE: Maybe some data has already been sent. */
  7096. /* TODO (low): If some data has been sent, a correct error
  7097. * reply can no longer be sent, so just close the connection */
  7098. send_http_error(conn, 500, "%s", "");
  7099. }
  7100. }
  7101. return success;
  7102. }
  7103. #endif
  7104. #if !defined(NO_CGI)
  7105. /* This structure helps to create an environment for the spawned CGI program.
  7106. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7107. * last element must be NULL.
  7108. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7109. * strings must reside in a contiguous buffer. The end of the buffer is
  7110. * marked by two '\0' characters.
  7111. * We satisfy both worlds: we create an envp array (which is vars), all
  7112. * entries are actually pointers inside buf. */
  7113. struct cgi_environment {
  7114. struct mg_connection *conn;
  7115. /* Data block */
  7116. char *buf; /* Environment buffer */
  7117. size_t buflen; /* Space available in buf */
  7118. size_t bufused; /* Space taken in buf */
  7119. /* Index block */
  7120. char **var; /* char **envp */
  7121. size_t varlen; /* Number of variables available in var */
  7122. size_t varused; /* Number of variables stored in var */
  7123. };
  7124. static void addenv(struct cgi_environment *env,
  7125. PRINTF_FORMAT_STRING(const char *fmt),
  7126. ...) PRINTF_ARGS(2, 3);
  7127. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7128. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7129. static void
  7130. addenv(struct cgi_environment *env, const char *fmt, ...)
  7131. {
  7132. size_t n, space;
  7133. int truncated = 0;
  7134. char *added;
  7135. va_list ap;
  7136. /* Calculate how much space is left in the buffer */
  7137. space = (env->buflen - env->bufused);
  7138. /* Calculate an estimate for the required space */
  7139. n = strlen(fmt) + 2 + 128;
  7140. do {
  7141. if (space <= n) {
  7142. /* Allocate new buffer */
  7143. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7144. added = (char *)mg_realloc(env->buf, n);
  7145. if (!added) {
  7146. /* Out of memory */
  7147. mg_cry(env->conn,
  7148. "%s: Cannot allocate memory for CGI variable [%s]",
  7149. __func__,
  7150. fmt);
  7151. return;
  7152. }
  7153. env->buf = added;
  7154. env->buflen = n;
  7155. space = (env->buflen - env->bufused);
  7156. }
  7157. /* Make a pointer to the free space int the buffer */
  7158. added = env->buf + env->bufused;
  7159. /* Copy VARIABLE=VALUE\0 string into the free space */
  7160. va_start(ap, fmt);
  7161. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7162. va_end(ap);
  7163. /* Do not add truncated strings to the environment */
  7164. if (truncated) {
  7165. /* Reallocate the buffer */
  7166. space = 0;
  7167. n = 1;
  7168. }
  7169. } while (truncated);
  7170. /* Calculate number of bytes added to the environment */
  7171. n = strlen(added) + 1;
  7172. env->bufused += n;
  7173. /* Now update the variable index */
  7174. space = (env->varlen - env->varused);
  7175. if (space < 2) {
  7176. mg_cry(env->conn,
  7177. "%s: Cannot register CGI variable [%s]",
  7178. __func__,
  7179. fmt);
  7180. return;
  7181. }
  7182. /* Append a pointer to the added string into the envp array */
  7183. env->var[env->varused] = added;
  7184. env->varused++;
  7185. }
  7186. static void
  7187. prepare_cgi_environment(struct mg_connection *conn,
  7188. const char *prog,
  7189. struct cgi_environment *env)
  7190. {
  7191. const char *s;
  7192. struct vec var_vec;
  7193. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7194. int i, truncated, uri_len;
  7195. if (conn == NULL || prog == NULL || env == NULL) {
  7196. return;
  7197. }
  7198. env->conn = conn;
  7199. env->buflen = CGI_ENVIRONMENT_SIZE;
  7200. env->bufused = 0;
  7201. env->buf = (char *)mg_malloc(env->buflen);
  7202. env->varlen = MAX_CGI_ENVIR_VARS;
  7203. env->varused = 0;
  7204. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7205. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7206. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7207. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7208. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7209. /* Prepare the environment block */
  7210. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7211. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7212. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7213. #if defined(USE_IPV6)
  7214. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7215. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7216. } else
  7217. #endif
  7218. {
  7219. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7220. }
  7221. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7222. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7223. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7224. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7225. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7226. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7227. /* SCRIPT_NAME */
  7228. uri_len = (int)strlen(conn->request_info.local_uri);
  7229. if (conn->path_info == NULL) {
  7230. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7231. /* URI: /path_to_script/script.cgi */
  7232. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7233. } else {
  7234. /* URI: /path_to_script/ ... using index.cgi */
  7235. char *index_file = strrchr(prog, '/');
  7236. if (index_file) {
  7237. addenv(env,
  7238. "SCRIPT_NAME=%s%s",
  7239. conn->request_info.local_uri,
  7240. index_file + 1);
  7241. }
  7242. }
  7243. } else {
  7244. /* URI: /path_to_script/script.cgi/path_info */
  7245. addenv(env,
  7246. "SCRIPT_NAME=%.*s",
  7247. uri_len - (int)strlen(conn->path_info),
  7248. conn->request_info.local_uri);
  7249. }
  7250. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7251. if (conn->path_info == NULL) {
  7252. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7253. } else {
  7254. addenv(env,
  7255. "PATH_TRANSLATED=%s%s",
  7256. conn->ctx->config[DOCUMENT_ROOT],
  7257. conn->path_info);
  7258. }
  7259. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7260. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7261. addenv(env, "CONTENT_TYPE=%s", s);
  7262. }
  7263. if (conn->request_info.query_string != NULL) {
  7264. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7265. }
  7266. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7267. addenv(env, "CONTENT_LENGTH=%s", s);
  7268. }
  7269. if ((s = getenv("PATH")) != NULL) {
  7270. addenv(env, "PATH=%s", s);
  7271. }
  7272. if (conn->path_info != NULL) {
  7273. addenv(env, "PATH_INFO=%s", conn->path_info);
  7274. }
  7275. if (conn->status_code > 0) {
  7276. /* CGI error handler should show the status code */
  7277. addenv(env, "STATUS=%d", conn->status_code);
  7278. }
  7279. #if defined(_WIN32)
  7280. if ((s = getenv("COMSPEC")) != NULL) {
  7281. addenv(env, "COMSPEC=%s", s);
  7282. }
  7283. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7284. addenv(env, "SYSTEMROOT=%s", s);
  7285. }
  7286. if ((s = getenv("SystemDrive")) != NULL) {
  7287. addenv(env, "SystemDrive=%s", s);
  7288. }
  7289. if ((s = getenv("ProgramFiles")) != NULL) {
  7290. addenv(env, "ProgramFiles=%s", s);
  7291. }
  7292. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7293. addenv(env, "ProgramFiles(x86)=%s", s);
  7294. }
  7295. #else
  7296. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7297. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7298. }
  7299. #endif /* _WIN32 */
  7300. if ((s = getenv("PERLLIB")) != NULL) {
  7301. addenv(env, "PERLLIB=%s", s);
  7302. }
  7303. if (conn->request_info.remote_user != NULL) {
  7304. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7305. addenv(env, "%s", "AUTH_TYPE=Digest");
  7306. }
  7307. /* Add all headers as HTTP_* variables */
  7308. for (i = 0; i < conn->request_info.num_headers; i++) {
  7309. (void)mg_snprintf(conn,
  7310. &truncated,
  7311. http_var_name,
  7312. sizeof(http_var_name),
  7313. "HTTP_%s",
  7314. conn->request_info.http_headers[i].name);
  7315. if (truncated) {
  7316. mg_cry(conn,
  7317. "%s: HTTP header variable too long [%s]",
  7318. __func__,
  7319. conn->request_info.http_headers[i].name);
  7320. continue;
  7321. }
  7322. /* Convert variable name into uppercase, and change - to _ */
  7323. for (p = http_var_name; *p != '\0'; p++) {
  7324. if (*p == '-') {
  7325. *p = '_';
  7326. }
  7327. *p = (char)toupper(*(unsigned char *)p);
  7328. }
  7329. addenv(env,
  7330. "%s=%s",
  7331. http_var_name,
  7332. conn->request_info.http_headers[i].value);
  7333. }
  7334. /* Add user-specified variables */
  7335. s = conn->ctx->config[CGI_ENVIRONMENT];
  7336. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7337. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7338. }
  7339. env->var[env->varused] = NULL;
  7340. env->buf[env->bufused] = '\0';
  7341. }
  7342. static void
  7343. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7344. {
  7345. char *buf;
  7346. size_t buflen;
  7347. int headers_len, data_len, i, truncated;
  7348. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7349. const char *status, *status_text, *connection_state;
  7350. char *pbuf, dir[PATH_MAX], *p;
  7351. struct mg_request_info ri;
  7352. struct cgi_environment blk;
  7353. FILE *in = NULL, *out = NULL, *err = NULL;
  7354. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7355. pid_t pid = (pid_t)-1;
  7356. if (conn == NULL) {
  7357. return;
  7358. }
  7359. buf = NULL;
  7360. buflen = 16384;
  7361. prepare_cgi_environment(conn, prog, &blk);
  7362. /* CGI must be executed in its own directory. 'dir' must point to the
  7363. * directory containing executable program, 'p' must point to the
  7364. * executable program name relative to 'dir'. */
  7365. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7366. if (truncated) {
  7367. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7368. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7369. goto done;
  7370. }
  7371. if ((p = strrchr(dir, '/')) != NULL) {
  7372. *p++ = '\0';
  7373. } else {
  7374. dir[0] = '.', dir[1] = '\0';
  7375. p = (char *)prog;
  7376. }
  7377. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7378. status = strerror(ERRNO);
  7379. mg_cry(conn,
  7380. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7381. prog,
  7382. status);
  7383. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7384. goto done;
  7385. }
  7386. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7387. if (pid == (pid_t)-1) {
  7388. status = strerror(ERRNO);
  7389. mg_cry(conn,
  7390. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7391. prog,
  7392. status);
  7393. send_http_error(conn,
  7394. 500,
  7395. "Error: Cannot spawn CGI process [%s]: %s",
  7396. prog,
  7397. status);
  7398. goto done;
  7399. }
  7400. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7401. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7402. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7403. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7404. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7405. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7406. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7407. /* Parent closes only one side of the pipes.
  7408. * If we don't mark them as closed, close() attempt before
  7409. * return from this function throws an exception on Windows.
  7410. * Windows does not like when closed descriptor is closed again. */
  7411. (void)close(fdin[0]);
  7412. (void)close(fdout[1]);
  7413. (void)close(fderr[1]);
  7414. fdin[0] = fdout[1] = fderr[1] = -1;
  7415. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7416. status = strerror(ERRNO);
  7417. mg_cry(conn,
  7418. "Error: CGI program \"%s\": Can not open stdin: %s",
  7419. prog,
  7420. status);
  7421. send_http_error(conn,
  7422. 500,
  7423. "Error: CGI can not open fdin\nfopen: %s",
  7424. status);
  7425. goto done;
  7426. }
  7427. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7428. status = strerror(ERRNO);
  7429. mg_cry(conn,
  7430. "Error: CGI program \"%s\": Can not open stdout: %s",
  7431. prog,
  7432. status);
  7433. send_http_error(conn,
  7434. 500,
  7435. "Error: CGI can not open fdout\nfopen: %s",
  7436. status);
  7437. goto done;
  7438. }
  7439. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7440. status = strerror(ERRNO);
  7441. mg_cry(conn,
  7442. "Error: CGI program \"%s\": Can not open stderr: %s",
  7443. prog,
  7444. status);
  7445. send_http_error(conn,
  7446. 500,
  7447. "Error: CGI can not open fdout\nfopen: %s",
  7448. status);
  7449. goto done;
  7450. }
  7451. setbuf(in, NULL);
  7452. setbuf(out, NULL);
  7453. setbuf(err, NULL);
  7454. fout.access.fp = out;
  7455. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7456. /* This is a POST/PUT request, or another request with body data. */
  7457. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7458. /* Error sending the body data */
  7459. mg_cry(conn,
  7460. "Error: CGI program \"%s\": Forward body data failed",
  7461. prog);
  7462. goto done;
  7463. }
  7464. }
  7465. /* Close so child gets an EOF. */
  7466. fclose(in);
  7467. in = NULL;
  7468. fdin[1] = -1;
  7469. /* Now read CGI reply into a buffer. We need to set correct
  7470. * status code, thus we need to see all HTTP headers first.
  7471. * Do not send anything back to client, until we buffer in all
  7472. * HTTP headers. */
  7473. data_len = 0;
  7474. buf = (char *)mg_malloc(buflen);
  7475. if (buf == NULL) {
  7476. send_http_error(conn,
  7477. 500,
  7478. "Error: Not enough memory for CGI buffer (%u bytes)",
  7479. (unsigned int)buflen);
  7480. mg_cry(conn,
  7481. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7482. "bytes)",
  7483. prog,
  7484. (unsigned int)buflen);
  7485. goto done;
  7486. }
  7487. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7488. if (headers_len <= 0) {
  7489. /* Could not parse the CGI response. Check if some error message on
  7490. * stderr. */
  7491. i = pull_all(err, conn, buf, (int)buflen);
  7492. if (i > 0) {
  7493. mg_cry(conn,
  7494. "Error: CGI program \"%s\" sent error "
  7495. "message: [%.*s]",
  7496. prog,
  7497. i,
  7498. buf);
  7499. send_http_error(conn,
  7500. 500,
  7501. "Error: CGI program \"%s\" sent error "
  7502. "message: [%.*s]",
  7503. prog,
  7504. i,
  7505. buf);
  7506. } else {
  7507. mg_cry(conn,
  7508. "Error: CGI program sent malformed or too big "
  7509. "(>%u bytes) HTTP headers: [%.*s]",
  7510. (unsigned)buflen,
  7511. data_len,
  7512. buf);
  7513. send_http_error(conn,
  7514. 500,
  7515. "Error: CGI program sent malformed or too big "
  7516. "(>%u bytes) HTTP headers: [%.*s]",
  7517. (unsigned)buflen,
  7518. data_len,
  7519. buf);
  7520. }
  7521. goto done;
  7522. }
  7523. pbuf = buf;
  7524. buf[headers_len - 1] = '\0';
  7525. parse_http_headers(&pbuf, &ri);
  7526. /* Make up and send the status line */
  7527. status_text = "OK";
  7528. if ((status = get_header(&ri, "Status")) != NULL) {
  7529. conn->status_code = atoi(status);
  7530. status_text = status;
  7531. while (isdigit(*(const unsigned char *)status_text)
  7532. || *status_text == ' ') {
  7533. status_text++;
  7534. }
  7535. } else if (get_header(&ri, "Location") != NULL) {
  7536. conn->status_code = 302;
  7537. } else {
  7538. conn->status_code = 200;
  7539. }
  7540. connection_state = get_header(&ri, "Connection");
  7541. if (!header_has_option(connection_state, "keep-alive")) {
  7542. conn->must_close = 1;
  7543. }
  7544. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7545. /* Send headers */
  7546. for (i = 0; i < ri.num_headers; i++) {
  7547. mg_printf(conn,
  7548. "%s: %s\r\n",
  7549. ri.http_headers[i].name,
  7550. ri.http_headers[i].value);
  7551. }
  7552. mg_write(conn, "\r\n", 2);
  7553. /* Send chunk of data that may have been read after the headers */
  7554. conn->num_bytes_sent +=
  7555. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7556. /* Read the rest of CGI output and send to the client */
  7557. send_file_data(conn, &fout, 0, INT64_MAX);
  7558. done:
  7559. mg_free(blk.var);
  7560. mg_free(blk.buf);
  7561. if (pid != (pid_t)-1) {
  7562. kill(pid, SIGKILL);
  7563. #if !defined(_WIN32)
  7564. {
  7565. int st;
  7566. while (waitpid(pid, &st, 0) != -1)
  7567. ; /* clean zombies */
  7568. }
  7569. #endif
  7570. }
  7571. if (fdin[0] != -1) {
  7572. close(fdin[0]);
  7573. }
  7574. if (fdout[1] != -1) {
  7575. close(fdout[1]);
  7576. }
  7577. if (in != NULL) {
  7578. fclose(in);
  7579. } else if (fdin[1] != -1) {
  7580. close(fdin[1]);
  7581. }
  7582. if (out != NULL) {
  7583. fclose(out);
  7584. } else if (fdout[0] != -1) {
  7585. close(fdout[0]);
  7586. }
  7587. if (err != NULL) {
  7588. fclose(err);
  7589. } else if (fderr[0] != -1) {
  7590. close(fderr[0]);
  7591. }
  7592. if (buf != NULL) {
  7593. mg_free(buf);
  7594. }
  7595. }
  7596. #endif /* !NO_CGI */
  7597. #if !defined(NO_FILES)
  7598. static void
  7599. mkcol(struct mg_connection *conn, const char *path)
  7600. {
  7601. int rc, body_len;
  7602. struct de de;
  7603. char date[64];
  7604. time_t curtime = time(NULL);
  7605. if (conn == NULL) {
  7606. return;
  7607. }
  7608. /* TODO (mid): Check the send_http_error situations in this function */
  7609. memset(&de.file, 0, sizeof(de.file));
  7610. if (!mg_stat(conn, path, &de.file)) {
  7611. mg_cry(conn,
  7612. "%s: mg_stat(%s) failed: %s",
  7613. __func__,
  7614. path,
  7615. strerror(ERRNO));
  7616. }
  7617. if (de.file.last_modified) {
  7618. /* TODO (mid): This check does not seem to make any sense ! */
  7619. /* TODO (mid): Add a webdav unit test first, before changing
  7620. * anything here. */
  7621. send_http_error(
  7622. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7623. return;
  7624. }
  7625. body_len = conn->data_len - conn->request_len;
  7626. if (body_len > 0) {
  7627. send_http_error(
  7628. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7629. return;
  7630. }
  7631. rc = mg_mkdir(conn, path, 0755);
  7632. if (rc == 0) {
  7633. conn->status_code = 201;
  7634. gmt_time_string(date, sizeof(date), &curtime);
  7635. mg_printf(conn,
  7636. "HTTP/1.1 %d Created\r\n"
  7637. "Date: %s\r\n",
  7638. conn->status_code,
  7639. date);
  7640. send_static_cache_header(conn);
  7641. mg_printf(conn,
  7642. "Content-Length: 0\r\n"
  7643. "Connection: %s\r\n\r\n",
  7644. suggest_connection_header(conn));
  7645. } else if (rc == -1) {
  7646. if (errno == EEXIST) {
  7647. send_http_error(
  7648. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7649. } else if (errno == EACCES) {
  7650. send_http_error(
  7651. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7652. } else if (errno == ENOENT) {
  7653. send_http_error(
  7654. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7655. } else {
  7656. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7657. }
  7658. }
  7659. }
  7660. static void
  7661. put_file(struct mg_connection *conn, const char *path)
  7662. {
  7663. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7664. const char *range;
  7665. int64_t r1, r2;
  7666. int rc;
  7667. char date[64];
  7668. time_t curtime = time(NULL);
  7669. if (conn == NULL) {
  7670. return;
  7671. }
  7672. if (mg_stat(conn, path, &file.stat)) {
  7673. /* File already exists */
  7674. conn->status_code = 200;
  7675. if (file.stat.is_directory) {
  7676. /* This is an already existing directory,
  7677. * so there is nothing to do for the server. */
  7678. rc = 0;
  7679. } else {
  7680. /* File exists and is not a directory. */
  7681. /* Can it be replaced? */
  7682. if (file.access.membuf != NULL) {
  7683. /* This is an "in-memory" file, that can not be replaced */
  7684. send_http_error(
  7685. conn,
  7686. 405,
  7687. "Error: Put not possible\nReplacing %s is not supported",
  7688. path);
  7689. return;
  7690. }
  7691. /* Check if the server may write this file */
  7692. if (access(path, W_OK) == 0) {
  7693. /* Access granted */
  7694. conn->status_code = 200;
  7695. rc = 1;
  7696. } else {
  7697. send_http_error(
  7698. conn,
  7699. 403,
  7700. "Error: Put not possible\nReplacing %s is not allowed",
  7701. path);
  7702. return;
  7703. }
  7704. }
  7705. } else {
  7706. /* File should be created */
  7707. conn->status_code = 201;
  7708. rc = put_dir(conn, path);
  7709. }
  7710. if (rc == 0) {
  7711. /* put_dir returns 0 if path is a directory */
  7712. gmt_time_string(date, sizeof(date), &curtime);
  7713. mg_printf(conn,
  7714. "HTTP/1.1 %d %s\r\n",
  7715. conn->status_code,
  7716. mg_get_response_code_text(NULL, conn->status_code));
  7717. send_no_cache_header(conn);
  7718. mg_printf(conn,
  7719. "Date: %s\r\n"
  7720. "Content-Length: 0\r\n"
  7721. "Connection: %s\r\n\r\n",
  7722. date,
  7723. suggest_connection_header(conn));
  7724. /* Request to create a directory has been fulfilled successfully.
  7725. * No need to put a file. */
  7726. return;
  7727. }
  7728. if (rc == -1) {
  7729. /* put_dir returns -1 if the path is too long */
  7730. send_http_error(conn,
  7731. 414,
  7732. "Error: Path too long\nput_dir(%s): %s",
  7733. path,
  7734. strerror(ERRNO));
  7735. return;
  7736. }
  7737. if (rc == -2) {
  7738. /* put_dir returns -2 if the directory can not be created */
  7739. send_http_error(conn,
  7740. 500,
  7741. "Error: Can not create directory\nput_dir(%s): %s",
  7742. path,
  7743. strerror(ERRNO));
  7744. return;
  7745. }
  7746. /* A file should be created or overwritten. */
  7747. /* Currently CivetWeb does not nead read+write access. */
  7748. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7749. || file.access.fp == NULL) {
  7750. (void)mg_fclose(&file.access);
  7751. send_http_error(conn,
  7752. 500,
  7753. "Error: Can not create file\nfopen(%s): %s",
  7754. path,
  7755. strerror(ERRNO));
  7756. return;
  7757. }
  7758. fclose_on_exec(&file.access, conn);
  7759. range = mg_get_header(conn, "Content-Range");
  7760. r1 = r2 = 0;
  7761. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7762. conn->status_code = 206; /* Partial content */
  7763. fseeko(file.access.fp, r1, SEEK_SET);
  7764. }
  7765. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7766. /* forward_body_data failed.
  7767. * The error code has already been sent to the client,
  7768. * and conn->status_code is already set. */
  7769. (void)mg_fclose(&file.access);
  7770. return;
  7771. }
  7772. if (mg_fclose(&file.access) != 0) {
  7773. /* fclose failed. This might have different reasons, but a likely
  7774. * one is "no space on disk", http 507. */
  7775. conn->status_code = 507;
  7776. }
  7777. gmt_time_string(date, sizeof(date), &curtime);
  7778. mg_printf(conn,
  7779. "HTTP/1.1 %d %s\r\n",
  7780. conn->status_code,
  7781. mg_get_response_code_text(NULL, conn->status_code));
  7782. send_no_cache_header(conn);
  7783. mg_printf(conn,
  7784. "Date: %s\r\n"
  7785. "Content-Length: 0\r\n"
  7786. "Connection: %s\r\n\r\n",
  7787. date,
  7788. suggest_connection_header(conn));
  7789. }
  7790. static void
  7791. delete_file(struct mg_connection *conn, const char *path)
  7792. {
  7793. struct de de;
  7794. memset(&de.file, 0, sizeof(de.file));
  7795. if (!mg_stat(conn, path, &de.file)) {
  7796. /* mg_stat returns 0 if the file does not exist */
  7797. send_http_error(conn,
  7798. 404,
  7799. "Error: Cannot delete file\nFile %s not found",
  7800. path);
  7801. return;
  7802. }
  7803. #if 0 /* Ignore if a file in memory is inside a folder */
  7804. if (de.access.membuf != NULL) {
  7805. /* the file is cached in memory */
  7806. send_http_error(
  7807. conn,
  7808. 405,
  7809. "Error: Delete not possible\nDeleting %s is not supported",
  7810. path);
  7811. return;
  7812. }
  7813. #endif
  7814. if (de.file.is_directory) {
  7815. if (remove_directory(conn, path)) {
  7816. /* Delete is successful: Return 204 without content. */
  7817. send_http_error(conn, 204, "%s", "");
  7818. } else {
  7819. /* Delete is not successful: Return 500 (Server error). */
  7820. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7821. }
  7822. return;
  7823. }
  7824. /* This is an existing file (not a directory).
  7825. * Check if write permission is granted. */
  7826. if (access(path, W_OK) != 0) {
  7827. /* File is read only */
  7828. send_http_error(
  7829. conn,
  7830. 403,
  7831. "Error: Delete not possible\nDeleting %s is not allowed",
  7832. path);
  7833. return;
  7834. }
  7835. /* Try to delete it. */
  7836. if (mg_remove(conn, path) == 0) {
  7837. /* Delete was successful: Return 204 without content. */
  7838. send_http_error(conn, 204, "%s", "");
  7839. } else {
  7840. /* Delete not successful (file locked). */
  7841. send_http_error(conn,
  7842. 423,
  7843. "Error: Cannot delete file\nremove(%s): %s",
  7844. path,
  7845. strerror(ERRNO));
  7846. }
  7847. }
  7848. #endif /* !NO_FILES */
  7849. static void
  7850. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7851. static void
  7852. do_ssi_include(struct mg_connection *conn,
  7853. const char *ssi,
  7854. char *tag,
  7855. int include_level)
  7856. {
  7857. char file_name[MG_BUF_LEN], path[512], *p;
  7858. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7859. size_t len;
  7860. int truncated = 0;
  7861. if (conn == NULL) {
  7862. return;
  7863. }
  7864. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7865. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7866. * always < MG_BUF_LEN. */
  7867. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7868. /* File name is relative to the webserver root */
  7869. file_name[511] = 0;
  7870. (void)mg_snprintf(conn,
  7871. &truncated,
  7872. path,
  7873. sizeof(path),
  7874. "%s/%s",
  7875. conn->ctx->config[DOCUMENT_ROOT],
  7876. file_name);
  7877. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7878. /* File name is relative to the webserver working directory
  7879. * or it is absolute system path */
  7880. file_name[511] = 0;
  7881. (void)
  7882. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7883. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7884. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7885. /* File name is relative to the currect document */
  7886. file_name[511] = 0;
  7887. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7888. if (!truncated) {
  7889. if ((p = strrchr(path, '/')) != NULL) {
  7890. p[1] = '\0';
  7891. }
  7892. len = strlen(path);
  7893. (void)mg_snprintf(conn,
  7894. &truncated,
  7895. path + len,
  7896. sizeof(path) - len,
  7897. "%s",
  7898. file_name);
  7899. }
  7900. } else {
  7901. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7902. return;
  7903. }
  7904. if (truncated) {
  7905. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7906. return;
  7907. }
  7908. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7909. mg_cry(conn,
  7910. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7911. tag,
  7912. path,
  7913. strerror(ERRNO));
  7914. } else {
  7915. fclose_on_exec(&file.access, conn);
  7916. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7917. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7918. path) > 0) {
  7919. send_ssi_file(conn, path, &file, include_level + 1);
  7920. } else {
  7921. send_file_data(conn, &file, 0, INT64_MAX);
  7922. }
  7923. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7924. }
  7925. }
  7926. #if !defined(NO_POPEN)
  7927. static void
  7928. do_ssi_exec(struct mg_connection *conn, char *tag)
  7929. {
  7930. char cmd[1024] = "";
  7931. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7932. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7933. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7934. } else {
  7935. cmd[1023] = 0;
  7936. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  7937. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7938. } else {
  7939. send_file_data(conn, &file, 0, INT64_MAX);
  7940. pclose(file.access.fp);
  7941. }
  7942. }
  7943. }
  7944. #endif /* !NO_POPEN */
  7945. static int
  7946. mg_fgetc(struct mg_file *filep, int offset)
  7947. {
  7948. if (filep == NULL) {
  7949. return EOF;
  7950. }
  7951. if (filep->access.membuf != NULL && offset >= 0
  7952. && ((unsigned int)(offset)) < filep->stat.size) {
  7953. return ((const unsigned char *)filep->access.membuf)[offset];
  7954. } else if (filep->access.fp != NULL) {
  7955. return fgetc(filep->access.fp);
  7956. } else {
  7957. return EOF;
  7958. }
  7959. }
  7960. static void
  7961. send_ssi_file(struct mg_connection *conn,
  7962. const char *path,
  7963. struct mg_file *filep,
  7964. int include_level)
  7965. {
  7966. char buf[MG_BUF_LEN];
  7967. int ch, offset, len, in_ssi_tag;
  7968. if (include_level > 10) {
  7969. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7970. return;
  7971. }
  7972. in_ssi_tag = len = offset = 0;
  7973. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7974. if (in_ssi_tag && ch == '>') {
  7975. in_ssi_tag = 0;
  7976. buf[len++] = (char)ch;
  7977. buf[len] = '\0';
  7978. /* assert(len <= (int) sizeof(buf)); */
  7979. if (len > (int)sizeof(buf)) {
  7980. break;
  7981. }
  7982. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7983. /* Not an SSI tag, pass it */
  7984. (void)mg_write(conn, buf, (size_t)len);
  7985. } else {
  7986. if (!memcmp(buf + 5, "include", 7)) {
  7987. do_ssi_include(conn, path, buf + 12, include_level);
  7988. #if !defined(NO_POPEN)
  7989. } else if (!memcmp(buf + 5, "exec", 4)) {
  7990. do_ssi_exec(conn, buf + 9);
  7991. #endif /* !NO_POPEN */
  7992. } else {
  7993. mg_cry(conn,
  7994. "%s: unknown SSI "
  7995. "command: \"%s\"",
  7996. path,
  7997. buf);
  7998. }
  7999. }
  8000. len = 0;
  8001. } else if (in_ssi_tag) {
  8002. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8003. /* Not an SSI tag */
  8004. in_ssi_tag = 0;
  8005. } else if (len == (int)sizeof(buf) - 2) {
  8006. mg_cry(conn, "%s: SSI tag is too large", path);
  8007. len = 0;
  8008. }
  8009. buf[len++] = (char)(ch & 0xff);
  8010. } else if (ch == '<') {
  8011. in_ssi_tag = 1;
  8012. if (len > 0) {
  8013. mg_write(conn, buf, (size_t)len);
  8014. }
  8015. len = 0;
  8016. buf[len++] = (char)(ch & 0xff);
  8017. } else {
  8018. buf[len++] = (char)(ch & 0xff);
  8019. if (len == (int)sizeof(buf)) {
  8020. mg_write(conn, buf, (size_t)len);
  8021. len = 0;
  8022. }
  8023. }
  8024. }
  8025. /* Send the rest of buffered data */
  8026. if (len > 0) {
  8027. mg_write(conn, buf, (size_t)len);
  8028. }
  8029. }
  8030. static void
  8031. handle_ssi_file_request(struct mg_connection *conn,
  8032. const char *path,
  8033. struct mg_file *filep)
  8034. {
  8035. char date[64];
  8036. time_t curtime = time(NULL);
  8037. const char *cors1, *cors2, *cors3;
  8038. if (conn == NULL || path == NULL || filep == NULL) {
  8039. return;
  8040. }
  8041. if (mg_get_header(conn, "Origin")) {
  8042. /* Cross-origin resource sharing (CORS). */
  8043. cors1 = "Access-Control-Allow-Origin: ";
  8044. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8045. cors3 = "\r\n";
  8046. } else {
  8047. cors1 = cors2 = cors3 = "";
  8048. }
  8049. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8050. /* File exists (precondition for calling this function),
  8051. * but can not be opened by the server. */
  8052. send_http_error(conn,
  8053. 500,
  8054. "Error: Cannot read file\nfopen(%s): %s",
  8055. path,
  8056. strerror(ERRNO));
  8057. } else {
  8058. conn->must_close = 1;
  8059. gmt_time_string(date, sizeof(date), &curtime);
  8060. fclose_on_exec(&filep->access, conn);
  8061. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8062. send_no_cache_header(conn);
  8063. mg_printf(conn,
  8064. "%s%s%s"
  8065. "Date: %s\r\n"
  8066. "Content-Type: text/html\r\n"
  8067. "Connection: %s\r\n\r\n",
  8068. cors1,
  8069. cors2,
  8070. cors3,
  8071. date,
  8072. suggest_connection_header(conn));
  8073. send_ssi_file(conn, path, filep, 0);
  8074. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8075. }
  8076. }
  8077. #if !defined(NO_FILES)
  8078. static void
  8079. send_options(struct mg_connection *conn)
  8080. {
  8081. char date[64];
  8082. time_t curtime = time(NULL);
  8083. if (!conn) {
  8084. return;
  8085. }
  8086. conn->status_code = 200;
  8087. conn->must_close = 1;
  8088. gmt_time_string(date, sizeof(date), &curtime);
  8089. /* We do not set a "Cache-Control" header here, but leave the default.
  8090. * Since browsers do not send an OPTIONS request, we can not test the
  8091. * effect anyway. */
  8092. mg_printf(conn,
  8093. "HTTP/1.1 200 OK\r\n"
  8094. "Date: %s\r\n"
  8095. "Connection: %s\r\n"
  8096. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8097. "PROPFIND, MKCOL\r\n"
  8098. "DAV: 1\r\n\r\n",
  8099. date,
  8100. suggest_connection_header(conn));
  8101. }
  8102. /* Writes PROPFIND properties for a collection element */
  8103. static void
  8104. print_props(struct mg_connection *conn,
  8105. const char *uri,
  8106. struct mg_file_stat *filep)
  8107. {
  8108. char mtime[64];
  8109. if (conn == NULL || uri == NULL || filep == NULL) {
  8110. return;
  8111. }
  8112. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8113. conn->num_bytes_sent +=
  8114. mg_printf(conn,
  8115. "<d:response>"
  8116. "<d:href>%s</d:href>"
  8117. "<d:propstat>"
  8118. "<d:prop>"
  8119. "<d:resourcetype>%s</d:resourcetype>"
  8120. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8121. "<d:getlastmodified>%s</d:getlastmodified>"
  8122. "</d:prop>"
  8123. "<d:status>HTTP/1.1 200 OK</d:status>"
  8124. "</d:propstat>"
  8125. "</d:response>\n",
  8126. uri,
  8127. filep->is_directory ? "<d:collection/>" : "",
  8128. filep->size,
  8129. mtime);
  8130. }
  8131. static void
  8132. print_dav_dir_entry(struct de *de, void *data)
  8133. {
  8134. char href[PATH_MAX];
  8135. char href_encoded[PATH_MAX * 3 /* worst case */];
  8136. int truncated;
  8137. struct mg_connection *conn = (struct mg_connection *)data;
  8138. if (!de || !conn) {
  8139. return;
  8140. }
  8141. mg_snprintf(conn,
  8142. &truncated,
  8143. href,
  8144. sizeof(href),
  8145. "%s%s",
  8146. conn->request_info.local_uri,
  8147. de->file_name);
  8148. if (!truncated) {
  8149. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8150. print_props(conn, href_encoded, &de->file);
  8151. }
  8152. }
  8153. static void
  8154. handle_propfind(struct mg_connection *conn,
  8155. const char *path,
  8156. struct mg_file_stat *filep)
  8157. {
  8158. const char *depth = mg_get_header(conn, "Depth");
  8159. char date[64];
  8160. time_t curtime = time(NULL);
  8161. gmt_time_string(date, sizeof(date), &curtime);
  8162. if (!conn || !path || !filep || !conn->ctx) {
  8163. return;
  8164. }
  8165. conn->must_close = 1;
  8166. conn->status_code = 207;
  8167. mg_printf(conn,
  8168. "HTTP/1.1 207 Multi-Status\r\n"
  8169. "Date: %s\r\n",
  8170. date);
  8171. send_static_cache_header(conn);
  8172. mg_printf(conn,
  8173. "Connection: %s\r\n"
  8174. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8175. suggest_connection_header(conn));
  8176. conn->num_bytes_sent +=
  8177. mg_printf(conn,
  8178. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8179. "<d:multistatus xmlns:d='DAV:'>\n");
  8180. /* Print properties for the requested resource itself */
  8181. print_props(conn, conn->request_info.local_uri, filep);
  8182. /* If it is a directory, print directory entries too if Depth is not 0 */
  8183. if (filep && filep->is_directory
  8184. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8185. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8186. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8187. }
  8188. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8189. }
  8190. #endif
  8191. void
  8192. mg_lock_connection(struct mg_connection *conn)
  8193. {
  8194. if (conn) {
  8195. (void)pthread_mutex_lock(&conn->mutex);
  8196. }
  8197. }
  8198. void
  8199. mg_unlock_connection(struct mg_connection *conn)
  8200. {
  8201. if (conn) {
  8202. (void)pthread_mutex_unlock(&conn->mutex);
  8203. }
  8204. }
  8205. void
  8206. mg_lock_context(struct mg_context *ctx)
  8207. {
  8208. if (ctx) {
  8209. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8210. }
  8211. }
  8212. void
  8213. mg_unlock_context(struct mg_context *ctx)
  8214. {
  8215. if (ctx) {
  8216. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8217. }
  8218. }
  8219. #if defined(USE_TIMERS)
  8220. #include "timer.inl"
  8221. #endif /* USE_TIMERS */
  8222. #ifdef USE_LUA
  8223. #include "mod_lua.inl"
  8224. #endif /* USE_LUA */
  8225. #ifdef USE_DUKTAPE
  8226. #include "mod_duktape.inl"
  8227. #endif /* USE_DUKTAPE */
  8228. #if defined(USE_WEBSOCKET)
  8229. #if !defined(NO_SSL_DL)
  8230. #define SHA_API static
  8231. #include "sha1.inl"
  8232. #endif
  8233. static int
  8234. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8235. {
  8236. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8237. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8238. SHA_CTX sha_ctx;
  8239. int truncated;
  8240. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8241. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8242. if (truncated) {
  8243. conn->must_close = 1;
  8244. return 0;
  8245. }
  8246. SHA1_Init(&sha_ctx);
  8247. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8248. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8249. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8250. mg_printf(conn,
  8251. "HTTP/1.1 101 Switching Protocols\r\n"
  8252. "Upgrade: websocket\r\n"
  8253. "Connection: Upgrade\r\n"
  8254. "Sec-WebSocket-Accept: %s\r\n",
  8255. b64_sha);
  8256. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8257. mg_printf(conn,
  8258. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8259. conn->request_info.acceptedWebSocketSubprotocol);
  8260. } else {
  8261. mg_printf(conn, "%s", "\r\n");
  8262. }
  8263. return 1;
  8264. }
  8265. static void
  8266. read_websocket(struct mg_connection *conn,
  8267. mg_websocket_data_handler ws_data_handler,
  8268. void *callback_data)
  8269. {
  8270. /* Pointer to the beginning of the portion of the incoming websocket
  8271. * message queue.
  8272. * The original websocket upgrade request is never removed, so the queue
  8273. * begins after it. */
  8274. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8275. int n, error, exit_by_callback;
  8276. /* body_len is the length of the entire queue in bytes
  8277. * len is the length of the current message
  8278. * data_len is the length of the current message's data payload
  8279. * header_len is the length of the current message's header */
  8280. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8281. /* "The masking key is a 32-bit value chosen at random by the client."
  8282. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8283. */
  8284. unsigned char mask[4];
  8285. /* data points to the place where the message is stored when passed to
  8286. * the
  8287. * websocket_data callback. This is either mem on the stack, or a
  8288. * dynamically allocated buffer if it is too large. */
  8289. unsigned char mem[4096];
  8290. unsigned char *data = mem;
  8291. unsigned char mop; /* mask flag and opcode */
  8292. double timeout = -1.0;
  8293. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8294. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8295. }
  8296. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8297. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8298. }
  8299. mg_set_thread_name("wsock");
  8300. /* Loop continuously, reading messages from the socket, invoking the
  8301. * callback, and waiting repeatedly until an error occurs. */
  8302. while (!conn->ctx->stop_flag) {
  8303. header_len = 0;
  8304. assert(conn->data_len >= conn->request_len);
  8305. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8306. len = buf[1] & 127;
  8307. mask_len = (buf[1] & 128) ? 4 : 0;
  8308. if ((len < 126) && (body_len >= mask_len)) {
  8309. data_len = len;
  8310. header_len = 2 + mask_len;
  8311. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8312. header_len = 4 + mask_len;
  8313. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8314. } else if (body_len >= (10 + mask_len)) {
  8315. header_len = 10 + mask_len;
  8316. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8317. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8318. }
  8319. }
  8320. if (header_len > 0 && body_len >= header_len) {
  8321. /* Allocate space to hold websocket payload */
  8322. data = mem;
  8323. if (data_len > sizeof(mem)) {
  8324. data = (unsigned char *)mg_malloc(data_len);
  8325. if (data == NULL) {
  8326. /* Allocation failed, exit the loop and then close the
  8327. * connection */
  8328. mg_cry(conn, "websocket out of memory; closing connection");
  8329. break;
  8330. }
  8331. }
  8332. /* Copy the mask before we shift the queue and destroy it */
  8333. if (mask_len > 0) {
  8334. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8335. } else {
  8336. memset(mask, 0, sizeof(mask));
  8337. }
  8338. /* Read frame payload from the first message in the queue into
  8339. * data and advance the queue by moving the memory in place. */
  8340. assert(body_len >= header_len);
  8341. if (data_len + header_len > body_len) {
  8342. mop = buf[0]; /* current mask and opcode */
  8343. /* Overflow case */
  8344. len = body_len - header_len;
  8345. memcpy(data, buf + header_len, len);
  8346. error = 0;
  8347. while (len < data_len) {
  8348. n = pull(NULL,
  8349. conn,
  8350. (char *)(data + len),
  8351. (int)(data_len - len),
  8352. timeout);
  8353. if (n <= 0) {
  8354. error = 1;
  8355. break;
  8356. }
  8357. len += (size_t)n;
  8358. }
  8359. if (error) {
  8360. mg_cry(conn, "Websocket pull failed; closing connection");
  8361. break;
  8362. }
  8363. conn->data_len = conn->request_len;
  8364. } else {
  8365. mop = buf[0]; /* current mask and opcode, overwritten by
  8366. * memmove() */
  8367. /* Length of the message being read at the front of the
  8368. * queue */
  8369. len = data_len + header_len;
  8370. /* Copy the data payload into the data pointer for the
  8371. * callback */
  8372. memcpy(data, buf + header_len, data_len);
  8373. /* Move the queue forward len bytes */
  8374. memmove(buf, buf + len, body_len - len);
  8375. /* Mark the queue as advanced */
  8376. conn->data_len -= (int)len;
  8377. }
  8378. /* Apply mask if necessary */
  8379. if (mask_len > 0) {
  8380. for (i = 0; i < data_len; ++i) {
  8381. data[i] ^= mask[i & 3];
  8382. }
  8383. }
  8384. /* Exit the loop if callback signals to exit (server side),
  8385. * or "connection close" opcode received (client side). */
  8386. exit_by_callback = 0;
  8387. if ((ws_data_handler != NULL)
  8388. && !ws_data_handler(
  8389. conn, mop, (char *)data, data_len, callback_data)) {
  8390. exit_by_callback = 1;
  8391. }
  8392. if (data != mem) {
  8393. mg_free(data);
  8394. }
  8395. if (exit_by_callback
  8396. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8397. /* Opcode == 8, connection close */
  8398. break;
  8399. }
  8400. /* Not breaking the loop, process next websocket frame. */
  8401. } else {
  8402. /* Read from the socket into the next available location in the
  8403. * message queue. */
  8404. if ((n = pull(NULL,
  8405. conn,
  8406. conn->buf + conn->data_len,
  8407. conn->buf_size - conn->data_len,
  8408. timeout)) <= 0) {
  8409. /* Error, no bytes read */
  8410. break;
  8411. }
  8412. conn->data_len += n;
  8413. }
  8414. }
  8415. mg_set_thread_name("worker");
  8416. }
  8417. static int
  8418. mg_websocket_write_exec(struct mg_connection *conn,
  8419. int opcode,
  8420. const char *data,
  8421. size_t dataLen,
  8422. uint32_t masking_key)
  8423. {
  8424. unsigned char header[14];
  8425. size_t headerLen = 1;
  8426. int retval = -1;
  8427. #if defined(__GNUC__) || defined(__MINGW32__)
  8428. /* Disable spurious conversion warning for GCC */
  8429. #pragma GCC diagnostic push
  8430. #pragma GCC diagnostic ignored "-Wconversion"
  8431. #endif
  8432. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8433. #if defined(__GNUC__) || defined(__MINGW32__)
  8434. #pragma GCC diagnostic pop
  8435. #endif
  8436. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8437. if (dataLen < 126) {
  8438. /* inline 7-bit length field */
  8439. header[1] = (unsigned char)dataLen;
  8440. headerLen = 2;
  8441. } else if (dataLen <= 0xFFFF) {
  8442. /* 16-bit length field */
  8443. uint16_t len = htons((uint16_t)dataLen);
  8444. header[1] = 126;
  8445. memcpy(header + 2, &len, 2);
  8446. headerLen = 4;
  8447. } else {
  8448. /* 64-bit length field */
  8449. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8450. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8451. header[1] = 127;
  8452. memcpy(header + 2, &len1, 4);
  8453. memcpy(header + 6, &len2, 4);
  8454. headerLen = 10;
  8455. }
  8456. if (masking_key) {
  8457. /* add mask */
  8458. header[1] |= 0x80;
  8459. memcpy(header + headerLen, &masking_key, 4);
  8460. headerLen += 4;
  8461. }
  8462. /* Note that POSIX/Winsock's send() is threadsafe
  8463. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8464. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8465. * push(), although that is only a problem if the packet is large or
  8466. * outgoing buffer is full). */
  8467. (void)mg_lock_connection(conn);
  8468. retval = mg_write(conn, header, headerLen);
  8469. if (dataLen > 0) {
  8470. retval = mg_write(conn, data, dataLen);
  8471. }
  8472. mg_unlock_connection(conn);
  8473. return retval;
  8474. }
  8475. int
  8476. mg_websocket_write(struct mg_connection *conn,
  8477. int opcode,
  8478. const char *data,
  8479. size_t dataLen)
  8480. {
  8481. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8482. }
  8483. static void
  8484. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8485. {
  8486. size_t i = 0;
  8487. i = 0;
  8488. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8489. /* Convert in 32 bit words, if data is 4 byte aligned */
  8490. while (i < (in_len - 3)) {
  8491. *(uint32_t *)(void *)(out + i) =
  8492. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8493. i += 4;
  8494. }
  8495. }
  8496. if (i != in_len) {
  8497. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8498. while (i < in_len) {
  8499. *(uint8_t *)(void *)(out + i) =
  8500. *(uint8_t *)(void *)(in + i)
  8501. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8502. i++;
  8503. }
  8504. }
  8505. }
  8506. int
  8507. mg_websocket_client_write(struct mg_connection *conn,
  8508. int opcode,
  8509. const char *data,
  8510. size_t dataLen)
  8511. {
  8512. int retval = -1;
  8513. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8514. uint32_t masking_key = (uint32_t)get_random();
  8515. if (masked_data == NULL) {
  8516. /* Return -1 in an error case */
  8517. mg_cry(conn,
  8518. "Cannot allocate buffer for masked websocket response: "
  8519. "Out of memory");
  8520. return -1;
  8521. }
  8522. mask_data(data, dataLen, masking_key, masked_data);
  8523. retval = mg_websocket_write_exec(
  8524. conn, opcode, masked_data, dataLen, masking_key);
  8525. mg_free(masked_data);
  8526. return retval;
  8527. }
  8528. static void
  8529. handle_websocket_request(struct mg_connection *conn,
  8530. const char *path,
  8531. int is_callback_resource,
  8532. struct mg_websocket_subprotocols *subprotocols,
  8533. mg_websocket_connect_handler ws_connect_handler,
  8534. mg_websocket_ready_handler ws_ready_handler,
  8535. mg_websocket_data_handler ws_data_handler,
  8536. mg_websocket_close_handler ws_close_handler,
  8537. void *cbData)
  8538. {
  8539. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8540. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8541. int lua_websock = 0;
  8542. #if !defined(USE_LUA)
  8543. (void)path;
  8544. #endif
  8545. /* Step 1: Check websocket protocol version. */
  8546. /* Step 1.1: Check Sec-WebSocket-Key. */
  8547. if (!websock_key) {
  8548. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8549. * requires a Sec-WebSocket-Key header.
  8550. */
  8551. /* It could be the hixie draft version
  8552. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8553. */
  8554. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8555. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8556. char key3[8];
  8557. if ((key1 != NULL) && (key2 != NULL)) {
  8558. /* This version uses 8 byte body data in a GET request */
  8559. conn->content_len = 8;
  8560. if (8 == mg_read(conn, key3, 8)) {
  8561. /* This is the hixie version */
  8562. send_http_error(conn,
  8563. 426,
  8564. "%s",
  8565. "Protocol upgrade to RFC 6455 required");
  8566. return;
  8567. }
  8568. }
  8569. /* This is an unknown version */
  8570. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8571. return;
  8572. }
  8573. /* Step 1.2: Check websocket protocol version. */
  8574. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8575. if (version == NULL || strcmp(version, "13") != 0) {
  8576. /* Reject wrong versions */
  8577. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8578. return;
  8579. }
  8580. /* Step 1.3: Could check for "Host", but we do not really nead this
  8581. * value for anything, so just ignore it. */
  8582. /* Step 2: If a callback is responsible, call it. */
  8583. if (is_callback_resource) {
  8584. /* Step 2.1 check and select subprotocol */
  8585. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8586. if (protocol && subprotocols) {
  8587. int idx;
  8588. unsigned long len;
  8589. const char *sep, *curSubProtocol,
  8590. *acceptedWebSocketSubprotocol = NULL;
  8591. /* look for matching subprotocol */
  8592. do {
  8593. sep = strchr(protocol, ',');
  8594. curSubProtocol = protocol;
  8595. len = sep ? (unsigned long)(sep - protocol)
  8596. : (unsigned long)strlen(protocol);
  8597. while (sep && isspace(*++sep)) {
  8598. ; /* ignore leading whitespaces */
  8599. }
  8600. protocol = sep;
  8601. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8602. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8603. && (strncmp(curSubProtocol,
  8604. subprotocols->subprotocols[idx],
  8605. len) == 0)) {
  8606. acceptedWebSocketSubprotocol =
  8607. subprotocols->subprotocols[idx];
  8608. break;
  8609. }
  8610. }
  8611. } while (sep && !acceptedWebSocketSubprotocol);
  8612. conn->request_info.acceptedWebSocketSubprotocol =
  8613. acceptedWebSocketSubprotocol;
  8614. } else if (protocol) {
  8615. /* keep legacy behavior */
  8616. /* The protocol is a comma seperated list of names. */
  8617. /* The server must only return one value from this list. */
  8618. /* First check if it is a list or just a single value. */
  8619. const char *sep = strrchr(protocol, ',');
  8620. if (sep == NULL) {
  8621. /* Just a single protocol -> accept it. */
  8622. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8623. } else {
  8624. /* Multiple protocols -> accept the last one. */
  8625. /* This is just a quick fix if the client offers multiple
  8626. * protocols. The handler should have a list of accepted
  8627. * protocols on his own
  8628. * and use it to select one protocol among those the client has
  8629. * offered.
  8630. */
  8631. while (isspace(*++sep)) {
  8632. ; /* ignore leading whitespaces */
  8633. }
  8634. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8635. }
  8636. }
  8637. if (ws_connect_handler != NULL
  8638. && ws_connect_handler(conn, cbData) != 0) {
  8639. /* C callback has returned non-zero, do not proceed with
  8640. * handshake.
  8641. */
  8642. /* Note that C callbacks are no longer called when Lua is
  8643. * responsible, so C can no longer filter callbacks for Lua. */
  8644. return;
  8645. }
  8646. }
  8647. #if defined(USE_LUA)
  8648. /* Step 3: No callback. Check if Lua is responsible. */
  8649. else {
  8650. /* Step 3.1: Check if Lua is responsible. */
  8651. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8652. lua_websock =
  8653. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8654. strlen(
  8655. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8656. path);
  8657. }
  8658. if (lua_websock) {
  8659. /* Step 3.2: Lua is responsible: call it. */
  8660. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8661. if (!conn->lua_websocket_state) {
  8662. /* Lua rejected the new client */
  8663. return;
  8664. }
  8665. }
  8666. }
  8667. #endif
  8668. /* Step 4: Check if there is a responsible websocket handler. */
  8669. if (!is_callback_resource && !lua_websock) {
  8670. /* There is no callback, and Lua is not responsible either. */
  8671. /* Reply with a 404 Not Found. We are still at a standard
  8672. * HTTP request here, before the websocket handshake, so
  8673. * we can still send standard HTTP error replies. */
  8674. send_http_error(conn, 404, "%s", "Not found");
  8675. return;
  8676. }
  8677. /* Step 5: The websocket connection has been accepted */
  8678. if (!send_websocket_handshake(conn, websock_key)) {
  8679. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8680. return;
  8681. }
  8682. /* Step 6: Call the ready handler */
  8683. if (is_callback_resource) {
  8684. if (ws_ready_handler != NULL) {
  8685. ws_ready_handler(conn, cbData);
  8686. }
  8687. #if defined(USE_LUA)
  8688. } else if (lua_websock) {
  8689. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8690. /* the ready handler returned false */
  8691. return;
  8692. }
  8693. #endif
  8694. }
  8695. /* Step 7: Enter the read loop */
  8696. if (is_callback_resource) {
  8697. read_websocket(conn, ws_data_handler, cbData);
  8698. #if defined(USE_LUA)
  8699. } else if (lua_websock) {
  8700. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8701. #endif
  8702. }
  8703. /* Step 8: Call the close handler */
  8704. if (ws_close_handler) {
  8705. ws_close_handler(conn, cbData);
  8706. }
  8707. }
  8708. static int
  8709. is_websocket_protocol(const struct mg_connection *conn)
  8710. {
  8711. const char *upgrade, *connection;
  8712. /* A websocket protocoll has the following HTTP headers:
  8713. *
  8714. * Connection: Upgrade
  8715. * Upgrade: Websocket
  8716. */
  8717. upgrade = mg_get_header(conn, "Upgrade");
  8718. if (upgrade == NULL) {
  8719. return 0; /* fail early, don't waste time checking other header
  8720. * fields
  8721. */
  8722. }
  8723. if (!mg_strcasestr(upgrade, "websocket")) {
  8724. return 0;
  8725. }
  8726. connection = mg_get_header(conn, "Connection");
  8727. if (connection == NULL) {
  8728. return 0;
  8729. }
  8730. if (!mg_strcasestr(connection, "upgrade")) {
  8731. return 0;
  8732. }
  8733. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8734. * "Sec-WebSocket-Version" are also required.
  8735. * Don't check them here, since even an unsupported websocket protocol
  8736. * request still IS a websocket request (in contrast to a standard HTTP
  8737. * request). It will fail later in handle_websocket_request.
  8738. */
  8739. return 1;
  8740. }
  8741. #endif /* !USE_WEBSOCKET */
  8742. static int
  8743. isbyte(int n)
  8744. {
  8745. return n >= 0 && n <= 255;
  8746. }
  8747. static int
  8748. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8749. {
  8750. int n, a, b, c, d, slash = 32, len = 0;
  8751. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8752. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8753. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8754. && slash < 33) {
  8755. len = n;
  8756. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8757. | (uint32_t)d;
  8758. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8759. }
  8760. return len;
  8761. }
  8762. static int
  8763. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8764. {
  8765. int throttle = 0;
  8766. struct vec vec, val;
  8767. uint32_t net, mask;
  8768. char mult;
  8769. double v;
  8770. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8771. mult = ',';
  8772. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8773. || (v < 0) || ((lowercase(&mult) != 'k')
  8774. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8775. continue;
  8776. }
  8777. v *= (lowercase(&mult) == 'k')
  8778. ? 1024
  8779. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8780. if (vec.len == 1 && vec.ptr[0] == '*') {
  8781. throttle = (int)v;
  8782. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8783. if ((remote_ip & mask) == net) {
  8784. throttle = (int)v;
  8785. }
  8786. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8787. throttle = (int)v;
  8788. }
  8789. }
  8790. return throttle;
  8791. }
  8792. static uint32_t
  8793. get_remote_ip(const struct mg_connection *conn)
  8794. {
  8795. if (!conn) {
  8796. return 0;
  8797. }
  8798. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8799. }
  8800. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8801. #include "handle_form.inl"
  8802. #if defined(MG_LEGACY_INTERFACE)
  8803. /* Implement the deprecated mg_upload function by calling the new
  8804. * mg_handle_form_request function. While mg_upload could only handle
  8805. * HTML forms sent as POST request in multipart/form-data format
  8806. * containing only file input elements, mg_handle_form_request can
  8807. * handle all form input elements and all standard request methods. */
  8808. struct mg_upload_user_data {
  8809. struct mg_connection *conn;
  8810. const char *destination_dir;
  8811. int num_uploaded_files;
  8812. };
  8813. /* Helper function for deprecated mg_upload. */
  8814. static int
  8815. mg_upload_field_found(const char *key,
  8816. const char *filename,
  8817. char *path,
  8818. size_t pathlen,
  8819. void *user_data)
  8820. {
  8821. int truncated = 0;
  8822. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8823. (void)key;
  8824. if (!filename) {
  8825. mg_cry(fud->conn, "%s: No filename set", __func__);
  8826. return FORM_FIELD_STORAGE_ABORT;
  8827. }
  8828. mg_snprintf(fud->conn,
  8829. &truncated,
  8830. path,
  8831. pathlen - 1,
  8832. "%s/%s",
  8833. fud->destination_dir,
  8834. filename);
  8835. if (!truncated) {
  8836. mg_cry(fud->conn, "%s: File path too long", __func__);
  8837. return FORM_FIELD_STORAGE_ABORT;
  8838. }
  8839. return FORM_FIELD_STORAGE_STORE;
  8840. }
  8841. /* Helper function for deprecated mg_upload. */
  8842. static int
  8843. mg_upload_field_get(const char *key,
  8844. const char *value,
  8845. size_t value_size,
  8846. void *user_data)
  8847. {
  8848. /* Function should never be called */
  8849. (void)key;
  8850. (void)value;
  8851. (void)value_size;
  8852. (void)user_data;
  8853. return 0;
  8854. }
  8855. /* Helper function for deprecated mg_upload. */
  8856. static int
  8857. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8858. {
  8859. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8860. (void)file_size;
  8861. fud->num_uploaded_files++;
  8862. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8863. return 0;
  8864. }
  8865. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8866. int
  8867. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8868. {
  8869. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8870. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8871. mg_upload_field_get,
  8872. mg_upload_field_stored,
  8873. 0};
  8874. int ret;
  8875. fdh.user_data = (void *)&fud;
  8876. ret = mg_handle_form_request(conn, &fdh);
  8877. if (ret < 0) {
  8878. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8879. }
  8880. return fud.num_uploaded_files;
  8881. }
  8882. #endif
  8883. static int
  8884. get_first_ssl_listener_index(const struct mg_context *ctx)
  8885. {
  8886. unsigned int i;
  8887. int idx = -1;
  8888. if (ctx) {
  8889. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8890. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8891. }
  8892. }
  8893. return idx;
  8894. }
  8895. static void
  8896. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8897. {
  8898. char host[1025];
  8899. const char *host_header;
  8900. size_t hostlen;
  8901. host_header = mg_get_header(conn, "Host");
  8902. hostlen = sizeof(host);
  8903. if (host_header != NULL) {
  8904. char *pos;
  8905. mg_strlcpy(host, host_header, hostlen);
  8906. host[hostlen - 1] = '\0';
  8907. pos = strchr(host, ':');
  8908. if (pos != NULL) {
  8909. *pos = '\0';
  8910. }
  8911. } else {
  8912. /* Cannot get host from the Host: header.
  8913. * Fallback to our IP address. */
  8914. if (conn) {
  8915. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8916. }
  8917. }
  8918. /* Send host, port, uri and (if it exists) ?query_string */
  8919. if (conn) {
  8920. mg_printf(conn,
  8921. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8922. host,
  8923. #if defined(USE_IPV6)
  8924. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8925. == AF_INET6)
  8926. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8927. .lsa.sin6.sin6_port)
  8928. :
  8929. #endif
  8930. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8931. .lsa.sin.sin_port),
  8932. conn->request_info.local_uri,
  8933. (conn->request_info.query_string == NULL) ? "" : "?",
  8934. (conn->request_info.query_string == NULL)
  8935. ? ""
  8936. : conn->request_info.query_string);
  8937. }
  8938. }
  8939. static void
  8940. mg_set_handler_type(struct mg_context *ctx,
  8941. const char *uri,
  8942. int handler_type,
  8943. int is_delete_request,
  8944. mg_request_handler handler,
  8945. struct mg_websocket_subprotocols *subprotocols,
  8946. mg_websocket_connect_handler connect_handler,
  8947. mg_websocket_ready_handler ready_handler,
  8948. mg_websocket_data_handler data_handler,
  8949. mg_websocket_close_handler close_handler,
  8950. mg_authorization_handler auth_handler,
  8951. void *cbdata)
  8952. {
  8953. struct mg_handler_info *tmp_rh, **lastref;
  8954. size_t urilen = strlen(uri);
  8955. if (handler_type == WEBSOCKET_HANDLER) {
  8956. /* assert(handler == NULL); */
  8957. /* assert(is_delete_request || connect_handler!=NULL ||
  8958. * ready_handler!=NULL || data_handler!=NULL ||
  8959. * close_handler!=NULL);
  8960. */
  8961. /* assert(auth_handler == NULL); */
  8962. if (handler != NULL) {
  8963. return;
  8964. }
  8965. if (!is_delete_request && connect_handler == NULL
  8966. && ready_handler == NULL
  8967. && data_handler == NULL
  8968. && close_handler == NULL) {
  8969. return;
  8970. }
  8971. if (auth_handler != NULL) {
  8972. return;
  8973. }
  8974. } else if (handler_type == REQUEST_HANDLER) {
  8975. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8976. * data_handler==NULL && close_handler==NULL); */
  8977. /* assert(is_delete_request || (handler!=NULL));
  8978. */
  8979. /* assert(auth_handler == NULL); */
  8980. if (connect_handler != NULL || ready_handler != NULL
  8981. || data_handler != NULL
  8982. || close_handler != NULL) {
  8983. return;
  8984. }
  8985. if (!is_delete_request && (handler == NULL)) {
  8986. return;
  8987. }
  8988. if (auth_handler != NULL) {
  8989. return;
  8990. }
  8991. } else { /* AUTH_HANDLER */
  8992. /* assert(handler == NULL); */
  8993. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8994. * data_handler==NULL && close_handler==NULL); */
  8995. /* assert(auth_handler != NULL); */
  8996. if (handler != NULL) {
  8997. return;
  8998. }
  8999. if (connect_handler != NULL || ready_handler != NULL
  9000. || data_handler != NULL
  9001. || close_handler != NULL) {
  9002. return;
  9003. }
  9004. if (!is_delete_request && (auth_handler == NULL)) {
  9005. return;
  9006. }
  9007. }
  9008. if (!ctx) {
  9009. return;
  9010. }
  9011. mg_lock_context(ctx);
  9012. /* first try to find an existing handler */
  9013. lastref = &(ctx->handlers);
  9014. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9015. if (tmp_rh->handler_type == handler_type) {
  9016. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9017. if (!is_delete_request) {
  9018. /* update existing handler */
  9019. if (handler_type == REQUEST_HANDLER) {
  9020. tmp_rh->handler = handler;
  9021. } else if (handler_type == WEBSOCKET_HANDLER) {
  9022. tmp_rh->subprotocols = subprotocols;
  9023. tmp_rh->connect_handler = connect_handler;
  9024. tmp_rh->ready_handler = ready_handler;
  9025. tmp_rh->data_handler = data_handler;
  9026. tmp_rh->close_handler = close_handler;
  9027. } else { /* AUTH_HANDLER */
  9028. tmp_rh->auth_handler = auth_handler;
  9029. }
  9030. tmp_rh->cbdata = cbdata;
  9031. } else {
  9032. /* remove existing handler */
  9033. *lastref = tmp_rh->next;
  9034. mg_free(tmp_rh->uri);
  9035. mg_free(tmp_rh);
  9036. }
  9037. mg_unlock_context(ctx);
  9038. return;
  9039. }
  9040. }
  9041. lastref = &(tmp_rh->next);
  9042. }
  9043. if (is_delete_request) {
  9044. /* no handler to set, this was a remove request to a non-existing
  9045. * handler */
  9046. mg_unlock_context(ctx);
  9047. return;
  9048. }
  9049. tmp_rh =
  9050. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  9051. if (tmp_rh == NULL) {
  9052. mg_unlock_context(ctx);
  9053. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9054. return;
  9055. }
  9056. tmp_rh->uri = mg_strdup(uri);
  9057. if (!tmp_rh->uri) {
  9058. mg_unlock_context(ctx);
  9059. mg_free(tmp_rh);
  9060. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9061. return;
  9062. }
  9063. tmp_rh->uri_len = urilen;
  9064. if (handler_type == REQUEST_HANDLER) {
  9065. tmp_rh->handler = handler;
  9066. } else if (handler_type == WEBSOCKET_HANDLER) {
  9067. tmp_rh->subprotocols = subprotocols;
  9068. tmp_rh->connect_handler = connect_handler;
  9069. tmp_rh->ready_handler = ready_handler;
  9070. tmp_rh->data_handler = data_handler;
  9071. tmp_rh->close_handler = close_handler;
  9072. } else { /* AUTH_HANDLER */
  9073. tmp_rh->auth_handler = auth_handler;
  9074. }
  9075. tmp_rh->cbdata = cbdata;
  9076. tmp_rh->handler_type = handler_type;
  9077. tmp_rh->next = NULL;
  9078. *lastref = tmp_rh;
  9079. mg_unlock_context(ctx);
  9080. }
  9081. void
  9082. mg_set_request_handler(struct mg_context *ctx,
  9083. const char *uri,
  9084. mg_request_handler handler,
  9085. void *cbdata)
  9086. {
  9087. mg_set_handler_type(ctx,
  9088. uri,
  9089. REQUEST_HANDLER,
  9090. handler == NULL,
  9091. handler,
  9092. NULL,
  9093. NULL,
  9094. NULL,
  9095. NULL,
  9096. NULL,
  9097. NULL,
  9098. cbdata);
  9099. }
  9100. void
  9101. mg_set_websocket_handler(struct mg_context *ctx,
  9102. const char *uri,
  9103. mg_websocket_connect_handler connect_handler,
  9104. mg_websocket_ready_handler ready_handler,
  9105. mg_websocket_data_handler data_handler,
  9106. mg_websocket_close_handler close_handler,
  9107. void *cbdata)
  9108. {
  9109. mg_set_websocket_handler_with_subprotocols(ctx,
  9110. uri,
  9111. NULL,
  9112. connect_handler,
  9113. ready_handler,
  9114. data_handler,
  9115. close_handler,
  9116. cbdata);
  9117. }
  9118. void
  9119. mg_set_websocket_handler_with_subprotocols(
  9120. struct mg_context *ctx,
  9121. const char *uri,
  9122. struct mg_websocket_subprotocols *subprotocols,
  9123. mg_websocket_connect_handler connect_handler,
  9124. mg_websocket_ready_handler ready_handler,
  9125. mg_websocket_data_handler data_handler,
  9126. mg_websocket_close_handler close_handler,
  9127. void *cbdata)
  9128. {
  9129. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9130. && (data_handler == NULL)
  9131. && (close_handler == NULL);
  9132. mg_set_handler_type(ctx,
  9133. uri,
  9134. WEBSOCKET_HANDLER,
  9135. is_delete_request,
  9136. NULL,
  9137. subprotocols,
  9138. connect_handler,
  9139. ready_handler,
  9140. data_handler,
  9141. close_handler,
  9142. NULL,
  9143. cbdata);
  9144. }
  9145. void
  9146. mg_set_auth_handler(struct mg_context *ctx,
  9147. const char *uri,
  9148. mg_request_handler handler,
  9149. void *cbdata)
  9150. {
  9151. mg_set_handler_type(ctx,
  9152. uri,
  9153. AUTH_HANDLER,
  9154. handler == NULL,
  9155. NULL,
  9156. NULL,
  9157. NULL,
  9158. NULL,
  9159. NULL,
  9160. NULL,
  9161. handler,
  9162. cbdata);
  9163. }
  9164. static int
  9165. get_request_handler(struct mg_connection *conn,
  9166. int handler_type,
  9167. mg_request_handler *handler,
  9168. struct mg_websocket_subprotocols **subprotocols,
  9169. mg_websocket_connect_handler *connect_handler,
  9170. mg_websocket_ready_handler *ready_handler,
  9171. mg_websocket_data_handler *data_handler,
  9172. mg_websocket_close_handler *close_handler,
  9173. mg_authorization_handler *auth_handler,
  9174. void **cbdata)
  9175. {
  9176. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9177. if (request_info) {
  9178. const char *uri = request_info->local_uri;
  9179. size_t urilen = strlen(uri);
  9180. struct mg_handler_info *tmp_rh;
  9181. if (!conn || !conn->ctx) {
  9182. return 0;
  9183. }
  9184. mg_lock_context(conn->ctx);
  9185. /* first try for an exact match */
  9186. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9187. tmp_rh = tmp_rh->next) {
  9188. if (tmp_rh->handler_type == handler_type) {
  9189. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9190. if (handler_type == WEBSOCKET_HANDLER) {
  9191. *subprotocols = tmp_rh->subprotocols;
  9192. *connect_handler = tmp_rh->connect_handler;
  9193. *ready_handler = tmp_rh->ready_handler;
  9194. *data_handler = tmp_rh->data_handler;
  9195. *close_handler = tmp_rh->close_handler;
  9196. } else if (handler_type == REQUEST_HANDLER) {
  9197. *handler = tmp_rh->handler;
  9198. } else { /* AUTH_HANDLER */
  9199. *auth_handler = tmp_rh->auth_handler;
  9200. }
  9201. *cbdata = tmp_rh->cbdata;
  9202. mg_unlock_context(conn->ctx);
  9203. return 1;
  9204. }
  9205. }
  9206. }
  9207. /* next try for a partial match, we will accept uri/something */
  9208. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9209. tmp_rh = tmp_rh->next) {
  9210. if (tmp_rh->handler_type == handler_type) {
  9211. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9212. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9213. if (handler_type == WEBSOCKET_HANDLER) {
  9214. *subprotocols = tmp_rh->subprotocols;
  9215. *connect_handler = tmp_rh->connect_handler;
  9216. *ready_handler = tmp_rh->ready_handler;
  9217. *data_handler = tmp_rh->data_handler;
  9218. *close_handler = tmp_rh->close_handler;
  9219. } else if (handler_type == REQUEST_HANDLER) {
  9220. *handler = tmp_rh->handler;
  9221. } else { /* AUTH_HANDLER */
  9222. *auth_handler = tmp_rh->auth_handler;
  9223. }
  9224. *cbdata = tmp_rh->cbdata;
  9225. mg_unlock_context(conn->ctx);
  9226. return 1;
  9227. }
  9228. }
  9229. }
  9230. /* finally try for pattern match */
  9231. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9232. tmp_rh = tmp_rh->next) {
  9233. if (tmp_rh->handler_type == handler_type) {
  9234. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9235. if (handler_type == WEBSOCKET_HANDLER) {
  9236. *subprotocols = tmp_rh->subprotocols;
  9237. *connect_handler = tmp_rh->connect_handler;
  9238. *ready_handler = tmp_rh->ready_handler;
  9239. *data_handler = tmp_rh->data_handler;
  9240. *close_handler = tmp_rh->close_handler;
  9241. } else if (handler_type == REQUEST_HANDLER) {
  9242. *handler = tmp_rh->handler;
  9243. } else { /* AUTH_HANDLER */
  9244. *auth_handler = tmp_rh->auth_handler;
  9245. }
  9246. *cbdata = tmp_rh->cbdata;
  9247. mg_unlock_context(conn->ctx);
  9248. return 1;
  9249. }
  9250. }
  9251. }
  9252. mg_unlock_context(conn->ctx);
  9253. }
  9254. return 0; /* none found */
  9255. }
  9256. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9257. static int
  9258. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9259. void *cbdata)
  9260. {
  9261. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9262. if (pcallbacks->websocket_connect) {
  9263. return pcallbacks->websocket_connect(conn);
  9264. }
  9265. /* No handler set - assume "OK" */
  9266. return 0;
  9267. }
  9268. static void
  9269. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9270. {
  9271. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9272. if (pcallbacks->websocket_ready) {
  9273. pcallbacks->websocket_ready(conn);
  9274. }
  9275. }
  9276. static int
  9277. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9278. int bits,
  9279. char *data,
  9280. size_t len,
  9281. void *cbdata)
  9282. {
  9283. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9284. if (pcallbacks->websocket_data) {
  9285. return pcallbacks->websocket_data(conn, bits, data, len);
  9286. }
  9287. /* No handler set - assume "OK" */
  9288. return 1;
  9289. }
  9290. #endif
  9291. /* This is the heart of the Civetweb's logic.
  9292. * This function is called when the request is read, parsed and validated,
  9293. * and Civetweb must decide what action to take: serve a file, or
  9294. * a directory, or call embedded function, etcetera. */
  9295. static void
  9296. handle_request(struct mg_connection *conn)
  9297. {
  9298. struct mg_request_info *ri = &conn->request_info;
  9299. char path[PATH_MAX];
  9300. int uri_len, ssl_index;
  9301. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9302. is_put_or_delete_request = 0, is_callback_resource = 0;
  9303. int i;
  9304. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9305. mg_request_handler callback_handler = NULL;
  9306. struct mg_websocket_subprotocols *subprotocols;
  9307. mg_websocket_connect_handler ws_connect_handler = NULL;
  9308. mg_websocket_ready_handler ws_ready_handler = NULL;
  9309. mg_websocket_data_handler ws_data_handler = NULL;
  9310. mg_websocket_close_handler ws_close_handler = NULL;
  9311. void *callback_data = NULL;
  9312. mg_authorization_handler auth_handler = NULL;
  9313. void *auth_callback_data = NULL;
  9314. #if !defined(NO_FILES)
  9315. time_t curtime = time(NULL);
  9316. char date[64];
  9317. #endif
  9318. path[0] = 0;
  9319. if (!ri) {
  9320. return;
  9321. }
  9322. /* 1. get the request url */
  9323. /* 1.1. split into url and query string */
  9324. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9325. != NULL) {
  9326. *((char *)conn->request_info.query_string++) = '\0';
  9327. }
  9328. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9329. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9330. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9331. if (ssl_index >= 0) {
  9332. redirect_to_https_port(conn, ssl_index);
  9333. } else {
  9334. /* A http to https forward port has been specified,
  9335. * but no https port to forward to. */
  9336. send_http_error(conn,
  9337. 503,
  9338. "%s",
  9339. "Error: SSL forward not configured properly");
  9340. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9341. }
  9342. return;
  9343. }
  9344. uri_len = (int)strlen(ri->local_uri);
  9345. /* 1.3. decode url (if config says so) */
  9346. if (should_decode_url(conn)) {
  9347. mg_url_decode(
  9348. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9349. }
  9350. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9351. * not possible */
  9352. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9353. /* step 1. completed, the url is known now */
  9354. uri_len = (int)strlen(ri->local_uri);
  9355. DEBUG_TRACE("URL: %s", ri->local_uri);
  9356. /* 3. if this ip has limited speed, set it for this connection */
  9357. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9358. get_remote_ip(conn),
  9359. ri->local_uri);
  9360. /* 4. call a "handle everything" callback, if registered */
  9361. if (conn->ctx->callbacks.begin_request != NULL) {
  9362. /* Note that since V1.7 the "begin_request" function is called
  9363. * before an authorization check. If an authorization check is
  9364. * required, use a request_handler instead. */
  9365. i = conn->ctx->callbacks.begin_request(conn);
  9366. if (i > 0) {
  9367. /* callback already processed the request. Store the
  9368. return value as a status code for the access log. */
  9369. conn->status_code = i;
  9370. discard_unread_request_data(conn);
  9371. return;
  9372. } else if (i == 0) {
  9373. /* civetweb should process the request */
  9374. } else {
  9375. /* unspecified - may change with the next version */
  9376. return;
  9377. }
  9378. }
  9379. /* request not yet handled by a handler or redirect, so the request
  9380. * is processed here */
  9381. /* 5. interpret the url to find out how the request must be handled
  9382. */
  9383. /* 5.1. first test, if the request targets the regular http(s)://
  9384. * protocol namespace or the websocket ws(s):// protocol namespace.
  9385. */
  9386. is_websocket_request = is_websocket_protocol(conn);
  9387. /* 5.2. check if the request will be handled by a callback */
  9388. if (get_request_handler(conn,
  9389. is_websocket_request ? WEBSOCKET_HANDLER
  9390. : REQUEST_HANDLER,
  9391. &callback_handler,
  9392. &subprotocols,
  9393. &ws_connect_handler,
  9394. &ws_ready_handler,
  9395. &ws_data_handler,
  9396. &ws_close_handler,
  9397. NULL,
  9398. &callback_data)) {
  9399. /* 5.2.1. A callback will handle this request. All requests
  9400. * handled
  9401. * by a callback have to be considered as requests to a script
  9402. * resource. */
  9403. is_callback_resource = 1;
  9404. is_script_resource = 1;
  9405. is_put_or_delete_request = is_put_or_delete_method(conn);
  9406. } else {
  9407. no_callback_resource:
  9408. /* 5.2.2. No callback is responsible for this request. The URI
  9409. * addresses a file based resource (static content or Lua/cgi
  9410. * scripts in the file system). */
  9411. is_callback_resource = 0;
  9412. interpret_uri(conn,
  9413. path,
  9414. sizeof(path),
  9415. &file.stat,
  9416. &is_found,
  9417. &is_script_resource,
  9418. &is_websocket_request,
  9419. &is_put_or_delete_request);
  9420. }
  9421. /* 6. authorization check */
  9422. /* 6.1. a custom authorization handler is installed */
  9423. if (get_request_handler(conn,
  9424. AUTH_HANDLER,
  9425. NULL,
  9426. NULL,
  9427. NULL,
  9428. NULL,
  9429. NULL,
  9430. NULL,
  9431. &auth_handler,
  9432. &auth_callback_data)) {
  9433. if (!auth_handler(conn, auth_callback_data)) {
  9434. return;
  9435. }
  9436. } else if (is_put_or_delete_request && !is_script_resource
  9437. && !is_callback_resource) {
  9438. /* 6.2. this request is a PUT/DELETE to a real file */
  9439. /* 6.2.1. thus, the server must have real files */
  9440. #if defined(NO_FILES)
  9441. if (1) {
  9442. #else
  9443. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9444. #endif
  9445. /* This server does not have any real files, thus the
  9446. * PUT/DELETE methods are not valid. */
  9447. send_http_error(conn,
  9448. 405,
  9449. "%s method not allowed",
  9450. conn->request_info.request_method);
  9451. return;
  9452. }
  9453. #if !defined(NO_FILES)
  9454. /* 6.2.2. Check if put authorization for static files is
  9455. * available.
  9456. */
  9457. if (!is_authorized_for_put(conn)) {
  9458. send_authorization_request(conn);
  9459. return;
  9460. }
  9461. #endif
  9462. } else {
  9463. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9464. * or it is a PUT or DELETE request to a resource that does not
  9465. * correspond to a file. Check authorization. */
  9466. if (!check_authorization(conn, path)) {
  9467. send_authorization_request(conn);
  9468. return;
  9469. }
  9470. }
  9471. /* request is authorized or does not need authorization */
  9472. /* 7. check if there are request handlers for this uri */
  9473. if (is_callback_resource) {
  9474. if (!is_websocket_request) {
  9475. i = callback_handler(conn, callback_data);
  9476. if (i > 0) {
  9477. /* Do nothing, callback has served the request. Store
  9478. * the
  9479. * return value as status code for the log and discard
  9480. * all
  9481. * data from the client not used by the callback. */
  9482. conn->status_code = i;
  9483. discard_unread_request_data(conn);
  9484. } else {
  9485. /* TODO (high): what if the handler did NOT handle the
  9486. * request */
  9487. /* The last version did handle this as a file request,
  9488. * but
  9489. * since a file request is not always a script resource,
  9490. * the authorization check might be different */
  9491. interpret_uri(conn,
  9492. path,
  9493. sizeof(path),
  9494. &file.stat,
  9495. &is_found,
  9496. &is_script_resource,
  9497. &is_websocket_request,
  9498. &is_put_or_delete_request);
  9499. callback_handler = NULL;
  9500. /* Here we are at a dead end:
  9501. * According to URI matching, a callback should be
  9502. * responsible for handling the request,
  9503. * we called it, but the callback declared itself
  9504. * not responsible.
  9505. * We use a goto here, to get out of this dead end,
  9506. * and continue with the default handling.
  9507. * A goto here is simpler and better to understand
  9508. * than some curious loop. */
  9509. goto no_callback_resource;
  9510. }
  9511. } else {
  9512. #if defined(USE_WEBSOCKET)
  9513. handle_websocket_request(conn,
  9514. path,
  9515. is_callback_resource,
  9516. subprotocols,
  9517. ws_connect_handler,
  9518. ws_ready_handler,
  9519. ws_data_handler,
  9520. ws_close_handler,
  9521. callback_data);
  9522. #endif
  9523. }
  9524. return;
  9525. }
  9526. /* 8. handle websocket requests */
  9527. #if defined(USE_WEBSOCKET)
  9528. if (is_websocket_request) {
  9529. if (is_script_resource) {
  9530. /* Websocket Lua script */
  9531. handle_websocket_request(conn,
  9532. path,
  9533. 0 /* Lua Script */,
  9534. NULL,
  9535. NULL,
  9536. NULL,
  9537. NULL,
  9538. NULL,
  9539. &conn->ctx->callbacks);
  9540. } else {
  9541. #if defined(MG_LEGACY_INTERFACE)
  9542. handle_websocket_request(
  9543. conn,
  9544. path,
  9545. !is_script_resource /* could be deprecated global callback */,
  9546. NULL,
  9547. deprecated_websocket_connect_wrapper,
  9548. deprecated_websocket_ready_wrapper,
  9549. deprecated_websocket_data_wrapper,
  9550. NULL,
  9551. &conn->ctx->callbacks);
  9552. #else
  9553. send_http_error(conn, 404, "%s", "Not found");
  9554. #endif
  9555. }
  9556. return;
  9557. } else
  9558. #endif
  9559. #if defined(NO_FILES)
  9560. /* 9a. In case the server uses only callbacks, this uri is
  9561. * unknown.
  9562. * Then, all request handling ends here. */
  9563. send_http_error(conn, 404, "%s", "Not Found");
  9564. #else
  9565. /* 9b. This request is either for a static file or resource handled
  9566. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9567. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9568. send_http_error(conn, 404, "%s", "Not Found");
  9569. return;
  9570. }
  9571. /* 10. File is handled by a script. */
  9572. if (is_script_resource) {
  9573. handle_file_based_request(conn, path, &file);
  9574. return;
  9575. }
  9576. /* 11. Handle put/delete/mkcol requests */
  9577. if (is_put_or_delete_request) {
  9578. /* 11.1. PUT method */
  9579. if (!strcmp(ri->request_method, "PUT")) {
  9580. put_file(conn, path);
  9581. return;
  9582. }
  9583. /* 11.2. DELETE method */
  9584. if (!strcmp(ri->request_method, "DELETE")) {
  9585. delete_file(conn, path);
  9586. return;
  9587. }
  9588. /* 11.3. MKCOL method */
  9589. if (!strcmp(ri->request_method, "MKCOL")) {
  9590. mkcol(conn, path);
  9591. return;
  9592. }
  9593. /* 11.4. PATCH method
  9594. * This method is not supported for static resources,
  9595. * only for scripts (Lua, CGI) and callbacks. */
  9596. send_http_error(conn,
  9597. 405,
  9598. "%s method not allowed",
  9599. conn->request_info.request_method);
  9600. return;
  9601. }
  9602. /* 11. File does not exist, or it was configured that it should be
  9603. * hidden */
  9604. if (!is_found || (must_hide_file(conn, path))) {
  9605. send_http_error(conn, 404, "%s", "Not found");
  9606. return;
  9607. }
  9608. /* 12. Directory uris should end with a slash */
  9609. if (file.stat.is_directory && (uri_len > 0)
  9610. && (ri->local_uri[uri_len - 1] != '/')) {
  9611. gmt_time_string(date, sizeof(date), &curtime);
  9612. mg_printf(conn,
  9613. "HTTP/1.1 301 Moved Permanently\r\n"
  9614. "Location: %s/\r\n"
  9615. "Date: %s\r\n"
  9616. /* "Cache-Control: private\r\n" (= default) */
  9617. "Content-Length: 0\r\n"
  9618. "Connection: %s\r\n\r\n",
  9619. ri->request_uri,
  9620. date,
  9621. suggest_connection_header(conn));
  9622. return;
  9623. }
  9624. /* 13. Handle other methods than GET/HEAD */
  9625. /* 13.1. Handle PROPFIND */
  9626. if (!strcmp(ri->request_method, "PROPFIND")) {
  9627. handle_propfind(conn, path, &file.stat);
  9628. return;
  9629. }
  9630. /* 13.2. Handle OPTIONS for files */
  9631. if (!strcmp(ri->request_method, "OPTIONS")) {
  9632. /* This standard handler is only used for real files.
  9633. * Scripts should support the OPTIONS method themselves, to allow a
  9634. * maximum flexibility.
  9635. * Lua and CGI scripts may fully support CORS this way (including
  9636. * preflights). */
  9637. send_options(conn);
  9638. return;
  9639. }
  9640. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9641. if (0 != strcmp(ri->request_method, "GET")
  9642. && 0 != strcmp(ri->request_method, "HEAD")) {
  9643. send_http_error(conn,
  9644. 405,
  9645. "%s method not allowed",
  9646. conn->request_info.request_method);
  9647. return;
  9648. }
  9649. /* 14. directories */
  9650. if (file.stat.is_directory) {
  9651. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9652. /* 14.1. use a substitute file */
  9653. /* TODO (high): substitute index may be a script resource.
  9654. * define what should be possible in this case. */
  9655. } else {
  9656. /* 14.2. no substitute file */
  9657. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9658. "yes")) {
  9659. handle_directory_request(conn, path);
  9660. } else {
  9661. send_http_error(conn,
  9662. 403,
  9663. "%s",
  9664. "Error: Directory listing denied");
  9665. }
  9666. return;
  9667. }
  9668. }
  9669. handle_file_based_request(conn, path, &file);
  9670. #endif /* !defined(NO_FILES) */
  9671. #if 0
  9672. /* Perform redirect and auth checks before calling begin_request()
  9673. * handler.
  9674. * Otherwise, begin_request() would need to perform auth checks and
  9675. * redirects. */
  9676. #endif
  9677. }
  9678. static void
  9679. handle_file_based_request(struct mg_connection *conn,
  9680. const char *path,
  9681. struct mg_file *file)
  9682. {
  9683. if (!conn || !conn->ctx) {
  9684. return;
  9685. }
  9686. if (0) {
  9687. #ifdef USE_LUA
  9688. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9689. strlen(
  9690. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9691. path) > 0) {
  9692. /* Lua server page: an SSI like page containing mostly plain html
  9693. * code
  9694. * plus some tags with server generated contents. */
  9695. handle_lsp_request(conn, path, file, NULL);
  9696. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9697. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9698. path) > 0) {
  9699. /* Lua in-server module script: a CGI like script used to generate
  9700. * the
  9701. * entire reply. */
  9702. mg_exec_lua_script(conn, path, NULL);
  9703. #endif
  9704. #if defined(USE_DUKTAPE)
  9705. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9706. strlen(
  9707. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9708. path) > 0) {
  9709. /* Call duktape to generate the page */
  9710. mg_exec_duktape_script(conn, path);
  9711. #endif
  9712. #if !defined(NO_CGI)
  9713. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9714. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9715. path) > 0) {
  9716. /* CGI scripts may support all HTTP methods */
  9717. handle_cgi_request(conn, path);
  9718. #endif /* !NO_CGI */
  9719. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9720. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9721. path) > 0) {
  9722. handle_ssi_file_request(conn, path, file);
  9723. #if !defined(NO_CACHING)
  9724. } else if ((!conn->in_error_handler)
  9725. && is_not_modified(conn, &file->stat)) {
  9726. /* Send 304 "Not Modified" - this must not send any body data */
  9727. handle_not_modified_static_file_request(conn, file);
  9728. #endif /* !NO_CACHING */
  9729. } else {
  9730. handle_static_file_request(conn, path, file, NULL, NULL);
  9731. }
  9732. }
  9733. static void
  9734. close_all_listening_sockets(struct mg_context *ctx)
  9735. {
  9736. unsigned int i;
  9737. if (!ctx) {
  9738. return;
  9739. }
  9740. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9741. closesocket(ctx->listening_sockets[i].sock);
  9742. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9743. }
  9744. mg_free(ctx->listening_sockets);
  9745. ctx->listening_sockets = NULL;
  9746. mg_free(ctx->listening_socket_fds);
  9747. ctx->listening_socket_fds = NULL;
  9748. }
  9749. /* Valid listening port specification is: [ip_address:]port[s]
  9750. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9751. * Examples for IPv6: [::]:80, [::1]:80,
  9752. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9753. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9754. * In order to bind to both, IPv4 and IPv6, you can either add
  9755. * both ports using 8080,[::]:8080, or the short form +8080.
  9756. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9757. * one only accepting IPv4 the other only IPv6. +8080 creates
  9758. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9759. * environment, they might work differently, or might not work
  9760. * at all - it must be tested what options work best in the
  9761. * relevant network environment.
  9762. */
  9763. static int
  9764. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9765. {
  9766. unsigned int a, b, c, d, port;
  9767. int ch, len;
  9768. #if defined(USE_IPV6)
  9769. char buf[100] = {0};
  9770. #endif
  9771. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9772. * Also, all-zeroes in the socket address means binding to all addresses
  9773. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9774. memset(so, 0, sizeof(*so));
  9775. so->lsa.sin.sin_family = AF_INET;
  9776. *ip_version = 0;
  9777. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9778. == 5) {
  9779. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9780. so->lsa.sin.sin_addr.s_addr =
  9781. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9782. so->lsa.sin.sin_port = htons((uint16_t)port);
  9783. *ip_version = 4;
  9784. #if defined(USE_IPV6)
  9785. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9786. && mg_inet_pton(
  9787. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9788. /* IPv6 address, examples: see above */
  9789. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9790. */
  9791. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9792. *ip_version = 6;
  9793. #endif
  9794. } else if ((vec->ptr[0] == '+')
  9795. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9796. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9797. /* Add 1 to len for the + character we skipped before */
  9798. len++;
  9799. #if defined(USE_IPV6)
  9800. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9801. so->lsa.sin6.sin6_family = AF_INET6;
  9802. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9803. *ip_version = 4 + 6;
  9804. #else
  9805. /* Bind to IPv4 only, since IPv6 is not built in. */
  9806. so->lsa.sin.sin_port = htons((uint16_t)port);
  9807. *ip_version = 4;
  9808. #endif
  9809. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9810. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9811. so->lsa.sin.sin_port = htons((uint16_t)port);
  9812. *ip_version = 4;
  9813. } else {
  9814. /* Parsing failure. Make port invalid. */
  9815. port = 0;
  9816. len = 0;
  9817. }
  9818. /* sscanf and the option splitting code ensure the following condition
  9819. */
  9820. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9821. *ip_version = 0;
  9822. return 0;
  9823. }
  9824. ch = vec->ptr[len]; /* Next character after the port number */
  9825. so->is_ssl = (ch == 's');
  9826. so->ssl_redir = (ch == 'r');
  9827. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9828. if (is_valid_port(port)
  9829. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9830. return 1;
  9831. }
  9832. /* Reset ip_version to 0 of there is an error */
  9833. *ip_version = 0;
  9834. return 0;
  9835. }
  9836. static int
  9837. set_ports_option(struct mg_context *ctx)
  9838. {
  9839. const char *list;
  9840. int on = 1;
  9841. #if defined(USE_IPV6)
  9842. int off = 0;
  9843. #endif
  9844. struct vec vec;
  9845. struct socket so, *ptr;
  9846. struct pollfd *pfd;
  9847. union usa usa;
  9848. socklen_t len;
  9849. int ip_version;
  9850. int portsTotal = 0;
  9851. int portsOk = 0;
  9852. if (!ctx) {
  9853. return 0;
  9854. }
  9855. memset(&so, 0, sizeof(so));
  9856. memset(&usa, 0, sizeof(usa));
  9857. len = sizeof(usa);
  9858. list = ctx->config[LISTENING_PORTS];
  9859. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9860. portsTotal++;
  9861. if (!parse_port_string(&vec, &so, &ip_version)) {
  9862. mg_cry(fc(ctx),
  9863. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9864. (int)vec.len,
  9865. vec.ptr,
  9866. portsTotal,
  9867. "[IP_ADDRESS:]PORT[s|r]");
  9868. continue;
  9869. }
  9870. #if !defined(NO_SSL)
  9871. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9872. mg_cry(fc(ctx),
  9873. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9874. "option set?",
  9875. portsTotal);
  9876. continue;
  9877. }
  9878. #endif
  9879. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9880. == INVALID_SOCKET) {
  9881. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9882. continue;
  9883. }
  9884. #ifdef _WIN32
  9885. /* Windows SO_REUSEADDR lets many procs binds to a
  9886. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9887. * if someone already has the socket -- DTL */
  9888. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9889. * Windows might need a few seconds before
  9890. * the same port can be used again in the
  9891. * same process, so a short Sleep may be
  9892. * required between mg_stop and mg_start.
  9893. */
  9894. if (setsockopt(so.sock,
  9895. SOL_SOCKET,
  9896. SO_EXCLUSIVEADDRUSE,
  9897. (SOCK_OPT_TYPE)&on,
  9898. sizeof(on)) != 0) {
  9899. /* Set reuse option, but don't abort on errors. */
  9900. mg_cry(fc(ctx),
  9901. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9902. portsTotal);
  9903. }
  9904. #else
  9905. if (setsockopt(so.sock,
  9906. SOL_SOCKET,
  9907. SO_REUSEADDR,
  9908. (SOCK_OPT_TYPE)&on,
  9909. sizeof(on)) != 0) {
  9910. /* Set reuse option, but don't abort on errors. */
  9911. mg_cry(fc(ctx),
  9912. "cannot set socket option SO_REUSEADDR (entry %i)",
  9913. portsTotal);
  9914. }
  9915. #endif
  9916. if (ip_version > 4) {
  9917. #if defined(USE_IPV6)
  9918. if (ip_version == 6) {
  9919. if (so.lsa.sa.sa_family == AF_INET6
  9920. && setsockopt(so.sock,
  9921. IPPROTO_IPV6,
  9922. IPV6_V6ONLY,
  9923. (void *)&off,
  9924. sizeof(off)) != 0) {
  9925. /* Set IPv6 only option, but don't abort on errors. */
  9926. mg_cry(fc(ctx),
  9927. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9928. portsTotal);
  9929. }
  9930. }
  9931. #else
  9932. mg_cry(fc(ctx), "IPv6 not available");
  9933. closesocket(so.sock);
  9934. so.sock = INVALID_SOCKET;
  9935. continue;
  9936. #endif
  9937. }
  9938. if (so.lsa.sa.sa_family == AF_INET) {
  9939. len = sizeof(so.lsa.sin);
  9940. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9941. mg_cry(fc(ctx),
  9942. "cannot bind to %.*s: %d (%s)",
  9943. (int)vec.len,
  9944. vec.ptr,
  9945. (int)ERRNO,
  9946. strerror(errno));
  9947. closesocket(so.sock);
  9948. so.sock = INVALID_SOCKET;
  9949. continue;
  9950. }
  9951. }
  9952. #if defined(USE_IPV6)
  9953. else if (so.lsa.sa.sa_family == AF_INET6) {
  9954. len = sizeof(so.lsa.sin6);
  9955. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9956. mg_cry(fc(ctx),
  9957. "cannot bind to IPv6 %.*s: %d (%s)",
  9958. (int)vec.len,
  9959. vec.ptr,
  9960. (int)ERRNO,
  9961. strerror(errno));
  9962. closesocket(so.sock);
  9963. so.sock = INVALID_SOCKET;
  9964. continue;
  9965. }
  9966. }
  9967. #endif
  9968. else {
  9969. mg_cry(fc(ctx),
  9970. "cannot bind: address family not supported (entry %i)",
  9971. portsTotal);
  9972. continue;
  9973. }
  9974. if (listen(so.sock, SOMAXCONN) != 0) {
  9975. mg_cry(fc(ctx),
  9976. "cannot listen to %.*s: %d (%s)",
  9977. (int)vec.len,
  9978. vec.ptr,
  9979. (int)ERRNO,
  9980. strerror(errno));
  9981. closesocket(so.sock);
  9982. so.sock = INVALID_SOCKET;
  9983. continue;
  9984. }
  9985. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9986. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9987. int err = (int)ERRNO;
  9988. mg_cry(fc(ctx),
  9989. "call to getsockname failed %.*s: %d (%s)",
  9990. (int)vec.len,
  9991. vec.ptr,
  9992. err,
  9993. strerror(errno));
  9994. closesocket(so.sock);
  9995. so.sock = INVALID_SOCKET;
  9996. continue;
  9997. }
  9998. /* Update lsa port in case of random free ports */
  9999. #if defined(USE_IPV6)
  10000. if (so.lsa.sa.sa_family == AF_INET6) {
  10001. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10002. } else
  10003. #endif
  10004. {
  10005. so.lsa.sin.sin_port = usa.sin.sin_port;
  10006. }
  10007. if ((ptr = (struct socket *)
  10008. mg_realloc(ctx->listening_sockets,
  10009. (ctx->num_listening_sockets + 1)
  10010. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  10011. mg_cry(fc(ctx), "%s", "Out of memory");
  10012. closesocket(so.sock);
  10013. so.sock = INVALID_SOCKET;
  10014. continue;
  10015. }
  10016. if ((pfd = (struct pollfd *)mg_realloc(
  10017. ctx->listening_socket_fds,
  10018. (ctx->num_listening_sockets + 1)
  10019. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  10020. mg_cry(fc(ctx), "%s", "Out of memory");
  10021. closesocket(so.sock);
  10022. so.sock = INVALID_SOCKET;
  10023. mg_free(ptr);
  10024. continue;
  10025. }
  10026. set_close_on_exec(so.sock, fc(ctx));
  10027. ctx->listening_sockets = ptr;
  10028. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10029. ctx->listening_socket_fds = pfd;
  10030. ctx->num_listening_sockets++;
  10031. portsOk++;
  10032. }
  10033. if (portsOk != portsTotal) {
  10034. close_all_listening_sockets(ctx);
  10035. portsOk = 0;
  10036. }
  10037. return portsOk;
  10038. }
  10039. static const char *
  10040. header_val(const struct mg_connection *conn, const char *header)
  10041. {
  10042. const char *header_value;
  10043. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10044. return "-";
  10045. } else {
  10046. return header_value;
  10047. }
  10048. }
  10049. static void
  10050. log_access(const struct mg_connection *conn)
  10051. {
  10052. const struct mg_request_info *ri;
  10053. struct mg_file fi;
  10054. char date[64], src_addr[IP_ADDR_STR_LEN];
  10055. struct tm *tm;
  10056. const char *referer;
  10057. const char *user_agent;
  10058. char buf[4096];
  10059. if (!conn || !conn->ctx) {
  10060. return;
  10061. }
  10062. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10063. if (mg_fopen(conn,
  10064. conn->ctx->config[ACCESS_LOG_FILE],
  10065. MG_FOPEN_MODE_APPEND,
  10066. &fi) == 0) {
  10067. fi.access.fp = NULL;
  10068. }
  10069. } else {
  10070. fi.access.fp = NULL;
  10071. }
  10072. /* Log is written to a file and/or a callback. If both are not set,
  10073. * executing the rest of the function is pointless. */
  10074. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10075. return;
  10076. }
  10077. tm = localtime(&conn->conn_birth_time);
  10078. if (tm != NULL) {
  10079. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10080. } else {
  10081. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10082. date[sizeof(date) - 1] = '\0';
  10083. }
  10084. ri = &conn->request_info;
  10085. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10086. referer = header_val(conn, "Referer");
  10087. user_agent = header_val(conn, "User-Agent");
  10088. mg_snprintf(conn,
  10089. NULL, /* Ignore truncation in access log */
  10090. buf,
  10091. sizeof(buf),
  10092. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10093. src_addr,
  10094. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10095. date,
  10096. ri->request_method ? ri->request_method : "-",
  10097. ri->request_uri ? ri->request_uri : "-",
  10098. ri->query_string ? "?" : "",
  10099. ri->query_string ? ri->query_string : "",
  10100. ri->http_version,
  10101. conn->status_code,
  10102. conn->num_bytes_sent,
  10103. referer,
  10104. user_agent);
  10105. if (conn->ctx->callbacks.log_access) {
  10106. conn->ctx->callbacks.log_access(conn, buf);
  10107. }
  10108. if (fi.access.fp) {
  10109. int ok = 1;
  10110. flockfile(fi.access.fp);
  10111. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10112. ok = 0;
  10113. }
  10114. if (fflush(fi.access.fp) != 0) {
  10115. ok = 0;
  10116. }
  10117. funlockfile(fi.access.fp);
  10118. if (mg_fclose(&fi.access) != 0) {
  10119. ok = 0;
  10120. }
  10121. if (!ok) {
  10122. mg_cry(conn,
  10123. "Error writing log file %s",
  10124. conn->ctx->config[ACCESS_LOG_FILE]);
  10125. }
  10126. }
  10127. }
  10128. /* Verify given socket address against the ACL.
  10129. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10130. */
  10131. static int
  10132. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10133. {
  10134. int allowed, flag;
  10135. uint32_t net, mask;
  10136. struct vec vec;
  10137. if (ctx) {
  10138. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10139. /* If any ACL is set, deny by default */
  10140. allowed = (list == NULL) ? '+' : '-';
  10141. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10142. flag = vec.ptr[0];
  10143. if ((flag != '+' && flag != '-')
  10144. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10145. mg_cry(fc(ctx),
  10146. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10147. __func__);
  10148. return -1;
  10149. }
  10150. if (net == (remote_ip & mask)) {
  10151. allowed = flag;
  10152. }
  10153. }
  10154. return allowed == '+';
  10155. }
  10156. return -1;
  10157. }
  10158. #if !defined(_WIN32)
  10159. static int
  10160. set_uid_option(struct mg_context *ctx)
  10161. {
  10162. struct passwd *pw;
  10163. if (ctx) {
  10164. const char *uid = ctx->config[RUN_AS_USER];
  10165. int success = 0;
  10166. if (uid == NULL) {
  10167. success = 1;
  10168. } else {
  10169. if ((pw = getpwnam(uid)) == NULL) {
  10170. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10171. } else if (setgid(pw->pw_gid) == -1) {
  10172. mg_cry(fc(ctx),
  10173. "%s: setgid(%s): %s",
  10174. __func__,
  10175. uid,
  10176. strerror(errno));
  10177. } else if (setgroups(0, NULL)) {
  10178. mg_cry(fc(ctx),
  10179. "%s: setgroups(): %s",
  10180. __func__,
  10181. strerror(errno));
  10182. } else if (setuid(pw->pw_uid) == -1) {
  10183. mg_cry(fc(ctx),
  10184. "%s: setuid(%s): %s",
  10185. __func__,
  10186. uid,
  10187. strerror(errno));
  10188. } else {
  10189. success = 1;
  10190. }
  10191. }
  10192. return success;
  10193. }
  10194. return 0;
  10195. }
  10196. #endif /* !_WIN32 */
  10197. static void
  10198. tls_dtor(void *key)
  10199. {
  10200. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10201. /* key == pthread_getspecific(sTlsKey); */
  10202. if (tls) {
  10203. if (tls->is_master == 2) {
  10204. tls->is_master = -3; /* Mark memory as dead */
  10205. mg_free(tls);
  10206. }
  10207. }
  10208. pthread_setspecific(sTlsKey, NULL);
  10209. }
  10210. #if !defined(NO_SSL)
  10211. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10212. static const char *ssl_error(void);
  10213. static int
  10214. refresh_trust(struct mg_connection *conn)
  10215. {
  10216. static int reload_lock = 0;
  10217. static long int data_check = 0;
  10218. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10219. struct stat cert_buf;
  10220. long int t;
  10221. char *pem;
  10222. int should_verify_peer;
  10223. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10224. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10225. * refresh_trust still can not work. */
  10226. return 0;
  10227. }
  10228. t = data_check;
  10229. if (stat(pem, &cert_buf) != -1) {
  10230. t = (long int)cert_buf.st_mtime;
  10231. }
  10232. if (data_check != t) {
  10233. data_check = t;
  10234. should_verify_peer =
  10235. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10236. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10237. == 0);
  10238. if (should_verify_peer) {
  10239. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10240. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10241. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10242. ca_file,
  10243. ca_path) != 1) {
  10244. mg_cry(fc(conn->ctx),
  10245. "SSL_CTX_load_verify_locations error: %s "
  10246. "ssl_verify_peer requires setting "
  10247. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10248. "present in "
  10249. "the .conf file?",
  10250. ssl_error());
  10251. return 0;
  10252. }
  10253. }
  10254. if (1 == mg_atomic_inc(p_reload_lock)) {
  10255. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10256. return 0;
  10257. }
  10258. *p_reload_lock = 0;
  10259. }
  10260. }
  10261. /* lock while cert is reloading */
  10262. while (*p_reload_lock) {
  10263. sleep(1);
  10264. }
  10265. return 1;
  10266. }
  10267. #ifdef OPENSSL_API_1_1
  10268. #else
  10269. static pthread_mutex_t *ssl_mutexes;
  10270. #endif /* OPENSSL_API_1_1 */
  10271. static int
  10272. sslize(struct mg_connection *conn,
  10273. SSL_CTX *s,
  10274. int (*func)(SSL *),
  10275. volatile int *stop_server)
  10276. {
  10277. int ret, err;
  10278. int short_trust;
  10279. unsigned i;
  10280. if (!conn) {
  10281. return 0;
  10282. }
  10283. short_trust =
  10284. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10285. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10286. if (short_trust) {
  10287. int trust_ret = refresh_trust(conn);
  10288. if (!trust_ret) {
  10289. return trust_ret;
  10290. }
  10291. }
  10292. conn->ssl = SSL_new(s);
  10293. if (conn->ssl == NULL) {
  10294. return 0;
  10295. }
  10296. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10297. if (ret != 1) {
  10298. err = SSL_get_error(conn->ssl, ret);
  10299. (void)err; /* TODO: set some error message */
  10300. SSL_free(conn->ssl);
  10301. conn->ssl = NULL;
  10302. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10303. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10304. #ifndef OPENSSL_API_1_1
  10305. ERR_remove_state(0);
  10306. #endif
  10307. return 0;
  10308. }
  10309. /* SSL functions may fail and require to be called again:
  10310. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10311. * Here "func" could be SSL_connect or SSL_accept. */
  10312. for (i = 16; i <= 1024; i *= 2) {
  10313. ret = func(conn->ssl);
  10314. if (ret != 1) {
  10315. err = SSL_get_error(conn->ssl, ret);
  10316. if ((err == SSL_ERROR_WANT_CONNECT)
  10317. || (err == SSL_ERROR_WANT_ACCEPT)
  10318. || (err == SSL_ERROR_WANT_READ)
  10319. || (err == SSL_ERROR_WANT_WRITE)) {
  10320. /* Need to retry the function call "later".
  10321. * See https://linux.die.net/man/3/ssl_get_error
  10322. * This is typical for non-blocking sockets. */
  10323. if (*stop_server) {
  10324. /* Don't wait if the server is going to be stopped. */
  10325. break;
  10326. }
  10327. mg_sleep(i);
  10328. } else if (err == SSL_ERROR_SYSCALL) {
  10329. /* This is an IO error. Look at errno. */
  10330. err = errno;
  10331. /* TODO: set some error message */
  10332. break;
  10333. } else {
  10334. /* This is an SSL specific error */
  10335. /* TODO: set some error message */
  10336. break;
  10337. }
  10338. } else {
  10339. /* success */
  10340. break;
  10341. }
  10342. }
  10343. if (ret != 1) {
  10344. SSL_free(conn->ssl);
  10345. conn->ssl = NULL;
  10346. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10347. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10348. #ifndef OPENSSL_API_1_1
  10349. ERR_remove_state(0);
  10350. #endif
  10351. return 0;
  10352. }
  10353. return 1;
  10354. }
  10355. /* Return OpenSSL error message (from CRYPTO lib) */
  10356. static const char *
  10357. ssl_error(void)
  10358. {
  10359. unsigned long err;
  10360. err = ERR_get_error();
  10361. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10362. }
  10363. static int
  10364. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10365. {
  10366. int i;
  10367. const char hexdigit[] = "0123456789abcdef";
  10368. if (memlen <= 0 || buflen <= 0) {
  10369. return 0;
  10370. }
  10371. if (buflen < (3 * memlen)) {
  10372. return 0;
  10373. }
  10374. for (i = 0; i < memlen; i++) {
  10375. if (i > 0) {
  10376. buf[3 * i - 1] = ' ';
  10377. }
  10378. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10379. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10380. }
  10381. buf[3 * memlen - 1] = 0;
  10382. return 1;
  10383. }
  10384. static void
  10385. ssl_get_client_cert_info(struct mg_connection *conn)
  10386. {
  10387. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10388. if (cert) {
  10389. char str_subject[1024];
  10390. char str_issuer[1024];
  10391. char str_finger[1024];
  10392. unsigned char buf[256];
  10393. char *str_serial = NULL;
  10394. unsigned int ulen;
  10395. /* Handle to algorithm used for fingerprint */
  10396. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10397. /* Get Subject and issuer */
  10398. X509_NAME *subj = X509_get_subject_name(cert);
  10399. X509_NAME *iss = X509_get_issuer_name(cert);
  10400. /* Get serial number */
  10401. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10402. /* Translate serial number to a hex string */
  10403. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10404. str_serial = BN_bn2hex(serial_bn);
  10405. BN_free(serial_bn);
  10406. /* Translate subject and issuer to a string */
  10407. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10408. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10409. /* Calculate SHA1 fingerprint and store as a hex string */
  10410. ulen = 0;
  10411. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10412. if (!hexdump2string(
  10413. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10414. *str_finger = 0;
  10415. }
  10416. conn->request_info.client_cert =
  10417. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10418. if (conn->request_info.client_cert) {
  10419. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10420. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10421. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10422. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10423. } else {
  10424. /* TODO: write some OOM message */
  10425. }
  10426. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10427. * see https://linux.die.net/man/3/bn_bn2hex */
  10428. OPENSSL_free(str_serial);
  10429. /* Free certificate memory */
  10430. X509_free(cert);
  10431. }
  10432. }
  10433. #ifdef OPENSSL_API_1_1
  10434. #else
  10435. static void
  10436. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10437. {
  10438. (void)line;
  10439. (void)file;
  10440. if (mode & 1) {
  10441. /* 1 is CRYPTO_LOCK */
  10442. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10443. } else {
  10444. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10445. }
  10446. }
  10447. #endif /* OPENSSL_API_1_1 */
  10448. #if !defined(NO_SSL_DL)
  10449. static void *
  10450. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10451. {
  10452. union {
  10453. void *p;
  10454. void (*fp)(void);
  10455. } u;
  10456. void *dll_handle;
  10457. struct ssl_func *fp;
  10458. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10459. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10460. return NULL;
  10461. }
  10462. for (fp = sw; fp->name != NULL; fp++) {
  10463. #ifdef _WIN32
  10464. /* GetProcAddress() returns pointer to function */
  10465. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10466. #else
  10467. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10468. * pointers to function pointers. We need to use a union to make a
  10469. * cast. */
  10470. u.p = dlsym(dll_handle, fp->name);
  10471. #endif /* _WIN32 */
  10472. if (u.fp == NULL) {
  10473. mg_cry(fc(ctx),
  10474. "%s: %s: cannot find %s",
  10475. __func__,
  10476. dll_name,
  10477. fp->name);
  10478. dlclose(dll_handle);
  10479. return NULL;
  10480. } else {
  10481. fp->ptr = u.fp;
  10482. }
  10483. }
  10484. return dll_handle;
  10485. }
  10486. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10487. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10488. #endif /* NO_SSL_DL */
  10489. #if defined(SSL_ALREADY_INITIALIZED)
  10490. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10491. #else
  10492. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10493. #endif
  10494. static int
  10495. initialize_ssl(struct mg_context *ctx)
  10496. {
  10497. #ifdef OPENSSL_API_1_1
  10498. #if !defined(NO_SSL_DL)
  10499. if (!cryptolib_dll_handle) {
  10500. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10501. if (!cryptolib_dll_handle) {
  10502. return 0;
  10503. }
  10504. }
  10505. #else
  10506. (void)ctx;
  10507. #endif /* NO_SSL_DL */
  10508. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10509. return 1;
  10510. }
  10511. #else
  10512. int i;
  10513. size_t size;
  10514. #if !defined(NO_SSL_DL)
  10515. if (!cryptolib_dll_handle) {
  10516. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10517. if (!cryptolib_dll_handle) {
  10518. return 0;
  10519. }
  10520. }
  10521. #else
  10522. (void)ctx;
  10523. #endif /* NO_SSL_DL */
  10524. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10525. return 1;
  10526. }
  10527. /* Initialize locking callbacks, needed for thread safety.
  10528. * http://www.openssl.org/support/faq.html#PROG1
  10529. */
  10530. i = CRYPTO_num_locks();
  10531. if (i < 0) {
  10532. i = 0;
  10533. }
  10534. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10535. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10536. mg_cry(fc(ctx),
  10537. "%s: cannot allocate mutexes: %s",
  10538. __func__,
  10539. ssl_error());
  10540. return 0;
  10541. }
  10542. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10543. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10544. }
  10545. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10546. CRYPTO_set_id_callback(&mg_current_thread_id);
  10547. #endif /* OPENSSL_API_1_1 */
  10548. return 1;
  10549. }
  10550. static int
  10551. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10552. {
  10553. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10554. mg_cry(fc(ctx),
  10555. "%s: cannot open certificate file %s: %s",
  10556. __func__,
  10557. pem,
  10558. ssl_error());
  10559. return 0;
  10560. }
  10561. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10562. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10563. mg_cry(fc(ctx),
  10564. "%s: cannot open private key file %s: %s",
  10565. __func__,
  10566. pem,
  10567. ssl_error());
  10568. return 0;
  10569. }
  10570. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10571. mg_cry(fc(ctx),
  10572. "%s: certificate and private key do not match: %s",
  10573. __func__,
  10574. pem);
  10575. return 0;
  10576. }
  10577. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10578. mg_cry(fc(ctx),
  10579. "%s: cannot use certificate chain file %s: %s",
  10580. __func__,
  10581. pem,
  10582. ssl_error());
  10583. return 0;
  10584. }
  10585. return 1;
  10586. }
  10587. #ifdef OPENSSL_API_1_1
  10588. static unsigned long
  10589. ssl_get_protocol(int version_id)
  10590. {
  10591. long unsigned ret = SSL_OP_ALL;
  10592. if (version_id > 0)
  10593. ret |= SSL_OP_NO_SSLv2;
  10594. if (version_id > 1)
  10595. ret |= SSL_OP_NO_SSLv3;
  10596. if (version_id > 2)
  10597. ret |= SSL_OP_NO_TLSv1;
  10598. if (version_id > 3)
  10599. ret |= SSL_OP_NO_TLSv1_1;
  10600. return ret;
  10601. }
  10602. #else
  10603. static long
  10604. ssl_get_protocol(int version_id)
  10605. {
  10606. long ret = SSL_OP_ALL;
  10607. if (version_id > 0)
  10608. ret |= SSL_OP_NO_SSLv2;
  10609. if (version_id > 1)
  10610. ret |= SSL_OP_NO_SSLv3;
  10611. if (version_id > 2)
  10612. ret |= SSL_OP_NO_TLSv1;
  10613. if (version_id > 3)
  10614. ret |= SSL_OP_NO_TLSv1_1;
  10615. return ret;
  10616. }
  10617. #endif /* OPENSSL_API_1_1 */
  10618. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10619. static int
  10620. set_ssl_option(struct mg_context *ctx)
  10621. {
  10622. const char *pem;
  10623. int callback_ret;
  10624. int should_verify_peer;
  10625. const char *ca_path;
  10626. const char *ca_file;
  10627. int use_default_verify_paths;
  10628. int verify_depth;
  10629. time_t now_rt = time(NULL);
  10630. struct timespec now_mt;
  10631. md5_byte_t ssl_context_id[16];
  10632. md5_state_t md5state;
  10633. int protocol_ver;
  10634. /* If PEM file is not specified and the init_ssl callback
  10635. * is not specified, skip SSL initialization. */
  10636. if (!ctx) {
  10637. return 0;
  10638. }
  10639. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10640. && ctx->callbacks.init_ssl == NULL) {
  10641. return 1;
  10642. }
  10643. if (!initialize_ssl(ctx)) {
  10644. return 0;
  10645. }
  10646. #if !defined(NO_SSL_DL)
  10647. if (!ssllib_dll_handle) {
  10648. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10649. if (!ssllib_dll_handle) {
  10650. return 0;
  10651. }
  10652. }
  10653. #endif /* NO_SSL_DL */
  10654. #ifdef OPENSSL_API_1_1
  10655. /* Initialize SSL library */
  10656. OPENSSL_init_ssl(0, NULL);
  10657. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  10658. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  10659. NULL);
  10660. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  10661. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10662. return 0;
  10663. }
  10664. #else
  10665. /* Initialize SSL library */
  10666. SSL_library_init();
  10667. SSL_load_error_strings();
  10668. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10669. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10670. return 0;
  10671. }
  10672. #endif /* OPENSSL_API_1_1 */
  10673. SSL_CTX_clear_options(ctx->ssl_ctx,
  10674. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10675. | SSL_OP_NO_TLSv1_1);
  10676. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10677. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10678. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10679. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10680. #if !defined(NO_SSL_DL)
  10681. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10682. #endif /* NO_SSL_DL */
  10683. /* If a callback has been specified, call it. */
  10684. callback_ret =
  10685. (ctx->callbacks.init_ssl == NULL)
  10686. ? 0
  10687. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10688. /* If callback returns 0, civetweb sets up the SSL certificate.
  10689. * If it returns 1, civetweb assumes the calback already did this.
  10690. * If it returns -1, initializing ssl fails. */
  10691. if (callback_ret < 0) {
  10692. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10693. return 0;
  10694. }
  10695. if (callback_ret > 0) {
  10696. if (pem != NULL) {
  10697. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10698. }
  10699. return 1;
  10700. }
  10701. /* Use some UID as session context ID. */
  10702. md5_init(&md5state);
  10703. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10704. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10705. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10706. md5_append(&md5state,
  10707. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10708. strlen(ctx->config[LISTENING_PORTS]));
  10709. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10710. md5_finish(&md5state, ssl_context_id);
  10711. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10712. (const unsigned char *)&ssl_context_id,
  10713. sizeof(ssl_context_id));
  10714. if (pem != NULL) {
  10715. if (!ssl_use_pem_file(ctx, pem)) {
  10716. return 0;
  10717. }
  10718. }
  10719. should_verify_peer =
  10720. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10721. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10722. use_default_verify_paths =
  10723. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10724. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10725. if (should_verify_peer) {
  10726. ca_path = ctx->config[SSL_CA_PATH];
  10727. ca_file = ctx->config[SSL_CA_FILE];
  10728. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10729. != 1) {
  10730. mg_cry(fc(ctx),
  10731. "SSL_CTX_load_verify_locations error: %s "
  10732. "ssl_verify_peer requires setting "
  10733. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10734. "present in "
  10735. "the .conf file?",
  10736. ssl_error());
  10737. return 0;
  10738. }
  10739. SSL_CTX_set_verify(ctx->ssl_ctx,
  10740. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10741. NULL);
  10742. if (use_default_verify_paths
  10743. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10744. mg_cry(fc(ctx),
  10745. "SSL_CTX_set_default_verify_paths error: %s",
  10746. ssl_error());
  10747. return 0;
  10748. }
  10749. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10750. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10751. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10752. }
  10753. }
  10754. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10755. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10756. != 1) {
  10757. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10758. }
  10759. }
  10760. return 1;
  10761. }
  10762. static void
  10763. uninitialize_ssl(struct mg_context *ctx)
  10764. {
  10765. #ifdef OPENSSL_API_1_1
  10766. (void)ctx;
  10767. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10768. /* Shutdown according to
  10769. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10770. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10771. */
  10772. CONF_modules_unload(1);
  10773. #else
  10774. int i;
  10775. (void)ctx;
  10776. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10777. /* Shutdown according to
  10778. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10779. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10780. */
  10781. CRYPTO_set_locking_callback(NULL);
  10782. CRYPTO_set_id_callback(NULL);
  10783. ENGINE_cleanup();
  10784. CONF_modules_unload(1);
  10785. ERR_free_strings();
  10786. EVP_cleanup();
  10787. CRYPTO_cleanup_all_ex_data();
  10788. ERR_remove_state(0);
  10789. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10790. pthread_mutex_destroy(&ssl_mutexes[i]);
  10791. }
  10792. mg_free(ssl_mutexes);
  10793. ssl_mutexes = NULL;
  10794. #endif /* OPENSSL_API_1_1 */
  10795. }
  10796. }
  10797. #endif /* !NO_SSL */
  10798. static int
  10799. set_gpass_option(struct mg_context *ctx)
  10800. {
  10801. if (ctx) {
  10802. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10803. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10804. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10805. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10806. return 0;
  10807. }
  10808. return 1;
  10809. }
  10810. return 0;
  10811. }
  10812. static int
  10813. set_acl_option(struct mg_context *ctx)
  10814. {
  10815. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10816. }
  10817. static void
  10818. reset_per_request_attributes(struct mg_connection *conn)
  10819. {
  10820. if (!conn) {
  10821. return;
  10822. }
  10823. conn->path_info = NULL;
  10824. conn->num_bytes_sent = conn->consumed_content = 0;
  10825. conn->status_code = -1;
  10826. conn->is_chunked = 0;
  10827. conn->must_close = conn->request_len = conn->throttle = 0;
  10828. conn->request_info.content_length = -1;
  10829. conn->request_info.remote_user = NULL;
  10830. conn->request_info.request_method = NULL;
  10831. conn->request_info.request_uri = NULL;
  10832. conn->request_info.local_uri = NULL;
  10833. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10834. * local_uri and request_uri */
  10835. conn->request_info.http_version = NULL;
  10836. conn->request_info.num_headers = 0;
  10837. conn->data_len = 0;
  10838. conn->chunk_remainder = 0;
  10839. }
  10840. #if 0
  10841. /* Note: set_sock_timeout is not required for non-blocking sockets.
  10842. * Leave this function here (commented out) for reference until
  10843. * CivetWeb 1.9 is tested, and the tests confirme this function is
  10844. * no longer required.
  10845. */
  10846. static int
  10847. set_sock_timeout(SOCKET sock, int milliseconds)
  10848. {
  10849. int r0 = 0, r1, r2;
  10850. #ifdef _WIN32
  10851. /* Windows specific */
  10852. DWORD tv = (DWORD)milliseconds;
  10853. #else
  10854. /* Linux, ... (not Windows) */
  10855. struct timeval tv;
  10856. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10857. * max. time waiting for the acknowledged of TCP data before the connection
  10858. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10859. * If this option is not set, the default timeout of 20-30 minutes is used.
  10860. */
  10861. /* #define TCP_USER_TIMEOUT (18) */
  10862. #if defined(TCP_USER_TIMEOUT)
  10863. unsigned int uto = (unsigned int)milliseconds;
  10864. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10865. #endif
  10866. memset(&tv, 0, sizeof(tv));
  10867. tv.tv_sec = milliseconds / 1000;
  10868. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10869. #endif /* _WIN32 */
  10870. r1 = setsockopt(
  10871. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10872. r2 = setsockopt(
  10873. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10874. return r0 || r1 || r2;
  10875. }
  10876. #endif
  10877. static int
  10878. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10879. {
  10880. if (setsockopt(sock,
  10881. IPPROTO_TCP,
  10882. TCP_NODELAY,
  10883. (SOCK_OPT_TYPE)&nodelay_on,
  10884. sizeof(nodelay_on)) != 0) {
  10885. /* Error */
  10886. return 1;
  10887. }
  10888. /* OK */
  10889. return 0;
  10890. }
  10891. static void
  10892. close_socket_gracefully(struct mg_connection *conn)
  10893. {
  10894. #if defined(_WIN32)
  10895. char buf[MG_BUF_LEN];
  10896. int n;
  10897. #endif
  10898. struct linger linger;
  10899. int error_code = 0;
  10900. int linger_timeout = -2;
  10901. socklen_t opt_len = sizeof(error_code);
  10902. if (!conn) {
  10903. return;
  10904. }
  10905. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  10906. * "Note that enabling a nonzero timeout on a nonblocking socket
  10907. * is not recommended.", so set it to blocking now */
  10908. set_blocking_mode(conn->client.sock, 1);
  10909. /* Send FIN to the client */
  10910. shutdown(conn->client.sock, SHUTDOWN_WR);
  10911. #if defined(_WIN32)
  10912. /* Read and discard pending incoming data. If we do not do that and
  10913. * close
  10914. * the socket, the data in the send buffer may be discarded. This
  10915. * behaviour is seen on Windows, when client keeps sending data
  10916. * when server decides to close the connection; then when client
  10917. * does recv() it gets no data back. */
  10918. do {
  10919. n = pull(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  10920. } while (n > 0);
  10921. #endif
  10922. if (conn->ctx->config[LINGER_TIMEOUT]) {
  10923. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  10924. }
  10925. /* Set linger option according to configuration */
  10926. if (linger_timeout >= 0) {
  10927. /* Set linger option to avoid socket hanging out after close. This
  10928. * prevent ephemeral port exhaust problem under high QPS. */
  10929. linger.l_onoff = 1;
  10930. #if defined(_MSC_VER)
  10931. #pragma warning(push)
  10932. #pragma warning(disable : 4244)
  10933. #endif
  10934. linger.l_linger = (linger_timeout + 999) / 1000;
  10935. #if defined(_MSC_VER)
  10936. #pragma warning(pop)
  10937. #endif
  10938. } else {
  10939. linger.l_onoff = 0;
  10940. linger.l_linger = 0;
  10941. }
  10942. if (linger_timeout < -1) {
  10943. /* Default: don't configure any linger */
  10944. } else if (getsockopt(conn->client.sock,
  10945. SOL_SOCKET,
  10946. SO_ERROR,
  10947. (char *)&error_code,
  10948. &opt_len) != 0) {
  10949. /* Cannot determine if socket is already closed. This should
  10950. * not occur and never did in a test. Log an error message
  10951. * and continue. */
  10952. mg_cry(conn,
  10953. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10954. __func__,
  10955. strerror(ERRNO));
  10956. } else if (error_code == ECONNRESET) {
  10957. /* Socket already closed by client/peer, close socket without linger */
  10958. } else {
  10959. /* Set linger timeout */
  10960. if (setsockopt(conn->client.sock,
  10961. SOL_SOCKET,
  10962. SO_LINGER,
  10963. (char *)&linger,
  10964. sizeof(linger)) != 0) {
  10965. mg_cry(conn,
  10966. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  10967. __func__,
  10968. linger.l_onoff,
  10969. linger.l_linger,
  10970. strerror(ERRNO));
  10971. }
  10972. }
  10973. /* Now we know that our FIN is ACK-ed, safe to close */
  10974. closesocket(conn->client.sock);
  10975. conn->client.sock = INVALID_SOCKET;
  10976. }
  10977. static void
  10978. close_connection(struct mg_connection *conn)
  10979. {
  10980. if (!conn || !conn->ctx) {
  10981. return;
  10982. }
  10983. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10984. if (conn->lua_websocket_state) {
  10985. lua_websocket_close(conn, conn->lua_websocket_state);
  10986. conn->lua_websocket_state = NULL;
  10987. }
  10988. #endif
  10989. /* call the connection_close callback if assigned */
  10990. if ((conn->ctx->callbacks.connection_close != NULL)
  10991. && (conn->ctx->context_type == 1)) {
  10992. conn->ctx->callbacks.connection_close(conn);
  10993. }
  10994. mg_lock_connection(conn);
  10995. conn->must_close = 1;
  10996. #ifndef NO_SSL
  10997. if (conn->ssl != NULL) {
  10998. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10999. */
  11000. SSL_shutdown(conn->ssl);
  11001. SSL_free(conn->ssl);
  11002. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11003. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11004. #ifndef OPENSSL_API_1_1
  11005. ERR_remove_state(0);
  11006. #endif
  11007. conn->ssl = NULL;
  11008. }
  11009. #endif
  11010. if (conn->client.sock != INVALID_SOCKET) {
  11011. close_socket_gracefully(conn);
  11012. conn->client.sock = INVALID_SOCKET;
  11013. }
  11014. mg_unlock_connection(conn);
  11015. }
  11016. void
  11017. mg_close_connection(struct mg_connection *conn)
  11018. {
  11019. struct mg_context *client_ctx = NULL;
  11020. if (conn == NULL) {
  11021. return;
  11022. }
  11023. #if defined(USE_WEBSOCKET)
  11024. if (conn->ctx->context_type == 2) {
  11025. unsigned int i;
  11026. /* ws/wss client */
  11027. client_ctx = conn->ctx;
  11028. /* client context: loops must end */
  11029. conn->ctx->stop_flag = 1;
  11030. /* We need to get the client thread out of the select/recv call here. */
  11031. /* Since we use a sleep quantum of some seconds to check for recv
  11032. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11033. /* join worker thread */
  11034. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11035. if (client_ctx->worker_threadids[i] != 0) {
  11036. mg_join_thread(client_ctx->worker_threadids[i]);
  11037. }
  11038. }
  11039. }
  11040. #else
  11041. (void)client_ctx;
  11042. #endif
  11043. close_connection(conn);
  11044. #ifndef NO_SSL
  11045. if (conn->client_ssl_ctx != NULL) {
  11046. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11047. }
  11048. #endif
  11049. if (client_ctx != NULL) {
  11050. /* free context */
  11051. mg_free(client_ctx->worker_threadids);
  11052. mg_free(client_ctx);
  11053. (void)pthread_mutex_destroy(&conn->mutex);
  11054. mg_free(conn);
  11055. }
  11056. }
  11057. static struct mg_connection *
  11058. mg_connect_client_impl(const struct mg_client_options *client_options,
  11059. int use_ssl,
  11060. char *ebuf,
  11061. size_t ebuf_len)
  11062. {
  11063. static struct mg_context fake_ctx;
  11064. struct mg_connection *conn = NULL;
  11065. SOCKET sock;
  11066. union usa sa;
  11067. if (!connect_socket(&fake_ctx,
  11068. client_options->host,
  11069. client_options->port,
  11070. use_ssl,
  11071. ebuf,
  11072. ebuf_len,
  11073. &sock,
  11074. &sa)) {
  11075. ;
  11076. } else if ((conn = (struct mg_connection *)
  11077. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  11078. mg_snprintf(NULL,
  11079. NULL, /* No truncation check for ebuf */
  11080. ebuf,
  11081. ebuf_len,
  11082. "calloc(): %s",
  11083. strerror(ERRNO));
  11084. closesocket(sock);
  11085. #ifndef NO_SSL
  11086. #ifdef OPENSSL_API_1_1
  11087. } else if (use_ssl
  11088. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method()))
  11089. == NULL) {
  11090. mg_snprintf(NULL,
  11091. NULL, /* No truncation check for ebuf */
  11092. ebuf,
  11093. ebuf_len,
  11094. "SSL_CTX_new error");
  11095. closesocket(sock);
  11096. mg_free(conn);
  11097. conn = NULL;
  11098. #else
  11099. } else if (use_ssl
  11100. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11101. == NULL) {
  11102. mg_snprintf(NULL,
  11103. NULL, /* No truncation check for ebuf */
  11104. ebuf,
  11105. ebuf_len,
  11106. "SSL_CTX_new error");
  11107. closesocket(sock);
  11108. mg_free(conn);
  11109. conn = NULL;
  11110. #endif /* OPENSSL_API_1_1 */
  11111. #endif /* NO_SSL */
  11112. } else {
  11113. #ifdef USE_IPV6
  11114. socklen_t len = (sa.sa.sa_family == AF_INET)
  11115. ? sizeof(conn->client.rsa.sin)
  11116. : sizeof(conn->client.rsa.sin6);
  11117. struct sockaddr *psa =
  11118. (sa.sa.sa_family == AF_INET)
  11119. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11120. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11121. #else
  11122. socklen_t len = sizeof(conn->client.rsa.sin);
  11123. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11124. #endif
  11125. conn->buf_size = MAX_REQUEST_SIZE;
  11126. conn->buf = (char *)(conn + 1);
  11127. conn->ctx = &fake_ctx;
  11128. conn->client.sock = sock;
  11129. conn->client.lsa = sa;
  11130. if (getsockname(sock, psa, &len) != 0) {
  11131. mg_cry(conn,
  11132. "%s: getsockname() failed: %s",
  11133. __func__,
  11134. strerror(ERRNO));
  11135. }
  11136. conn->client.is_ssl = use_ssl ? 1 : 0;
  11137. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11138. #ifndef NO_SSL
  11139. if (use_ssl) {
  11140. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  11141. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11142. * SSL_CTX_set_verify call is needed to switch off server
  11143. * certificate checking, which is off by default in OpenSSL and
  11144. * on in yaSSL. */
  11145. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11146. * SSL_VERIFY_PEER, verify_ssl_server); */
  11147. if (client_options->client_cert) {
  11148. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  11149. mg_snprintf(NULL,
  11150. NULL, /* No truncation check for ebuf */
  11151. ebuf,
  11152. ebuf_len,
  11153. "Can not use SSL client certificate");
  11154. SSL_CTX_free(conn->client_ssl_ctx);
  11155. closesocket(sock);
  11156. mg_free(conn);
  11157. conn = NULL;
  11158. }
  11159. }
  11160. if (client_options->server_cert) {
  11161. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11162. client_options->server_cert,
  11163. NULL);
  11164. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11165. } else {
  11166. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11167. }
  11168. if (!sslize(conn,
  11169. conn->client_ssl_ctx,
  11170. SSL_connect,
  11171. &(conn->ctx->stop_flag))) {
  11172. mg_snprintf(NULL,
  11173. NULL, /* No truncation check for ebuf */
  11174. ebuf,
  11175. ebuf_len,
  11176. "SSL connection error");
  11177. SSL_CTX_free(conn->client_ssl_ctx);
  11178. closesocket(sock);
  11179. mg_free(conn);
  11180. conn = NULL;
  11181. }
  11182. }
  11183. #endif
  11184. }
  11185. if (conn) {
  11186. set_blocking_mode(sock, 0);
  11187. }
  11188. return conn;
  11189. }
  11190. CIVETWEB_API struct mg_connection *
  11191. mg_connect_client_secure(const struct mg_client_options *client_options,
  11192. char *error_buffer,
  11193. size_t error_buffer_size)
  11194. {
  11195. return mg_connect_client_impl(client_options,
  11196. 1,
  11197. error_buffer,
  11198. error_buffer_size);
  11199. }
  11200. struct mg_connection *
  11201. mg_connect_client(const char *host,
  11202. int port,
  11203. int use_ssl,
  11204. char *error_buffer,
  11205. size_t error_buffer_size)
  11206. {
  11207. struct mg_client_options opts;
  11208. memset(&opts, 0, sizeof(opts));
  11209. opts.host = host;
  11210. opts.port = port;
  11211. return mg_connect_client_impl(&opts,
  11212. use_ssl,
  11213. error_buffer,
  11214. error_buffer_size);
  11215. }
  11216. static const struct {
  11217. const char *proto;
  11218. size_t proto_len;
  11219. unsigned default_port;
  11220. } abs_uri_protocols[] = {{"http://", 7, 80},
  11221. {"https://", 8, 443},
  11222. {"ws://", 5, 80},
  11223. {"wss://", 6, 443},
  11224. {NULL, 0, 0}};
  11225. /* Check if the uri is valid.
  11226. * return 0 for invalid uri,
  11227. * return 1 for *,
  11228. * return 2 for relative uri,
  11229. * return 3 for absolute uri without port,
  11230. * return 4 for absolute uri with port */
  11231. static int
  11232. get_uri_type(const char *uri)
  11233. {
  11234. int i;
  11235. char *hostend, *portbegin, *portend;
  11236. unsigned long port;
  11237. /* According to the HTTP standard
  11238. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11239. * URI can be an asterisk (*) or should start with slash (relative uri),
  11240. * or it should start with the protocol (absolute uri). */
  11241. if (uri[0] == '*' && uri[1] == '\0') {
  11242. /* asterisk */
  11243. return 1;
  11244. }
  11245. /* Valid URIs according to RFC 3986
  11246. * (https://www.ietf.org/rfc/rfc3986.txt)
  11247. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11248. * and unreserved characters A-Z a-z 0-9 and -._~
  11249. * and % encoded symbols.
  11250. */
  11251. for (i = 0; uri[i] != 0; i++) {
  11252. if (uri[i] < 33) {
  11253. /* control characters and spaces are invalid */
  11254. return 0;
  11255. }
  11256. if (uri[i] > 126) {
  11257. /* non-ascii characters must be % encoded */
  11258. return 0;
  11259. } else {
  11260. switch (uri[i]) {
  11261. case '"': /* 34 */
  11262. case '<': /* 60 */
  11263. case '>': /* 62 */
  11264. case '\\': /* 92 */
  11265. case '^': /* 94 */
  11266. case '`': /* 96 */
  11267. case '{': /* 123 */
  11268. case '|': /* 124 */
  11269. case '}': /* 125 */
  11270. return 0;
  11271. default:
  11272. /* character is ok */
  11273. break;
  11274. }
  11275. }
  11276. }
  11277. /* A relative uri starts with a / character */
  11278. if (uri[0] == '/') {
  11279. /* relative uri */
  11280. return 2;
  11281. }
  11282. /* It could be an absolute uri: */
  11283. /* This function only checks if the uri is valid, not if it is
  11284. * addressing the current server. So civetweb can also be used
  11285. * as a proxy server. */
  11286. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11287. if (mg_strncasecmp(uri,
  11288. abs_uri_protocols[i].proto,
  11289. abs_uri_protocols[i].proto_len) == 0) {
  11290. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11291. if (!hostend) {
  11292. return 0;
  11293. }
  11294. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11295. if (!portbegin) {
  11296. return 3;
  11297. }
  11298. port = strtoul(portbegin + 1, &portend, 10);
  11299. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11300. return 0;
  11301. }
  11302. return 4;
  11303. }
  11304. }
  11305. return 0;
  11306. }
  11307. /* Return NULL or the relative uri at the current server */
  11308. static const char *
  11309. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11310. {
  11311. const char *server_domain;
  11312. size_t server_domain_len;
  11313. size_t request_domain_len = 0;
  11314. unsigned long port = 0;
  11315. int i;
  11316. const char *hostbegin = NULL;
  11317. const char *hostend = NULL;
  11318. const char *portbegin;
  11319. char *portend;
  11320. /* DNS is case insensitive, so use case insensitive string compare here
  11321. */
  11322. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11323. if (!server_domain) {
  11324. return 0;
  11325. }
  11326. server_domain_len = strlen(server_domain);
  11327. if (!server_domain_len) {
  11328. return 0;
  11329. }
  11330. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11331. if (mg_strncasecmp(uri,
  11332. abs_uri_protocols[i].proto,
  11333. abs_uri_protocols[i].proto_len) == 0) {
  11334. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11335. hostend = strchr(hostbegin, '/');
  11336. if (!hostend) {
  11337. return 0;
  11338. }
  11339. portbegin = strchr(hostbegin, ':');
  11340. if ((!portbegin) || (portbegin > hostend)) {
  11341. port = abs_uri_protocols[i].default_port;
  11342. request_domain_len = (size_t)(hostend - hostbegin);
  11343. } else {
  11344. port = strtoul(portbegin + 1, &portend, 10);
  11345. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11346. return 0;
  11347. }
  11348. request_domain_len = (size_t)(portbegin - hostbegin);
  11349. }
  11350. /* protocol found, port set */
  11351. break;
  11352. }
  11353. }
  11354. if (!port) {
  11355. /* port remains 0 if the protocol is not found */
  11356. return 0;
  11357. }
  11358. /* Check if the request is directed to a different server. */
  11359. /* First check if the port is the same (IPv4 and IPv6). */
  11360. #if defined(USE_IPV6)
  11361. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11362. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11363. /* Request is directed to a different port */
  11364. return 0;
  11365. }
  11366. } else
  11367. #endif
  11368. {
  11369. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11370. /* Request is directed to a different port */
  11371. return 0;
  11372. }
  11373. }
  11374. /* Finally check if the server corresponds to the authentication
  11375. * domain of the server (the server domain).
  11376. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11377. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11378. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11379. * or http://mydomain.com.fake/path/file.ext).
  11380. */
  11381. if ((request_domain_len == server_domain_len)
  11382. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11383. /* Request is directed to this server - full name match. */
  11384. } else {
  11385. if (request_domain_len < (server_domain_len + 2)) {
  11386. /* Request is directed to another server: The server name is longer
  11387. * than
  11388. * the request name. Drop this case here to avoid overflows in the
  11389. * following checks. */
  11390. return 0;
  11391. }
  11392. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11393. /* Request is directed to another server: It could be a substring
  11394. * like notmyserver.com */
  11395. return 0;
  11396. }
  11397. if (0 != memcmp(server_domain,
  11398. hostbegin + request_domain_len - server_domain_len,
  11399. server_domain_len)) {
  11400. /* Request is directed to another server:
  11401. * The server name is different. */
  11402. return 0;
  11403. }
  11404. }
  11405. return hostend;
  11406. }
  11407. static int
  11408. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11409. {
  11410. const char *cl;
  11411. if (ebuf_len > 0) {
  11412. ebuf[0] = '\0';
  11413. }
  11414. *err = 0;
  11415. reset_per_request_attributes(conn);
  11416. if (!conn) {
  11417. mg_snprintf(conn,
  11418. NULL, /* No truncation check for ebuf */
  11419. ebuf,
  11420. ebuf_len,
  11421. "%s",
  11422. "Internal error");
  11423. *err = 500;
  11424. return 0;
  11425. }
  11426. /* Set the time the request was received. This value should be used for
  11427. * timeouts. */
  11428. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11429. conn->request_len =
  11430. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11431. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11432. */
  11433. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11434. mg_snprintf(conn,
  11435. NULL, /* No truncation check for ebuf */
  11436. ebuf,
  11437. ebuf_len,
  11438. "%s",
  11439. "Invalid request size");
  11440. *err = 500;
  11441. return 0;
  11442. }
  11443. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11444. mg_snprintf(conn,
  11445. NULL, /* No truncation check for ebuf */
  11446. ebuf,
  11447. ebuf_len,
  11448. "%s",
  11449. "Request Too Large");
  11450. *err = 413;
  11451. return 0;
  11452. } else if (conn->request_len <= 0) {
  11453. if (conn->data_len > 0) {
  11454. mg_snprintf(conn,
  11455. NULL, /* No truncation check for ebuf */
  11456. ebuf,
  11457. ebuf_len,
  11458. "%s",
  11459. "Client sent malformed request");
  11460. *err = 400;
  11461. } else {
  11462. /* Server did not recv anything -> just close the connection */
  11463. conn->must_close = 1;
  11464. mg_snprintf(conn,
  11465. NULL, /* No truncation check for ebuf */
  11466. ebuf,
  11467. ebuf_len,
  11468. "%s",
  11469. "Client did not send a request");
  11470. *err = 0;
  11471. }
  11472. return 0;
  11473. } else if (parse_http_message(conn->buf,
  11474. conn->buf_size,
  11475. &conn->request_info) <= 0) {
  11476. mg_snprintf(conn,
  11477. NULL, /* No truncation check for ebuf */
  11478. ebuf,
  11479. ebuf_len,
  11480. "%s",
  11481. "Bad Request");
  11482. *err = 400;
  11483. return 0;
  11484. } else {
  11485. /* Message is a valid request or response */
  11486. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11487. /* Request/response has content length set */
  11488. char *endptr = NULL;
  11489. conn->content_len = strtoll(cl, &endptr, 10);
  11490. if (endptr == cl) {
  11491. mg_snprintf(conn,
  11492. NULL, /* No truncation check for ebuf */
  11493. ebuf,
  11494. ebuf_len,
  11495. "%s",
  11496. "Bad Request");
  11497. *err = 411;
  11498. return 0;
  11499. }
  11500. /* Publish the content length back to the request info. */
  11501. conn->request_info.content_length = conn->content_len;
  11502. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11503. != NULL
  11504. && !mg_strcasecmp(cl, "chunked")) {
  11505. conn->is_chunked = 1;
  11506. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11507. || !mg_strcasecmp(conn->request_info.request_method,
  11508. "PUT")) {
  11509. /* POST or PUT request without content length set */
  11510. conn->content_len = -1;
  11511. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11512. "HTTP/",
  11513. 5)) {
  11514. /* Response without content length set */
  11515. conn->content_len = -1;
  11516. } else {
  11517. /* Other request */
  11518. conn->content_len = 0;
  11519. }
  11520. }
  11521. return 1;
  11522. }
  11523. int
  11524. mg_get_response(struct mg_connection *conn,
  11525. char *ebuf,
  11526. size_t ebuf_len,
  11527. int timeout)
  11528. {
  11529. if (conn) {
  11530. /* Implementation of API function for HTTP clients */
  11531. int err, ret;
  11532. struct mg_context *octx = conn->ctx;
  11533. struct mg_context rctx = *(conn->ctx);
  11534. char txt[32]; /* will not overflow */
  11535. if (timeout >= 0) {
  11536. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11537. rctx.config[REQUEST_TIMEOUT] = txt;
  11538. /* Not required for non-blocking sockets.
  11539. set_sock_timeout(conn->client.sock, timeout);
  11540. */
  11541. } else {
  11542. rctx.config[REQUEST_TIMEOUT] = NULL;
  11543. }
  11544. conn->ctx = &rctx;
  11545. ret = getreq(conn, ebuf, ebuf_len, &err);
  11546. conn->ctx = octx;
  11547. /* TODO: 1) uri is deprecated;
  11548. * 2) here, ri.uri is the http response code */
  11549. conn->request_info.uri = conn->request_info.request_uri;
  11550. /* TODO (mid): Define proper return values - maybe return length?
  11551. * For the first test use <0 for error and >0 for OK */
  11552. return (ret == 0) ? -1 : +1;
  11553. }
  11554. return -1;
  11555. }
  11556. struct mg_connection *
  11557. mg_download(const char *host,
  11558. int port,
  11559. int use_ssl,
  11560. char *ebuf,
  11561. size_t ebuf_len,
  11562. const char *fmt,
  11563. ...)
  11564. {
  11565. struct mg_connection *conn;
  11566. va_list ap;
  11567. int i;
  11568. int reqerr;
  11569. va_start(ap, fmt);
  11570. ebuf[0] = '\0';
  11571. /* open a connection */
  11572. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11573. if (conn != NULL) {
  11574. i = mg_vprintf(conn, fmt, ap);
  11575. if (i <= 0) {
  11576. mg_snprintf(conn,
  11577. NULL, /* No truncation check for ebuf */
  11578. ebuf,
  11579. ebuf_len,
  11580. "%s",
  11581. "Error sending request");
  11582. } else {
  11583. getreq(conn, ebuf, ebuf_len, &reqerr);
  11584. /* TODO: 1) uri is deprecated;
  11585. * 2) here, ri.uri is the http response code */
  11586. conn->request_info.uri = conn->request_info.request_uri;
  11587. }
  11588. }
  11589. /* if an error occured, close the connection */
  11590. if (ebuf[0] != '\0' && conn != NULL) {
  11591. mg_close_connection(conn);
  11592. conn = NULL;
  11593. }
  11594. va_end(ap);
  11595. return conn;
  11596. }
  11597. struct websocket_client_thread_data {
  11598. struct mg_connection *conn;
  11599. mg_websocket_data_handler data_handler;
  11600. mg_websocket_close_handler close_handler;
  11601. void *callback_data;
  11602. };
  11603. #if defined(USE_WEBSOCKET)
  11604. #ifdef _WIN32
  11605. static unsigned __stdcall websocket_client_thread(void *data)
  11606. #else
  11607. static void *
  11608. websocket_client_thread(void *data)
  11609. #endif
  11610. {
  11611. struct websocket_client_thread_data *cdata =
  11612. (struct websocket_client_thread_data *)data;
  11613. mg_set_thread_name("ws-clnt");
  11614. if (cdata->conn->ctx) {
  11615. if (cdata->conn->ctx->callbacks.init_thread) {
  11616. /* 3 indicates a websocket client thread */
  11617. /* TODO: check if conn->ctx can be set */
  11618. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11619. }
  11620. }
  11621. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11622. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11623. if (cdata->close_handler != NULL) {
  11624. cdata->close_handler(cdata->conn, cdata->callback_data);
  11625. }
  11626. /* The websocket_client context has only this thread. If it runs out,
  11627. set the stop_flag to 2 (= "stopped"). */
  11628. cdata->conn->ctx->stop_flag = 2;
  11629. mg_free((void *)cdata);
  11630. #ifdef _WIN32
  11631. return 0;
  11632. #else
  11633. return NULL;
  11634. #endif
  11635. }
  11636. #endif
  11637. struct mg_connection *
  11638. mg_connect_websocket_client(const char *host,
  11639. int port,
  11640. int use_ssl,
  11641. char *error_buffer,
  11642. size_t error_buffer_size,
  11643. const char *path,
  11644. const char *origin,
  11645. mg_websocket_data_handler data_func,
  11646. mg_websocket_close_handler close_func,
  11647. void *user_data)
  11648. {
  11649. struct mg_connection *conn = NULL;
  11650. #if defined(USE_WEBSOCKET)
  11651. struct mg_context *newctx = NULL;
  11652. struct websocket_client_thread_data *thread_data;
  11653. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11654. static const char *handshake_req;
  11655. if (origin != NULL) {
  11656. handshake_req = "GET %s HTTP/1.1\r\n"
  11657. "Host: %s\r\n"
  11658. "Upgrade: websocket\r\n"
  11659. "Connection: Upgrade\r\n"
  11660. "Sec-WebSocket-Key: %s\r\n"
  11661. "Sec-WebSocket-Version: 13\r\n"
  11662. "Origin: %s\r\n"
  11663. "\r\n";
  11664. } else {
  11665. handshake_req = "GET %s HTTP/1.1\r\n"
  11666. "Host: %s\r\n"
  11667. "Upgrade: websocket\r\n"
  11668. "Connection: Upgrade\r\n"
  11669. "Sec-WebSocket-Key: %s\r\n"
  11670. "Sec-WebSocket-Version: 13\r\n"
  11671. "\r\n";
  11672. }
  11673. /* Establish the client connection and request upgrade */
  11674. conn = mg_download(host,
  11675. port,
  11676. use_ssl,
  11677. error_buffer,
  11678. error_buffer_size,
  11679. handshake_req,
  11680. path,
  11681. host,
  11682. magic,
  11683. origin);
  11684. /* Connection object will be null if something goes wrong */
  11685. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11686. if (!*error_buffer) {
  11687. /* if there is a connection, but it did not return 101,
  11688. * error_buffer is not yet set */
  11689. mg_snprintf(conn,
  11690. NULL, /* No truncation check for ebuf */
  11691. error_buffer,
  11692. error_buffer_size,
  11693. "Unexpected server reply");
  11694. }
  11695. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11696. if (conn != NULL) {
  11697. mg_free(conn);
  11698. conn = NULL;
  11699. }
  11700. return conn;
  11701. }
  11702. /* For client connections, mg_context is fake. Since we need to set a
  11703. * callback function, we need to create a copy and modify it. */
  11704. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11705. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11706. newctx->user_data = user_data;
  11707. newctx->context_type = 2; /* ws/wss client context type */
  11708. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11709. newctx->worker_threadids =
  11710. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11711. conn->ctx = newctx;
  11712. thread_data = (struct websocket_client_thread_data *)
  11713. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11714. thread_data->conn = conn;
  11715. thread_data->data_handler = data_func;
  11716. thread_data->close_handler = close_func;
  11717. thread_data->callback_data = NULL;
  11718. /* Start a thread to read the websocket client connection
  11719. * This thread will automatically stop when mg_disconnect is
  11720. * called on the client connection */
  11721. if (mg_start_thread_with_id(websocket_client_thread,
  11722. (void *)thread_data,
  11723. newctx->worker_threadids) != 0) {
  11724. mg_free((void *)thread_data);
  11725. mg_free((void *)newctx->worker_threadids);
  11726. mg_free((void *)newctx);
  11727. mg_free((void *)conn);
  11728. conn = NULL;
  11729. DEBUG_TRACE("%s",
  11730. "Websocket client connect thread could not be started\r\n");
  11731. }
  11732. #else
  11733. /* Appease "unused parameter" warnings */
  11734. (void)host;
  11735. (void)port;
  11736. (void)use_ssl;
  11737. (void)error_buffer;
  11738. (void)error_buffer_size;
  11739. (void)path;
  11740. (void)origin;
  11741. (void)user_data;
  11742. (void)data_func;
  11743. (void)close_func;
  11744. #endif
  11745. return conn;
  11746. }
  11747. static void
  11748. process_new_connection(struct mg_connection *conn)
  11749. {
  11750. if (conn && conn->ctx) {
  11751. struct mg_request_info *ri = &conn->request_info;
  11752. int keep_alive_enabled, keep_alive, discard_len;
  11753. char ebuf[100];
  11754. const char *hostend;
  11755. int reqerr, uri_type;
  11756. keep_alive_enabled =
  11757. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11758. /* Important: on new connection, reset the receiving buffer. Credit
  11759. * goes to crule42. */
  11760. conn->data_len = 0;
  11761. conn->handled_requests = 0;
  11762. do {
  11763. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11764. conn->handled_requests + 1);
  11765. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11766. /* The request sent by the client could not be understood by
  11767. * the server, or it was incomplete or a timeout. Send an
  11768. * error message and close the connection. */
  11769. if (reqerr > 0) {
  11770. /*assert(ebuf[0] != '\0');*/
  11771. send_http_error(conn, reqerr, "%s", ebuf);
  11772. }
  11773. } else if (strcmp(ri->http_version, "1.0")
  11774. && strcmp(ri->http_version, "1.1")) {
  11775. mg_snprintf(conn,
  11776. NULL, /* No truncation check for ebuf */
  11777. ebuf,
  11778. sizeof(ebuf),
  11779. "Bad HTTP version: [%s]",
  11780. ri->http_version);
  11781. send_http_error(conn, 505, "%s", ebuf);
  11782. }
  11783. if (ebuf[0] == '\0') {
  11784. uri_type = get_uri_type(conn->request_info.request_uri);
  11785. switch (uri_type) {
  11786. case 1:
  11787. /* Asterisk */
  11788. conn->request_info.local_uri = NULL;
  11789. break;
  11790. case 2:
  11791. /* relative uri */
  11792. conn->request_info.local_uri =
  11793. conn->request_info.request_uri;
  11794. break;
  11795. case 3:
  11796. case 4:
  11797. /* absolute uri (with/without port) */
  11798. hostend = get_rel_url_at_current_server(
  11799. conn->request_info.request_uri, conn);
  11800. if (hostend) {
  11801. conn->request_info.local_uri = hostend;
  11802. } else {
  11803. conn->request_info.local_uri = NULL;
  11804. }
  11805. break;
  11806. default:
  11807. mg_snprintf(conn,
  11808. NULL, /* No truncation check for ebuf */
  11809. ebuf,
  11810. sizeof(ebuf),
  11811. "Invalid URI");
  11812. send_http_error(conn, 400, "%s", ebuf);
  11813. conn->request_info.local_uri = NULL;
  11814. break;
  11815. }
  11816. /* TODO: cleanup uri, local_uri and request_uri */
  11817. conn->request_info.uri = conn->request_info.local_uri;
  11818. }
  11819. DEBUG_TRACE("http: %s, error: %s",
  11820. (ri->http_version ? ri->http_version : "none"),
  11821. (ebuf[0] ? ebuf : "none"));
  11822. if (ebuf[0] == '\0') {
  11823. if (conn->request_info.local_uri) {
  11824. /* handle request to local server */
  11825. handle_request(conn);
  11826. DEBUG_TRACE("%s", "handle_request done");
  11827. if (conn->ctx->callbacks.end_request != NULL) {
  11828. conn->ctx->callbacks.end_request(conn,
  11829. conn->status_code);
  11830. DEBUG_TRACE("%s", "end_request callback done");
  11831. }
  11832. log_access(conn);
  11833. } else {
  11834. /* TODO: handle non-local request (PROXY) */
  11835. conn->must_close = 1;
  11836. }
  11837. } else {
  11838. conn->must_close = 1;
  11839. }
  11840. if (ri->remote_user != NULL) {
  11841. mg_free((void *)ri->remote_user);
  11842. /* Important! When having connections with and without auth
  11843. * would cause double free and then crash */
  11844. ri->remote_user = NULL;
  11845. }
  11846. /* NOTE(lsm): order is important here. should_keep_alive() call
  11847. * is
  11848. * using parsed request, which will be invalid after memmove's
  11849. * below.
  11850. * Therefore, memorize should_keep_alive() result now for later
  11851. * use
  11852. * in loop exit condition. */
  11853. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11854. && (conn->content_len >= 0) && should_keep_alive(conn);
  11855. /* Discard all buffered data for this request */
  11856. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11857. && ((conn->request_len + conn->content_len)
  11858. < (int64_t)conn->data_len))
  11859. ? (int)(conn->request_len + conn->content_len)
  11860. : conn->data_len;
  11861. /*assert(discard_len >= 0);*/
  11862. if (discard_len < 0) {
  11863. DEBUG_TRACE("internal error: discard_len = %li",
  11864. (long int)discard_len);
  11865. break;
  11866. }
  11867. conn->data_len -= discard_len;
  11868. if (conn->data_len > 0) {
  11869. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  11870. memmove(conn->buf,
  11871. conn->buf + discard_len,
  11872. (size_t)conn->data_len);
  11873. }
  11874. /* assert(conn->data_len >= 0); */
  11875. /* assert(conn->data_len <= conn->buf_size); */
  11876. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11877. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  11878. (long int)conn->data_len,
  11879. (long int)conn->buf_size);
  11880. break;
  11881. }
  11882. conn->handled_requests++;
  11883. } while (keep_alive);
  11884. }
  11885. }
  11886. #if defined(ALTERNATIVE_QUEUE)
  11887. static void
  11888. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11889. {
  11890. unsigned int i;
  11891. for (;;) {
  11892. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11893. /* find a free worker slot and signal it */
  11894. if (ctx->client_socks[i].in_use == 0) {
  11895. ctx->client_socks[i] = *sp;
  11896. ctx->client_socks[i].in_use = 1;
  11897. event_signal(ctx->client_wait_events[i]);
  11898. return;
  11899. }
  11900. }
  11901. /* queue is full */
  11902. mg_sleep(1);
  11903. }
  11904. }
  11905. static int
  11906. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11907. {
  11908. DEBUG_TRACE("%s", "going idle");
  11909. ctx->client_socks[thread_index].in_use = 0;
  11910. event_wait(ctx->client_wait_events[thread_index]);
  11911. *sp = ctx->client_socks[thread_index];
  11912. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11913. return !ctx->stop_flag;
  11914. }
  11915. #else /* ALTERNATIVE_QUEUE */
  11916. /* Worker threads take accepted socket from the queue */
  11917. static int
  11918. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11919. {
  11920. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11921. (void)thread_index;
  11922. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11923. DEBUG_TRACE("%s", "going idle");
  11924. /* If the queue is empty, wait. We're idle at this point. */
  11925. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11926. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11927. }
  11928. /* If we're stopping, sq_head may be equal to sq_tail. */
  11929. if (ctx->sq_head > ctx->sq_tail) {
  11930. /* Copy socket from the queue and increment tail */
  11931. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11932. ctx->sq_tail++;
  11933. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11934. /* Wrap pointers if needed */
  11935. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11936. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11937. ctx->sq_head -= QUEUE_SIZE(ctx);
  11938. }
  11939. }
  11940. (void)pthread_cond_signal(&ctx->sq_empty);
  11941. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11942. return !ctx->stop_flag;
  11943. #undef QUEUE_SIZE
  11944. }
  11945. /* Master thread adds accepted socket to a queue */
  11946. static void
  11947. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11948. {
  11949. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11950. if (!ctx) {
  11951. return;
  11952. }
  11953. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11954. /* If the queue is full, wait */
  11955. while (ctx->stop_flag == 0
  11956. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11957. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11958. }
  11959. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11960. /* Copy socket to the queue and increment head */
  11961. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11962. ctx->sq_head++;
  11963. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11964. }
  11965. (void)pthread_cond_signal(&ctx->sq_full);
  11966. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11967. #undef QUEUE_SIZE
  11968. }
  11969. #endif /* ALTERNATIVE_QUEUE */
  11970. struct worker_thread_args {
  11971. struct mg_context *ctx;
  11972. int index;
  11973. };
  11974. static void *
  11975. worker_thread_run(struct worker_thread_args *thread_args)
  11976. {
  11977. struct mg_context *ctx = thread_args->ctx;
  11978. struct mg_connection *conn;
  11979. struct mg_workerTLS tls;
  11980. #if defined(MG_LEGACY_INTERFACE)
  11981. uint32_t addr;
  11982. #endif
  11983. mg_set_thread_name("worker");
  11984. tls.is_master = 0;
  11985. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11986. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11987. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11988. #endif
  11989. /* Initialize thread local storage before calling any callback */
  11990. pthread_setspecific(sTlsKey, &tls);
  11991. if (ctx->callbacks.init_thread) {
  11992. /* call init_thread for a worker thread (type 1) */
  11993. ctx->callbacks.init_thread(ctx, 1);
  11994. }
  11995. /* Connection structure has been pre-allocated */
  11996. if (((int)thread_args->index < 0)
  11997. || ((unsigned)thread_args->index
  11998. >= (unsigned)ctx->cfg_worker_threads)) {
  11999. mg_cry(fc(ctx),
  12000. "Internal error: Invalid worker index %i",
  12001. (int)thread_args->index);
  12002. return NULL;
  12003. }
  12004. conn = ctx->worker_connections + thread_args->index;
  12005. /* Request buffers are not pre-allocated. They are private to the
  12006. * request and do not contain any state information that might be
  12007. * of interest to anyone observing a server status. */
  12008. conn->buf = (char *)mg_malloc(MAX_REQUEST_SIZE);
  12009. if (conn->buf == NULL) {
  12010. mg_cry(fc(ctx),
  12011. "Out of memory: Cannot allocate buffer for worker %i",
  12012. (int)thread_args->index);
  12013. return NULL;
  12014. }
  12015. conn->buf_size = MAX_REQUEST_SIZE;
  12016. conn->ctx = ctx;
  12017. conn->thread_index = thread_args->index;
  12018. conn->request_info.user_data = ctx->user_data;
  12019. /* Allocate a mutex for this connection to allow communication both
  12020. * within the request handler and from elsewhere in the application
  12021. */
  12022. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12023. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12024. * signal sq_empty condvar to wake up the master waiting in
  12025. * produce_socket() */
  12026. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12027. conn->conn_birth_time = time(NULL);
  12028. /* Fill in IP, port info early so even if SSL setup below fails,
  12029. * error handler would have the corresponding info.
  12030. * Thanks to Johannes Winkelmann for the patch.
  12031. */
  12032. #if defined(USE_IPV6)
  12033. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12034. conn->request_info.remote_port =
  12035. ntohs(conn->client.rsa.sin6.sin6_port);
  12036. } else
  12037. #endif
  12038. {
  12039. conn->request_info.remote_port =
  12040. ntohs(conn->client.rsa.sin.sin_port);
  12041. }
  12042. sockaddr_to_string(conn->request_info.remote_addr,
  12043. sizeof(conn->request_info.remote_addr),
  12044. &conn->client.rsa);
  12045. DEBUG_TRACE("Start processing connection from %s",
  12046. conn->request_info.remote_addr);
  12047. #if defined(MG_LEGACY_INTERFACE)
  12048. /* This legacy interface only works for the IPv4 case */
  12049. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12050. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12051. #endif
  12052. conn->request_info.is_ssl = conn->client.is_ssl;
  12053. if (conn->client.is_ssl) {
  12054. #ifndef NO_SSL
  12055. /* HTTPS connection */
  12056. if (sslize(conn,
  12057. conn->ctx->ssl_ctx,
  12058. SSL_accept,
  12059. &(conn->ctx->stop_flag))) {
  12060. /* Get SSL client certificate information (if set) */
  12061. ssl_get_client_cert_info(conn);
  12062. /* process HTTPS connection */
  12063. process_new_connection(conn);
  12064. /* Free client certificate info */
  12065. if (conn->request_info.client_cert) {
  12066. mg_free((void *)(conn->request_info.client_cert->subject));
  12067. mg_free((void *)(conn->request_info.client_cert->issuer));
  12068. mg_free((void *)(conn->request_info.client_cert->serial));
  12069. mg_free((void *)(conn->request_info.client_cert->finger));
  12070. conn->request_info.client_cert->subject = 0;
  12071. conn->request_info.client_cert->issuer = 0;
  12072. conn->request_info.client_cert->serial = 0;
  12073. conn->request_info.client_cert->finger = 0;
  12074. mg_free(conn->request_info.client_cert);
  12075. conn->request_info.client_cert = 0;
  12076. }
  12077. }
  12078. #endif
  12079. } else {
  12080. /* process HTTP connection */
  12081. process_new_connection(conn);
  12082. }
  12083. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12084. conn->request_info.remote_addr,
  12085. difftime(time(NULL), conn->conn_birth_time));
  12086. close_connection(conn);
  12087. DEBUG_TRACE("%s", "Connection closed");
  12088. }
  12089. pthread_setspecific(sTlsKey, NULL);
  12090. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12091. CloseHandle(tls.pthread_cond_helper_mutex);
  12092. #endif
  12093. pthread_mutex_destroy(&conn->mutex);
  12094. /* Free the request buffer. */
  12095. conn->buf_size = 0;
  12096. mg_free(conn->buf);
  12097. conn->buf = NULL;
  12098. DEBUG_TRACE("%s", "exiting");
  12099. return NULL;
  12100. }
  12101. /* Threads have different return types on Windows and Unix. */
  12102. #ifdef _WIN32
  12103. static unsigned __stdcall worker_thread(void *thread_func_param)
  12104. {
  12105. struct worker_thread_args *pwta =
  12106. (struct worker_thread_args *)thread_func_param;
  12107. worker_thread_run(pwta);
  12108. mg_free(thread_func_param);
  12109. return 0;
  12110. }
  12111. #else
  12112. static void *
  12113. worker_thread(void *thread_func_param)
  12114. {
  12115. struct worker_thread_args *pwta =
  12116. (struct worker_thread_args *)thread_func_param;
  12117. worker_thread_run(pwta);
  12118. mg_free(thread_func_param);
  12119. return NULL;
  12120. }
  12121. #endif /* _WIN32 */
  12122. static void
  12123. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12124. {
  12125. struct socket so;
  12126. char src_addr[IP_ADDR_STR_LEN];
  12127. socklen_t len = sizeof(so.rsa);
  12128. int on = 1;
  12129. if (!listener) {
  12130. return;
  12131. }
  12132. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12133. == INVALID_SOCKET) {
  12134. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12135. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12136. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12137. closesocket(so.sock);
  12138. so.sock = INVALID_SOCKET;
  12139. } else {
  12140. /* Put so socket structure into the queue */
  12141. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12142. set_close_on_exec(so.sock, fc(ctx));
  12143. so.is_ssl = listener->is_ssl;
  12144. so.ssl_redir = listener->ssl_redir;
  12145. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12146. mg_cry(fc(ctx),
  12147. "%s: getsockname() failed: %s",
  12148. __func__,
  12149. strerror(ERRNO));
  12150. }
  12151. /* Set TCP keep-alive. This is needed because if HTTP-level
  12152. * keep-alive
  12153. * is enabled, and client resets the connection, server won't get
  12154. * TCP FIN or RST and will keep the connection open forever. With
  12155. * TCP keep-alive, next keep-alive handshake will figure out that
  12156. * the client is down and will close the server end.
  12157. * Thanks to Igor Klopov who suggested the patch. */
  12158. if (setsockopt(so.sock,
  12159. SOL_SOCKET,
  12160. SO_KEEPALIVE,
  12161. (SOCK_OPT_TYPE)&on,
  12162. sizeof(on)) != 0) {
  12163. mg_cry(fc(ctx),
  12164. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12165. __func__,
  12166. strerror(ERRNO));
  12167. }
  12168. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12169. * to effectively fill up the underlying IP packet payload and
  12170. * reduce the overhead of sending lots of small buffers. However
  12171. * this hurts the server's throughput (ie. operations per second)
  12172. * when HTTP 1.1 persistent connections are used and the responses
  12173. * are relatively small (eg. less than 1400 bytes).
  12174. */
  12175. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12176. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12177. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12178. mg_cry(fc(ctx),
  12179. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12180. __func__,
  12181. strerror(ERRNO));
  12182. }
  12183. }
  12184. /* We are using non-blocking sockets. Thus, the
  12185. * set_sock_timeout(so.sock, timeout);
  12186. * call is no longer required. */
  12187. set_blocking_mode(so.sock, 0);
  12188. produce_socket(ctx, &so);
  12189. }
  12190. }
  12191. static void
  12192. master_thread_run(void *thread_func_param)
  12193. {
  12194. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12195. struct mg_workerTLS tls;
  12196. struct pollfd *pfd;
  12197. unsigned int i;
  12198. unsigned int workerthreadcount;
  12199. if (!ctx) {
  12200. return;
  12201. }
  12202. mg_set_thread_name("master");
  12203. /* Increase priority of the master thread */
  12204. #if defined(_WIN32)
  12205. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12206. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12207. int min_prio = sched_get_priority_min(SCHED_RR);
  12208. int max_prio = sched_get_priority_max(SCHED_RR);
  12209. if ((min_prio >= 0) && (max_prio >= 0)
  12210. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12211. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12212. struct sched_param sched_param = {0};
  12213. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12214. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12215. }
  12216. #endif
  12217. /* Initialize thread local storage */
  12218. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12219. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12220. #endif
  12221. tls.is_master = 1;
  12222. pthread_setspecific(sTlsKey, &tls);
  12223. if (ctx->callbacks.init_thread) {
  12224. /* Callback for the master thread (type 0) */
  12225. ctx->callbacks.init_thread(ctx, 0);
  12226. }
  12227. /* Server starts *now* */
  12228. ctx->start_time = time(NULL);
  12229. /* Start the server */
  12230. pfd = ctx->listening_socket_fds;
  12231. while (ctx->stop_flag == 0) {
  12232. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12233. pfd[i].fd = ctx->listening_sockets[i].sock;
  12234. pfd[i].events = POLLIN;
  12235. }
  12236. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12237. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12238. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12239. * successful poll, and POLLIN is defined as
  12240. * (POLLRDNORM | POLLRDBAND)
  12241. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12242. * pfd[i].revents == POLLIN. */
  12243. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12244. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12245. }
  12246. }
  12247. }
  12248. }
  12249. /* Here stop_flag is 1 - Initiate shutdown. */
  12250. DEBUG_TRACE("%s", "stopping workers");
  12251. /* Stop signal received: somebody called mg_stop. Quit. */
  12252. close_all_listening_sockets(ctx);
  12253. /* Wakeup workers that are waiting for connections to handle. */
  12254. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12255. #if defined(ALTERNATIVE_QUEUE)
  12256. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12257. event_signal(ctx->client_wait_events[i]);
  12258. /* Since we know all sockets, we can shutdown the connections. */
  12259. if (ctx->client_socks[i].in_use) {
  12260. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12261. }
  12262. }
  12263. #else
  12264. pthread_cond_broadcast(&ctx->sq_full);
  12265. #endif
  12266. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12267. /* Join all worker threads to avoid leaking threads. */
  12268. workerthreadcount = ctx->cfg_worker_threads;
  12269. for (i = 0; i < workerthreadcount; i++) {
  12270. if (ctx->worker_threadids[i] != 0) {
  12271. mg_join_thread(ctx->worker_threadids[i]);
  12272. }
  12273. }
  12274. #if defined(USE_LUA)
  12275. /* Free Lua state of lua background task */
  12276. if (ctx->lua_background_state) {
  12277. lua_close((lua_State *)ctx->lua_background_state);
  12278. ctx->lua_background_state = 0;
  12279. }
  12280. #endif
  12281. #if !defined(NO_SSL)
  12282. if (ctx->ssl_ctx != NULL) {
  12283. uninitialize_ssl(ctx);
  12284. }
  12285. #endif
  12286. DEBUG_TRACE("%s", "exiting");
  12287. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12288. CloseHandle(tls.pthread_cond_helper_mutex);
  12289. #endif
  12290. pthread_setspecific(sTlsKey, NULL);
  12291. /* Signal mg_stop() that we're done.
  12292. * WARNING: This must be the very last thing this
  12293. * thread does, as ctx becomes invalid after this line. */
  12294. ctx->stop_flag = 2;
  12295. }
  12296. /* Threads have different return types on Windows and Unix. */
  12297. #ifdef _WIN32
  12298. static unsigned __stdcall master_thread(void *thread_func_param)
  12299. {
  12300. master_thread_run(thread_func_param);
  12301. return 0;
  12302. }
  12303. #else
  12304. static void *
  12305. master_thread(void *thread_func_param)
  12306. {
  12307. master_thread_run(thread_func_param);
  12308. return NULL;
  12309. }
  12310. #endif /* _WIN32 */
  12311. static void
  12312. free_context(struct mg_context *ctx)
  12313. {
  12314. int i;
  12315. struct mg_handler_info *tmp_rh;
  12316. if (ctx == NULL) {
  12317. return;
  12318. }
  12319. if (ctx->callbacks.exit_context) {
  12320. ctx->callbacks.exit_context(ctx);
  12321. }
  12322. /* All threads exited, no sync is needed. Destroy thread mutex and
  12323. * condvars
  12324. */
  12325. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12326. #if defined(ALTERNATIVE_QUEUE)
  12327. mg_free(ctx->client_socks);
  12328. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12329. event_destroy(ctx->client_wait_events[i]);
  12330. }
  12331. mg_free(ctx->client_wait_events);
  12332. #else
  12333. (void)pthread_cond_destroy(&ctx->sq_empty);
  12334. (void)pthread_cond_destroy(&ctx->sq_full);
  12335. #endif
  12336. /* Destroy other context global data structures mutex */
  12337. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12338. #if defined(USE_TIMERS)
  12339. timers_exit(ctx);
  12340. #endif
  12341. /* Deallocate config parameters */
  12342. for (i = 0; i < NUM_OPTIONS; i++) {
  12343. if (ctx->config[i] != NULL) {
  12344. #if defined(_MSC_VER)
  12345. #pragma warning(suppress : 6001)
  12346. #endif
  12347. mg_free(ctx->config[i]);
  12348. }
  12349. }
  12350. /* Deallocate request handlers */
  12351. while (ctx->handlers) {
  12352. tmp_rh = ctx->handlers;
  12353. ctx->handlers = tmp_rh->next;
  12354. mg_free(tmp_rh->uri);
  12355. mg_free(tmp_rh);
  12356. }
  12357. #ifndef NO_SSL
  12358. /* Deallocate SSL context */
  12359. if (ctx->ssl_ctx != NULL) {
  12360. SSL_CTX_free(ctx->ssl_ctx);
  12361. }
  12362. #endif /* !NO_SSL */
  12363. /* Deallocate worker thread ID array */
  12364. if (ctx->worker_threadids != NULL) {
  12365. mg_free(ctx->worker_threadids);
  12366. }
  12367. /* Deallocate worker thread ID array */
  12368. if (ctx->worker_connections != NULL) {
  12369. mg_free(ctx->worker_connections);
  12370. }
  12371. /* Deallocate the tls variable */
  12372. if (mg_atomic_dec(&sTlsInit) == 0) {
  12373. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12374. DeleteCriticalSection(&global_log_file_lock);
  12375. #endif /* _WIN32 && !__SYMBIAN32__ */
  12376. #if !defined(_WIN32)
  12377. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12378. #endif
  12379. pthread_key_delete(sTlsKey);
  12380. #if defined(USE_LUA)
  12381. lua_exit_optional_libraries();
  12382. #endif
  12383. }
  12384. /* deallocate system name string */
  12385. mg_free(ctx->systemName);
  12386. /* Deallocate context itself */
  12387. mg_free(ctx);
  12388. }
  12389. void
  12390. mg_stop(struct mg_context *ctx)
  12391. {
  12392. pthread_t mt;
  12393. if (!ctx) {
  12394. return;
  12395. }
  12396. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12397. * two threads is not allowed. */
  12398. mt = ctx->masterthreadid;
  12399. if (mt == 0) {
  12400. return;
  12401. }
  12402. ctx->masterthreadid = 0;
  12403. /* Set stop flag, so all threads know they have to exit. */
  12404. ctx->stop_flag = 1;
  12405. /* Wait until everything has stopped. */
  12406. while (ctx->stop_flag != 2) {
  12407. (void)mg_sleep(10);
  12408. }
  12409. mg_join_thread(mt);
  12410. free_context(ctx);
  12411. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12412. (void)WSACleanup();
  12413. #endif /* _WIN32 && !__SYMBIAN32__ */
  12414. }
  12415. static void
  12416. get_system_name(char **sysName)
  12417. {
  12418. #if defined(_WIN32)
  12419. #if !defined(__SYMBIAN32__)
  12420. #if defined(_WIN32_WCE)
  12421. *sysName = mg_strdup("WinCE");
  12422. #else
  12423. char name[128];
  12424. DWORD dwVersion = 0;
  12425. DWORD dwMajorVersion = 0;
  12426. DWORD dwMinorVersion = 0;
  12427. DWORD dwBuild = 0;
  12428. #ifdef _MSC_VER
  12429. #pragma warning(push)
  12430. /* GetVersion was declared deprecated */
  12431. #pragma warning(disable : 4996)
  12432. #endif
  12433. dwVersion = GetVersion();
  12434. #ifdef _MSC_VER
  12435. #pragma warning(pop)
  12436. #endif
  12437. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12438. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12439. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12440. (void)dwBuild;
  12441. sprintf(name,
  12442. "Windows %u.%u",
  12443. (unsigned)dwMajorVersion,
  12444. (unsigned)dwMinorVersion);
  12445. *sysName = mg_strdup(name);
  12446. #endif
  12447. #else
  12448. *sysName = mg_strdup("Symbian");
  12449. #endif
  12450. #else
  12451. struct utsname name;
  12452. memset(&name, 0, sizeof(name));
  12453. uname(&name);
  12454. *sysName = mg_strdup(name.sysname);
  12455. #endif
  12456. }
  12457. struct mg_context *
  12458. mg_start(const struct mg_callbacks *callbacks,
  12459. void *user_data,
  12460. const char **options)
  12461. {
  12462. struct mg_context *ctx;
  12463. const char *name, *value, *default_value;
  12464. int idx, ok, workerthreadcount;
  12465. unsigned int i;
  12466. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12467. struct mg_workerTLS tls;
  12468. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12469. WSADATA data;
  12470. WSAStartup(MAKEWORD(2, 2), &data);
  12471. #endif /* _WIN32 && !__SYMBIAN32__ */
  12472. /* Allocate context and initialize reasonable general case defaults. */
  12473. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12474. return NULL;
  12475. }
  12476. /* Random number generator will initialize at the first call */
  12477. ctx->auth_nonce_mask =
  12478. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12479. if (mg_atomic_inc(&sTlsInit) == 1) {
  12480. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12481. InitializeCriticalSection(&global_log_file_lock);
  12482. #endif /* _WIN32 && !__SYMBIAN32__ */
  12483. #if !defined(_WIN32)
  12484. pthread_mutexattr_init(&pthread_mutex_attr);
  12485. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12486. #endif
  12487. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12488. /* Fatal error - abort start. However, this situation should
  12489. * never
  12490. * occur in practice. */
  12491. mg_atomic_dec(&sTlsInit);
  12492. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12493. mg_free(ctx);
  12494. return NULL;
  12495. }
  12496. #if defined(USE_LUA)
  12497. lua_init_optional_libraries();
  12498. #endif
  12499. } else {
  12500. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12501. * initialized. */
  12502. mg_sleep(1);
  12503. }
  12504. tls.is_master = -1;
  12505. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12506. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12507. tls.pthread_cond_helper_mutex = NULL;
  12508. #endif
  12509. pthread_setspecific(sTlsKey, &tls);
  12510. /* Dummy use this function - in some #ifdef combinations it's used,
  12511. * while it's not used in others, but GCC seems to stupid to understand
  12512. * #pragma GCC diagnostic ignored "-Wunused-function"
  12513. * in cases the function is unused, and it also complains on
  12514. * __attribute((unused))__ in cases it is used.
  12515. * So dummy use it, to have our peace. */
  12516. (void)mg_current_thread_id();
  12517. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12518. #if !defined(ALTERNATIVE_QUEUE)
  12519. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12520. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12521. #endif
  12522. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12523. if (!ok) {
  12524. /* Fatal error - abort start. However, this situation should never
  12525. * occur in practice. */
  12526. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12527. mg_free(ctx);
  12528. pthread_setspecific(sTlsKey, NULL);
  12529. return NULL;
  12530. }
  12531. if (callbacks) {
  12532. ctx->callbacks = *callbacks;
  12533. exit_callback = callbacks->exit_context;
  12534. ctx->callbacks.exit_context = 0;
  12535. }
  12536. ctx->user_data = user_data;
  12537. ctx->handlers = NULL;
  12538. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12539. ctx->shared_lua_websockets = 0;
  12540. #endif
  12541. while (options && (name = *options++) != NULL) {
  12542. if ((idx = get_option_index(name)) == -1) {
  12543. mg_cry(fc(ctx), "Invalid option: %s", name);
  12544. free_context(ctx);
  12545. pthread_setspecific(sTlsKey, NULL);
  12546. return NULL;
  12547. } else if ((value = *options++) == NULL) {
  12548. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12549. free_context(ctx);
  12550. pthread_setspecific(sTlsKey, NULL);
  12551. return NULL;
  12552. }
  12553. if (ctx->config[idx] != NULL) {
  12554. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12555. mg_free(ctx->config[idx]);
  12556. }
  12557. ctx->config[idx] = mg_strdup(value);
  12558. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12559. }
  12560. /* Set default value if needed */
  12561. for (i = 0; config_options[i].name != NULL; i++) {
  12562. default_value = config_options[i].default_value;
  12563. if (ctx->config[i] == NULL && default_value != NULL) {
  12564. ctx->config[i] = mg_strdup(default_value);
  12565. }
  12566. }
  12567. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12568. if (workerthreadcount > MAX_WORKER_THREADS) {
  12569. mg_cry(fc(ctx), "Too many worker threads");
  12570. free_context(ctx);
  12571. pthread_setspecific(sTlsKey, NULL);
  12572. return NULL;
  12573. }
  12574. if (workerthreadcount <= 0) {
  12575. mg_cry(fc(ctx), "Invalid number of worker threads");
  12576. free_context(ctx);
  12577. pthread_setspecific(sTlsKey, NULL);
  12578. return NULL;
  12579. }
  12580. #if defined(NO_FILES)
  12581. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12582. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12583. free_context(ctx);
  12584. pthread_setspecific(sTlsKey, NULL);
  12585. return NULL;
  12586. }
  12587. #endif
  12588. get_system_name(&ctx->systemName);
  12589. #if defined(USE_LUA)
  12590. /* If a Lua background script has been configured, start it. */
  12591. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  12592. char ebuf[256];
  12593. void *state = (void *)mg_prepare_lua_context_script(
  12594. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  12595. if (!state) {
  12596. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  12597. free_context(ctx);
  12598. pthread_setspecific(sTlsKey, NULL);
  12599. return NULL;
  12600. }
  12601. ctx->lua_background_state = state;
  12602. } else {
  12603. ctx->lua_background_state = 0;
  12604. }
  12605. #endif
  12606. /* NOTE(lsm): order is important here. SSL certificates must
  12607. * be initialized before listening ports. UID must be set last. */
  12608. if (!set_gpass_option(ctx) ||
  12609. #if !defined(NO_SSL)
  12610. !set_ssl_option(ctx) ||
  12611. #endif
  12612. !set_ports_option(ctx) ||
  12613. #if !defined(_WIN32)
  12614. !set_uid_option(ctx) ||
  12615. #endif
  12616. !set_acl_option(ctx)) {
  12617. free_context(ctx);
  12618. pthread_setspecific(sTlsKey, NULL);
  12619. return NULL;
  12620. }
  12621. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12622. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12623. * won't kill the whole process. */
  12624. (void)signal(SIGPIPE, SIG_IGN);
  12625. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12626. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12627. ctx->worker_threadids =
  12628. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12629. if (ctx->worker_threadids == NULL) {
  12630. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12631. free_context(ctx);
  12632. pthread_setspecific(sTlsKey, NULL);
  12633. return NULL;
  12634. }
  12635. ctx->worker_connections =
  12636. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  12637. sizeof(struct mg_connection));
  12638. if (ctx->worker_connections == NULL) {
  12639. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  12640. free_context(ctx);
  12641. pthread_setspecific(sTlsKey, NULL);
  12642. return NULL;
  12643. }
  12644. #if defined(ALTERNATIVE_QUEUE)
  12645. ctx->client_wait_events =
  12646. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  12647. if (ctx->client_wait_events == NULL) {
  12648. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12649. mg_free(ctx->worker_threadids);
  12650. free_context(ctx);
  12651. pthread_setspecific(sTlsKey, NULL);
  12652. return NULL;
  12653. }
  12654. ctx->client_socks =
  12655. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12656. if (ctx->client_wait_events == NULL) {
  12657. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12658. mg_free(ctx->client_socks);
  12659. mg_free(ctx->worker_threadids);
  12660. free_context(ctx);
  12661. pthread_setspecific(sTlsKey, NULL);
  12662. return NULL;
  12663. }
  12664. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12665. ctx->client_wait_events[i] = event_create();
  12666. if (ctx->client_wait_events[i] == 0) {
  12667. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12668. while (i > 0) {
  12669. i--;
  12670. event_destroy(ctx->client_wait_events[i]);
  12671. }
  12672. mg_free(ctx->client_socks);
  12673. mg_free(ctx->worker_threadids);
  12674. free_context(ctx);
  12675. pthread_setspecific(sTlsKey, NULL);
  12676. return NULL;
  12677. }
  12678. }
  12679. #endif
  12680. #if defined(USE_TIMERS)
  12681. if (timers_init(ctx) != 0) {
  12682. mg_cry(fc(ctx), "Error creating timers");
  12683. free_context(ctx);
  12684. pthread_setspecific(sTlsKey, NULL);
  12685. return NULL;
  12686. }
  12687. #endif
  12688. /* Context has been created - init user libraries */
  12689. if (ctx->callbacks.init_context) {
  12690. ctx->callbacks.init_context(ctx);
  12691. }
  12692. ctx->callbacks.exit_context = exit_callback;
  12693. ctx->context_type = 1; /* server context */
  12694. /* Start master (listening) thread */
  12695. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12696. /* Start worker threads */
  12697. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12698. struct worker_thread_args *wta =
  12699. mg_malloc(sizeof(struct worker_thread_args));
  12700. if (wta) {
  12701. wta->ctx = ctx;
  12702. wta->index = (int)i;
  12703. }
  12704. if ((wta == NULL)
  12705. || (mg_start_thread_with_id(worker_thread,
  12706. wta,
  12707. &ctx->worker_threadids[i]) != 0)) {
  12708. /* thread was not created */
  12709. if (wta != NULL) {
  12710. mg_free(wta);
  12711. }
  12712. if (i > 0) {
  12713. mg_cry(fc(ctx),
  12714. "Cannot start worker thread %i: error %ld",
  12715. i + 1,
  12716. (long)ERRNO);
  12717. } else {
  12718. mg_cry(fc(ctx),
  12719. "Cannot create threads: error %ld",
  12720. (long)ERRNO);
  12721. free_context(ctx);
  12722. pthread_setspecific(sTlsKey, NULL);
  12723. return NULL;
  12724. }
  12725. break;
  12726. }
  12727. }
  12728. pthread_setspecific(sTlsKey, NULL);
  12729. return ctx;
  12730. }
  12731. /* Feature check API function */
  12732. unsigned
  12733. mg_check_feature(unsigned feature)
  12734. {
  12735. static const unsigned feature_set = 0
  12736. /* Set bits for available features according to API documentation.
  12737. * This bit mask is created at compile time, according to the active
  12738. * preprocessor defines. It is a single const value at runtime. */
  12739. #if !defined(NO_FILES)
  12740. | 0x0001u
  12741. #endif
  12742. #if !defined(NO_SSL)
  12743. | 0x0002u
  12744. #endif
  12745. #if !defined(NO_CGI)
  12746. | 0x0004u
  12747. #endif
  12748. #if defined(USE_IPV6)
  12749. | 0x0008u
  12750. #endif
  12751. #if defined(USE_WEBSOCKET)
  12752. | 0x0010u
  12753. #endif
  12754. #if defined(USE_LUA)
  12755. | 0x0020u
  12756. #endif
  12757. #if defined(USE_DUKTAPE)
  12758. | 0x0040u
  12759. #endif
  12760. #if !defined(NO_CACHING)
  12761. | 0x0080u
  12762. #endif
  12763. /* Set some extra bits not defined in the API documentation.
  12764. * These bits may change without further notice. */
  12765. #if defined(MG_LEGACY_INTERFACE)
  12766. | 0x8000u
  12767. #endif
  12768. #if defined(MEMORY_DEBUGGING)
  12769. | 0x0100u
  12770. #endif
  12771. #if defined(USE_TIMERS)
  12772. | 0x0200u
  12773. #endif
  12774. #if !defined(NO_NONCE_CHECK)
  12775. | 0x0400u
  12776. #endif
  12777. #if !defined(NO_POPEN)
  12778. | 0x0800u
  12779. #endif
  12780. ;
  12781. return (feature & feature_set);
  12782. }
  12783. /* Get system information. It can be printed or stored by the caller.
  12784. * Return the size of available information. */
  12785. static int
  12786. mg_get_system_info_impl(char *buffer, int buflen)
  12787. {
  12788. char block[256];
  12789. int system_info_length = 0;
  12790. #if defined(_WIN32)
  12791. const char *eol = "\r\n";
  12792. #else
  12793. const char *eol = "\n";
  12794. #endif
  12795. /* Server version */
  12796. {
  12797. const char *version = mg_version();
  12798. mg_snprintf(NULL,
  12799. NULL,
  12800. block,
  12801. sizeof(block),
  12802. "Server Version: %s%s",
  12803. version,
  12804. eol);
  12805. system_info_length += (int)strlen(block);
  12806. if (system_info_length < buflen) {
  12807. strcat(buffer, block);
  12808. }
  12809. }
  12810. /* System info */
  12811. {
  12812. #if defined(_WIN32)
  12813. #if !defined(__SYMBIAN32__)
  12814. DWORD dwVersion = 0;
  12815. DWORD dwMajorVersion = 0;
  12816. DWORD dwMinorVersion = 0;
  12817. SYSTEM_INFO si;
  12818. GetSystemInfo(&si);
  12819. #ifdef _MSC_VER
  12820. #pragma warning(push)
  12821. /* GetVersion was declared deprecated */
  12822. #pragma warning(disable : 4996)
  12823. #endif
  12824. dwVersion = GetVersion();
  12825. #ifdef _MSC_VER
  12826. #pragma warning(pop)
  12827. #endif
  12828. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12829. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12830. mg_snprintf(NULL,
  12831. NULL,
  12832. block,
  12833. sizeof(block),
  12834. "Windows %u.%u%s",
  12835. (unsigned)dwMajorVersion,
  12836. (unsigned)dwMinorVersion,
  12837. eol);
  12838. system_info_length += (int)strlen(block);
  12839. if (system_info_length < buflen) {
  12840. strcat(buffer, block);
  12841. }
  12842. mg_snprintf(NULL,
  12843. NULL,
  12844. block,
  12845. sizeof(block),
  12846. "CPU: type %u, cores %u, mask %x%s",
  12847. (unsigned)si.wProcessorArchitecture,
  12848. (unsigned)si.dwNumberOfProcessors,
  12849. (unsigned)si.dwActiveProcessorMask,
  12850. eol);
  12851. system_info_length += (int)strlen(block);
  12852. if (system_info_length < buflen) {
  12853. strcat(buffer, block);
  12854. }
  12855. #else
  12856. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  12857. system_info_length += (int)strlen(block);
  12858. if (system_info_length < buflen) {
  12859. strcat(buffer, block);
  12860. }
  12861. #endif
  12862. #else
  12863. struct utsname name;
  12864. memset(&name, 0, sizeof(name));
  12865. uname(&name);
  12866. mg_snprintf(NULL,
  12867. NULL,
  12868. block,
  12869. sizeof(block),
  12870. "%s %s (%s) - %s%s",
  12871. name.sysname,
  12872. name.version,
  12873. name.release,
  12874. name.machine,
  12875. eol);
  12876. system_info_length += (int)strlen(block);
  12877. if (system_info_length < buflen) {
  12878. strcat(buffer, block);
  12879. }
  12880. #endif
  12881. }
  12882. /* Features */
  12883. {
  12884. mg_snprintf(NULL,
  12885. NULL,
  12886. block,
  12887. sizeof(block),
  12888. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  12889. mg_check_feature(0xFFFFFFFFu),
  12890. eol,
  12891. mg_check_feature(1) ? " Files" : "",
  12892. mg_check_feature(2) ? " HTTPS" : "",
  12893. mg_check_feature(4) ? " CGI" : "",
  12894. mg_check_feature(8) ? " IPv6" : "",
  12895. mg_check_feature(16) ? " WebSockets" : "",
  12896. mg_check_feature(32) ? " Lua" : "",
  12897. mg_check_feature(64) ? " JavaScript" : "",
  12898. mg_check_feature(128) ? " Cache" : "",
  12899. eol);
  12900. system_info_length += (int)strlen(block);
  12901. if (system_info_length < buflen) {
  12902. strcat(buffer, block);
  12903. }
  12904. #ifdef USE_LUA
  12905. mg_snprintf(NULL,
  12906. NULL,
  12907. block,
  12908. sizeof(block),
  12909. "Lua Version: %u (%s)%s",
  12910. (unsigned)LUA_VERSION_NUM,
  12911. LUA_RELEASE,
  12912. eol);
  12913. system_info_length += (int)strlen(block);
  12914. if (system_info_length < buflen) {
  12915. strcat(buffer, block);
  12916. }
  12917. #endif
  12918. #if defined(USE_DUKTAPE)
  12919. mg_snprintf(NULL,
  12920. NULL,
  12921. block,
  12922. sizeof(block),
  12923. "JavaScript: Duktape %u.%u.%u%s",
  12924. (unsigned)DUK_VERSION / 10000,
  12925. ((unsigned)DUK_VERSION / 100) % 100,
  12926. (unsigned)DUK_VERSION % 100,
  12927. eol);
  12928. system_info_length += (int)strlen(block);
  12929. if (system_info_length < buflen) {
  12930. strcat(buffer, block);
  12931. }
  12932. #endif
  12933. }
  12934. /* Build date */
  12935. {
  12936. mg_snprintf(
  12937. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  12938. system_info_length += (int)strlen(block);
  12939. if (system_info_length < buflen) {
  12940. strcat(buffer, block);
  12941. }
  12942. }
  12943. /* Compiler information */
  12944. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  12945. {
  12946. #if defined(_MSC_VER)
  12947. mg_snprintf(NULL,
  12948. NULL,
  12949. block,
  12950. sizeof(block),
  12951. "MSC: %u (%u)%s",
  12952. (unsigned)_MSC_VER,
  12953. (unsigned)_MSC_FULL_VER,
  12954. eol);
  12955. system_info_length += (int)strlen(block);
  12956. if (system_info_length < buflen) {
  12957. strcat(buffer, block);
  12958. }
  12959. #elif defined(__MINGW64__)
  12960. mg_snprintf(NULL,
  12961. NULL,
  12962. block,
  12963. sizeof(block),
  12964. "MinGW64: %u.%u%s",
  12965. (unsigned)__MINGW64_VERSION_MAJOR,
  12966. (unsigned)__MINGW64_VERSION_MINOR,
  12967. eol);
  12968. system_info_length += (int)strlen(block);
  12969. if (system_info_length < buflen) {
  12970. strcat(buffer, block);
  12971. }
  12972. mg_snprintf(NULL,
  12973. NULL,
  12974. block,
  12975. sizeof(block),
  12976. "MinGW32: %u.%u%s",
  12977. (unsigned)__MINGW32_MAJOR_VERSION,
  12978. (unsigned)__MINGW32_MINOR_VERSION,
  12979. eol);
  12980. system_info_length += (int)strlen(block);
  12981. if (system_info_length < buflen) {
  12982. strcat(buffer, block);
  12983. }
  12984. #elif defined(__MINGW32__)
  12985. mg_snprintf(NULL,
  12986. NULL,
  12987. block,
  12988. sizeof(block),
  12989. "MinGW32: %u.%u%s",
  12990. (unsigned)__MINGW32_MAJOR_VERSION,
  12991. (unsigned)__MINGW32_MINOR_VERSION,
  12992. eol);
  12993. system_info_length += (int)strlen(block);
  12994. if (system_info_length < buflen) {
  12995. strcat(buffer, block);
  12996. }
  12997. #elif defined(__clang__)
  12998. mg_snprintf(NULL,
  12999. NULL,
  13000. block,
  13001. sizeof(block),
  13002. "clang: %u.%u.%u (%s)%s",
  13003. __clang_major__,
  13004. __clang_minor__,
  13005. __clang_patchlevel__,
  13006. __clang_version__,
  13007. eol);
  13008. system_info_length += (int)strlen(block);
  13009. if (system_info_length < buflen) {
  13010. strcat(buffer, block);
  13011. }
  13012. #elif defined(__GNUC__)
  13013. mg_snprintf(NULL,
  13014. NULL,
  13015. block,
  13016. sizeof(block),
  13017. "gcc: %u.%u.%u%s",
  13018. (unsigned)__GNUC__,
  13019. (unsigned)__GNUC_MINOR__,
  13020. (unsigned)__GNUC_PATCHLEVEL__,
  13021. eol);
  13022. system_info_length += (int)strlen(block);
  13023. if (system_info_length < buflen) {
  13024. strcat(buffer, block);
  13025. }
  13026. #elif defined(__INTEL_COMPILER)
  13027. mg_snprintf(NULL,
  13028. NULL,
  13029. block,
  13030. sizeof(block),
  13031. "Intel C/C++: %u%s",
  13032. (unsigned)__INTEL_COMPILER,
  13033. eol);
  13034. system_info_length += (int)strlen(block);
  13035. if (system_info_length < buflen) {
  13036. strcat(buffer, block);
  13037. }
  13038. #elif defined(__BORLANDC__)
  13039. mg_snprintf(NULL,
  13040. NULL,
  13041. block,
  13042. sizeof(block),
  13043. "Borland C: 0x%x%s",
  13044. (unsigned)__BORLANDC__,
  13045. eol);
  13046. system_info_length += (int)strlen(block);
  13047. if (system_info_length < buflen) {
  13048. strcat(buffer, block);
  13049. }
  13050. #elif defined(__SUNPRO_C)
  13051. mg_snprintf(NULL,
  13052. NULL,
  13053. block,
  13054. sizeof(block),
  13055. "Solaris: 0x%x%s",
  13056. (unsigned)__SUNPRO_C,
  13057. eol);
  13058. system_info_length += (int)strlen(block);
  13059. if (system_info_length < buflen) {
  13060. strcat(buffer, block);
  13061. }
  13062. #else
  13063. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13064. system_info_length += (int)strlen(block);
  13065. if (system_info_length < buflen) {
  13066. strcat(buffer, block);
  13067. }
  13068. #endif
  13069. }
  13070. /* Determine 32/64 bit data mode.
  13071. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13072. {
  13073. mg_snprintf(NULL,
  13074. NULL,
  13075. block,
  13076. sizeof(block),
  13077. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13078. "ptr:%u, size:%u, time:%u%s",
  13079. (unsigned)sizeof(short),
  13080. (unsigned)sizeof(int),
  13081. (unsigned)sizeof(long),
  13082. (unsigned)sizeof(long long),
  13083. (unsigned)sizeof(float),
  13084. (unsigned)sizeof(double),
  13085. (unsigned)sizeof(long double),
  13086. (unsigned)sizeof(char),
  13087. (unsigned)sizeof(wchar_t),
  13088. (unsigned)sizeof(void *),
  13089. (unsigned)sizeof(size_t),
  13090. (unsigned)sizeof(time_t),
  13091. eol);
  13092. system_info_length += (int)strlen(block);
  13093. if (system_info_length < buflen) {
  13094. strcat(buffer, block);
  13095. }
  13096. }
  13097. return system_info_length;
  13098. }
  13099. /* Get system information. It can be printed or stored by the caller.
  13100. * Return the size of available information. */
  13101. int
  13102. mg_get_system_info(char *buffer, int buflen)
  13103. {
  13104. if ((buffer == NULL) || (buflen < 1)) {
  13105. return mg_get_system_info_impl(NULL, 0);
  13106. } else {
  13107. /* Reset buffer, so we can always use strcat. */
  13108. buffer[0] = 0;
  13109. return mg_get_system_info_impl(buffer, buflen);
  13110. }
  13111. }
  13112. /* mg_init_library counter */
  13113. static int mg_init_library_called = 0;
  13114. /* Initialize this library. This function does not need to be thread safe. */
  13115. unsigned
  13116. mg_init_library(unsigned features)
  13117. {
  13118. /* Currently we do nothing here. This is planned for Version 1.10.
  13119. * For now, we just add this function, so clients can be changed early. */
  13120. if (mg_init_library_called <= 0) {
  13121. mg_init_library_called = 1;
  13122. return mg_check_feature(features & 0xFFu);
  13123. }
  13124. return 0;
  13125. }
  13126. /* Un-initialize this library. */
  13127. unsigned
  13128. mg_exit_library(void)
  13129. {
  13130. if (mg_init_library_called <= 0) {
  13131. return 0;
  13132. }
  13133. mg_init_library_called--;
  13134. return 1;
  13135. }
  13136. /* End of civetweb.c */