civetweb.c 403 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230
  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. #ifndef CIVETWEB_HEADER_INCLUDED
  101. /* Include the header file here, so the CivetWeb interface is defined for the
  102. * entire implementation, including the following forward definitions. */
  103. #include "civetweb.h"
  104. #endif
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __clang__
  116. /* When using -Weverything, clang does not accept it's own headers
  117. * in a release build configuration. Disable what is too much in
  118. * -Weverything. */
  119. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  120. #endif
  121. #ifdef __MACH__ /* Apple OSX section */
  122. #ifdef __clang__
  123. /* Avoid warnings for Xopen 7.00 and higher */
  124. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  125. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  126. #endif
  127. #define CLOCK_MONOTONIC (1)
  128. #define CLOCK_REALTIME (2)
  129. #include <sys/errno.h>
  130. #include <sys/time.h>
  131. #include <mach/clock.h>
  132. #include <mach/mach.h>
  133. #include <mach/mach_time.h>
  134. #include <assert.h>
  135. /* clock_gettime is not implemented on OSX prior to 10.12 */
  136. static int
  137. _civet_clock_gettime(int clk_id, struct timespec *t)
  138. {
  139. memset(t, 0, sizeof(*t));
  140. if (clk_id == CLOCK_REALTIME) {
  141. struct timeval now;
  142. int rv = gettimeofday(&now, NULL);
  143. if (rv) {
  144. return rv;
  145. }
  146. t->tv_sec = now.tv_sec;
  147. t->tv_nsec = now.tv_usec * 1000;
  148. return 0;
  149. } else if (clk_id == CLOCK_MONOTONIC) {
  150. static uint64_t clock_start_time = 0;
  151. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  152. uint64_t now = mach_absolute_time();
  153. if (clock_start_time == 0) {
  154. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  155. #if defined(DEBUG)
  156. assert(mach_status == KERN_SUCCESS);
  157. #else
  158. /* appease "unused variable" warning for release builds */
  159. (void)mach_status;
  160. #endif
  161. clock_start_time = now;
  162. }
  163. now = (uint64_t)((double)(now - clock_start_time)
  164. * (double)timebase_ifo.numer
  165. / (double)timebase_ifo.denom);
  166. t->tv_sec = now / 1000000000;
  167. t->tv_nsec = now % 1000000000;
  168. return 0;
  169. }
  170. return -1; /* EINVAL - Clock ID is unknown */
  171. }
  172. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  173. #ifdef __CLOCK_AVAILABILITY
  174. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  175. * declared but it may be NULL at runtime. So we need to check before using
  176. * it. */
  177. static int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #include <stdint.h>
  200. #ifndef INT64_MAX
  201. #define INT64_MAX (9223372036854775807)
  202. #endif
  203. #ifndef MAX_WORKER_THREADS
  204. #define MAX_WORKER_THREADS (1024 * 64)
  205. #endif
  206. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  207. #define SOCKET_TIMEOUT_QUANTUM (2000)
  208. #endif
  209. #define SHUTDOWN_RD (0)
  210. #define SHUTDOWN_WR (1)
  211. #define SHUTDOWN_BOTH (2)
  212. mg_static_assert(MAX_WORKER_THREADS >= 1,
  213. "worker threads must be a positive number");
  214. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  215. "size_t data type size check");
  216. #if defined(_WIN32) \
  217. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  218. #include <windows.h>
  219. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  220. #include <ws2tcpip.h>
  221. typedef const char *SOCK_OPT_TYPE;
  222. #if !defined(PATH_MAX)
  223. #define PATH_MAX (MAX_PATH)
  224. #endif
  225. #if !defined(PATH_MAX)
  226. #define PATH_MAX (4096)
  227. #endif
  228. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  229. #ifndef _IN_PORT_T
  230. #ifndef in_port_t
  231. #define in_port_t u_short
  232. #endif
  233. #endif
  234. #ifndef _WIN32_WCE
  235. #include <process.h>
  236. #include <direct.h>
  237. #include <io.h>
  238. #else /* _WIN32_WCE */
  239. #define NO_CGI /* WinCE has no pipes */
  240. #define NO_POPEN /* WinCE has no popen */
  241. typedef long off_t;
  242. #define errno ((int)(GetLastError()))
  243. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  244. #endif /* _WIN32_WCE */
  245. #define MAKEUQUAD(lo, hi) \
  246. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  247. #define RATE_DIFF (10000000) /* 100 nsecs */
  248. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  249. #define SYS2UNIX_TIME(lo, hi) \
  250. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  251. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  252. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  253. * Also use _strtoui64 on modern M$ compilers */
  254. #if defined(_MSC_VER)
  255. #if (_MSC_VER < 1300)
  256. #define STRX(x) #x
  257. #define STR(x) STRX(x)
  258. #define __func__ __FILE__ ":" STR(__LINE__)
  259. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  260. #define strtoll(x, y, z) (_atoi64(x))
  261. #else
  262. #define __func__ __FUNCTION__
  263. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  264. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  265. #endif
  266. #endif /* _MSC_VER */
  267. #define ERRNO ((int)(GetLastError()))
  268. #define NO_SOCKLEN_T
  269. #if defined(_WIN64) || defined(__MINGW64__)
  270. #define SSL_LIB "ssleay64.dll"
  271. #define CRYPTO_LIB "libeay64.dll"
  272. #else
  273. #define SSL_LIB "ssleay32.dll"
  274. #define CRYPTO_LIB "libeay32.dll"
  275. #endif
  276. #define O_NONBLOCK (0)
  277. #ifndef W_OK
  278. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  279. #endif
  280. #if !defined(EWOULDBLOCK)
  281. #define EWOULDBLOCK WSAEWOULDBLOCK
  282. #endif /* !EWOULDBLOCK */
  283. #define _POSIX_
  284. #define INT64_FMT "I64d"
  285. #define UINT64_FMT "I64u"
  286. #define WINCDECL __cdecl
  287. #define vsnprintf_impl _vsnprintf
  288. #define access _access
  289. #define mg_sleep(x) (Sleep(x))
  290. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  291. #ifndef popen
  292. #define popen(x, y) (_popen(x, y))
  293. #endif
  294. #ifndef pclose
  295. #define pclose(x) (_pclose(x))
  296. #endif
  297. #define close(x) (_close(x))
  298. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  299. #define RTLD_LAZY (0)
  300. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  301. #define fdopen(x, y) (_fdopen((x), (y)))
  302. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  303. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  304. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  305. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  306. #define sleep(x) (Sleep((x)*1000))
  307. #define rmdir(x) (_rmdir(x))
  308. #define timegm(x) (_mkgmtime(x))
  309. #if !defined(fileno)
  310. #define fileno(x) (_fileno(x))
  311. #endif /* !fileno MINGW #defines fileno */
  312. typedef HANDLE pthread_mutex_t;
  313. typedef DWORD pthread_key_t;
  314. typedef HANDLE pthread_t;
  315. typedef struct {
  316. CRITICAL_SECTION threadIdSec;
  317. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  318. } pthread_cond_t;
  319. #ifndef __clockid_t_defined
  320. typedef DWORD clockid_t;
  321. #endif
  322. #ifndef CLOCK_MONOTONIC
  323. #define CLOCK_MONOTONIC (1)
  324. #endif
  325. #ifndef CLOCK_REALTIME
  326. #define CLOCK_REALTIME (2)
  327. #endif
  328. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  329. #define _TIMESPEC_DEFINED
  330. #endif
  331. #ifndef _TIMESPEC_DEFINED
  332. struct timespec {
  333. time_t tv_sec; /* seconds */
  334. long tv_nsec; /* nanoseconds */
  335. };
  336. #endif
  337. #if !defined(WIN_PTHREADS_TIME_H)
  338. #define MUST_IMPLEMENT_CLOCK_GETTIME
  339. #endif
  340. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  341. #define clock_gettime mg_clock_gettime
  342. static int
  343. clock_gettime(clockid_t clk_id, struct timespec *tp)
  344. {
  345. FILETIME ft;
  346. ULARGE_INTEGER li;
  347. BOOL ok = FALSE;
  348. double d;
  349. static double perfcnt_per_sec = 0.0;
  350. if (tp) {
  351. memset(tp, 0, sizeof(*tp));
  352. if (clk_id == CLOCK_REALTIME) {
  353. GetSystemTimeAsFileTime(&ft);
  354. li.LowPart = ft.dwLowDateTime;
  355. li.HighPart = ft.dwHighDateTime;
  356. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  357. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  358. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  359. ok = TRUE;
  360. } else if (clk_id == CLOCK_MONOTONIC) {
  361. if (perfcnt_per_sec == 0.0) {
  362. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  363. perfcnt_per_sec = 1.0 / li.QuadPart;
  364. }
  365. if (perfcnt_per_sec != 0.0) {
  366. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  367. d = li.QuadPart * perfcnt_per_sec;
  368. tp->tv_sec = (time_t)d;
  369. d -= tp->tv_sec;
  370. tp->tv_nsec = (long)(d * 1.0E9);
  371. ok = TRUE;
  372. }
  373. }
  374. }
  375. return ok ? 0 : -1;
  376. }
  377. #endif
  378. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  379. static int pthread_mutex_lock(pthread_mutex_t *);
  380. static int pthread_mutex_unlock(pthread_mutex_t *);
  381. static void path_to_unicode(const struct mg_connection *conn,
  382. const char *path,
  383. wchar_t *wbuf,
  384. size_t wbuf_len);
  385. /* All file operations need to be rewritten to solve #246. */
  386. #include "file_ops.inl"
  387. struct mg_file;
  388. static const char *
  389. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  390. /* POSIX dirent interface */
  391. struct dirent {
  392. char d_name[PATH_MAX];
  393. };
  394. typedef struct DIR {
  395. HANDLE handle;
  396. WIN32_FIND_DATAW info;
  397. struct dirent result;
  398. } DIR;
  399. #if defined(_WIN32) && !defined(POLLIN)
  400. #ifndef HAVE_POLL
  401. struct pollfd {
  402. SOCKET fd;
  403. short events;
  404. short revents;
  405. };
  406. #define POLLIN (0x0300)
  407. #endif
  408. #endif
  409. /* Mark required libraries */
  410. #if defined(_MSC_VER)
  411. #pragma comment(lib, "Ws2_32.lib")
  412. #endif
  413. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. #include <sys/wait.h>
  416. #include <sys/socket.h>
  417. #include <sys/poll.h>
  418. #include <netinet/in.h>
  419. #include <arpa/inet.h>
  420. #include <sys/time.h>
  421. #include <sys/utsname.h>
  422. #include <stdint.h>
  423. #include <inttypes.h>
  424. #include <netdb.h>
  425. #include <netinet/tcp.h>
  426. typedef const void *SOCK_OPT_TYPE;
  427. #if defined(ANDROID)
  428. typedef unsigned short int in_port_t;
  429. #endif
  430. #include <pwd.h>
  431. #include <unistd.h>
  432. #include <grp.h>
  433. #include <dirent.h>
  434. #define vsnprintf_impl vsnprintf
  435. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  436. #include <dlfcn.h>
  437. #endif
  438. #include <pthread.h>
  439. #if defined(__MACH__)
  440. #define SSL_LIB "libssl.dylib"
  441. #define CRYPTO_LIB "libcrypto.dylib"
  442. #else
  443. #if !defined(SSL_LIB)
  444. #define SSL_LIB "libssl.so"
  445. #endif
  446. #if !defined(CRYPTO_LIB)
  447. #define CRYPTO_LIB "libcrypto.so"
  448. #endif
  449. #endif
  450. #ifndef O_BINARY
  451. #define O_BINARY (0)
  452. #endif /* O_BINARY */
  453. #define closesocket(a) (close(a))
  454. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  455. #define mg_remove(conn, x) (remove(x))
  456. #define mg_sleep(x) (usleep((x)*1000))
  457. #define mg_opendir(conn, x) (opendir(x))
  458. #define mg_closedir(x) (closedir(x))
  459. #define mg_readdir(x) (readdir(x))
  460. #define ERRNO (errno)
  461. #define INVALID_SOCKET (-1)
  462. #define INT64_FMT PRId64
  463. #define UINT64_FMT PRIu64
  464. typedef int SOCKET;
  465. #define WINCDECL
  466. #if defined(__hpux)
  467. /* HPUX 11 does not have monotonic, fall back to realtime */
  468. #ifndef CLOCK_MONOTONIC
  469. #define CLOCK_MONOTONIC CLOCK_REALTIME
  470. #endif
  471. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  472. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  473. * the prototypes use int* rather than socklen_t* which matches the
  474. * actual library expectation. When called with the wrong size arg
  475. * accept() returns a zero client inet addr and check_acl() always
  476. * fails. Since socklen_t is widely used below, just force replace
  477. * their typedef with int. - DTL
  478. */
  479. #define socklen_t int
  480. #endif /* hpux */
  481. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  482. WINDOWS / UNIX include block */
  483. /* va_copy should always be a macro, C99 and C++11 - DTL */
  484. #ifndef va_copy
  485. #define va_copy(x, y) ((x) = (y))
  486. #endif
  487. #ifdef _WIN32
  488. /* Create substitutes for POSIX functions in Win32. */
  489. #if defined(__MINGW32__)
  490. /* Show no warning in case system functions are not used. */
  491. #pragma GCC diagnostic push
  492. #pragma GCC diagnostic ignored "-Wunused-function"
  493. #endif
  494. static CRITICAL_SECTION global_log_file_lock;
  495. static DWORD
  496. pthread_self(void)
  497. {
  498. return GetCurrentThreadId();
  499. }
  500. static int
  501. pthread_key_create(
  502. pthread_key_t *key,
  503. void (*_ignored)(void *) /* destructor not supported for Windows */
  504. )
  505. {
  506. (void)_ignored;
  507. if ((key != 0)) {
  508. *key = TlsAlloc();
  509. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  510. }
  511. return -2;
  512. }
  513. static int
  514. pthread_key_delete(pthread_key_t key)
  515. {
  516. return TlsFree(key) ? 0 : 1;
  517. }
  518. static int
  519. pthread_setspecific(pthread_key_t key, void *value)
  520. {
  521. return TlsSetValue(key, value) ? 0 : 1;
  522. }
  523. static void *
  524. pthread_getspecific(pthread_key_t key)
  525. {
  526. return TlsGetValue(key);
  527. }
  528. #if defined(__MINGW32__)
  529. /* Enable unused function warning again */
  530. #pragma GCC diagnostic pop
  531. #endif
  532. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  533. #else
  534. static pthread_mutexattr_t pthread_mutex_attr;
  535. #endif /* _WIN32 */
  536. #define PASSWORDS_FILE_NAME ".htpasswd"
  537. #define CGI_ENVIRONMENT_SIZE (4096)
  538. #define MAX_CGI_ENVIR_VARS (256)
  539. #define MG_BUF_LEN (8192)
  540. #ifndef MAX_REQUEST_SIZE
  541. #define MAX_REQUEST_SIZE (16384)
  542. #endif
  543. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  544. "request size length must be a positive number");
  545. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  546. #if defined(_WIN32_WCE)
  547. /* Create substitutes for POSIX functions in Win32. */
  548. #if defined(__MINGW32__)
  549. /* Show no warning in case system functions are not used. */
  550. #pragma GCC diagnostic push
  551. #pragma GCC diagnostic ignored "-Wunused-function"
  552. #endif
  553. static time_t
  554. time(time_t *ptime)
  555. {
  556. time_t t;
  557. SYSTEMTIME st;
  558. FILETIME ft;
  559. GetSystemTime(&st);
  560. SystemTimeToFileTime(&st, &ft);
  561. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  562. if (ptime != NULL) {
  563. *ptime = t;
  564. }
  565. return t;
  566. }
  567. static struct tm *
  568. localtime_s(const time_t *ptime, struct tm *ptm)
  569. {
  570. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  571. FILETIME ft, lft;
  572. SYSTEMTIME st;
  573. TIME_ZONE_INFORMATION tzinfo;
  574. if (ptm == NULL) {
  575. return NULL;
  576. }
  577. *(int64_t *)&ft = t;
  578. FileTimeToLocalFileTime(&ft, &lft);
  579. FileTimeToSystemTime(&lft, &st);
  580. ptm->tm_year = st.wYear - 1900;
  581. ptm->tm_mon = st.wMonth - 1;
  582. ptm->tm_wday = st.wDayOfWeek;
  583. ptm->tm_mday = st.wDay;
  584. ptm->tm_hour = st.wHour;
  585. ptm->tm_min = st.wMinute;
  586. ptm->tm_sec = st.wSecond;
  587. ptm->tm_yday = 0; /* hope nobody uses this */
  588. ptm->tm_isdst =
  589. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  590. return ptm;
  591. }
  592. static struct tm *
  593. gmtime_s(const time_t *ptime, struct tm *ptm)
  594. {
  595. /* FIXME(lsm): fix this. */
  596. return localtime_s(ptime, ptm);
  597. }
  598. static int mg_atomic_inc(volatile int *addr);
  599. static struct tm tm_array[MAX_WORKER_THREADS];
  600. static int tm_index = 0;
  601. static struct tm *
  602. localtime(const time_t *ptime)
  603. {
  604. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  605. return localtime_s(ptime, tm_array + i);
  606. }
  607. static struct tm *
  608. gmtime(const time_t *ptime)
  609. {
  610. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  611. return gmtime_s(ptime, tm_array + i);
  612. }
  613. static size_t
  614. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  615. {
  616. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  617. * for WinCE"); */
  618. return 0;
  619. }
  620. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  621. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  622. #define remove(f) mg_remove(NULL, f)
  623. static int
  624. rename(const char *a, const char *b)
  625. {
  626. wchar_t wa[PATH_MAX];
  627. wchar_t wb[PATH_MAX];
  628. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  629. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  630. return MoveFileW(wa, wb) ? 0 : -1;
  631. }
  632. struct stat {
  633. int64_t st_size;
  634. time_t st_mtime;
  635. };
  636. static int
  637. stat(const char *name, struct stat *st)
  638. {
  639. wchar_t wbuf[PATH_MAX];
  640. WIN32_FILE_ATTRIBUTE_DATA attr;
  641. time_t creation_time, write_time;
  642. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  643. memset(&attr, 0, sizeof(attr));
  644. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  645. st->st_size =
  646. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  647. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  648. attr.ftLastWriteTime.dwHighDateTime);
  649. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  650. attr.ftCreationTime.dwHighDateTime);
  651. if (creation_time > write_time) {
  652. st->st_mtime = creation_time;
  653. } else {
  654. st->st_mtime = write_time;
  655. }
  656. return 0;
  657. }
  658. #define access(x, a) 1 /* not required anyway */
  659. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  660. /* Values from errno.h in Windows SDK (Visual Studio). */
  661. #define EEXIST 17
  662. #define EACCES 13
  663. #define ENOENT 2
  664. #if defined(__MINGW32__)
  665. /* Enable unused function warning again */
  666. #pragma GCC diagnostic pop
  667. #endif
  668. #endif /* defined(_WIN32_WCE) */
  669. static int
  670. mg_atomic_inc(volatile int *addr)
  671. {
  672. int ret;
  673. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  674. /* Depending on the SDK, this function uses either
  675. * (volatile unsigned int *) or (volatile LONG *),
  676. * so whatever you use, the other SDK is likely to raise a warning. */
  677. ret = InterlockedIncrement((volatile long *)addr);
  678. #elif defined(__GNUC__) \
  679. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  680. ret = __sync_add_and_fetch(addr, 1);
  681. #else
  682. ret = (++(*addr));
  683. #endif
  684. return ret;
  685. }
  686. static int
  687. mg_atomic_dec(volatile int *addr)
  688. {
  689. int ret;
  690. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  691. /* Depending on the SDK, this function uses either
  692. * (volatile unsigned int *) or (volatile LONG *),
  693. * so whatever you use, the other SDK is likely to raise a warning. */
  694. ret = InterlockedDecrement((volatile long *)addr);
  695. #elif defined(__GNUC__) \
  696. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  697. ret = __sync_sub_and_fetch(addr, 1);
  698. #else
  699. ret = (--(*addr));
  700. #endif
  701. return ret;
  702. }
  703. #if defined(MEMORY_DEBUGGING)
  704. static unsigned long mg_memory_debug_blockCount = 0;
  705. static unsigned long mg_memory_debug_totalMemUsed = 0;
  706. static void *
  707. mg_malloc_ex(size_t size, const char *file, unsigned line)
  708. {
  709. void *data = malloc(size + sizeof(size_t));
  710. void *memory = 0;
  711. char mallocStr[256];
  712. if (data) {
  713. *(size_t *)data = size;
  714. mg_memory_debug_totalMemUsed += size;
  715. mg_memory_debug_blockCount++;
  716. memory = (void *)(((char *)data) + sizeof(size_t));
  717. }
  718. sprintf(mallocStr,
  719. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  720. memory,
  721. (unsigned long)size,
  722. mg_memory_debug_totalMemUsed,
  723. mg_memory_debug_blockCount,
  724. file,
  725. line);
  726. #if defined(_WIN32)
  727. OutputDebugStringA(mallocStr);
  728. #else
  729. DEBUG_TRACE("%s", mallocStr);
  730. #endif
  731. return memory;
  732. }
  733. static void *
  734. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  735. {
  736. void *data = mg_malloc_ex(size * count, file, line);
  737. if (data) {
  738. memset(data, 0, size * count);
  739. }
  740. return data;
  741. }
  742. static void
  743. mg_free_ex(void *memory, const char *file, unsigned line)
  744. {
  745. char mallocStr[256];
  746. void *data = (void *)(((char *)memory) - sizeof(size_t));
  747. size_t size;
  748. if (memory) {
  749. size = *(size_t *)data;
  750. mg_memory_debug_totalMemUsed -= size;
  751. mg_memory_debug_blockCount--;
  752. sprintf(mallocStr,
  753. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  754. memory,
  755. (unsigned long)size,
  756. mg_memory_debug_totalMemUsed,
  757. mg_memory_debug_blockCount,
  758. file,
  759. line);
  760. #if defined(_WIN32)
  761. OutputDebugStringA(mallocStr);
  762. #else
  763. DEBUG_TRACE("%s", mallocStr);
  764. #endif
  765. free(data);
  766. }
  767. }
  768. static void *
  769. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  770. {
  771. char mallocStr[256];
  772. void *data;
  773. void *_realloc;
  774. size_t oldsize;
  775. if (newsize) {
  776. if (memory) {
  777. data = (void *)(((char *)memory) - sizeof(size_t));
  778. oldsize = *(size_t *)data;
  779. _realloc = realloc(data, newsize + sizeof(size_t));
  780. if (_realloc) {
  781. data = _realloc;
  782. mg_memory_debug_totalMemUsed -= oldsize;
  783. sprintf(mallocStr,
  784. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  785. memory,
  786. (unsigned long)oldsize,
  787. mg_memory_debug_totalMemUsed,
  788. mg_memory_debug_blockCount,
  789. file,
  790. line);
  791. #if defined(_WIN32)
  792. OutputDebugStringA(mallocStr);
  793. #else
  794. DEBUG_TRACE("%s", mallocStr);
  795. #endif
  796. mg_memory_debug_totalMemUsed += newsize;
  797. sprintf(mallocStr,
  798. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  799. memory,
  800. (unsigned long)newsize,
  801. mg_memory_debug_totalMemUsed,
  802. mg_memory_debug_blockCount,
  803. file,
  804. line);
  805. #if defined(_WIN32)
  806. OutputDebugStringA(mallocStr);
  807. #else
  808. DEBUG_TRACE("%s", mallocStr);
  809. #endif
  810. *(size_t *)data = newsize;
  811. data = (void *)(((char *)data) + sizeof(size_t));
  812. } else {
  813. #if defined(_WIN32)
  814. OutputDebugStringA("MEM: realloc failed\n");
  815. #else
  816. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  817. #endif
  818. return _realloc;
  819. }
  820. } else {
  821. data = mg_malloc_ex(newsize, file, line);
  822. }
  823. } else {
  824. data = 0;
  825. mg_free_ex(memory, file, line);
  826. }
  827. return data;
  828. }
  829. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  830. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  831. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  832. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  833. #else
  834. static __inline void *
  835. mg_malloc(size_t a)
  836. {
  837. return malloc(a);
  838. }
  839. static __inline void *
  840. mg_calloc(size_t a, size_t b)
  841. {
  842. return calloc(a, b);
  843. }
  844. static __inline void *
  845. mg_realloc(void *a, size_t b)
  846. {
  847. return realloc(a, b);
  848. }
  849. static __inline void
  850. mg_free(void *a)
  851. {
  852. free(a);
  853. }
  854. #endif
  855. static void mg_vsnprintf(const struct mg_connection *conn,
  856. int *truncated,
  857. char *buf,
  858. size_t buflen,
  859. const char *fmt,
  860. va_list ap);
  861. static void mg_snprintf(const struct mg_connection *conn,
  862. int *truncated,
  863. char *buf,
  864. size_t buflen,
  865. PRINTF_FORMAT_STRING(const char *fmt),
  866. ...) PRINTF_ARGS(5, 6);
  867. /* This following lines are just meant as a reminder to use the mg-functions
  868. * for memory management */
  869. #ifdef malloc
  870. #undef malloc
  871. #endif
  872. #ifdef calloc
  873. #undef calloc
  874. #endif
  875. #ifdef realloc
  876. #undef realloc
  877. #endif
  878. #ifdef free
  879. #undef free
  880. #endif
  881. #ifdef snprintf
  882. #undef snprintf
  883. #endif
  884. #ifdef vsnprintf
  885. #undef vsnprintf
  886. #endif
  887. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  888. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  889. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  890. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  891. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  892. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  893. * but this define only works well for Windows. */
  894. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  895. #endif
  896. static pthread_key_t sTlsKey; /* Thread local storage index */
  897. static int sTlsInit = 0;
  898. static int thread_idx_max = 0;
  899. struct mg_workerTLS {
  900. int is_master;
  901. unsigned long thread_idx;
  902. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  903. HANDLE pthread_cond_helper_mutex;
  904. struct mg_workerTLS *next_waiting_thread;
  905. #endif
  906. };
  907. #if defined(__GNUC__) || defined(__MINGW32__)
  908. /* Show no warning in case system functions are not used. */
  909. #pragma GCC diagnostic push
  910. #pragma GCC diagnostic ignored "-Wunused-function"
  911. #endif
  912. #if defined(__clang__)
  913. /* Show no warning in case system functions are not used. */
  914. #pragma clang diagnostic push
  915. #pragma clang diagnostic ignored "-Wunused-function"
  916. #endif
  917. /* Get a unique thread ID as unsigned long, independent from the data type
  918. * of thread IDs defined by the operating system API.
  919. * If two calls to mg_current_thread_id return the same value, they calls
  920. * are done from the same thread. If they return different values, they are
  921. * done from different threads. (Provided this function is used in the same
  922. * process context and threads are not repeatedly created and deleted, but
  923. * CivetWeb does not do that).
  924. * This function must match the signature required for SSL id callbacks:
  925. * CRYPTO_set_id_callback
  926. */
  927. static unsigned long
  928. mg_current_thread_id(void)
  929. {
  930. #ifdef _WIN32
  931. return GetCurrentThreadId();
  932. #else
  933. #ifdef __clang__
  934. #pragma clang diagnostic push
  935. #pragma clang diagnostic ignored "-Wunreachable-code"
  936. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  937. * or not, so one of the two conditions will be unreachable by construction.
  938. * Unfortunately the C standard does not define a way to check this at
  939. * compile time, since the #if preprocessor conditions can not use the sizeof
  940. * operator as an argument. */
  941. #endif
  942. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  943. /* This is the problematic case for CRYPTO_set_id_callback:
  944. * The OS pthread_t can not be cast to unsigned long. */
  945. struct mg_workerTLS *tls =
  946. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  947. if (tls == NULL) {
  948. /* SSL called from an unknown thread: Create some thread index.
  949. */
  950. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  951. tls->is_master = -2; /* -2 means "3rd party thread" */
  952. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  953. pthread_setspecific(sTlsKey, tls);
  954. }
  955. return tls->thread_idx;
  956. } else {
  957. /* pthread_t may be any data type, so a simple cast to unsigned long
  958. * can rise a warning/error, depending on the platform.
  959. * Here memcpy is used as an anything-to-anything cast. */
  960. unsigned long ret = 0;
  961. pthread_t t = pthread_self();
  962. memcpy(&ret, &t, sizeof(pthread_t));
  963. return ret;
  964. }
  965. #ifdef __clang__
  966. #pragma clang diagnostic pop
  967. #endif
  968. #endif
  969. }
  970. #if defined(__GNUC__)
  971. /* Show no warning in case system functions are not used. */
  972. #pragma GCC diagnostic pop
  973. #endif
  974. #if defined(__clang__)
  975. /* Show no warning in case system functions are not used. */
  976. #pragma clang diagnostic pop
  977. #endif
  978. #if !defined(DEBUG_TRACE)
  979. #if defined(DEBUG)
  980. static void DEBUG_TRACE_FUNC(const char *func,
  981. unsigned line,
  982. PRINTF_FORMAT_STRING(const char *fmt),
  983. ...) PRINTF_ARGS(3, 4);
  984. static void
  985. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  986. {
  987. va_list args;
  988. struct timespec tsnow;
  989. uint64_t nsnow;
  990. static uint64_t nslast;
  991. /* Get some operating system independent thread id */
  992. unsigned long thread_id = mg_current_thread_id();
  993. clock_gettime(CLOCK_REALTIME, &tsnow);
  994. nsnow = (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  995. flockfile(stdout);
  996. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  997. (unsigned long)tsnow.tv_sec,
  998. (unsigned long)tsnow.tv_nsec,
  999. nsnow - nslast,
  1000. thread_id,
  1001. func,
  1002. line);
  1003. va_start(args, fmt);
  1004. vprintf(fmt, args);
  1005. va_end(args);
  1006. putchar('\n');
  1007. fflush(stdout);
  1008. funlockfile(stdout);
  1009. nslast = nsnow;
  1010. }
  1011. #define DEBUG_TRACE(fmt, ...) \
  1012. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1013. #else
  1014. #define DEBUG_TRACE(fmt, ...) \
  1015. do { \
  1016. } while (0)
  1017. #endif /* DEBUG */
  1018. #endif /* DEBUG_TRACE */
  1019. #define MD5_STATIC static
  1020. #include "md5.inl"
  1021. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1022. #ifdef NO_SOCKLEN_T
  1023. typedef int socklen_t;
  1024. #endif /* NO_SOCKLEN_T */
  1025. #define _DARWIN_UNLIMITED_SELECT
  1026. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1027. #if !defined(MSG_NOSIGNAL)
  1028. #define MSG_NOSIGNAL (0)
  1029. #endif
  1030. #if !defined(SOMAXCONN)
  1031. #define SOMAXCONN (100)
  1032. #endif
  1033. /* Size of the accepted socket queue */
  1034. #if !defined(MGSQLEN)
  1035. #define MGSQLEN (20)
  1036. #endif
  1037. #if defined(NO_SSL)
  1038. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1039. typedef struct SSL_CTX SSL_CTX;
  1040. #else
  1041. #if defined(NO_SSL_DL)
  1042. #include <openssl/ssl.h>
  1043. #include <openssl/err.h>
  1044. #include <openssl/crypto.h>
  1045. #include <openssl/x509.h>
  1046. #include <openssl/pem.h>
  1047. #include <openssl/engine.h>
  1048. #include <openssl/conf.h>
  1049. #include <openssl/dh.h>
  1050. #include <openssl/bn.h>
  1051. #include <openssl/opensslv.h>
  1052. #else
  1053. /* SSL loaded dynamically from DLL.
  1054. * I put the prototypes here to be independent from OpenSSL source
  1055. * installation. */
  1056. typedef struct ssl_st SSL;
  1057. typedef struct ssl_method_st SSL_METHOD;
  1058. typedef struct ssl_ctx_st SSL_CTX;
  1059. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1060. typedef struct x509_name X509_NAME;
  1061. typedef struct asn1_integer ASN1_INTEGER;
  1062. typedef struct bignum BIGNUM;
  1063. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1064. typedef struct evp_md EVP_MD;
  1065. typedef struct x509 X509;
  1066. #define SSL_CTRL_OPTIONS (32)
  1067. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1068. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1069. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1070. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1071. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1072. #define SSL_VERIFY_NONE (0)
  1073. #define SSL_VERIFY_PEER (1)
  1074. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1075. #define SSL_VERIFY_CLIENT_ONCE (4)
  1076. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1077. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1078. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1079. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1080. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1081. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1082. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1083. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1084. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1085. #define SSL_ERROR_NONE (0)
  1086. #define SSL_ERROR_SSL (1)
  1087. #define SSL_ERROR_WANT_READ (2)
  1088. #define SSL_ERROR_WANT_WRITE (3)
  1089. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1090. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1091. #define SSL_ERROR_ZERO_RETURN (6)
  1092. #define SSL_ERROR_WANT_CONNECT (7)
  1093. #define SSL_ERROR_WANT_ACCEPT (8)
  1094. struct ssl_func {
  1095. const char *name; /* SSL function name */
  1096. void (*ptr)(void); /* Function pointer */
  1097. };
  1098. #ifdef OPENSSL_API_1_1
  1099. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1100. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1101. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1102. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1103. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1104. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1105. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1106. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1107. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1108. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1109. #define OPENSSL_init_ssl \
  1110. (*(int (*)(uint64_t opts, \
  1111. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1112. #define SSL_CTX_use_PrivateKey_file \
  1113. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1114. #define SSL_CTX_use_certificate_file \
  1115. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1116. #define SSL_CTX_set_default_passwd_cb \
  1117. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1118. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1119. #define SSL_CTX_use_certificate_chain_file \
  1120. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1121. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1122. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1123. #define SSL_CTX_set_verify \
  1124. (*(void (*)(SSL_CTX *, \
  1125. int, \
  1126. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1127. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1128. #define SSL_CTX_load_verify_locations \
  1129. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1130. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1131. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1132. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1133. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1134. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1135. #define SSL_CIPHER_get_name \
  1136. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1137. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1138. #define SSL_CTX_set_session_id_context \
  1139. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1140. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1141. #define SSL_CTX_set_cipher_list \
  1142. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1143. #define SSL_CTX_set_options \
  1144. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1145. #define SSL_CTX_clear_options(ctx, op) \
  1146. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1147. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1148. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1149. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1150. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1151. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1152. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1153. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1154. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1155. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1156. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1157. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1158. #define X509_NAME_oneline \
  1159. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1160. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1161. #define EVP_get_digestbyname \
  1162. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1163. #define ASN1_digest \
  1164. (*(int (*)(int (*)(), \
  1165. const EVP_MD *, \
  1166. char *, \
  1167. unsigned char *, \
  1168. unsigned int *))crypto_sw[10].ptr)
  1169. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1170. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1171. #define ASN1_INTEGER_to_BN \
  1172. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1173. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1174. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1175. #define OPENSSL_free(a) CRYPTO_free(a)
  1176. /* set_ssl_option() function updates this array.
  1177. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1178. * of respective functions. The macros above (like SSL_connect()) are really
  1179. * just calling these functions indirectly via the pointer. */
  1180. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1181. {"SSL_accept", NULL},
  1182. {"SSL_connect", NULL},
  1183. {"SSL_read", NULL},
  1184. {"SSL_write", NULL},
  1185. {"SSL_get_error", NULL},
  1186. {"SSL_set_fd", NULL},
  1187. {"SSL_new", NULL},
  1188. {"SSL_CTX_new", NULL},
  1189. {"TLS_server_method", NULL},
  1190. {"OPENSSL_init_ssl", NULL},
  1191. {"SSL_CTX_use_PrivateKey_file", NULL},
  1192. {"SSL_CTX_use_certificate_file", NULL},
  1193. {"SSL_CTX_set_default_passwd_cb", NULL},
  1194. {"SSL_CTX_free", NULL},
  1195. {"SSL_CTX_use_certificate_chain_file", NULL},
  1196. {"TLS_client_method", NULL},
  1197. {"SSL_pending", NULL},
  1198. {"SSL_CTX_set_verify", NULL},
  1199. {"SSL_shutdown", NULL},
  1200. {"SSL_CTX_load_verify_locations", NULL},
  1201. {"SSL_CTX_set_default_verify_paths", NULL},
  1202. {"SSL_CTX_set_verify_depth", NULL},
  1203. {"SSL_get_peer_certificate", NULL},
  1204. {"SSL_get_version", NULL},
  1205. {"SSL_get_current_cipher", NULL},
  1206. {"SSL_CIPHER_get_name", NULL},
  1207. {"SSL_CTX_check_private_key", NULL},
  1208. {"SSL_CTX_set_session_id_context", NULL},
  1209. {"SSL_CTX_ctrl", NULL},
  1210. {"SSL_CTX_set_cipher_list", NULL},
  1211. {"SSL_CTX_set_options", NULL},
  1212. {NULL, NULL}};
  1213. /* Similar array as ssl_sw. These functions could be located in different
  1214. * lib. */
  1215. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1216. {"ERR_error_string", NULL},
  1217. {"ERR_remove_state", NULL},
  1218. {"CONF_modules_unload", NULL},
  1219. {"X509_free", NULL},
  1220. {"X509_get_subject_name", NULL},
  1221. {"X509_get_issuer_name", NULL},
  1222. {"X509_NAME_oneline", NULL},
  1223. {"X509_get_serialNumber", NULL},
  1224. {"EVP_get_digestbyname", NULL},
  1225. {"ASN1_digest", NULL},
  1226. {"i2d_X509", NULL},
  1227. {"BN_bn2hex", NULL},
  1228. {"ASN1_INTEGER_to_BN", NULL},
  1229. {"BN_free", NULL},
  1230. {"CRYPTO_free", NULL},
  1231. {NULL, NULL}};
  1232. #else
  1233. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1234. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1235. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1236. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1237. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1238. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1239. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1240. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1241. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1242. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1243. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1244. #define SSL_CTX_use_PrivateKey_file \
  1245. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1246. #define SSL_CTX_use_certificate_file \
  1247. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1248. #define SSL_CTX_set_default_passwd_cb \
  1249. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1250. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1251. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1252. #define SSL_CTX_use_certificate_chain_file \
  1253. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1254. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1255. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1256. #define SSL_CTX_set_verify \
  1257. (*(void (*)(SSL_CTX *, \
  1258. int, \
  1259. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1260. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1261. #define SSL_CTX_load_verify_locations \
  1262. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1263. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1264. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1265. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1266. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1267. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1268. #define SSL_CIPHER_get_name \
  1269. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1270. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1271. #define SSL_CTX_set_session_id_context \
  1272. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1273. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1274. #define SSL_CTX_set_cipher_list \
  1275. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1276. #define SSL_CTX_set_options(ctx, op) \
  1277. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1278. #define SSL_CTX_clear_options(ctx, op) \
  1279. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1280. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1281. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1282. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1283. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1284. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1285. #define CRYPTO_set_locking_callback \
  1286. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1287. #define CRYPTO_set_id_callback \
  1288. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1289. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1290. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1291. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1292. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1293. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1294. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1295. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1296. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1297. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1298. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1299. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1300. #define X509_NAME_oneline \
  1301. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1302. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1303. #define i2c_ASN1_INTEGER \
  1304. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1305. #define EVP_get_digestbyname \
  1306. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1307. #define ASN1_digest \
  1308. (*(int (*)(int (*)(), \
  1309. const EVP_MD *, \
  1310. char *, \
  1311. unsigned char *, \
  1312. unsigned int *))crypto_sw[18].ptr)
  1313. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1314. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1315. #define ASN1_INTEGER_to_BN \
  1316. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1317. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1318. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1319. #define OPENSSL_free(a) CRYPTO_free(a)
  1320. /* set_ssl_option() function updates this array.
  1321. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1322. * of respective functions. The macros above (like SSL_connect()) are really
  1323. * just calling these functions indirectly via the pointer. */
  1324. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1325. {"SSL_accept", NULL},
  1326. {"SSL_connect", NULL},
  1327. {"SSL_read", NULL},
  1328. {"SSL_write", NULL},
  1329. {"SSL_get_error", NULL},
  1330. {"SSL_set_fd", NULL},
  1331. {"SSL_new", NULL},
  1332. {"SSL_CTX_new", NULL},
  1333. {"SSLv23_server_method", NULL},
  1334. {"SSL_library_init", NULL},
  1335. {"SSL_CTX_use_PrivateKey_file", NULL},
  1336. {"SSL_CTX_use_certificate_file", NULL},
  1337. {"SSL_CTX_set_default_passwd_cb", NULL},
  1338. {"SSL_CTX_free", NULL},
  1339. {"SSL_load_error_strings", NULL},
  1340. {"SSL_CTX_use_certificate_chain_file", NULL},
  1341. {"SSLv23_client_method", NULL},
  1342. {"SSL_pending", NULL},
  1343. {"SSL_CTX_set_verify", NULL},
  1344. {"SSL_shutdown", NULL},
  1345. {"SSL_CTX_load_verify_locations", NULL},
  1346. {"SSL_CTX_set_default_verify_paths", NULL},
  1347. {"SSL_CTX_set_verify_depth", NULL},
  1348. {"SSL_get_peer_certificate", NULL},
  1349. {"SSL_get_version", NULL},
  1350. {"SSL_get_current_cipher", NULL},
  1351. {"SSL_CIPHER_get_name", NULL},
  1352. {"SSL_CTX_check_private_key", NULL},
  1353. {"SSL_CTX_set_session_id_context", NULL},
  1354. {"SSL_CTX_ctrl", NULL},
  1355. {"SSL_CTX_set_cipher_list", NULL},
  1356. {NULL, NULL}};
  1357. /* Similar array as ssl_sw. These functions could be located in different
  1358. * lib. */
  1359. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1360. {"CRYPTO_set_locking_callback", NULL},
  1361. {"CRYPTO_set_id_callback", NULL},
  1362. {"ERR_get_error", NULL},
  1363. {"ERR_error_string", NULL},
  1364. {"ERR_remove_state", NULL},
  1365. {"ERR_free_strings", NULL},
  1366. {"ENGINE_cleanup", NULL},
  1367. {"CONF_modules_unload", NULL},
  1368. {"CRYPTO_cleanup_all_ex_data", NULL},
  1369. {"EVP_cleanup", NULL},
  1370. {"X509_free", NULL},
  1371. {"X509_get_subject_name", NULL},
  1372. {"X509_get_issuer_name", NULL},
  1373. {"X509_NAME_oneline", NULL},
  1374. {"X509_get_serialNumber", NULL},
  1375. {"i2c_ASN1_INTEGER", NULL},
  1376. {"EVP_get_digestbyname", NULL},
  1377. {"ASN1_digest", NULL},
  1378. {"i2d_X509", NULL},
  1379. {"BN_bn2hex", NULL},
  1380. {"ASN1_INTEGER_to_BN", NULL},
  1381. {"BN_free", NULL},
  1382. {"CRYPTO_free", NULL},
  1383. {NULL, NULL}};
  1384. #endif /* OPENSSL_API_1_1 */
  1385. #endif /* NO_SSL_DL */
  1386. #endif /* NO_SSL */
  1387. #if !defined(NO_CACHING)
  1388. static const char *month_names[] = {"Jan",
  1389. "Feb",
  1390. "Mar",
  1391. "Apr",
  1392. "May",
  1393. "Jun",
  1394. "Jul",
  1395. "Aug",
  1396. "Sep",
  1397. "Oct",
  1398. "Nov",
  1399. "Dec"};
  1400. #endif /* !NO_CACHING */
  1401. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1402. * union u. */
  1403. union usa {
  1404. struct sockaddr sa;
  1405. struct sockaddr_in sin;
  1406. #if defined(USE_IPV6)
  1407. struct sockaddr_in6 sin6;
  1408. #endif
  1409. };
  1410. /* Describes a string (chunk of memory). */
  1411. struct vec {
  1412. const char *ptr;
  1413. size_t len;
  1414. };
  1415. struct mg_file_stat {
  1416. /* File properties filled by mg_stat: */
  1417. uint64_t size;
  1418. time_t last_modified;
  1419. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1420. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1421. * case we need a "Content-Eencoding: gzip" header */
  1422. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1423. };
  1424. struct mg_file_in_memory {
  1425. char *p;
  1426. uint32_t pos;
  1427. char mode;
  1428. };
  1429. struct mg_file_access {
  1430. /* File properties filled by mg_fopen: */
  1431. FILE *fp;
  1432. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1433. * support library. Use some struct mg_file_in_memory *mf; instead of
  1434. * membuf char pointer. */
  1435. const char *membuf;
  1436. };
  1437. struct mg_file {
  1438. struct mg_file_stat stat;
  1439. struct mg_file_access access;
  1440. };
  1441. #define STRUCT_FILE_INITIALIZER \
  1442. { \
  1443. { \
  1444. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1445. } \
  1446. , \
  1447. { \
  1448. (FILE *) NULL, (const char *)NULL \
  1449. } \
  1450. }
  1451. /* Describes listening socket, or socket which was accept()-ed by the master
  1452. * thread and queued for future handling by the worker thread. */
  1453. struct socket {
  1454. SOCKET sock; /* Listening socket */
  1455. union usa lsa; /* Local socket address */
  1456. union usa rsa; /* Remote socket address */
  1457. unsigned char is_ssl; /* Is port SSL-ed */
  1458. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1459. * port */
  1460. unsigned char in_use; /* Is valid */
  1461. };
  1462. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1463. enum {
  1464. CGI_EXTENSIONS,
  1465. CGI_ENVIRONMENT,
  1466. PUT_DELETE_PASSWORDS_FILE,
  1467. CGI_INTERPRETER,
  1468. PROTECT_URI,
  1469. AUTHENTICATION_DOMAIN,
  1470. ENABLE_AUTH_DOMAIN_CHECK,
  1471. SSI_EXTENSIONS,
  1472. THROTTLE,
  1473. ACCESS_LOG_FILE,
  1474. ENABLE_DIRECTORY_LISTING,
  1475. ERROR_LOG_FILE,
  1476. GLOBAL_PASSWORDS_FILE,
  1477. INDEX_FILES,
  1478. ENABLE_KEEP_ALIVE,
  1479. ACCESS_CONTROL_LIST,
  1480. EXTRA_MIME_TYPES,
  1481. LISTENING_PORTS,
  1482. DOCUMENT_ROOT,
  1483. SSL_CERTIFICATE,
  1484. NUM_THREADS,
  1485. RUN_AS_USER,
  1486. REWRITE,
  1487. HIDE_FILES,
  1488. REQUEST_TIMEOUT,
  1489. KEEP_ALIVE_TIMEOUT,
  1490. LINGER_TIMEOUT,
  1491. SSL_DO_VERIFY_PEER,
  1492. SSL_CA_PATH,
  1493. SSL_CA_FILE,
  1494. SSL_VERIFY_DEPTH,
  1495. SSL_DEFAULT_VERIFY_PATHS,
  1496. SSL_CIPHER_LIST,
  1497. SSL_PROTOCOL_VERSION,
  1498. SSL_SHORT_TRUST,
  1499. #if defined(USE_WEBSOCKET)
  1500. WEBSOCKET_TIMEOUT,
  1501. #endif
  1502. DECODE_URL,
  1503. #if defined(USE_LUA)
  1504. LUA_PRELOAD_FILE,
  1505. LUA_SCRIPT_EXTENSIONS,
  1506. LUA_SERVER_PAGE_EXTENSIONS,
  1507. #endif
  1508. #if defined(USE_DUKTAPE)
  1509. DUKTAPE_SCRIPT_EXTENSIONS,
  1510. #endif
  1511. #if defined(USE_WEBSOCKET)
  1512. WEBSOCKET_ROOT,
  1513. #endif
  1514. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1515. LUA_WEBSOCKET_EXTENSIONS,
  1516. #endif
  1517. ACCESS_CONTROL_ALLOW_ORIGIN,
  1518. ERROR_PAGES,
  1519. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1520. * socket option typedef TCP_NODELAY. */
  1521. #if !defined(NO_CACHING)
  1522. STATIC_FILE_MAX_AGE,
  1523. #endif
  1524. #if defined(__linux__)
  1525. ALLOW_SENDFILE_CALL,
  1526. #endif
  1527. #if defined(_WIN32)
  1528. CASE_SENSITIVE_FILES,
  1529. #endif
  1530. #if defined(USE_LUA)
  1531. LUA_BACKGROUND_SCRIPT,
  1532. #endif
  1533. NUM_OPTIONS
  1534. };
  1535. /* Config option name, config types, default value */
  1536. static struct mg_option config_options[] = {
  1537. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1538. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1539. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1540. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1541. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1542. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1543. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1544. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1545. {"throttle", CONFIG_TYPE_STRING, NULL},
  1546. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1547. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1548. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1549. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1550. {"index_files",
  1551. CONFIG_TYPE_STRING,
  1552. #ifdef USE_LUA
  1553. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1554. "index.shtml,index.php"},
  1555. #else
  1556. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1557. #endif
  1558. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1559. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1560. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1561. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1562. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1563. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1564. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1565. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1566. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1567. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1568. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1569. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1570. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1571. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1572. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1573. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1574. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1575. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1576. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1577. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1578. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1579. #if defined(USE_WEBSOCKET)
  1580. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1581. #endif
  1582. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1583. #if defined(USE_LUA)
  1584. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1585. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1586. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1587. #endif
  1588. #if defined(USE_DUKTAPE)
  1589. /* The support for duktape is still in alpha version state.
  1590. * The name of this config option might change. */
  1591. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1592. #endif
  1593. #if defined(USE_WEBSOCKET)
  1594. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1595. #endif
  1596. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1597. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1598. #endif
  1599. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1600. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1601. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1602. #if !defined(NO_CACHING)
  1603. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1604. #endif
  1605. #if defined(__linux__)
  1606. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1607. #endif
  1608. #if defined(_WIN32)
  1609. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1610. #endif
  1611. #if defined(USE_LUA)
  1612. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1613. #endif
  1614. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1615. /* Check if the config_options and the corresponding enum have compatible
  1616. * sizes. */
  1617. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1618. == (NUM_OPTIONS + 1),
  1619. "config_options and enum not sync");
  1620. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1621. struct mg_handler_info {
  1622. /* Name/Pattern of the URI. */
  1623. char *uri;
  1624. size_t uri_len;
  1625. /* handler type */
  1626. int handler_type;
  1627. /* Handler for http/https or authorization requests. */
  1628. mg_request_handler handler;
  1629. /* Handler for ws/wss (websocket) requests. */
  1630. mg_websocket_connect_handler connect_handler;
  1631. mg_websocket_ready_handler ready_handler;
  1632. mg_websocket_data_handler data_handler;
  1633. mg_websocket_close_handler close_handler;
  1634. /* accepted subprotocols for ws/wss requests. */
  1635. struct mg_websocket_subprotocols *subprotocols;
  1636. /* Handler for authorization requests */
  1637. mg_authorization_handler auth_handler;
  1638. /* User supplied argument for the handler function. */
  1639. void *cbdata;
  1640. /* next handler in a linked list */
  1641. struct mg_handler_info *next;
  1642. };
  1643. struct mg_context {
  1644. volatile int stop_flag; /* Should we stop event loop */
  1645. SSL_CTX *ssl_ctx; /* SSL context */
  1646. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1647. struct mg_callbacks callbacks; /* User-defined callback function */
  1648. void *user_data; /* User-defined data */
  1649. int context_type; /* 1 = server context,
  1650. * 2 = ws/wss client context,
  1651. */
  1652. struct socket *listening_sockets;
  1653. struct pollfd *listening_socket_fds;
  1654. unsigned int num_listening_sockets;
  1655. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1656. #ifdef ALTERNATIVE_QUEUE
  1657. struct socket *client_socks;
  1658. void **client_wait_events;
  1659. #else
  1660. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1661. volatile int sq_head; /* Head of the socket queue */
  1662. volatile int sq_tail; /* Tail of the socket queue */
  1663. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1664. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1665. #endif
  1666. pthread_t masterthreadid; /* The master thread ID */
  1667. unsigned int
  1668. cfg_worker_threads; /* The number of configured worker threads. */
  1669. pthread_t *worker_threadids; /* The worker thread IDs */
  1670. struct mg_connection *worker_connections; /* The connection struct, pre-
  1671. * allocated for each worker */
  1672. time_t start_time; /* Server start time, used for authentication */
  1673. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1674. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1675. unsigned long nonce_count; /* Used nonces, used for authentication */
  1676. char *systemName; /* What operating system is running */
  1677. /* linked list of uri handlers */
  1678. struct mg_handler_info *handlers;
  1679. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1680. /* linked list of shared lua websockets */
  1681. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1682. #endif
  1683. #if defined(USE_TIMERS)
  1684. struct ttimers *timers;
  1685. #endif
  1686. #if defined(USE_LUA)
  1687. void *lua_background_state;
  1688. #endif
  1689. };
  1690. struct mg_connection {
  1691. struct mg_request_info request_info;
  1692. struct mg_context *ctx;
  1693. SSL *ssl; /* SSL descriptor */
  1694. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1695. struct socket client; /* Connected client */
  1696. time_t conn_birth_time; /* Time (wall clock) when connection was
  1697. * established */
  1698. struct timespec req_time; /* Time (since system start) when the request
  1699. * was received */
  1700. int64_t num_bytes_sent; /* Total bytes sent to client */
  1701. int64_t content_len; /* Content-Length header value */
  1702. int64_t consumed_content; /* How many bytes of content have been read */
  1703. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1704. * data available, 2: all data read */
  1705. size_t chunk_remainder; /* Unread data from the last chunk */
  1706. char *buf; /* Buffer for received data */
  1707. char *path_info; /* PATH_INFO part of the URL */
  1708. int must_close; /* 1 if connection must be closed */
  1709. int in_error_handler; /* 1 if in handler for user defined error
  1710. * pages */
  1711. int handled_requests; /* Number of requests handled by this connection */
  1712. int buf_size; /* Buffer size */
  1713. int request_len; /* Size of the request + headers in a buffer */
  1714. int data_len; /* Total size of data in a buffer */
  1715. int status_code; /* HTTP reply status code, e.g. 200 */
  1716. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1717. * throttle */
  1718. time_t last_throttle_time; /* Last time throttled data was sent */
  1719. int64_t last_throttle_bytes; /* Bytes sent this second */
  1720. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1721. * atomic transmissions for websockets */
  1722. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1723. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1724. #endif
  1725. int thread_index; /* Thread index within ctx */
  1726. };
  1727. /* Directory entry */
  1728. struct de {
  1729. struct mg_connection *conn;
  1730. char *file_name;
  1731. struct mg_file_stat file;
  1732. };
  1733. #if defined(USE_WEBSOCKET)
  1734. static int is_websocket_protocol(const struct mg_connection *conn);
  1735. #else
  1736. #define is_websocket_protocol(conn) (0)
  1737. #endif
  1738. #if !defined(NO_THREAD_NAME)
  1739. #if defined(_WIN32) && defined(_MSC_VER)
  1740. /* Set the thread name for debugging purposes in Visual Studio
  1741. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1742. */
  1743. #pragma pack(push, 8)
  1744. typedef struct tagTHREADNAME_INFO {
  1745. DWORD dwType; /* Must be 0x1000. */
  1746. LPCSTR szName; /* Pointer to name (in user addr space). */
  1747. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1748. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1749. } THREADNAME_INFO;
  1750. #pragma pack(pop)
  1751. #elif defined(__linux__)
  1752. #include <sys/prctl.h>
  1753. #include <sys/sendfile.h>
  1754. #include <sys/eventfd.h>
  1755. #if defined(ALTERNATIVE_QUEUE)
  1756. static void *
  1757. event_create(void)
  1758. {
  1759. int ret = eventfd(0, EFD_CLOEXEC);
  1760. if (ret == -1) {
  1761. /* Linux uses -1 on error, Windows NULL. */
  1762. /* However, Linux does not return 0 on success either. */
  1763. return 0;
  1764. }
  1765. return (void *)ret;
  1766. }
  1767. static int
  1768. event_wait(void *eventhdl)
  1769. {
  1770. uint64_t u;
  1771. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1772. if (s != sizeof(uint64_t)) {
  1773. /* error */
  1774. return 0;
  1775. }
  1776. (void)u; /* the value is not required */
  1777. return 1;
  1778. }
  1779. static int
  1780. event_signal(void *eventhdl)
  1781. {
  1782. uint64_t u = 1;
  1783. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1784. if (s != sizeof(uint64_t)) {
  1785. /* error */
  1786. return 0;
  1787. }
  1788. return 1;
  1789. }
  1790. static void
  1791. event_destroy(void *eventhdl)
  1792. {
  1793. close((int)eventhdl);
  1794. }
  1795. #endif
  1796. #endif
  1797. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1798. struct posix_event {
  1799. pthread_mutex_t mutex;
  1800. pthread_cond_t cond;
  1801. };
  1802. static void *
  1803. event_create(void)
  1804. {
  1805. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1806. if (ret == 0) {
  1807. /* out of memory */
  1808. return 0;
  1809. }
  1810. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1811. /* pthread mutex not available */
  1812. mg_free(ret);
  1813. return 0;
  1814. }
  1815. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1816. /* pthread cond not available */
  1817. pthread_mutex_destroy(&(ret->mutex));
  1818. mg_free(ret);
  1819. return 0;
  1820. }
  1821. return (void *)ret;
  1822. }
  1823. static int
  1824. event_wait(void *eventhdl)
  1825. {
  1826. struct posix_event *ev = (struct posix_event *)eventhdl;
  1827. pthread_mutex_lock(&(ev->mutex));
  1828. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1829. pthread_mutex_unlock(&(ev->mutex));
  1830. return 1;
  1831. }
  1832. static int
  1833. event_signal(void *eventhdl)
  1834. {
  1835. struct posix_event *ev = (struct posix_event *)eventhdl;
  1836. pthread_mutex_lock(&(ev->mutex));
  1837. pthread_cond_signal(&(ev->cond));
  1838. pthread_mutex_unlock(&(ev->mutex));
  1839. return 1;
  1840. }
  1841. static void
  1842. event_destroy(void *eventhdl)
  1843. {
  1844. struct posix_event *ev = (struct posix_event *)eventhdl;
  1845. pthread_cond_destroy(&(ev->cond));
  1846. pthread_mutex_destroy(&(ev->mutex));
  1847. mg_free(ev);
  1848. }
  1849. #endif
  1850. static void
  1851. mg_set_thread_name(const char *name)
  1852. {
  1853. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1854. mg_snprintf(
  1855. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1856. #if defined(_WIN32)
  1857. #if defined(_MSC_VER)
  1858. /* Windows and Visual Studio Compiler */
  1859. __try
  1860. {
  1861. THREADNAME_INFO info;
  1862. info.dwType = 0x1000;
  1863. info.szName = threadName;
  1864. info.dwThreadID = ~0U;
  1865. info.dwFlags = 0;
  1866. RaiseException(0x406D1388,
  1867. 0,
  1868. sizeof(info) / sizeof(ULONG_PTR),
  1869. (ULONG_PTR *)&info);
  1870. }
  1871. __except(EXCEPTION_EXECUTE_HANDLER)
  1872. {
  1873. }
  1874. #elif defined(__MINGW32__)
  1875. /* No option known to set thread name for MinGW */
  1876. #endif
  1877. #elif defined(__GLIBC__) \
  1878. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1879. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1880. (void)pthread_setname_np(pthread_self(), threadName);
  1881. #elif defined(__linux__)
  1882. /* on linux we can use the old prctl function */
  1883. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1884. #endif
  1885. }
  1886. #else /* !defined(NO_THREAD_NAME) */
  1887. void
  1888. mg_set_thread_name(const char *threadName)
  1889. {
  1890. }
  1891. #endif
  1892. #if defined(MG_LEGACY_INTERFACE)
  1893. const char **
  1894. mg_get_valid_option_names(void)
  1895. {
  1896. /* This function is deprecated. Use mg_get_valid_options instead. */
  1897. static const char *
  1898. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1899. int i;
  1900. for (i = 0; config_options[i].name != NULL; i++) {
  1901. data[i * 2] = config_options[i].name;
  1902. data[i * 2 + 1] = config_options[i].default_value;
  1903. }
  1904. return data;
  1905. }
  1906. #endif
  1907. const struct mg_option *
  1908. mg_get_valid_options(void)
  1909. {
  1910. return config_options;
  1911. }
  1912. /* Do not open file (used in is_file_in_memory) */
  1913. #define MG_FOPEN_MODE_NONE (0)
  1914. /* Open file for read only access */
  1915. #define MG_FOPEN_MODE_READ (1)
  1916. /* Open file for writing, create and overwrite */
  1917. #define MG_FOPEN_MODE_WRITE (2)
  1918. /* Open file for writing, create and append */
  1919. #define MG_FOPEN_MODE_APPEND (4)
  1920. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1921. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1922. static int
  1923. open_file_in_memory(const struct mg_connection *conn,
  1924. const char *path,
  1925. struct mg_file *filep,
  1926. int mode)
  1927. {
  1928. size_t size = 0;
  1929. const char *buf = NULL;
  1930. if (!conn) {
  1931. return 0;
  1932. }
  1933. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1934. return 0;
  1935. }
  1936. if (conn->ctx->callbacks.open_file) {
  1937. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1938. if (buf != NULL) {
  1939. if (filep == NULL) {
  1940. /* This is a file in memory, but we cannot store the properties
  1941. * now.
  1942. * Called from "is_file_in_memory" function. */
  1943. return 1;
  1944. }
  1945. /* NOTE: override filep->size only on success. Otherwise, it might
  1946. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1947. filep->access.membuf = buf;
  1948. filep->access.fp = NULL;
  1949. /* Size was set by the callback */
  1950. filep->stat.size = size;
  1951. /* Assume the data may change during runtime by setting
  1952. * last_modified = now */
  1953. filep->stat.last_modified = time(NULL);
  1954. filep->stat.is_directory = 0;
  1955. filep->stat.is_gzipped = 0;
  1956. }
  1957. }
  1958. return (buf != NULL);
  1959. }
  1960. static int
  1961. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1962. {
  1963. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1964. }
  1965. static int
  1966. is_file_opened(const struct mg_file_access *fileacc)
  1967. {
  1968. if (!fileacc) {
  1969. return 0;
  1970. }
  1971. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1972. }
  1973. static int mg_stat(const struct mg_connection *conn,
  1974. const char *path,
  1975. struct mg_file_stat *filep);
  1976. /* mg_fopen will open a file either in memory or on the disk.
  1977. * The input parameter path is a string in UTF-8 encoding.
  1978. * The input parameter mode is MG_FOPEN_MODE_*
  1979. * On success, either fp or membuf will be set in the output
  1980. * struct file. All status members will also be set.
  1981. * The function returns 1 on success, 0 on error. */
  1982. static int
  1983. mg_fopen(const struct mg_connection *conn,
  1984. const char *path,
  1985. int mode,
  1986. struct mg_file *filep)
  1987. {
  1988. int found;
  1989. if (!filep) {
  1990. return 0;
  1991. }
  1992. filep->access.fp = NULL;
  1993. filep->access.membuf = NULL;
  1994. if (!is_file_in_memory(conn, path)) {
  1995. /* filep is initialized in mg_stat: all fields with memset to,
  1996. * some fields like size and modification date with values */
  1997. found = mg_stat(conn, path, &(filep->stat));
  1998. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  1999. /* file does not exist and will not be created */
  2000. return 0;
  2001. }
  2002. #ifdef _WIN32
  2003. {
  2004. wchar_t wbuf[PATH_MAX];
  2005. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2006. switch (mode) {
  2007. case MG_FOPEN_MODE_READ:
  2008. filep->access.fp = _wfopen(wbuf, L"rb");
  2009. break;
  2010. case MG_FOPEN_MODE_WRITE:
  2011. filep->access.fp = _wfopen(wbuf, L"wb");
  2012. break;
  2013. case MG_FOPEN_MODE_APPEND:
  2014. filep->access.fp = _wfopen(wbuf, L"ab");
  2015. break;
  2016. }
  2017. }
  2018. #else
  2019. /* Linux et al already use unicode. No need to convert. */
  2020. switch (mode) {
  2021. case MG_FOPEN_MODE_READ:
  2022. filep->access.fp = fopen(path, "r");
  2023. break;
  2024. case MG_FOPEN_MODE_WRITE:
  2025. filep->access.fp = fopen(path, "w");
  2026. break;
  2027. case MG_FOPEN_MODE_APPEND:
  2028. filep->access.fp = fopen(path, "a");
  2029. break;
  2030. }
  2031. #endif
  2032. if (!found) {
  2033. /* File did not exist before fopen was called.
  2034. * Maybe it has been created now. Get stat info
  2035. * like creation time now. */
  2036. found = mg_stat(conn, path, &(filep->stat));
  2037. (void)found;
  2038. }
  2039. /* file is on disk */
  2040. return (filep->access.fp != NULL);
  2041. } else {
  2042. /* is_file_in_memory returned true */
  2043. if (open_file_in_memory(conn, path, filep, mode)) {
  2044. /* file is in memory */
  2045. return (filep->access.membuf != NULL);
  2046. }
  2047. }
  2048. /* Open failed */
  2049. return 0;
  2050. }
  2051. /* return 0 on success, just like fclose */
  2052. static int
  2053. mg_fclose(struct mg_file_access *fileacc)
  2054. {
  2055. int ret = -1;
  2056. if (fileacc != NULL) {
  2057. if (fileacc->fp != NULL) {
  2058. ret = fclose(fileacc->fp);
  2059. } else if (fileacc->membuf != NULL) {
  2060. ret = 0;
  2061. }
  2062. /* reset all members of fileacc */
  2063. memset(fileacc, 0, sizeof(*fileacc));
  2064. }
  2065. return ret;
  2066. }
  2067. static void
  2068. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2069. {
  2070. for (; *src != '\0' && n > 1; n--) {
  2071. *dst++ = *src++;
  2072. }
  2073. *dst = '\0';
  2074. }
  2075. static int
  2076. lowercase(const char *s)
  2077. {
  2078. return tolower(*(const unsigned char *)s);
  2079. }
  2080. int
  2081. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2082. {
  2083. int diff = 0;
  2084. if (len > 0) {
  2085. do {
  2086. diff = lowercase(s1++) - lowercase(s2++);
  2087. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2088. }
  2089. return diff;
  2090. }
  2091. int
  2092. mg_strcasecmp(const char *s1, const char *s2)
  2093. {
  2094. int diff;
  2095. do {
  2096. diff = lowercase(s1++) - lowercase(s2++);
  2097. } while (diff == 0 && s1[-1] != '\0');
  2098. return diff;
  2099. }
  2100. static char *
  2101. mg_strndup(const char *ptr, size_t len)
  2102. {
  2103. char *p;
  2104. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2105. mg_strlcpy(p, ptr, len + 1);
  2106. }
  2107. return p;
  2108. }
  2109. static char *
  2110. mg_strdup(const char *str)
  2111. {
  2112. return mg_strndup(str, strlen(str));
  2113. }
  2114. static const char *
  2115. mg_strcasestr(const char *big_str, const char *small_str)
  2116. {
  2117. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2118. if (big_len >= small_len) {
  2119. for (i = 0; i <= (big_len - small_len); i++) {
  2120. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2121. return big_str + i;
  2122. }
  2123. }
  2124. }
  2125. return NULL;
  2126. }
  2127. /* Return null terminated string of given maximum length.
  2128. * Report errors if length is exceeded. */
  2129. static void
  2130. mg_vsnprintf(const struct mg_connection *conn,
  2131. int *truncated,
  2132. char *buf,
  2133. size_t buflen,
  2134. const char *fmt,
  2135. va_list ap)
  2136. {
  2137. int n, ok;
  2138. if (buflen == 0) {
  2139. return;
  2140. }
  2141. #ifdef __clang__
  2142. #pragma clang diagnostic push
  2143. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2144. /* Using fmt as a non-literal is intended here, since it is mostly called
  2145. * indirectly by mg_snprintf */
  2146. #endif
  2147. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2148. ok = (n >= 0) && ((size_t)n < buflen);
  2149. #ifdef __clang__
  2150. #pragma clang diagnostic pop
  2151. #endif
  2152. if (ok) {
  2153. if (truncated) {
  2154. *truncated = 0;
  2155. }
  2156. } else {
  2157. if (truncated) {
  2158. *truncated = 1;
  2159. }
  2160. mg_cry(conn,
  2161. "truncating vsnprintf buffer: [%.*s]",
  2162. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2163. buf);
  2164. n = (int)buflen - 1;
  2165. }
  2166. buf[n] = '\0';
  2167. }
  2168. static void
  2169. mg_snprintf(const struct mg_connection *conn,
  2170. int *truncated,
  2171. char *buf,
  2172. size_t buflen,
  2173. const char *fmt,
  2174. ...)
  2175. {
  2176. va_list ap;
  2177. va_start(ap, fmt);
  2178. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2179. va_end(ap);
  2180. }
  2181. static int
  2182. get_option_index(const char *name)
  2183. {
  2184. int i;
  2185. for (i = 0; config_options[i].name != NULL; i++) {
  2186. if (strcmp(config_options[i].name, name) == 0) {
  2187. return i;
  2188. }
  2189. }
  2190. return -1;
  2191. }
  2192. const char *
  2193. mg_get_option(const struct mg_context *ctx, const char *name)
  2194. {
  2195. int i;
  2196. if ((i = get_option_index(name)) == -1) {
  2197. return NULL;
  2198. } else if (!ctx || ctx->config[i] == NULL) {
  2199. return "";
  2200. } else {
  2201. return ctx->config[i];
  2202. }
  2203. }
  2204. struct mg_context *
  2205. mg_get_context(const struct mg_connection *conn)
  2206. {
  2207. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2208. }
  2209. void *
  2210. mg_get_user_data(const struct mg_context *ctx)
  2211. {
  2212. return (ctx == NULL) ? NULL : ctx->user_data;
  2213. }
  2214. void
  2215. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2216. {
  2217. if (conn != NULL) {
  2218. conn->request_info.conn_data = data;
  2219. }
  2220. }
  2221. void *
  2222. mg_get_user_connection_data(const struct mg_connection *conn)
  2223. {
  2224. if (conn != NULL) {
  2225. return conn->request_info.conn_data;
  2226. }
  2227. return NULL;
  2228. }
  2229. size_t
  2230. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2231. {
  2232. size_t i;
  2233. if (!ctx) {
  2234. return 0;
  2235. }
  2236. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2237. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2238. ports[i] =
  2239. #if defined(USE_IPV6)
  2240. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2241. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2242. :
  2243. #endif
  2244. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2245. }
  2246. return i;
  2247. }
  2248. int
  2249. mg_get_server_ports(const struct mg_context *ctx,
  2250. int size,
  2251. struct mg_server_ports *ports)
  2252. {
  2253. int i, cnt = 0;
  2254. if (size <= 0) {
  2255. return -1;
  2256. }
  2257. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2258. if (!ctx) {
  2259. return -1;
  2260. }
  2261. if (!ctx->listening_sockets) {
  2262. return -1;
  2263. }
  2264. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2265. ports[cnt].port =
  2266. #if defined(USE_IPV6)
  2267. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2268. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2269. :
  2270. #endif
  2271. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2272. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2273. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2274. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2275. /* IPv4 */
  2276. ports[cnt].protocol = 1;
  2277. cnt++;
  2278. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2279. /* IPv6 */
  2280. ports[cnt].protocol = 3;
  2281. cnt++;
  2282. }
  2283. }
  2284. return cnt;
  2285. }
  2286. static void
  2287. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2288. {
  2289. buf[0] = '\0';
  2290. if (!usa) {
  2291. return;
  2292. }
  2293. if (usa->sa.sa_family == AF_INET) {
  2294. getnameinfo(&usa->sa,
  2295. sizeof(usa->sin),
  2296. buf,
  2297. (unsigned)len,
  2298. NULL,
  2299. 0,
  2300. NI_NUMERICHOST);
  2301. }
  2302. #if defined(USE_IPV6)
  2303. else if (usa->sa.sa_family == AF_INET6) {
  2304. getnameinfo(&usa->sa,
  2305. sizeof(usa->sin6),
  2306. buf,
  2307. (unsigned)len,
  2308. NULL,
  2309. 0,
  2310. NI_NUMERICHOST);
  2311. }
  2312. #endif
  2313. }
  2314. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2315. * included in all responses other than 100, 101, 5xx. */
  2316. static void
  2317. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2318. {
  2319. struct tm *tm;
  2320. tm = ((t != NULL) ? gmtime(t) : NULL);
  2321. if (tm != NULL) {
  2322. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2323. } else {
  2324. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2325. buf[buf_len - 1] = '\0';
  2326. }
  2327. }
  2328. /* difftime for struct timespec. Return value is in seconds. */
  2329. static double
  2330. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2331. {
  2332. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2333. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2334. }
  2335. /* Print error message to the opened error log stream. */
  2336. void
  2337. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2338. {
  2339. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2340. va_list ap;
  2341. struct mg_file fi;
  2342. time_t timestamp;
  2343. va_start(ap, fmt);
  2344. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2345. va_end(ap);
  2346. buf[sizeof(buf) - 1] = 0;
  2347. if (!conn) {
  2348. puts(buf);
  2349. return;
  2350. }
  2351. /* Do not lock when getting the callback value, here and below.
  2352. * I suppose this is fine, since function cannot disappear in the
  2353. * same way string option can. */
  2354. if ((conn->ctx->callbacks.log_message == NULL)
  2355. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2356. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2357. if (mg_fopen(conn,
  2358. conn->ctx->config[ERROR_LOG_FILE],
  2359. MG_FOPEN_MODE_APPEND,
  2360. &fi) == 0) {
  2361. fi.access.fp = NULL;
  2362. }
  2363. } else {
  2364. fi.access.fp = NULL;
  2365. }
  2366. if (fi.access.fp != NULL) {
  2367. flockfile(fi.access.fp);
  2368. timestamp = time(NULL);
  2369. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2370. fprintf(fi.access.fp,
  2371. "[%010lu] [error] [client %s] ",
  2372. (unsigned long)timestamp,
  2373. src_addr);
  2374. if (conn->request_info.request_method != NULL) {
  2375. fprintf(fi.access.fp,
  2376. "%s %s: ",
  2377. conn->request_info.request_method,
  2378. conn->request_info.request_uri);
  2379. }
  2380. fprintf(fi.access.fp, "%s", buf);
  2381. fputc('\n', fi.access.fp);
  2382. fflush(fi.access.fp);
  2383. funlockfile(fi.access.fp);
  2384. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2385. * mg_cry here anyway ;-) */
  2386. }
  2387. }
  2388. }
  2389. /* Return fake connection structure. Used for logging, if connection
  2390. * is not applicable at the moment of logging. */
  2391. static struct mg_connection *
  2392. fc(struct mg_context *ctx)
  2393. {
  2394. static struct mg_connection fake_connection;
  2395. fake_connection.ctx = ctx;
  2396. return &fake_connection;
  2397. }
  2398. const char *
  2399. mg_version(void)
  2400. {
  2401. return CIVETWEB_VERSION;
  2402. }
  2403. const struct mg_request_info *
  2404. mg_get_request_info(const struct mg_connection *conn)
  2405. {
  2406. if (!conn) {
  2407. return NULL;
  2408. }
  2409. return &conn->request_info;
  2410. }
  2411. /* Skip the characters until one of the delimiters characters found.
  2412. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2413. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2414. * Delimiters can be quoted with quotechar. */
  2415. static char *
  2416. skip_quoted(char **buf,
  2417. const char *delimiters,
  2418. const char *whitespace,
  2419. char quotechar)
  2420. {
  2421. char *p, *begin_word, *end_word, *end_whitespace;
  2422. begin_word = *buf;
  2423. end_word = begin_word + strcspn(begin_word, delimiters);
  2424. /* Check for quotechar */
  2425. if (end_word > begin_word) {
  2426. p = end_word - 1;
  2427. while (*p == quotechar) {
  2428. /* While the delimiter is quoted, look for the next delimiter. */
  2429. /* This happens, e.g., in calls from parse_auth_header,
  2430. * if the user name contains a " character. */
  2431. /* If there is anything beyond end_word, copy it. */
  2432. if (*end_word != '\0') {
  2433. size_t end_off = strcspn(end_word + 1, delimiters);
  2434. memmove(p, end_word, end_off + 1);
  2435. p += end_off; /* p must correspond to end_word - 1 */
  2436. end_word += end_off + 1;
  2437. } else {
  2438. *p = '\0';
  2439. break;
  2440. }
  2441. }
  2442. for (p++; p < end_word; p++) {
  2443. *p = '\0';
  2444. }
  2445. }
  2446. if (*end_word == '\0') {
  2447. *buf = end_word;
  2448. } else {
  2449. #if defined(__GNUC__) || defined(__MINGW32__)
  2450. /* Disable spurious conversion warning for GCC */
  2451. #pragma GCC diagnostic push
  2452. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2453. #endif
  2454. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2455. #if defined(__GNUC__) || defined(__MINGW32__)
  2456. #pragma GCC diagnostic pop
  2457. #endif
  2458. for (p = end_word; p < end_whitespace; p++) {
  2459. *p = '\0';
  2460. }
  2461. *buf = end_whitespace;
  2462. }
  2463. return begin_word;
  2464. }
  2465. /* Simplified version of skip_quoted without quote char
  2466. * and whitespace == delimiters */
  2467. static char *
  2468. skip(char **buf, const char *delimiters)
  2469. {
  2470. return skip_quoted(buf, delimiters, delimiters, 0);
  2471. }
  2472. /* Return HTTP header value, or NULL if not found. */
  2473. static const char *
  2474. get_header(const struct mg_request_info *ri, const char *name)
  2475. {
  2476. int i;
  2477. if (ri) {
  2478. for (i = 0; i < ri->num_headers; i++) {
  2479. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2480. return ri->http_headers[i].value;
  2481. }
  2482. }
  2483. }
  2484. return NULL;
  2485. }
  2486. const char *
  2487. mg_get_header(const struct mg_connection *conn, const char *name)
  2488. {
  2489. if (!conn) {
  2490. return NULL;
  2491. }
  2492. return get_header(&conn->request_info, name);
  2493. }
  2494. /* A helper function for traversing a comma separated list of values.
  2495. * It returns a list pointer shifted to the next value, or NULL if the end
  2496. * of the list found.
  2497. * Value is stored in val vector. If value has form "x=y", then eq_val
  2498. * vector is initialized to point to the "y" part, and val vector length
  2499. * is adjusted to point only to "x". */
  2500. static const char *
  2501. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2502. {
  2503. int end;
  2504. reparse:
  2505. if (val == NULL || list == NULL || *list == '\0') {
  2506. /* End of the list */
  2507. list = NULL;
  2508. } else {
  2509. /* Skip over leading LWS */
  2510. while (*list == ' ' || *list == '\t')
  2511. list++;
  2512. val->ptr = list;
  2513. if ((list = strchr(val->ptr, ',')) != NULL) {
  2514. /* Comma found. Store length and shift the list ptr */
  2515. val->len = ((size_t)(list - val->ptr));
  2516. list++;
  2517. } else {
  2518. /* This value is the last one */
  2519. list = val->ptr + strlen(val->ptr);
  2520. val->len = ((size_t)(list - val->ptr));
  2521. }
  2522. /* Adjust length for trailing LWS */
  2523. end = (int)val->len - 1;
  2524. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2525. end--;
  2526. val->len = (size_t)(end + 1);
  2527. if (val->len == 0) {
  2528. /* Ignore any empty entries. */
  2529. goto reparse;
  2530. }
  2531. if (eq_val != NULL) {
  2532. /* Value has form "x=y", adjust pointers and lengths
  2533. * so that val points to "x", and eq_val points to "y". */
  2534. eq_val->len = 0;
  2535. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2536. if (eq_val->ptr != NULL) {
  2537. eq_val->ptr++; /* Skip over '=' character */
  2538. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2539. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2540. }
  2541. }
  2542. }
  2543. return list;
  2544. }
  2545. /* A helper function for checking if a comma separated list of values contains
  2546. * the given option (case insensitvely).
  2547. * 'header' can be NULL, in which case false is returned. */
  2548. static int
  2549. header_has_option(const char *header, const char *option)
  2550. {
  2551. struct vec opt_vec;
  2552. struct vec eq_vec;
  2553. assert(option != NULL);
  2554. assert(option[0] != '\0');
  2555. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2556. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2557. return 1;
  2558. }
  2559. return 0;
  2560. }
  2561. /* Perform case-insensitive match of string against pattern */
  2562. static int
  2563. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2564. {
  2565. const char *or_str;
  2566. size_t i;
  2567. int j, len, res;
  2568. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2569. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2570. return (res > 0) ? res : match_prefix(or_str + 1,
  2571. (size_t)((pattern + pattern_len)
  2572. - (or_str + 1)),
  2573. str);
  2574. }
  2575. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2576. if (pattern[i] == '?' && str[j] != '\0') {
  2577. continue;
  2578. } else if (pattern[i] == '$') {
  2579. return (str[j] == '\0') ? j : -1;
  2580. } else if (pattern[i] == '*') {
  2581. i++;
  2582. if (pattern[i] == '*') {
  2583. i++;
  2584. len = (int)strlen(str + j);
  2585. } else {
  2586. len = (int)strcspn(str + j, "/");
  2587. }
  2588. if (i == pattern_len) {
  2589. return j + len;
  2590. }
  2591. do {
  2592. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2593. } while (res == -1 && len-- > 0);
  2594. return (res == -1) ? -1 : j + res + len;
  2595. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2596. return -1;
  2597. }
  2598. }
  2599. return j;
  2600. }
  2601. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2602. * This function must tolerate situations when connection info is not
  2603. * set up, for example if request parsing failed. */
  2604. static int
  2605. should_keep_alive(const struct mg_connection *conn)
  2606. {
  2607. if (conn != NULL) {
  2608. const char *http_version = conn->request_info.http_version;
  2609. const char *header = mg_get_header(conn, "Connection");
  2610. if (conn->must_close || conn->status_code == 401
  2611. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2612. || (header != NULL && !header_has_option(header, "keep-alive"))
  2613. || (header == NULL && http_version
  2614. && 0 != strcmp(http_version, "1.1"))) {
  2615. return 0;
  2616. }
  2617. return 1;
  2618. }
  2619. return 0;
  2620. }
  2621. static int
  2622. should_decode_url(const struct mg_connection *conn)
  2623. {
  2624. if (!conn || !conn->ctx) {
  2625. return 0;
  2626. }
  2627. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2628. }
  2629. static const char *
  2630. suggest_connection_header(const struct mg_connection *conn)
  2631. {
  2632. return should_keep_alive(conn) ? "keep-alive" : "close";
  2633. }
  2634. static int
  2635. send_no_cache_header(struct mg_connection *conn)
  2636. {
  2637. /* Send all current and obsolete cache opt-out directives. */
  2638. return mg_printf(conn,
  2639. "Cache-Control: no-cache, no-store, "
  2640. "must-revalidate, private, max-age=0\r\n"
  2641. "Pragma: no-cache\r\n"
  2642. "Expires: 0\r\n");
  2643. }
  2644. static int
  2645. send_static_cache_header(struct mg_connection *conn)
  2646. {
  2647. #if !defined(NO_CACHING)
  2648. /* Read the server config to check how long a file may be cached.
  2649. * The configuration is in seconds. */
  2650. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2651. if (max_age <= 0) {
  2652. /* 0 means "do not cache". All values <0 are reserved
  2653. * and may be used differently in the future. */
  2654. /* If a file should not be cached, do not only send
  2655. * max-age=0, but also pragmas and Expires headers. */
  2656. return send_no_cache_header(conn);
  2657. }
  2658. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2659. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2660. /* See also https://www.mnot.net/cache_docs/ */
  2661. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2662. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2663. * year to 31622400 seconds. For the moment, we just send whatever has
  2664. * been configured, still the behavior for >1 year should be considered
  2665. * as undefined. */
  2666. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2667. #else /* NO_CACHING */
  2668. return send_no_cache_header(conn);
  2669. #endif /* !NO_CACHING */
  2670. }
  2671. static int
  2672. send_additional_header(struct mg_connection *conn)
  2673. {
  2674. int i = 0;
  2675. #if 0
  2676. i += mg_printf(conn, "Strict-Transport-Security: max-age=%u\r\n", 3600);
  2677. #endif
  2678. i += mg_printf(conn, "X-Some-Test-Header: %u\r\n", 42);
  2679. return i;
  2680. }
  2681. static void handle_file_based_request(struct mg_connection *conn,
  2682. const char *path,
  2683. struct mg_file *filep);
  2684. const char *
  2685. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2686. {
  2687. /* See IANA HTTP status code assignment:
  2688. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2689. */
  2690. switch (response_code) {
  2691. /* RFC2616 Section 10.1 - Informational 1xx */
  2692. case 100:
  2693. return "Continue"; /* RFC2616 Section 10.1.1 */
  2694. case 101:
  2695. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2696. case 102:
  2697. return "Processing"; /* RFC2518 Section 10.1 */
  2698. /* RFC2616 Section 10.2 - Successful 2xx */
  2699. case 200:
  2700. return "OK"; /* RFC2616 Section 10.2.1 */
  2701. case 201:
  2702. return "Created"; /* RFC2616 Section 10.2.2 */
  2703. case 202:
  2704. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2705. case 203:
  2706. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2707. case 204:
  2708. return "No Content"; /* RFC2616 Section 10.2.5 */
  2709. case 205:
  2710. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2711. case 206:
  2712. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2713. case 207:
  2714. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2715. case 208:
  2716. return "Already Reported"; /* RFC5842 Section 7.1 */
  2717. case 226:
  2718. return "IM used"; /* RFC3229 Section 10.4.1 */
  2719. /* RFC2616 Section 10.3 - Redirection 3xx */
  2720. case 300:
  2721. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2722. case 301:
  2723. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2724. case 302:
  2725. return "Found"; /* RFC2616 Section 10.3.3 */
  2726. case 303:
  2727. return "See Other"; /* RFC2616 Section 10.3.4 */
  2728. case 304:
  2729. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2730. case 305:
  2731. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2732. case 307:
  2733. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2734. case 308:
  2735. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2736. /* RFC2616 Section 10.4 - Client Error 4xx */
  2737. case 400:
  2738. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2739. case 401:
  2740. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2741. case 402:
  2742. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2743. case 403:
  2744. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2745. case 404:
  2746. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2747. case 405:
  2748. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2749. case 406:
  2750. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2751. case 407:
  2752. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2753. case 408:
  2754. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2755. case 409:
  2756. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2757. case 410:
  2758. return "Gone"; /* RFC2616 Section 10.4.11 */
  2759. case 411:
  2760. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2761. case 412:
  2762. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2763. case 413:
  2764. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2765. case 414:
  2766. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2767. case 415:
  2768. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2769. case 416:
  2770. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2771. case 417:
  2772. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2773. case 421:
  2774. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2775. case 422:
  2776. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2777. * Section 11.2 */
  2778. case 423:
  2779. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2780. case 424:
  2781. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2782. * Section 11.4 */
  2783. case 426:
  2784. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2785. case 428:
  2786. return "Precondition Required"; /* RFC 6585, Section 3 */
  2787. case 429:
  2788. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2789. case 431:
  2790. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2791. case 451:
  2792. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2793. * Section 3 */
  2794. /* RFC2616 Section 10.5 - Server Error 5xx */
  2795. case 500:
  2796. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2797. case 501:
  2798. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2799. case 502:
  2800. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2801. case 503:
  2802. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2803. case 504:
  2804. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2805. case 505:
  2806. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2807. case 506:
  2808. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2809. case 507:
  2810. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2811. * Section 11.5 */
  2812. case 508:
  2813. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2814. case 510:
  2815. return "Not Extended"; /* RFC 2774, Section 7 */
  2816. case 511:
  2817. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2818. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2819. * E.g., "de facto" standards due to common use, ... */
  2820. case 418:
  2821. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2822. case 419:
  2823. return "Authentication Timeout"; /* common use */
  2824. case 420:
  2825. return "Enhance Your Calm"; /* common use */
  2826. case 440:
  2827. return "Login Timeout"; /* common use */
  2828. case 509:
  2829. return "Bandwidth Limit Exceeded"; /* common use */
  2830. default:
  2831. /* This error code is unknown. This should not happen. */
  2832. if (conn) {
  2833. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2834. }
  2835. /* Return at least a category according to RFC 2616 Section 10. */
  2836. if (response_code >= 100 && response_code < 200) {
  2837. /* Unknown informational status code */
  2838. return "Information";
  2839. }
  2840. if (response_code >= 200 && response_code < 300) {
  2841. /* Unknown success code */
  2842. return "Success";
  2843. }
  2844. if (response_code >= 300 && response_code < 400) {
  2845. /* Unknown redirection code */
  2846. return "Redirection";
  2847. }
  2848. if (response_code >= 400 && response_code < 500) {
  2849. /* Unknown request error code */
  2850. return "Client Error";
  2851. }
  2852. if (response_code >= 500 && response_code < 600) {
  2853. /* Unknown server error code */
  2854. return "Server Error";
  2855. }
  2856. /* Response code not even within reasonable range */
  2857. return "";
  2858. }
  2859. }
  2860. static void send_http_error(struct mg_connection *,
  2861. int,
  2862. PRINTF_FORMAT_STRING(const char *fmt),
  2863. ...) PRINTF_ARGS(3, 4);
  2864. static void
  2865. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2866. {
  2867. char buf[MG_BUF_LEN];
  2868. va_list ap;
  2869. int len, i, page_handler_found, scope, truncated, has_body;
  2870. char date[64];
  2871. time_t curtime = time(NULL);
  2872. const char *error_handler = NULL;
  2873. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2874. const char *error_page_file_ext, *tstr;
  2875. const char *status_text = mg_get_response_code_text(conn, status);
  2876. if (conn == NULL) {
  2877. return;
  2878. }
  2879. conn->status_code = status;
  2880. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2881. || conn->ctx->callbacks.http_error(conn, status)) {
  2882. if (!conn->in_error_handler) {
  2883. /* Send user defined error pages, if defined */
  2884. error_handler = conn->ctx->config[ERROR_PAGES];
  2885. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2886. page_handler_found = 0;
  2887. if (error_handler != NULL) {
  2888. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2889. switch (scope) {
  2890. case 1: /* Handler for specific error, e.g. 404 error */
  2891. mg_snprintf(conn,
  2892. &truncated,
  2893. buf,
  2894. sizeof(buf) - 32,
  2895. "%serror%03u.",
  2896. error_handler,
  2897. status);
  2898. break;
  2899. case 2: /* Handler for error group, e.g., 5xx error handler
  2900. * for all server errors (500-599) */
  2901. mg_snprintf(conn,
  2902. &truncated,
  2903. buf,
  2904. sizeof(buf) - 32,
  2905. "%serror%01uxx.",
  2906. error_handler,
  2907. status / 100);
  2908. break;
  2909. default: /* Handler for all errors */
  2910. mg_snprintf(conn,
  2911. &truncated,
  2912. buf,
  2913. sizeof(buf) - 32,
  2914. "%serror.",
  2915. error_handler);
  2916. break;
  2917. }
  2918. /* String truncation in buf may only occur if error_handler
  2919. * is too long. This string is from the config, not from a
  2920. * client. */
  2921. (void)truncated;
  2922. len = (int)strlen(buf);
  2923. tstr = strchr(error_page_file_ext, '.');
  2924. while (tstr) {
  2925. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2926. i++)
  2927. buf[len + i - 1] = tstr[i];
  2928. buf[len + i - 1] = 0;
  2929. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2930. page_handler_found = 1;
  2931. break;
  2932. }
  2933. tstr = strchr(tstr + i, '.');
  2934. }
  2935. }
  2936. }
  2937. if (page_handler_found) {
  2938. conn->in_error_handler = 1;
  2939. handle_file_based_request(conn, buf, &error_page_file);
  2940. conn->in_error_handler = 0;
  2941. return;
  2942. }
  2943. }
  2944. /* No custom error page. Send default error page. */
  2945. gmt_time_string(date, sizeof(date), &curtime);
  2946. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2947. has_body = (status > 199 && status != 204 && status != 304);
  2948. conn->must_close = 1;
  2949. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2950. send_no_cache_header(conn);
  2951. send_additional_header(conn);
  2952. if (has_body) {
  2953. mg_printf(conn,
  2954. "%s",
  2955. "Content-Type: text/plain; charset=utf-8\r\n");
  2956. }
  2957. mg_printf(conn,
  2958. "Date: %s\r\n"
  2959. "Connection: close\r\n\r\n",
  2960. date);
  2961. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2962. if (has_body) {
  2963. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2964. if (fmt != NULL) {
  2965. va_start(ap, fmt);
  2966. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2967. va_end(ap);
  2968. mg_write(conn, buf, strlen(buf));
  2969. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2970. }
  2971. } else {
  2972. /* No body allowed. Close the connection. */
  2973. DEBUG_TRACE("Error %i", status);
  2974. }
  2975. }
  2976. }
  2977. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2978. /* Create substitutes for POSIX functions in Win32. */
  2979. #if defined(__MINGW32__)
  2980. /* Show no warning in case system functions are not used. */
  2981. #pragma GCC diagnostic push
  2982. #pragma GCC diagnostic ignored "-Wunused-function"
  2983. #endif
  2984. static int
  2985. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2986. {
  2987. (void)unused;
  2988. *mutex = CreateMutex(NULL, FALSE, NULL);
  2989. return (*mutex == NULL) ? -1 : 0;
  2990. }
  2991. static int
  2992. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2993. {
  2994. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2995. }
  2996. static int
  2997. pthread_mutex_lock(pthread_mutex_t *mutex)
  2998. {
  2999. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3000. }
  3001. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3002. static int
  3003. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3004. {
  3005. switch (WaitForSingleObject(*mutex, 0)) {
  3006. case WAIT_OBJECT_0:
  3007. return 0;
  3008. case WAIT_TIMEOUT:
  3009. return -2; /* EBUSY */
  3010. }
  3011. return -1;
  3012. }
  3013. #endif
  3014. static int
  3015. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3016. {
  3017. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3018. }
  3019. static int
  3020. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3021. {
  3022. (void)unused;
  3023. InitializeCriticalSection(&cv->threadIdSec);
  3024. cv->waiting_thread = NULL;
  3025. return 0;
  3026. }
  3027. static int
  3028. pthread_cond_timedwait(pthread_cond_t *cv,
  3029. pthread_mutex_t *mutex,
  3030. const struct timespec *abstime)
  3031. {
  3032. struct mg_workerTLS **ptls,
  3033. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3034. int ok;
  3035. struct timespec tsnow;
  3036. int64_t nsnow, nswaitabs, nswaitrel;
  3037. DWORD mswaitrel;
  3038. EnterCriticalSection(&cv->threadIdSec);
  3039. /* Add this thread to cv's waiting list */
  3040. ptls = &cv->waiting_thread;
  3041. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3042. ;
  3043. tls->next_waiting_thread = NULL;
  3044. *ptls = tls;
  3045. LeaveCriticalSection(&cv->threadIdSec);
  3046. if (abstime) {
  3047. clock_gettime(CLOCK_REALTIME, &tsnow);
  3048. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  3049. nswaitabs =
  3050. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3051. nswaitrel = nswaitabs - nsnow;
  3052. if (nswaitrel < 0) {
  3053. nswaitrel = 0;
  3054. }
  3055. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3056. } else {
  3057. mswaitrel = INFINITE;
  3058. }
  3059. pthread_mutex_unlock(mutex);
  3060. ok = (WAIT_OBJECT_0
  3061. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3062. if (!ok) {
  3063. ok = 1;
  3064. EnterCriticalSection(&cv->threadIdSec);
  3065. ptls = &cv->waiting_thread;
  3066. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3067. if (*ptls == tls) {
  3068. *ptls = tls->next_waiting_thread;
  3069. ok = 0;
  3070. break;
  3071. }
  3072. }
  3073. LeaveCriticalSection(&cv->threadIdSec);
  3074. if (ok) {
  3075. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3076. }
  3077. }
  3078. /* This thread has been removed from cv's waiting list */
  3079. pthread_mutex_lock(mutex);
  3080. return ok ? 0 : -1;
  3081. }
  3082. static int
  3083. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3084. {
  3085. return pthread_cond_timedwait(cv, mutex, NULL);
  3086. }
  3087. static int
  3088. pthread_cond_signal(pthread_cond_t *cv)
  3089. {
  3090. HANDLE wkup = NULL;
  3091. BOOL ok = FALSE;
  3092. EnterCriticalSection(&cv->threadIdSec);
  3093. if (cv->waiting_thread) {
  3094. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3095. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3096. ok = SetEvent(wkup);
  3097. assert(ok);
  3098. }
  3099. LeaveCriticalSection(&cv->threadIdSec);
  3100. return ok ? 0 : 1;
  3101. }
  3102. static int
  3103. pthread_cond_broadcast(pthread_cond_t *cv)
  3104. {
  3105. EnterCriticalSection(&cv->threadIdSec);
  3106. while (cv->waiting_thread) {
  3107. pthread_cond_signal(cv);
  3108. }
  3109. LeaveCriticalSection(&cv->threadIdSec);
  3110. return 0;
  3111. }
  3112. static int
  3113. pthread_cond_destroy(pthread_cond_t *cv)
  3114. {
  3115. EnterCriticalSection(&cv->threadIdSec);
  3116. assert(cv->waiting_thread == NULL);
  3117. LeaveCriticalSection(&cv->threadIdSec);
  3118. DeleteCriticalSection(&cv->threadIdSec);
  3119. return 0;
  3120. }
  3121. #ifdef ALTERNATIVE_QUEUE
  3122. static void *
  3123. event_create(void)
  3124. {
  3125. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3126. }
  3127. static int
  3128. event_wait(void *eventhdl)
  3129. {
  3130. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3131. return (res == WAIT_OBJECT_0);
  3132. }
  3133. static int
  3134. event_signal(void *eventhdl)
  3135. {
  3136. return (int)SetEvent((HANDLE)eventhdl);
  3137. }
  3138. static void
  3139. event_destroy(void *eventhdl)
  3140. {
  3141. CloseHandle((HANDLE)eventhdl);
  3142. }
  3143. #endif
  3144. #if defined(__MINGW32__)
  3145. /* Enable unused function warning again */
  3146. #pragma GCC diagnostic pop
  3147. #endif
  3148. /* For Windows, change all slashes to backslashes in path names. */
  3149. static void
  3150. change_slashes_to_backslashes(char *path)
  3151. {
  3152. int i;
  3153. for (i = 0; path[i] != '\0'; i++) {
  3154. if (path[i] == '/') {
  3155. path[i] = '\\';
  3156. }
  3157. /* remove double backslash (check i > 0 to preserve UNC paths,
  3158. * like \\server\file.txt) */
  3159. if ((path[i] == '\\') && (i > 0)) {
  3160. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3161. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3162. }
  3163. }
  3164. }
  3165. }
  3166. static int
  3167. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3168. {
  3169. int diff;
  3170. do {
  3171. diff = tolower(*s1) - tolower(*s2);
  3172. s1++;
  3173. s2++;
  3174. } while (diff == 0 && s1[-1] != '\0');
  3175. return diff;
  3176. }
  3177. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3178. * wbuf and wbuf_len is a target buffer and its length. */
  3179. static void
  3180. path_to_unicode(const struct mg_connection *conn,
  3181. const char *path,
  3182. wchar_t *wbuf,
  3183. size_t wbuf_len)
  3184. {
  3185. char buf[PATH_MAX], buf2[PATH_MAX];
  3186. wchar_t wbuf2[MAX_PATH + 1];
  3187. DWORD long_len, err;
  3188. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3189. mg_strlcpy(buf, path, sizeof(buf));
  3190. change_slashes_to_backslashes(buf);
  3191. /* Convert to Unicode and back. If doubly-converted string does not
  3192. * match the original, something is fishy, reject. */
  3193. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3194. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3195. WideCharToMultiByte(
  3196. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3197. if (strcmp(buf, buf2) != 0) {
  3198. wbuf[0] = L'\0';
  3199. }
  3200. /* Windows file systems are not case sensitive, but you can still use
  3201. * uppercase and lowercase letters (on all modern file systems).
  3202. * The server can check if the URI uses the same upper/lowercase
  3203. * letters an the file system, effectively making Windows servers
  3204. * case sensitive (like Linux servers are). It is still not possible
  3205. * to use two files with the same name in different cases on Windows
  3206. * (like /a and /A) - this would be possible in Linux.
  3207. * As a default, Windows is not case sensitive, but the case sensitive
  3208. * file name check can be activated by an additional configuration. */
  3209. if (conn) {
  3210. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3211. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3212. /* Use case sensitive compare function */
  3213. fcompare = wcscmp;
  3214. }
  3215. }
  3216. (void)conn; /* conn is currently unused */
  3217. #if !defined(_WIN32_WCE)
  3218. /* Only accept a full file path, not a Windows short (8.3) path. */
  3219. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3220. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3221. if (long_len == 0) {
  3222. err = GetLastError();
  3223. if (err == ERROR_FILE_NOT_FOUND) {
  3224. /* File does not exist. This is not always a problem here. */
  3225. return;
  3226. }
  3227. }
  3228. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3229. /* Short name is used. */
  3230. wbuf[0] = L'\0';
  3231. }
  3232. #else
  3233. (void)long_len;
  3234. (void)wbuf2;
  3235. (void)err;
  3236. if (strchr(path, '~')) {
  3237. wbuf[0] = L'\0';
  3238. }
  3239. #endif
  3240. }
  3241. /* Windows happily opens files with some garbage at the end of file name.
  3242. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3243. * "a.cgi", despite one would expect an error back.
  3244. * This function returns non-0 if path ends with some garbage. */
  3245. static int
  3246. path_cannot_disclose_cgi(const char *path)
  3247. {
  3248. static const char *allowed_last_characters = "_-";
  3249. int last = path[strlen(path) - 1];
  3250. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3251. }
  3252. static int
  3253. mg_stat(const struct mg_connection *conn,
  3254. const char *path,
  3255. struct mg_file_stat *filep)
  3256. {
  3257. wchar_t wbuf[PATH_MAX];
  3258. WIN32_FILE_ATTRIBUTE_DATA info;
  3259. time_t creation_time;
  3260. if (!filep) {
  3261. return 0;
  3262. }
  3263. memset(filep, 0, sizeof(*filep));
  3264. if (conn && is_file_in_memory(conn, path)) {
  3265. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3266. * memset */
  3267. /* Quick fix (for 1.9.x): */
  3268. /* mg_stat must fill all fields, also for files in memory */
  3269. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3270. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3271. filep->size = tmp_file.stat.size;
  3272. filep->location = 2;
  3273. /* TODO: for 1.10: restructure how files in memory are handled */
  3274. filep->last_modified = time(NULL); /* xxxxxxxx */
  3275. /* last_modified = now ... assumes the file may change during runtime,
  3276. * so every mg_fopen call may return different data */
  3277. /* last_modified = conn->ctx.start_time;
  3278. * May be used it the data does not change during runtime. This allows
  3279. * browser caching. Since we do not know, we have to assume the file
  3280. * in memory may change. */
  3281. return 1;
  3282. }
  3283. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3284. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3285. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3286. filep->last_modified =
  3287. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3288. info.ftLastWriteTime.dwHighDateTime);
  3289. /* On Windows, the file creation time can be higher than the
  3290. * modification time, e.g. when a file is copied.
  3291. * Since the Last-Modified timestamp is used for caching
  3292. * it should be based on the most recent timestamp. */
  3293. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3294. info.ftCreationTime.dwHighDateTime);
  3295. if (creation_time > filep->last_modified) {
  3296. filep->last_modified = creation_time;
  3297. }
  3298. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3299. /* If file name is fishy, reset the file structure and return
  3300. * error.
  3301. * Note it is important to reset, not just return the error, cause
  3302. * functions like is_file_opened() check the struct. */
  3303. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3304. memset(filep, 0, sizeof(*filep));
  3305. return 0;
  3306. }
  3307. return 1;
  3308. }
  3309. return 0;
  3310. }
  3311. static int
  3312. mg_remove(const struct mg_connection *conn, const char *path)
  3313. {
  3314. wchar_t wbuf[PATH_MAX];
  3315. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3316. return DeleteFileW(wbuf) ? 0 : -1;
  3317. }
  3318. static int
  3319. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3320. {
  3321. wchar_t wbuf[PATH_MAX];
  3322. (void)mode;
  3323. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3324. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3325. }
  3326. /* Create substitutes for POSIX functions in Win32. */
  3327. #if defined(__MINGW32__)
  3328. /* Show no warning in case system functions are not used. */
  3329. #pragma GCC diagnostic push
  3330. #pragma GCC diagnostic ignored "-Wunused-function"
  3331. #endif
  3332. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3333. static DIR *
  3334. mg_opendir(const struct mg_connection *conn, const char *name)
  3335. {
  3336. DIR *dir = NULL;
  3337. wchar_t wpath[PATH_MAX];
  3338. DWORD attrs;
  3339. if (name == NULL) {
  3340. SetLastError(ERROR_BAD_ARGUMENTS);
  3341. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3342. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3343. } else {
  3344. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3345. attrs = GetFileAttributesW(wpath);
  3346. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3347. == FILE_ATTRIBUTE_DIRECTORY)) {
  3348. (void)wcscat(wpath, L"\\*");
  3349. dir->handle = FindFirstFileW(wpath, &dir->info);
  3350. dir->result.d_name[0] = '\0';
  3351. } else {
  3352. mg_free(dir);
  3353. dir = NULL;
  3354. }
  3355. }
  3356. return dir;
  3357. }
  3358. static int
  3359. mg_closedir(DIR *dir)
  3360. {
  3361. int result = 0;
  3362. if (dir != NULL) {
  3363. if (dir->handle != INVALID_HANDLE_VALUE)
  3364. result = FindClose(dir->handle) ? 0 : -1;
  3365. mg_free(dir);
  3366. } else {
  3367. result = -1;
  3368. SetLastError(ERROR_BAD_ARGUMENTS);
  3369. }
  3370. return result;
  3371. }
  3372. static struct dirent *
  3373. mg_readdir(DIR *dir)
  3374. {
  3375. struct dirent *result = 0;
  3376. if (dir) {
  3377. if (dir->handle != INVALID_HANDLE_VALUE) {
  3378. result = &dir->result;
  3379. (void)WideCharToMultiByte(CP_UTF8,
  3380. 0,
  3381. dir->info.cFileName,
  3382. -1,
  3383. result->d_name,
  3384. sizeof(result->d_name),
  3385. NULL,
  3386. NULL);
  3387. if (!FindNextFileW(dir->handle, &dir->info)) {
  3388. (void)FindClose(dir->handle);
  3389. dir->handle = INVALID_HANDLE_VALUE;
  3390. }
  3391. } else {
  3392. SetLastError(ERROR_FILE_NOT_FOUND);
  3393. }
  3394. } else {
  3395. SetLastError(ERROR_BAD_ARGUMENTS);
  3396. }
  3397. return result;
  3398. }
  3399. #ifndef HAVE_POLL
  3400. static int
  3401. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3402. {
  3403. struct timeval tv;
  3404. fd_set set;
  3405. unsigned int i;
  3406. int result;
  3407. SOCKET maxfd = 0;
  3408. memset(&tv, 0, sizeof(tv));
  3409. tv.tv_sec = milliseconds / 1000;
  3410. tv.tv_usec = (milliseconds % 1000) * 1000;
  3411. FD_ZERO(&set);
  3412. for (i = 0; i < n; i++) {
  3413. FD_SET((SOCKET)pfd[i].fd, &set);
  3414. pfd[i].revents = 0;
  3415. if (pfd[i].fd > maxfd) {
  3416. maxfd = pfd[i].fd;
  3417. }
  3418. }
  3419. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3420. for (i = 0; i < n; i++) {
  3421. if (FD_ISSET(pfd[i].fd, &set)) {
  3422. pfd[i].revents = POLLIN;
  3423. }
  3424. }
  3425. }
  3426. /* We should subtract the time used in select from remaining
  3427. * "milliseconds", in particular if called from mg_poll with a
  3428. * timeout quantum.
  3429. * Unfortunately, the remaining time is not stored in "tv" in all
  3430. * implementations, so the result in "tv" must be considered undefined.
  3431. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3432. return result;
  3433. }
  3434. #endif /* HAVE_POLL */
  3435. #if defined(__MINGW32__)
  3436. /* Enable unused function warning again */
  3437. #pragma GCC diagnostic pop
  3438. #endif
  3439. static void
  3440. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3441. {
  3442. (void)conn; /* Unused. */
  3443. #if defined(_WIN32_WCE)
  3444. (void)sock;
  3445. #else
  3446. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3447. #endif
  3448. }
  3449. int
  3450. mg_start_thread(mg_thread_func_t f, void *p)
  3451. {
  3452. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3453. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3454. */
  3455. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3456. == ((uintptr_t)(-1L)))
  3457. ? -1
  3458. : 0);
  3459. #else
  3460. return (
  3461. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3462. ? -1
  3463. : 0);
  3464. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3465. }
  3466. /* Start a thread storing the thread context. */
  3467. static int
  3468. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3469. void *p,
  3470. pthread_t *threadidptr)
  3471. {
  3472. uintptr_t uip;
  3473. HANDLE threadhandle;
  3474. int result = -1;
  3475. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3476. threadhandle = (HANDLE)uip;
  3477. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3478. *threadidptr = threadhandle;
  3479. result = 0;
  3480. }
  3481. return result;
  3482. }
  3483. /* Wait for a thread to finish. */
  3484. static int
  3485. mg_join_thread(pthread_t threadid)
  3486. {
  3487. int result;
  3488. DWORD dwevent;
  3489. result = -1;
  3490. dwevent = WaitForSingleObject(threadid, INFINITE);
  3491. if (dwevent == WAIT_FAILED) {
  3492. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3493. } else {
  3494. if (dwevent == WAIT_OBJECT_0) {
  3495. CloseHandle(threadid);
  3496. result = 0;
  3497. }
  3498. }
  3499. return result;
  3500. }
  3501. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3502. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3503. /* Create substitutes for POSIX functions in Win32. */
  3504. #if defined(__MINGW32__)
  3505. /* Show no warning in case system functions are not used. */
  3506. #pragma GCC diagnostic push
  3507. #pragma GCC diagnostic ignored "-Wunused-function"
  3508. #endif
  3509. static HANDLE
  3510. dlopen(const char *dll_name, int flags)
  3511. {
  3512. wchar_t wbuf[PATH_MAX];
  3513. (void)flags;
  3514. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3515. return LoadLibraryW(wbuf);
  3516. }
  3517. static int
  3518. dlclose(void *handle)
  3519. {
  3520. int result;
  3521. if (FreeLibrary((HMODULE)handle) != 0) {
  3522. result = 0;
  3523. } else {
  3524. result = -1;
  3525. }
  3526. return result;
  3527. }
  3528. #if defined(__MINGW32__)
  3529. /* Enable unused function warning again */
  3530. #pragma GCC diagnostic pop
  3531. #endif
  3532. #endif
  3533. #if !defined(NO_CGI)
  3534. #define SIGKILL (0)
  3535. static int
  3536. kill(pid_t pid, int sig_num)
  3537. {
  3538. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3539. (void)CloseHandle((HANDLE)pid);
  3540. return 0;
  3541. }
  3542. static void
  3543. trim_trailing_whitespaces(char *s)
  3544. {
  3545. char *e = s + strlen(s) - 1;
  3546. while (e > s && isspace(*(unsigned char *)e)) {
  3547. *e-- = '\0';
  3548. }
  3549. }
  3550. static pid_t
  3551. spawn_process(struct mg_connection *conn,
  3552. const char *prog,
  3553. char *envblk,
  3554. char *envp[],
  3555. int fdin[2],
  3556. int fdout[2],
  3557. int fderr[2],
  3558. const char *dir)
  3559. {
  3560. HANDLE me;
  3561. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3562. cmdline[PATH_MAX], buf[PATH_MAX];
  3563. int truncated;
  3564. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3565. STARTUPINFOA si;
  3566. PROCESS_INFORMATION pi = {0};
  3567. (void)envp;
  3568. memset(&si, 0, sizeof(si));
  3569. si.cb = sizeof(si);
  3570. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3571. si.wShowWindow = SW_HIDE;
  3572. me = GetCurrentProcess();
  3573. DuplicateHandle(me,
  3574. (HANDLE)_get_osfhandle(fdin[0]),
  3575. me,
  3576. &si.hStdInput,
  3577. 0,
  3578. TRUE,
  3579. DUPLICATE_SAME_ACCESS);
  3580. DuplicateHandle(me,
  3581. (HANDLE)_get_osfhandle(fdout[1]),
  3582. me,
  3583. &si.hStdOutput,
  3584. 0,
  3585. TRUE,
  3586. DUPLICATE_SAME_ACCESS);
  3587. DuplicateHandle(me,
  3588. (HANDLE)_get_osfhandle(fderr[1]),
  3589. me,
  3590. &si.hStdError,
  3591. 0,
  3592. TRUE,
  3593. DUPLICATE_SAME_ACCESS);
  3594. /* Mark handles that should not be inherited. See
  3595. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3596. */
  3597. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3598. HANDLE_FLAG_INHERIT,
  3599. 0);
  3600. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3601. HANDLE_FLAG_INHERIT,
  3602. 0);
  3603. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3604. HANDLE_FLAG_INHERIT,
  3605. 0);
  3606. /* If CGI file is a script, try to read the interpreter line */
  3607. interp = conn->ctx->config[CGI_INTERPRETER];
  3608. if (interp == NULL) {
  3609. buf[0] = buf[1] = '\0';
  3610. /* Read the first line of the script into the buffer */
  3611. mg_snprintf(
  3612. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3613. if (truncated) {
  3614. pi.hProcess = (pid_t)-1;
  3615. goto spawn_cleanup;
  3616. }
  3617. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3618. p = (char *)file.access.membuf;
  3619. mg_fgets(buf, sizeof(buf), &file, &p);
  3620. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3621. buf[sizeof(buf) - 1] = '\0';
  3622. }
  3623. if (buf[0] == '#' && buf[1] == '!') {
  3624. trim_trailing_whitespaces(buf + 2);
  3625. } else {
  3626. buf[2] = '\0';
  3627. }
  3628. interp = buf + 2;
  3629. }
  3630. if (interp[0] != '\0') {
  3631. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3632. interp = full_interp;
  3633. }
  3634. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3635. if (interp[0] != '\0') {
  3636. mg_snprintf(conn,
  3637. &truncated,
  3638. cmdline,
  3639. sizeof(cmdline),
  3640. "\"%s\" \"%s\\%s\"",
  3641. interp,
  3642. full_dir,
  3643. prog);
  3644. } else {
  3645. mg_snprintf(conn,
  3646. &truncated,
  3647. cmdline,
  3648. sizeof(cmdline),
  3649. "\"%s\\%s\"",
  3650. full_dir,
  3651. prog);
  3652. }
  3653. if (truncated) {
  3654. pi.hProcess = (pid_t)-1;
  3655. goto spawn_cleanup;
  3656. }
  3657. DEBUG_TRACE("Running [%s]", cmdline);
  3658. if (CreateProcessA(NULL,
  3659. cmdline,
  3660. NULL,
  3661. NULL,
  3662. TRUE,
  3663. CREATE_NEW_PROCESS_GROUP,
  3664. envblk,
  3665. NULL,
  3666. &si,
  3667. &pi) == 0) {
  3668. mg_cry(
  3669. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3670. pi.hProcess = (pid_t)-1;
  3671. /* goto spawn_cleanup; */
  3672. }
  3673. spawn_cleanup:
  3674. (void)CloseHandle(si.hStdOutput);
  3675. (void)CloseHandle(si.hStdError);
  3676. (void)CloseHandle(si.hStdInput);
  3677. if (pi.hThread != NULL) {
  3678. (void)CloseHandle(pi.hThread);
  3679. }
  3680. return (pid_t)pi.hProcess;
  3681. }
  3682. #endif /* !NO_CGI */
  3683. static int
  3684. set_blocking_mode(SOCKET sock, int blocking)
  3685. {
  3686. unsigned long non_blocking = !blocking;
  3687. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3688. }
  3689. #else
  3690. static int
  3691. mg_stat(const struct mg_connection *conn,
  3692. const char *path,
  3693. struct mg_file_stat *filep)
  3694. {
  3695. struct stat st;
  3696. if (!filep) {
  3697. return 0;
  3698. }
  3699. memset(filep, 0, sizeof(*filep));
  3700. if (conn && is_file_in_memory(conn, path)) {
  3701. /* Quick fix (for 1.9.x): */
  3702. /* mg_stat must fill all fields, also for files in memory */
  3703. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3704. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3705. filep->size = tmp_file.stat.size;
  3706. filep->last_modified = time(NULL);
  3707. filep->location = 2;
  3708. /* TODO: for 1.10: restructure how files in memory are handled */
  3709. return 1;
  3710. }
  3711. if (0 == stat(path, &st)) {
  3712. filep->size = (uint64_t)(st.st_size);
  3713. filep->last_modified = st.st_mtime;
  3714. filep->is_directory = S_ISDIR(st.st_mode);
  3715. return 1;
  3716. }
  3717. return 0;
  3718. }
  3719. static void
  3720. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3721. {
  3722. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3723. if (conn) {
  3724. mg_cry(conn,
  3725. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3726. __func__,
  3727. strerror(ERRNO));
  3728. }
  3729. }
  3730. }
  3731. int
  3732. mg_start_thread(mg_thread_func_t func, void *param)
  3733. {
  3734. pthread_t thread_id;
  3735. pthread_attr_t attr;
  3736. int result;
  3737. (void)pthread_attr_init(&attr);
  3738. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3739. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3740. /* Compile-time option to control stack size,
  3741. * e.g. -DUSE_STACK_SIZE=16384 */
  3742. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3743. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3744. result = pthread_create(&thread_id, &attr, func, param);
  3745. pthread_attr_destroy(&attr);
  3746. return result;
  3747. }
  3748. /* Start a thread storing the thread context. */
  3749. static int
  3750. mg_start_thread_with_id(mg_thread_func_t func,
  3751. void *param,
  3752. pthread_t *threadidptr)
  3753. {
  3754. pthread_t thread_id;
  3755. pthread_attr_t attr;
  3756. int result;
  3757. (void)pthread_attr_init(&attr);
  3758. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3759. /* Compile-time option to control stack size,
  3760. * e.g. -DUSE_STACK_SIZE=16384 */
  3761. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3762. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3763. result = pthread_create(&thread_id, &attr, func, param);
  3764. pthread_attr_destroy(&attr);
  3765. if ((result == 0) && (threadidptr != NULL)) {
  3766. *threadidptr = thread_id;
  3767. }
  3768. return result;
  3769. }
  3770. /* Wait for a thread to finish. */
  3771. static int
  3772. mg_join_thread(pthread_t threadid)
  3773. {
  3774. int result;
  3775. result = pthread_join(threadid, NULL);
  3776. return result;
  3777. }
  3778. #ifndef NO_CGI
  3779. static pid_t
  3780. spawn_process(struct mg_connection *conn,
  3781. const char *prog,
  3782. char *envblk,
  3783. char *envp[],
  3784. int fdin[2],
  3785. int fdout[2],
  3786. int fderr[2],
  3787. const char *dir)
  3788. {
  3789. pid_t pid;
  3790. const char *interp;
  3791. (void)envblk;
  3792. if (conn == NULL) {
  3793. return 0;
  3794. }
  3795. if ((pid = fork()) == -1) {
  3796. /* Parent */
  3797. send_http_error(conn,
  3798. 500,
  3799. "Error: Creating CGI process\nfork(): %s",
  3800. strerror(ERRNO));
  3801. } else if (pid == 0) {
  3802. /* Child */
  3803. if (chdir(dir) != 0) {
  3804. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3805. } else if (dup2(fdin[0], 0) == -1) {
  3806. mg_cry(conn,
  3807. "%s: dup2(%d, 0): %s",
  3808. __func__,
  3809. fdin[0],
  3810. strerror(ERRNO));
  3811. } else if (dup2(fdout[1], 1) == -1) {
  3812. mg_cry(conn,
  3813. "%s: dup2(%d, 1): %s",
  3814. __func__,
  3815. fdout[1],
  3816. strerror(ERRNO));
  3817. } else if (dup2(fderr[1], 2) == -1) {
  3818. mg_cry(conn,
  3819. "%s: dup2(%d, 2): %s",
  3820. __func__,
  3821. fderr[1],
  3822. strerror(ERRNO));
  3823. } else {
  3824. /* Keep stderr and stdout in two different pipes.
  3825. * Stdout will be sent back to the client,
  3826. * stderr should go into a server error log. */
  3827. (void)close(fdin[0]);
  3828. (void)close(fdout[1]);
  3829. (void)close(fderr[1]);
  3830. /* Close write end fdin and read end fdout and fderr */
  3831. (void)close(fdin[1]);
  3832. (void)close(fdout[0]);
  3833. (void)close(fderr[0]);
  3834. /* After exec, all signal handlers are restored to their default
  3835. * values, with one exception of SIGCHLD. According to
  3836. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3837. * leave unchanged after exec if it was set to be ignored. Restore
  3838. * it to default action. */
  3839. signal(SIGCHLD, SIG_DFL);
  3840. interp = conn->ctx->config[CGI_INTERPRETER];
  3841. if (interp == NULL) {
  3842. (void)execle(prog, prog, NULL, envp);
  3843. mg_cry(conn,
  3844. "%s: execle(%s): %s",
  3845. __func__,
  3846. prog,
  3847. strerror(ERRNO));
  3848. } else {
  3849. (void)execle(interp, interp, prog, NULL, envp);
  3850. mg_cry(conn,
  3851. "%s: execle(%s %s): %s",
  3852. __func__,
  3853. interp,
  3854. prog,
  3855. strerror(ERRNO));
  3856. }
  3857. }
  3858. exit(EXIT_FAILURE);
  3859. }
  3860. return pid;
  3861. }
  3862. #endif /* !NO_CGI */
  3863. static int
  3864. set_blocking_mode(SOCKET sock, int blocking)
  3865. {
  3866. int flags;
  3867. flags = fcntl(sock, F_GETFL, 0);
  3868. if (blocking) {
  3869. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3870. } else {
  3871. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3872. }
  3873. return 0;
  3874. }
  3875. #endif /* _WIN32 */
  3876. /* End of initial operating system specific define block. */
  3877. /* Get a random number (independent of C rand function) */
  3878. static uint64_t
  3879. get_random(void)
  3880. {
  3881. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3882. static uint64_t lcg = 0; /* Linear congruential generator */
  3883. struct timespec now;
  3884. memset(&now, 0, sizeof(now));
  3885. clock_gettime(CLOCK_MONOTONIC, &now);
  3886. if (lfsr == 0) {
  3887. /* lfsr will be only 0 if has not been initialized,
  3888. * so this code is called only once. */
  3889. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3890. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3891. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3892. + (uint64_t)(ptrdiff_t)&now;
  3893. } else {
  3894. /* Get the next step of both random number generators. */
  3895. lfsr = (lfsr >> 1)
  3896. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3897. << 63);
  3898. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3899. }
  3900. /* Combining two pseudo-random number generators and a high resolution part
  3901. * of the current server time will make it hard (impossible?) to guess the
  3902. * next number. */
  3903. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3904. }
  3905. static int
  3906. mg_poll(struct pollfd *pfd,
  3907. unsigned int n,
  3908. int milliseconds,
  3909. volatile int *stop_server)
  3910. {
  3911. int ms_now, result;
  3912. /* Call poll, but only for a maximum time of a few seconds.
  3913. * This will allow to stop the server after some seconds, instead
  3914. * of having to wait for a long socket timeout. */
  3915. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3916. do {
  3917. if (*stop_server) {
  3918. /* Shut down signal */
  3919. return -2;
  3920. }
  3921. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3922. ms_now = milliseconds;
  3923. }
  3924. result = poll(pfd, n, ms_now);
  3925. if (result != 0) {
  3926. /* Poll returned either success (1) or error (-1).
  3927. * Forward both to the caller. */
  3928. return result;
  3929. }
  3930. /* Poll returned timeout (0). */
  3931. if (milliseconds > 0) {
  3932. milliseconds -= ms_now;
  3933. }
  3934. } while (milliseconds != 0);
  3935. return result;
  3936. }
  3937. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3938. * descriptor. Return number of bytes written. */
  3939. static int
  3940. push(struct mg_context *ctx,
  3941. FILE *fp,
  3942. SOCKET sock,
  3943. SSL *ssl,
  3944. const char *buf,
  3945. int len,
  3946. double timeout)
  3947. {
  3948. struct timespec start, now;
  3949. int n, err;
  3950. #ifdef _WIN32
  3951. typedef int len_t;
  3952. #else
  3953. typedef size_t len_t;
  3954. #endif
  3955. if (timeout > 0) {
  3956. memset(&start, 0, sizeof(start));
  3957. memset(&now, 0, sizeof(now));
  3958. clock_gettime(CLOCK_MONOTONIC, &start);
  3959. }
  3960. if (ctx == NULL) {
  3961. return -1;
  3962. }
  3963. #ifdef NO_SSL
  3964. if (ssl) {
  3965. return -1;
  3966. }
  3967. #endif
  3968. do {
  3969. #ifndef NO_SSL
  3970. if (ssl != NULL) {
  3971. n = SSL_write(ssl, buf, len);
  3972. if (n <= 0) {
  3973. err = SSL_get_error(ssl, n);
  3974. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3975. err = ERRNO;
  3976. } else if ((err == SSL_ERROR_WANT_READ)
  3977. || (err == SSL_ERROR_WANT_WRITE)) {
  3978. n = 0;
  3979. } else {
  3980. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3981. return -1;
  3982. }
  3983. } else {
  3984. err = 0;
  3985. }
  3986. } else
  3987. #endif
  3988. if (fp != NULL) {
  3989. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3990. if (ferror(fp)) {
  3991. n = -1;
  3992. err = ERRNO;
  3993. } else {
  3994. err = 0;
  3995. }
  3996. } else {
  3997. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3998. err = (n < 0) ? ERRNO : 0;
  3999. #ifdef _WIN32
  4000. if (err == WSAEWOULDBLOCK) {
  4001. err = 0;
  4002. n = 0;
  4003. }
  4004. #else
  4005. if (err == EWOULDBLOCK) {
  4006. err = 0;
  4007. n = 0;
  4008. }
  4009. #endif
  4010. if (n < 0) {
  4011. /* shutdown of the socket at client side */
  4012. return -1;
  4013. }
  4014. }
  4015. if (ctx->stop_flag) {
  4016. return -1;
  4017. }
  4018. if ((n > 0) || (n == 0 && len == 0)) {
  4019. /* some data has been read, or no data was requested */
  4020. return n;
  4021. }
  4022. if (n < 0) {
  4023. /* socket error - check errno */
  4024. DEBUG_TRACE("send() failed, error %d", err);
  4025. /* TODO (mid): error handling depending on the error code.
  4026. * These codes are different between Windows and Linux.
  4027. * Currently there is no problem with failing send calls,
  4028. * if there is a reproducible situation, it should be
  4029. * investigated in detail.
  4030. */
  4031. return -1;
  4032. }
  4033. /* Only in case n=0 (timeout), repeat calling the write function */
  4034. if (timeout > 0) {
  4035. clock_gettime(CLOCK_MONOTONIC, &now);
  4036. }
  4037. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  4038. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4039. used */
  4040. return -1;
  4041. }
  4042. static int64_t
  4043. push_all(struct mg_context *ctx,
  4044. FILE *fp,
  4045. SOCKET sock,
  4046. SSL *ssl,
  4047. const char *buf,
  4048. int64_t len)
  4049. {
  4050. double timeout = -1.0;
  4051. int64_t n, nwritten = 0;
  4052. if (ctx == NULL) {
  4053. return -1;
  4054. }
  4055. if (ctx->config[REQUEST_TIMEOUT]) {
  4056. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4057. }
  4058. while (len > 0 && ctx->stop_flag == 0) {
  4059. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4060. if (n < 0) {
  4061. if (nwritten == 0) {
  4062. nwritten = n; /* Propagate the error */
  4063. }
  4064. break;
  4065. } else if (n == 0) {
  4066. break; /* No more data to write */
  4067. } else {
  4068. nwritten += n;
  4069. len -= n;
  4070. }
  4071. }
  4072. return nwritten;
  4073. }
  4074. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4075. * Return negative value on error, or number of bytes read on success. */
  4076. static int
  4077. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  4078. {
  4079. int nread, err = 0;
  4080. #ifdef _WIN32
  4081. typedef int len_t;
  4082. #else
  4083. typedef size_t len_t;
  4084. #endif
  4085. if (fp != NULL) {
  4086. #if !defined(_WIN32_WCE)
  4087. /* Use read() instead of fread(), because if we're reading from the
  4088. * CGI pipe, fread() may block until IO buffer is filled up. We
  4089. * cannot afford to block and must pass all read bytes immediately
  4090. * to the client. */
  4091. nread = (int)read(fileno(fp), buf, (size_t)len);
  4092. #else
  4093. /* WinCE does not support CGI pipes */
  4094. nread = (int)fread(buf, 1, (size_t)len, fp);
  4095. #endif
  4096. err = (nread < 0) ? ERRNO : 0;
  4097. #ifndef NO_SSL
  4098. } else if (conn->ssl != NULL) {
  4099. struct pollfd pfd[1];
  4100. int pollres;
  4101. pfd[0].fd = conn->client.sock;
  4102. pfd[0].events = POLLIN;
  4103. pollres =
  4104. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4105. if (conn->ctx->stop_flag) {
  4106. return -1;
  4107. }
  4108. if (pollres > 0) {
  4109. nread = SSL_read(conn->ssl, buf, len);
  4110. if (nread <= 0) {
  4111. err = SSL_get_error(conn->ssl, nread);
  4112. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4113. err = ERRNO;
  4114. } else if ((err == SSL_ERROR_WANT_READ)
  4115. || (err == SSL_ERROR_WANT_WRITE)) {
  4116. nread = 0;
  4117. } else {
  4118. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4119. return -1;
  4120. }
  4121. } else {
  4122. err = 0;
  4123. }
  4124. } else if (pollres < 0) {
  4125. /* Error */
  4126. return -1;
  4127. } else {
  4128. /* pollres = 0 means timeout */
  4129. nread = 0;
  4130. }
  4131. #endif
  4132. } else {
  4133. struct pollfd pfd[1];
  4134. int pollres;
  4135. pfd[0].fd = conn->client.sock;
  4136. pfd[0].events = POLLIN;
  4137. pollres =
  4138. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4139. if (conn->ctx->stop_flag) {
  4140. return -1;
  4141. }
  4142. if (pollres > 0) {
  4143. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4144. err = (nread < 0) ? ERRNO : 0;
  4145. if (nread <= 0) {
  4146. /* shutdown of the socket at client side */
  4147. return -1;
  4148. }
  4149. } else if (pollres < 0) {
  4150. /* error callint poll */
  4151. return -1;
  4152. } else {
  4153. /* pollres = 0 means timeout */
  4154. nread = 0;
  4155. }
  4156. }
  4157. if (conn->ctx->stop_flag) {
  4158. return -1;
  4159. }
  4160. if ((nread > 0) || (nread == 0 && len == 0)) {
  4161. /* some data has been read, or no data was requested */
  4162. return nread;
  4163. }
  4164. if (nread < 0) {
  4165. /* socket error - check errno */
  4166. #ifdef _WIN32
  4167. if (err == WSAEWOULDBLOCK) {
  4168. /* TODO (low): check if this is still required */
  4169. /* standard case if called from close_socket_gracefully */
  4170. return -1;
  4171. } else if (err == WSAETIMEDOUT) {
  4172. /* TODO (low): check if this is still required */
  4173. /* timeout is handled by the while loop */
  4174. return 0;
  4175. } else if (err == WSAECONNABORTED) {
  4176. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4177. return -1;
  4178. } else {
  4179. DEBUG_TRACE("recv() failed, error %d", err);
  4180. return -1;
  4181. }
  4182. #else
  4183. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4184. * if the timeout is reached and if the socket was set to non-
  4185. * blocking in close_socket_gracefully, so we can not distinguish
  4186. * here. We have to wait for the timeout in both cases for now.
  4187. */
  4188. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4189. /* TODO (low): check if this is still required */
  4190. /* EAGAIN/EWOULDBLOCK:
  4191. * standard case if called from close_socket_gracefully
  4192. * => should return -1 */
  4193. /* or timeout occured
  4194. * => the code must stay in the while loop */
  4195. /* EINTR can be generated on a socket with a timeout set even
  4196. * when SA_RESTART is effective for all relevant signals
  4197. * (see signal(7)).
  4198. * => stay in the while loop */
  4199. } else {
  4200. DEBUG_TRACE("recv() failed, error %d", err);
  4201. return -1;
  4202. }
  4203. #endif
  4204. }
  4205. /* Timeout occured, but no data available. */
  4206. return -1;
  4207. }
  4208. static int
  4209. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4210. {
  4211. int n, nread = 0;
  4212. double timeout = -1.0;
  4213. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4214. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4215. }
  4216. while (len > 0 && conn->ctx->stop_flag == 0) {
  4217. n = pull(fp, conn, buf + nread, len, timeout);
  4218. if (n < 0) {
  4219. if (nread == 0) {
  4220. nread = n; /* Propagate the error */
  4221. }
  4222. break;
  4223. } else if (n == 0) {
  4224. break; /* No more data to read */
  4225. } else {
  4226. conn->consumed_content += n;
  4227. nread += n;
  4228. len -= n;
  4229. }
  4230. }
  4231. return nread;
  4232. }
  4233. static void
  4234. discard_unread_request_data(struct mg_connection *conn)
  4235. {
  4236. char buf[MG_BUF_LEN];
  4237. size_t to_read;
  4238. int nread;
  4239. if (conn == NULL) {
  4240. return;
  4241. }
  4242. to_read = sizeof(buf);
  4243. if (conn->is_chunked) {
  4244. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4245. * completely */
  4246. while (conn->is_chunked == 1) {
  4247. nread = mg_read(conn, buf, to_read);
  4248. if (nread <= 0) {
  4249. break;
  4250. }
  4251. }
  4252. } else {
  4253. /* Not chunked: content length is known */
  4254. while (conn->consumed_content < conn->content_len) {
  4255. if (to_read
  4256. > (size_t)(conn->content_len - conn->consumed_content)) {
  4257. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4258. }
  4259. nread = mg_read(conn, buf, to_read);
  4260. if (nread <= 0) {
  4261. break;
  4262. }
  4263. }
  4264. }
  4265. }
  4266. static int
  4267. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4268. {
  4269. int64_t n, buffered_len, nread;
  4270. int64_t len64 =
  4271. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4272. * int, we may not read more
  4273. * bytes */
  4274. const char *body;
  4275. if (conn == NULL) {
  4276. return 0;
  4277. }
  4278. /* If Content-Length is not set for a PUT or POST request, read until
  4279. * socket is closed */
  4280. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4281. conn->content_len = INT64_MAX;
  4282. conn->must_close = 1;
  4283. }
  4284. nread = 0;
  4285. if (conn->consumed_content < conn->content_len) {
  4286. /* Adjust number of bytes to read. */
  4287. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4288. if (left_to_read < len64) {
  4289. /* Do not read more than the total content length of the request.
  4290. */
  4291. len64 = left_to_read;
  4292. }
  4293. /* Return buffered data */
  4294. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4295. - conn->consumed_content;
  4296. if (buffered_len > 0) {
  4297. if (len64 < buffered_len) {
  4298. buffered_len = len64;
  4299. }
  4300. body = conn->buf + conn->request_len + conn->consumed_content;
  4301. memcpy(buf, body, (size_t)buffered_len);
  4302. len64 -= buffered_len;
  4303. conn->consumed_content += buffered_len;
  4304. nread += buffered_len;
  4305. buf = (char *)buf + buffered_len;
  4306. }
  4307. /* We have returned all buffered data. Read new data from the remote
  4308. * socket.
  4309. */
  4310. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4311. nread += n;
  4312. } else {
  4313. nread = ((nread > 0) ? nread : n);
  4314. }
  4315. }
  4316. return (int)nread;
  4317. }
  4318. static char
  4319. mg_getc(struct mg_connection *conn)
  4320. {
  4321. char c;
  4322. if (conn == NULL) {
  4323. return 0;
  4324. }
  4325. conn->content_len++;
  4326. if (mg_read_inner(conn, &c, 1) <= 0) {
  4327. return (char)0;
  4328. }
  4329. return c;
  4330. }
  4331. int
  4332. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4333. {
  4334. if (len > INT_MAX) {
  4335. len = INT_MAX;
  4336. }
  4337. if (conn == NULL) {
  4338. return 0;
  4339. }
  4340. if (conn->is_chunked) {
  4341. size_t all_read = 0;
  4342. while (len > 0) {
  4343. if (conn->is_chunked == 2) {
  4344. /* No more data left to read */
  4345. return 0;
  4346. }
  4347. if (conn->chunk_remainder) {
  4348. /* copy from the remainder of the last received chunk */
  4349. long read_ret;
  4350. size_t read_now =
  4351. ((conn->chunk_remainder > len) ? (len)
  4352. : (conn->chunk_remainder));
  4353. conn->content_len += (int)read_now;
  4354. read_ret =
  4355. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4356. if (read_ret < 1) {
  4357. /* read error */
  4358. return -1;
  4359. }
  4360. all_read += (size_t)read_ret;
  4361. conn->chunk_remainder -= (size_t)read_ret;
  4362. len -= (size_t)read_ret;
  4363. if (conn->chunk_remainder == 0) {
  4364. /* Add data bytes in the current chunk have been read,
  4365. * so we are expecting \r\n now. */
  4366. char x1 = mg_getc(conn);
  4367. char x2 = mg_getc(conn);
  4368. if ((x1 != '\r') || (x2 != '\n')) {
  4369. /* Protocol violation */
  4370. return -1;
  4371. }
  4372. }
  4373. } else {
  4374. /* fetch a new chunk */
  4375. int i = 0;
  4376. char lenbuf[64];
  4377. char *end = 0;
  4378. unsigned long chunkSize = 0;
  4379. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4380. lenbuf[i] = mg_getc(conn);
  4381. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4382. continue;
  4383. }
  4384. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4385. lenbuf[i + 1] = 0;
  4386. chunkSize = strtoul(lenbuf, &end, 16);
  4387. if (chunkSize == 0) {
  4388. /* regular end of content */
  4389. conn->is_chunked = 2;
  4390. }
  4391. break;
  4392. }
  4393. if (!isxdigit(lenbuf[i])) {
  4394. /* illegal character for chunk length */
  4395. return -1;
  4396. }
  4397. }
  4398. if ((end == NULL) || (*end != '\r')) {
  4399. /* chunksize not set correctly */
  4400. return -1;
  4401. }
  4402. if (chunkSize == 0) {
  4403. break;
  4404. }
  4405. conn->chunk_remainder = chunkSize;
  4406. }
  4407. }
  4408. return (int)all_read;
  4409. }
  4410. return mg_read_inner(conn, buf, len);
  4411. }
  4412. int
  4413. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4414. {
  4415. time_t now;
  4416. int64_t n, total, allowed;
  4417. if (conn == NULL) {
  4418. return 0;
  4419. }
  4420. if (conn->throttle > 0) {
  4421. if ((now = time(NULL)) != conn->last_throttle_time) {
  4422. conn->last_throttle_time = now;
  4423. conn->last_throttle_bytes = 0;
  4424. }
  4425. allowed = conn->throttle - conn->last_throttle_bytes;
  4426. if (allowed > (int64_t)len) {
  4427. allowed = (int64_t)len;
  4428. }
  4429. if ((total = push_all(conn->ctx,
  4430. NULL,
  4431. conn->client.sock,
  4432. conn->ssl,
  4433. (const char *)buf,
  4434. (int64_t)allowed)) == allowed) {
  4435. buf = (const char *)buf + total;
  4436. conn->last_throttle_bytes += total;
  4437. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4438. allowed = (conn->throttle > ((int64_t)len - total))
  4439. ? (int64_t)len - total
  4440. : conn->throttle;
  4441. if ((n = push_all(conn->ctx,
  4442. NULL,
  4443. conn->client.sock,
  4444. conn->ssl,
  4445. (const char *)buf,
  4446. (int64_t)allowed)) != allowed) {
  4447. break;
  4448. }
  4449. sleep(1);
  4450. conn->last_throttle_bytes = allowed;
  4451. conn->last_throttle_time = time(NULL);
  4452. buf = (const char *)buf + n;
  4453. total += n;
  4454. }
  4455. }
  4456. } else {
  4457. total = push_all(conn->ctx,
  4458. NULL,
  4459. conn->client.sock,
  4460. conn->ssl,
  4461. (const char *)buf,
  4462. (int64_t)len);
  4463. }
  4464. return (int)total;
  4465. }
  4466. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4467. static int
  4468. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4469. {
  4470. va_list ap_copy;
  4471. size_t size = MG_BUF_LEN / 4;
  4472. int len = -1;
  4473. *buf = NULL;
  4474. while (len < 0) {
  4475. if (*buf) {
  4476. mg_free(*buf);
  4477. }
  4478. size *= 4;
  4479. *buf = (char *)mg_malloc(size);
  4480. if (!*buf) {
  4481. break;
  4482. }
  4483. va_copy(ap_copy, ap);
  4484. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4485. va_end(ap_copy);
  4486. (*buf)[size - 1] = 0;
  4487. }
  4488. return len;
  4489. }
  4490. /* Print message to buffer. If buffer is large enough to hold the message,
  4491. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4492. * and return allocated buffer. */
  4493. static int
  4494. alloc_vprintf(char **out_buf,
  4495. char *prealloc_buf,
  4496. size_t prealloc_size,
  4497. const char *fmt,
  4498. va_list ap)
  4499. {
  4500. va_list ap_copy;
  4501. int len;
  4502. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4503. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4504. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4505. * Therefore, we make two passes: on first pass, get required message
  4506. * length.
  4507. * On second pass, actually print the message. */
  4508. va_copy(ap_copy, ap);
  4509. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4510. va_end(ap_copy);
  4511. if (len < 0) {
  4512. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4513. * Switch to alternative code path that uses incremental allocations.
  4514. */
  4515. va_copy(ap_copy, ap);
  4516. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4517. va_end(ap_copy);
  4518. } else if ((size_t)(len) >= prealloc_size) {
  4519. /* The pre-allocated buffer not large enough. */
  4520. /* Allocate a new buffer. */
  4521. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4522. if (!*out_buf) {
  4523. /* Allocation failed. Return -1 as "out of memory" error. */
  4524. return -1;
  4525. }
  4526. /* Buffer allocation successful. Store the string there. */
  4527. va_copy(ap_copy, ap);
  4528. IGNORE_UNUSED_RESULT(
  4529. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4530. va_end(ap_copy);
  4531. } else {
  4532. /* The pre-allocated buffer is large enough.
  4533. * Use it to store the string and return the address. */
  4534. va_copy(ap_copy, ap);
  4535. IGNORE_UNUSED_RESULT(
  4536. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4537. va_end(ap_copy);
  4538. *out_buf = prealloc_buf;
  4539. }
  4540. return len;
  4541. }
  4542. static int
  4543. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4544. {
  4545. char mem[MG_BUF_LEN];
  4546. char *buf = NULL;
  4547. int len;
  4548. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4549. len = mg_write(conn, buf, (size_t)len);
  4550. }
  4551. if (buf != mem && buf != NULL) {
  4552. mg_free(buf);
  4553. }
  4554. return len;
  4555. }
  4556. int
  4557. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4558. {
  4559. va_list ap;
  4560. int result;
  4561. va_start(ap, fmt);
  4562. result = mg_vprintf(conn, fmt, ap);
  4563. va_end(ap);
  4564. return result;
  4565. }
  4566. int
  4567. mg_url_decode(const char *src,
  4568. int src_len,
  4569. char *dst,
  4570. int dst_len,
  4571. int is_form_url_encoded)
  4572. {
  4573. int i, j, a, b;
  4574. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4575. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4576. if (i < src_len - 2 && src[i] == '%'
  4577. && isxdigit(*(const unsigned char *)(src + i + 1))
  4578. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4579. a = tolower(*(const unsigned char *)(src + i + 1));
  4580. b = tolower(*(const unsigned char *)(src + i + 2));
  4581. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4582. i += 2;
  4583. } else if (is_form_url_encoded && src[i] == '+') {
  4584. dst[j] = ' ';
  4585. } else {
  4586. dst[j] = src[i];
  4587. }
  4588. }
  4589. dst[j] = '\0'; /* Null-terminate the destination */
  4590. return (i >= src_len) ? j : -1;
  4591. }
  4592. int
  4593. mg_get_var(const char *data,
  4594. size_t data_len,
  4595. const char *name,
  4596. char *dst,
  4597. size_t dst_len)
  4598. {
  4599. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4600. }
  4601. int
  4602. mg_get_var2(const char *data,
  4603. size_t data_len,
  4604. const char *name,
  4605. char *dst,
  4606. size_t dst_len,
  4607. size_t occurrence)
  4608. {
  4609. const char *p, *e, *s;
  4610. size_t name_len;
  4611. int len;
  4612. if (dst == NULL || dst_len == 0) {
  4613. len = -2;
  4614. } else if (data == NULL || name == NULL || data_len == 0) {
  4615. len = -1;
  4616. dst[0] = '\0';
  4617. } else {
  4618. name_len = strlen(name);
  4619. e = data + data_len;
  4620. len = -1;
  4621. dst[0] = '\0';
  4622. /* data is "var1=val1&var2=val2...". Find variable first */
  4623. for (p = data; p + name_len < e; p++) {
  4624. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4625. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4626. /* Point p to variable value */
  4627. p += name_len + 1;
  4628. /* Point s to the end of the value */
  4629. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4630. if (s == NULL) {
  4631. s = e;
  4632. }
  4633. /* assert(s >= p); */
  4634. if (s < p) {
  4635. return -3;
  4636. }
  4637. /* Decode variable into destination buffer */
  4638. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4639. /* Redirect error code from -1 to -2 (destination buffer too
  4640. * small). */
  4641. if (len == -1) {
  4642. len = -2;
  4643. }
  4644. break;
  4645. }
  4646. }
  4647. }
  4648. return len;
  4649. }
  4650. /* HCP24: some changes to compare hole var_name */
  4651. int
  4652. mg_get_cookie(const char *cookie_header,
  4653. const char *var_name,
  4654. char *dst,
  4655. size_t dst_size)
  4656. {
  4657. const char *s, *p, *end;
  4658. int name_len, len = -1;
  4659. if (dst == NULL || dst_size == 0) {
  4660. return -2;
  4661. }
  4662. dst[0] = '\0';
  4663. if (var_name == NULL || (s = cookie_header) == NULL) {
  4664. return -1;
  4665. }
  4666. name_len = (int)strlen(var_name);
  4667. end = s + strlen(s);
  4668. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4669. if (s[name_len] == '=') {
  4670. /* HCP24: now check is it a substring or a full cookie name */
  4671. if ((s == cookie_header) || (s[-1] == ' ')) {
  4672. s += name_len + 1;
  4673. if ((p = strchr(s, ' ')) == NULL) {
  4674. p = end;
  4675. }
  4676. if (p[-1] == ';') {
  4677. p--;
  4678. }
  4679. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4680. s++;
  4681. p--;
  4682. }
  4683. if ((size_t)(p - s) < dst_size) {
  4684. len = (int)(p - s);
  4685. mg_strlcpy(dst, s, (size_t)len + 1);
  4686. } else {
  4687. len = -3;
  4688. }
  4689. break;
  4690. }
  4691. }
  4692. }
  4693. return len;
  4694. }
  4695. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4696. static void
  4697. base64_encode(const unsigned char *src, int src_len, char *dst)
  4698. {
  4699. static const char *b64 =
  4700. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4701. int i, j, a, b, c;
  4702. for (i = j = 0; i < src_len; i += 3) {
  4703. a = src[i];
  4704. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4705. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4706. dst[j++] = b64[a >> 2];
  4707. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4708. if (i + 1 < src_len) {
  4709. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4710. }
  4711. if (i + 2 < src_len) {
  4712. dst[j++] = b64[c & 63];
  4713. }
  4714. }
  4715. while (j % 4 != 0) {
  4716. dst[j++] = '=';
  4717. }
  4718. dst[j++] = '\0';
  4719. }
  4720. #endif
  4721. #if defined(USE_LUA)
  4722. static unsigned char
  4723. b64reverse(char letter)
  4724. {
  4725. if (letter >= 'A' && letter <= 'Z') {
  4726. return letter - 'A';
  4727. }
  4728. if (letter >= 'a' && letter <= 'z') {
  4729. return letter - 'a' + 26;
  4730. }
  4731. if (letter >= '0' && letter <= '9') {
  4732. return letter - '0' + 52;
  4733. }
  4734. if (letter == '+') {
  4735. return 62;
  4736. }
  4737. if (letter == '/') {
  4738. return 63;
  4739. }
  4740. if (letter == '=') {
  4741. return 255; /* normal end */
  4742. }
  4743. return 254; /* error */
  4744. }
  4745. static int
  4746. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4747. {
  4748. int i;
  4749. unsigned char a, b, c, d;
  4750. *dst_len = 0;
  4751. for (i = 0; i < src_len; i += 4) {
  4752. a = b64reverse(src[i]);
  4753. if (a >= 254) {
  4754. return i;
  4755. }
  4756. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4757. if (b >= 254) {
  4758. return i + 1;
  4759. }
  4760. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4761. if (c == 254) {
  4762. return i + 2;
  4763. }
  4764. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4765. if (d == 254) {
  4766. return i + 3;
  4767. }
  4768. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4769. if (c != 255) {
  4770. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4771. if (d != 255) {
  4772. dst[(*dst_len)++] = (c << 6) + d;
  4773. }
  4774. }
  4775. }
  4776. return -1;
  4777. }
  4778. #endif
  4779. static int
  4780. is_put_or_delete_method(const struct mg_connection *conn)
  4781. {
  4782. if (conn) {
  4783. const char *s = conn->request_info.request_method;
  4784. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4785. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4786. }
  4787. return 0;
  4788. }
  4789. static void
  4790. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4791. char *filename, /* out: filename */
  4792. size_t filename_buf_len, /* in: size of filename buffer */
  4793. struct mg_file_stat *filestat, /* out: file structure */
  4794. int *is_found, /* out: file found (directly) */
  4795. int *is_script_resource, /* out: handled by a script? */
  4796. int *is_websocket_request, /* out: websocket connetion? */
  4797. int *is_put_or_delete_request /* out: put/delete a file? */
  4798. )
  4799. {
  4800. /* TODO (high / maintainability issue): Restructure this function */
  4801. #if !defined(NO_FILES)
  4802. const char *uri = conn->request_info.local_uri;
  4803. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4804. const char *rewrite;
  4805. struct vec a, b;
  4806. int match_len;
  4807. char gz_path[PATH_MAX];
  4808. char const *accept_encoding;
  4809. int truncated;
  4810. #if !defined(NO_CGI) || defined(USE_LUA)
  4811. char *p;
  4812. #endif
  4813. #else
  4814. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4815. #endif
  4816. memset(filestat, 0, sizeof(*filestat));
  4817. *filename = 0;
  4818. *is_found = 0;
  4819. *is_script_resource = 0;
  4820. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4821. #if defined(USE_WEBSOCKET)
  4822. *is_websocket_request = is_websocket_protocol(conn);
  4823. #if !defined(NO_FILES)
  4824. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4825. root = conn->ctx->config[WEBSOCKET_ROOT];
  4826. }
  4827. #endif /* !NO_FILES */
  4828. #else /* USE_WEBSOCKET */
  4829. *is_websocket_request = 0;
  4830. #endif /* USE_WEBSOCKET */
  4831. #if !defined(NO_FILES)
  4832. /* Note that root == NULL is a regular use case here. This occurs,
  4833. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4834. * config is not required. */
  4835. if (root == NULL) {
  4836. /* all file related outputs have already been set to 0, just return
  4837. */
  4838. return;
  4839. }
  4840. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4841. * of the path one byte on the right.
  4842. * If document_root is NULL, leave the file empty. */
  4843. mg_snprintf(
  4844. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4845. if (truncated) {
  4846. goto interpret_cleanup;
  4847. }
  4848. rewrite = conn->ctx->config[REWRITE];
  4849. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4850. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4851. mg_snprintf(conn,
  4852. &truncated,
  4853. filename,
  4854. filename_buf_len - 1,
  4855. "%.*s%s",
  4856. (int)b.len,
  4857. b.ptr,
  4858. uri + match_len);
  4859. break;
  4860. }
  4861. }
  4862. if (truncated) {
  4863. goto interpret_cleanup;
  4864. }
  4865. /* Local file path and name, corresponding to requested URI
  4866. * is now stored in "filename" variable. */
  4867. if (mg_stat(conn, filename, filestat)) {
  4868. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4869. /* File exists. Check if it is a script type. */
  4870. if (0
  4871. #if !defined(NO_CGI)
  4872. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4873. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4874. filename) > 0
  4875. #endif
  4876. #if defined(USE_LUA)
  4877. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4878. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4879. filename) > 0
  4880. #endif
  4881. #if defined(USE_DUKTAPE)
  4882. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4883. strlen(
  4884. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4885. filename) > 0
  4886. #endif
  4887. ) {
  4888. /* The request addresses a CGI script or a Lua script. The URI
  4889. * corresponds to the script itself (like /path/script.cgi),
  4890. * and there is no additional resource path
  4891. * (like /path/script.cgi/something).
  4892. * Requests that modify (replace or delete) a resource, like
  4893. * PUT and DELETE requests, should replace/delete the script
  4894. * file.
  4895. * Requests that read or write from/to a resource, like GET and
  4896. * POST requests, should call the script and return the
  4897. * generated response. */
  4898. *is_script_resource = !*is_put_or_delete_request;
  4899. }
  4900. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4901. *is_found = 1;
  4902. return;
  4903. }
  4904. /* If we can't find the actual file, look for the file
  4905. * with the same name but a .gz extension. If we find it,
  4906. * use that and set the gzipped flag in the file struct
  4907. * to indicate that the response need to have the content-
  4908. * encoding: gzip header.
  4909. * We can only do this if the browser declares support. */
  4910. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4911. if (strstr(accept_encoding, "gzip") != NULL) {
  4912. mg_snprintf(
  4913. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4914. if (truncated) {
  4915. goto interpret_cleanup;
  4916. }
  4917. if (mg_stat(conn, gz_path, filestat)) {
  4918. if (filestat) {
  4919. filestat->is_gzipped = 1;
  4920. *is_found = 1;
  4921. }
  4922. /* Currently gz files can not be scripts. */
  4923. return;
  4924. }
  4925. }
  4926. }
  4927. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4928. /* Support PATH_INFO for CGI scripts. */
  4929. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4930. if (*p == '/') {
  4931. *p = '\0';
  4932. if ((0
  4933. #if !defined(NO_CGI)
  4934. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4935. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4936. filename) > 0
  4937. #endif
  4938. #if defined(USE_LUA)
  4939. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4940. strlen(
  4941. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4942. filename) > 0
  4943. #endif
  4944. #if defined(USE_DUKTAPE)
  4945. || match_prefix(
  4946. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4947. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4948. filename) > 0
  4949. #endif
  4950. ) && mg_stat(conn, filename, filestat)) {
  4951. /* Shift PATH_INFO block one character right, e.g.
  4952. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4953. * conn->path_info is pointing to the local variable "path"
  4954. * declared in handle_request(), so PATH_INFO is not valid
  4955. * after handle_request returns. */
  4956. conn->path_info = p + 1;
  4957. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4958. * trailing \0 */
  4959. p[1] = '/';
  4960. *is_script_resource = 1;
  4961. break;
  4962. } else {
  4963. *p = '/';
  4964. }
  4965. }
  4966. }
  4967. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4968. #endif /* !defined(NO_FILES) */
  4969. return;
  4970. #if !defined(NO_FILES)
  4971. /* Reset all outputs */
  4972. interpret_cleanup:
  4973. memset(filestat, 0, sizeof(*filestat));
  4974. *filename = 0;
  4975. *is_found = 0;
  4976. *is_script_resource = 0;
  4977. *is_websocket_request = 0;
  4978. *is_put_or_delete_request = 0;
  4979. #endif /* !defined(NO_FILES) */
  4980. }
  4981. /* Check whether full request is buffered. Return:
  4982. * -1 if request is malformed
  4983. * 0 if request is not yet fully buffered
  4984. * >0 actual request length, including last \r\n\r\n */
  4985. static int
  4986. get_request_len(const char *buf, int buflen)
  4987. {
  4988. const char *s, *e;
  4989. int len = 0;
  4990. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4991. /* Control characters are not allowed but >=128 is. */
  4992. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4993. && *(const unsigned char *)s < 128) {
  4994. len = -1;
  4995. break; /* [i_a] abort scan as soon as one malformed character is
  4996. * found; */
  4997. /* don't let subsequent \r\n\r\n win us over anyhow */
  4998. } else if (s[0] == '\n' && s[1] == '\n') {
  4999. len = (int)(s - buf) + 2;
  5000. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  5001. len = (int)(s - buf) + 3;
  5002. }
  5003. return len;
  5004. }
  5005. #if !defined(NO_CACHING)
  5006. /* Convert month to the month number. Return -1 on error, or month number */
  5007. static int
  5008. get_month_index(const char *s)
  5009. {
  5010. size_t i;
  5011. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5012. if (!strcmp(s, month_names[i])) {
  5013. return (int)i;
  5014. }
  5015. }
  5016. return -1;
  5017. }
  5018. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5019. static time_t
  5020. parse_date_string(const char *datetime)
  5021. {
  5022. char month_str[32] = {0};
  5023. int second, minute, hour, day, month, year;
  5024. time_t result = (time_t)0;
  5025. struct tm tm;
  5026. if ((sscanf(datetime,
  5027. "%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. || (sscanf(datetime,
  5042. "%*3s, %d %3s %d %d:%d:%d",
  5043. &day,
  5044. month_str,
  5045. &year,
  5046. &hour,
  5047. &minute,
  5048. &second) == 6) || (sscanf(datetime,
  5049. "%d-%3s-%d %d:%d:%d",
  5050. &day,
  5051. month_str,
  5052. &year,
  5053. &hour,
  5054. &minute,
  5055. &second) == 6)) {
  5056. month = get_month_index(month_str);
  5057. if ((month >= 0) && (year >= 1970)) {
  5058. memset(&tm, 0, sizeof(tm));
  5059. tm.tm_year = year - 1900;
  5060. tm.tm_mon = month;
  5061. tm.tm_mday = day;
  5062. tm.tm_hour = hour;
  5063. tm.tm_min = minute;
  5064. tm.tm_sec = second;
  5065. result = timegm(&tm);
  5066. }
  5067. }
  5068. return result;
  5069. }
  5070. #endif /* !NO_CACHING */
  5071. /* Protect against directory disclosure attack by removing '..',
  5072. * excessive '/' and '\' characters */
  5073. static void
  5074. remove_double_dots_and_double_slashes(char *s)
  5075. {
  5076. char *p = s;
  5077. while ((s[0] == '.') && (s[1] == '.')) {
  5078. s++;
  5079. }
  5080. while (*s != '\0') {
  5081. *p++ = *s++;
  5082. if (s[-1] == '/' || s[-1] == '\\') {
  5083. /* Skip all following slashes, backslashes and double-dots */
  5084. while (s[0] != '\0') {
  5085. if (s[0] == '/' || s[0] == '\\') {
  5086. s++;
  5087. } else if (s[0] == '.' && s[1] == '.') {
  5088. s += 2;
  5089. } else {
  5090. break;
  5091. }
  5092. }
  5093. }
  5094. }
  5095. *p = '\0';
  5096. }
  5097. static const struct {
  5098. const char *extension;
  5099. size_t ext_len;
  5100. const char *mime_type;
  5101. } builtin_mime_types[] = {
  5102. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5103. * application types */
  5104. {".doc", 4, "application/msword"},
  5105. {".eps", 4, "application/postscript"},
  5106. {".exe", 4, "application/octet-stream"},
  5107. {".js", 3, "application/javascript"},
  5108. {".json", 5, "application/json"},
  5109. {".pdf", 4, "application/pdf"},
  5110. {".ps", 3, "application/postscript"},
  5111. {".rtf", 4, "application/rtf"},
  5112. {".xhtml", 6, "application/xhtml+xml"},
  5113. {".xsl", 4, "application/xml"},
  5114. {".xslt", 5, "application/xml"},
  5115. /* fonts */
  5116. {".ttf", 4, "application/font-sfnt"},
  5117. {".cff", 4, "application/font-sfnt"},
  5118. {".otf", 4, "application/font-sfnt"},
  5119. {".aat", 4, "application/font-sfnt"},
  5120. {".sil", 4, "application/font-sfnt"},
  5121. {".pfr", 4, "application/font-tdpfr"},
  5122. {".woff", 5, "application/font-woff"},
  5123. /* audio */
  5124. {".mp3", 4, "audio/mpeg"},
  5125. {".oga", 4, "audio/ogg"},
  5126. {".ogg", 4, "audio/ogg"},
  5127. /* image */
  5128. {".gif", 4, "image/gif"},
  5129. {".ief", 4, "image/ief"},
  5130. {".jpeg", 5, "image/jpeg"},
  5131. {".jpg", 4, "image/jpeg"},
  5132. {".jpm", 4, "image/jpm"},
  5133. {".jpx", 4, "image/jpx"},
  5134. {".png", 4, "image/png"},
  5135. {".svg", 4, "image/svg+xml"},
  5136. {".tif", 4, "image/tiff"},
  5137. {".tiff", 5, "image/tiff"},
  5138. /* model */
  5139. {".wrl", 4, "model/vrml"},
  5140. /* text */
  5141. {".css", 4, "text/css"},
  5142. {".csv", 4, "text/csv"},
  5143. {".htm", 4, "text/html"},
  5144. {".html", 5, "text/html"},
  5145. {".sgm", 4, "text/sgml"},
  5146. {".shtm", 5, "text/html"},
  5147. {".shtml", 6, "text/html"},
  5148. {".txt", 4, "text/plain"},
  5149. {".xml", 4, "text/xml"},
  5150. /* video */
  5151. {".mov", 4, "video/quicktime"},
  5152. {".mp4", 4, "video/mp4"},
  5153. {".mpeg", 5, "video/mpeg"},
  5154. {".mpg", 4, "video/mpeg"},
  5155. {".ogv", 4, "video/ogg"},
  5156. {".qt", 3, "video/quicktime"},
  5157. /* not registered types
  5158. * (http://reference.sitepoint.com/html/mime-types-full,
  5159. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5160. {".arj", 4, "application/x-arj-compressed"},
  5161. {".gz", 3, "application/x-gunzip"},
  5162. {".rar", 4, "application/x-arj-compressed"},
  5163. {".swf", 4, "application/x-shockwave-flash"},
  5164. {".tar", 4, "application/x-tar"},
  5165. {".tgz", 4, "application/x-tar-gz"},
  5166. {".torrent", 8, "application/x-bittorrent"},
  5167. {".ppt", 4, "application/x-mspowerpoint"},
  5168. {".xls", 4, "application/x-msexcel"},
  5169. {".zip", 4, "application/x-zip-compressed"},
  5170. {".aac",
  5171. 4,
  5172. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5173. {".aif", 4, "audio/x-aif"},
  5174. {".m3u", 4, "audio/x-mpegurl"},
  5175. {".mid", 4, "audio/x-midi"},
  5176. {".ra", 3, "audio/x-pn-realaudio"},
  5177. {".ram", 4, "audio/x-pn-realaudio"},
  5178. {".wav", 4, "audio/x-wav"},
  5179. {".bmp", 4, "image/bmp"},
  5180. {".ico", 4, "image/x-icon"},
  5181. {".pct", 4, "image/x-pct"},
  5182. {".pict", 5, "image/pict"},
  5183. {".rgb", 4, "image/x-rgb"},
  5184. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5185. {".asf", 4, "video/x-ms-asf"},
  5186. {".avi", 4, "video/x-msvideo"},
  5187. {".m4v", 4, "video/x-m4v"},
  5188. {NULL, 0, NULL}};
  5189. const char *
  5190. mg_get_builtin_mime_type(const char *path)
  5191. {
  5192. const char *ext;
  5193. size_t i, path_len;
  5194. path_len = strlen(path);
  5195. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5196. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5197. if (path_len > builtin_mime_types[i].ext_len
  5198. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5199. return builtin_mime_types[i].mime_type;
  5200. }
  5201. }
  5202. return "text/plain";
  5203. }
  5204. /* Look at the "path" extension and figure what mime type it has.
  5205. * Store mime type in the vector. */
  5206. static void
  5207. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5208. {
  5209. struct vec ext_vec, mime_vec;
  5210. const char *list, *ext;
  5211. size_t path_len;
  5212. path_len = strlen(path);
  5213. if (ctx == NULL || vec == NULL) {
  5214. return;
  5215. }
  5216. /* Scan user-defined mime types first, in case user wants to
  5217. * override default mime types. */
  5218. list = ctx->config[EXTRA_MIME_TYPES];
  5219. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5220. /* ext now points to the path suffix */
  5221. ext = path + path_len - ext_vec.len;
  5222. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5223. *vec = mime_vec;
  5224. return;
  5225. }
  5226. }
  5227. vec->ptr = mg_get_builtin_mime_type(path);
  5228. vec->len = strlen(vec->ptr);
  5229. }
  5230. /* Stringify binary data. Output buffer must be twice as big as input,
  5231. * because each byte takes 2 bytes in string representation */
  5232. static void
  5233. bin2str(char *to, const unsigned char *p, size_t len)
  5234. {
  5235. static const char *hex = "0123456789abcdef";
  5236. for (; len--; p++) {
  5237. *to++ = hex[p[0] >> 4];
  5238. *to++ = hex[p[0] & 0x0f];
  5239. }
  5240. *to = '\0';
  5241. }
  5242. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5243. char *
  5244. mg_md5(char buf[33], ...)
  5245. {
  5246. md5_byte_t hash[16];
  5247. const char *p;
  5248. va_list ap;
  5249. md5_state_t ctx;
  5250. md5_init(&ctx);
  5251. va_start(ap, buf);
  5252. while ((p = va_arg(ap, const char *)) != NULL) {
  5253. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5254. }
  5255. va_end(ap);
  5256. md5_finish(&ctx, hash);
  5257. bin2str(buf, hash, sizeof(hash));
  5258. return buf;
  5259. }
  5260. /* Check the user's password, return 1 if OK */
  5261. static int
  5262. check_password(const char *method,
  5263. const char *ha1,
  5264. const char *uri,
  5265. const char *nonce,
  5266. const char *nc,
  5267. const char *cnonce,
  5268. const char *qop,
  5269. const char *response)
  5270. {
  5271. char ha2[32 + 1], expected_response[32 + 1];
  5272. /* Some of the parameters may be NULL */
  5273. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5274. || qop == NULL
  5275. || response == NULL) {
  5276. return 0;
  5277. }
  5278. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5279. if (strlen(response) != 32) {
  5280. return 0;
  5281. }
  5282. mg_md5(ha2, method, ":", uri, NULL);
  5283. mg_md5(expected_response,
  5284. ha1,
  5285. ":",
  5286. nonce,
  5287. ":",
  5288. nc,
  5289. ":",
  5290. cnonce,
  5291. ":",
  5292. qop,
  5293. ":",
  5294. ha2,
  5295. NULL);
  5296. return mg_strcasecmp(response, expected_response) == 0;
  5297. }
  5298. /* Use the global passwords file, if specified by auth_gpass option,
  5299. * or search for .htpasswd in the requested directory. */
  5300. static void
  5301. open_auth_file(struct mg_connection *conn,
  5302. const char *path,
  5303. struct mg_file *filep)
  5304. {
  5305. if (conn != NULL && conn->ctx != NULL) {
  5306. char name[PATH_MAX];
  5307. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5308. int truncated;
  5309. if (gpass != NULL) {
  5310. /* Use global passwords file */
  5311. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5312. #ifdef DEBUG
  5313. /* Use mg_cry here, since gpass has been configured. */
  5314. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5315. #endif
  5316. }
  5317. /* Important: using local struct mg_file to test path for
  5318. * is_directory flag. If filep is used, mg_stat() makes it
  5319. * appear as if auth file was opened.
  5320. * TODO(mid): Check if this is still required after rewriting
  5321. * mg_stat */
  5322. } else if (mg_stat(conn, path, &filep->stat)
  5323. && filep->stat.is_directory) {
  5324. mg_snprintf(conn,
  5325. &truncated,
  5326. name,
  5327. sizeof(name),
  5328. "%s/%s",
  5329. path,
  5330. PASSWORDS_FILE_NAME);
  5331. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5332. #ifdef DEBUG
  5333. /* Don't use mg_cry here, but only a trace, since this is
  5334. * a typical case. It will occur for every directory
  5335. * without a password file. */
  5336. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5337. #endif
  5338. }
  5339. } else {
  5340. /* Try to find .htpasswd in requested directory. */
  5341. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5342. if (e[0] == '/') {
  5343. break;
  5344. }
  5345. }
  5346. mg_snprintf(conn,
  5347. &truncated,
  5348. name,
  5349. sizeof(name),
  5350. "%.*s/%s",
  5351. (int)(e - p),
  5352. p,
  5353. PASSWORDS_FILE_NAME);
  5354. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5355. #ifdef DEBUG
  5356. /* Don't use mg_cry here, but only a trace, since this is
  5357. * a typical case. It will occur for every directory
  5358. * without a password file. */
  5359. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5360. #endif
  5361. }
  5362. }
  5363. }
  5364. }
  5365. /* Parsed Authorization header */
  5366. struct ah {
  5367. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5368. };
  5369. /* Return 1 on success. Always initializes the ah structure. */
  5370. static int
  5371. parse_auth_header(struct mg_connection *conn,
  5372. char *buf,
  5373. size_t buf_size,
  5374. struct ah *ah)
  5375. {
  5376. char *name, *value, *s;
  5377. const char *auth_header;
  5378. uint64_t nonce;
  5379. if (!ah || !conn) {
  5380. return 0;
  5381. }
  5382. (void)memset(ah, 0, sizeof(*ah));
  5383. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5384. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5385. return 0;
  5386. }
  5387. /* Make modifiable copy of the auth header */
  5388. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5389. s = buf;
  5390. /* Parse authorization header */
  5391. for (;;) {
  5392. /* Gobble initial spaces */
  5393. while (isspace(*(unsigned char *)s)) {
  5394. s++;
  5395. }
  5396. name = skip_quoted(&s, "=", " ", 0);
  5397. /* Value is either quote-delimited, or ends at first comma or space. */
  5398. if (s[0] == '\"') {
  5399. s++;
  5400. value = skip_quoted(&s, "\"", " ", '\\');
  5401. if (s[0] == ',') {
  5402. s++;
  5403. }
  5404. } else {
  5405. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5406. * spaces */
  5407. }
  5408. if (*name == '\0') {
  5409. break;
  5410. }
  5411. if (!strcmp(name, "username")) {
  5412. ah->user = value;
  5413. } else if (!strcmp(name, "cnonce")) {
  5414. ah->cnonce = value;
  5415. } else if (!strcmp(name, "response")) {
  5416. ah->response = value;
  5417. } else if (!strcmp(name, "uri")) {
  5418. ah->uri = value;
  5419. } else if (!strcmp(name, "qop")) {
  5420. ah->qop = value;
  5421. } else if (!strcmp(name, "nc")) {
  5422. ah->nc = value;
  5423. } else if (!strcmp(name, "nonce")) {
  5424. ah->nonce = value;
  5425. }
  5426. }
  5427. #ifndef NO_NONCE_CHECK
  5428. /* Read the nonce from the response. */
  5429. if (ah->nonce == NULL) {
  5430. return 0;
  5431. }
  5432. s = NULL;
  5433. nonce = strtoull(ah->nonce, &s, 10);
  5434. if ((s == NULL) || (*s != 0)) {
  5435. return 0;
  5436. }
  5437. /* Convert the nonce from the client to a number. */
  5438. nonce ^= conn->ctx->auth_nonce_mask;
  5439. /* The converted number corresponds to the time the nounce has been
  5440. * created. This should not be earlier than the server start. */
  5441. /* Server side nonce check is valuable in all situations but one:
  5442. * if the server restarts frequently, but the client should not see
  5443. * that, so the server should accept nonces from previous starts. */
  5444. /* However, the reasonable default is to not accept a nonce from a
  5445. * previous start, so if anyone changed the access rights between
  5446. * two restarts, a new login is required. */
  5447. if (nonce < (uint64_t)conn->ctx->start_time) {
  5448. /* nonce is from a previous start of the server and no longer valid
  5449. * (replay attack?) */
  5450. return 0;
  5451. }
  5452. /* Check if the nonce is too high, so it has not (yet) been used by the
  5453. * server. */
  5454. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5455. return 0;
  5456. }
  5457. #else
  5458. (void)nonce;
  5459. #endif
  5460. /* CGI needs it as REMOTE_USER */
  5461. if (ah->user != NULL) {
  5462. conn->request_info.remote_user = mg_strdup(ah->user);
  5463. } else {
  5464. return 0;
  5465. }
  5466. return 1;
  5467. }
  5468. static const char *
  5469. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5470. {
  5471. const char *eof;
  5472. size_t len;
  5473. const char *memend;
  5474. if (!filep) {
  5475. return NULL;
  5476. }
  5477. if (filep->access.membuf != NULL && *p != NULL) {
  5478. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5479. /* Search for \n from p till the end of stream */
  5480. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5481. if (eof != NULL) {
  5482. eof += 1; /* Include \n */
  5483. } else {
  5484. eof = memend; /* Copy remaining data */
  5485. }
  5486. len =
  5487. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5488. memcpy(buf, *p, len);
  5489. buf[len] = '\0';
  5490. *p += len;
  5491. return len ? eof : NULL;
  5492. } else if (filep->access.fp != NULL) {
  5493. return fgets(buf, (int)size, filep->access.fp);
  5494. } else {
  5495. return NULL;
  5496. }
  5497. }
  5498. /* Define the initial recursion depth for procesesing htpasswd files that
  5499. * include other htpasswd
  5500. * (or even the same) files. It is not difficult to provide a file or files
  5501. * s.t. they force civetweb
  5502. * to infinitely recurse and then crash.
  5503. */
  5504. #define INITIAL_DEPTH 9
  5505. #if INITIAL_DEPTH <= 0
  5506. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5507. #endif
  5508. struct read_auth_file_struct {
  5509. struct mg_connection *conn;
  5510. struct ah ah;
  5511. char *domain;
  5512. char buf[256 + 256 + 40];
  5513. char *f_user;
  5514. char *f_domain;
  5515. char *f_ha1;
  5516. };
  5517. static int
  5518. read_auth_file(struct mg_file *filep,
  5519. struct read_auth_file_struct *workdata,
  5520. int depth)
  5521. {
  5522. char *p;
  5523. int is_authorized = 0;
  5524. struct mg_file fp;
  5525. size_t l;
  5526. if (!filep || !workdata || 0 == depth) {
  5527. return 0;
  5528. }
  5529. /* Loop over passwords file */
  5530. p = (char *)filep->access.membuf;
  5531. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5532. l = strlen(workdata->buf);
  5533. while (l > 0) {
  5534. if (isspace(workdata->buf[l - 1])
  5535. || iscntrl(workdata->buf[l - 1])) {
  5536. l--;
  5537. workdata->buf[l] = 0;
  5538. } else
  5539. break;
  5540. }
  5541. if (l < 1) {
  5542. continue;
  5543. }
  5544. workdata->f_user = workdata->buf;
  5545. if (workdata->f_user[0] == ':') {
  5546. /* user names may not contain a ':' and may not be empty,
  5547. * so lines starting with ':' may be used for a special purpose */
  5548. if (workdata->f_user[1] == '#') {
  5549. /* :# is a comment */
  5550. continue;
  5551. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5552. if (mg_fopen(workdata->conn,
  5553. workdata->f_user + 9,
  5554. MG_FOPEN_MODE_READ,
  5555. &fp)) {
  5556. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5557. (void)mg_fclose(
  5558. &fp.access); /* ignore error on read only file */
  5559. /* No need to continue processing files once we have a
  5560. * match, since nothing will reset it back
  5561. * to 0.
  5562. */
  5563. if (is_authorized) {
  5564. return is_authorized;
  5565. }
  5566. } else {
  5567. mg_cry(workdata->conn,
  5568. "%s: cannot open authorization file: %s",
  5569. __func__,
  5570. workdata->buf);
  5571. }
  5572. continue;
  5573. }
  5574. /* everything is invalid for the moment (might change in the
  5575. * future) */
  5576. mg_cry(workdata->conn,
  5577. "%s: syntax error in authorization file: %s",
  5578. __func__,
  5579. workdata->buf);
  5580. continue;
  5581. }
  5582. workdata->f_domain = strchr(workdata->f_user, ':');
  5583. if (workdata->f_domain == NULL) {
  5584. mg_cry(workdata->conn,
  5585. "%s: syntax error in authorization file: %s",
  5586. __func__,
  5587. workdata->buf);
  5588. continue;
  5589. }
  5590. *(workdata->f_domain) = 0;
  5591. (workdata->f_domain)++;
  5592. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5593. if (workdata->f_ha1 == NULL) {
  5594. mg_cry(workdata->conn,
  5595. "%s: syntax error in authorization file: %s",
  5596. __func__,
  5597. workdata->buf);
  5598. continue;
  5599. }
  5600. *(workdata->f_ha1) = 0;
  5601. (workdata->f_ha1)++;
  5602. if (!strcmp(workdata->ah.user, workdata->f_user)
  5603. && !strcmp(workdata->domain, workdata->f_domain)) {
  5604. return check_password(workdata->conn->request_info.request_method,
  5605. workdata->f_ha1,
  5606. workdata->ah.uri,
  5607. workdata->ah.nonce,
  5608. workdata->ah.nc,
  5609. workdata->ah.cnonce,
  5610. workdata->ah.qop,
  5611. workdata->ah.response);
  5612. }
  5613. }
  5614. return is_authorized;
  5615. }
  5616. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5617. static int
  5618. authorize(struct mg_connection *conn, struct mg_file *filep)
  5619. {
  5620. struct read_auth_file_struct workdata;
  5621. char buf[MG_BUF_LEN];
  5622. if (!conn || !conn->ctx) {
  5623. return 0;
  5624. }
  5625. memset(&workdata, 0, sizeof(workdata));
  5626. workdata.conn = conn;
  5627. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5628. return 0;
  5629. }
  5630. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5631. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5632. }
  5633. /* Return 1 if request is authorised, 0 otherwise. */
  5634. static int
  5635. check_authorization(struct mg_connection *conn, const char *path)
  5636. {
  5637. char fname[PATH_MAX];
  5638. struct vec uri_vec, filename_vec;
  5639. const char *list;
  5640. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5641. int authorized = 1, truncated;
  5642. if (!conn || !conn->ctx) {
  5643. return 0;
  5644. }
  5645. list = conn->ctx->config[PROTECT_URI];
  5646. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5647. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5648. mg_snprintf(conn,
  5649. &truncated,
  5650. fname,
  5651. sizeof(fname),
  5652. "%.*s",
  5653. (int)filename_vec.len,
  5654. filename_vec.ptr);
  5655. if (truncated
  5656. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5657. mg_cry(conn,
  5658. "%s: cannot open %s: %s",
  5659. __func__,
  5660. fname,
  5661. strerror(errno));
  5662. }
  5663. break;
  5664. }
  5665. }
  5666. if (!is_file_opened(&file.access)) {
  5667. open_auth_file(conn, path, &file);
  5668. }
  5669. if (is_file_opened(&file.access)) {
  5670. authorized = authorize(conn, &file);
  5671. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5672. }
  5673. return authorized;
  5674. }
  5675. static void
  5676. send_authorization_request(struct mg_connection *conn)
  5677. {
  5678. char date[64];
  5679. time_t curtime = time(NULL);
  5680. if (conn && conn->ctx) {
  5681. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5682. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5683. nonce += conn->ctx->nonce_count;
  5684. ++conn->ctx->nonce_count;
  5685. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5686. nonce ^= conn->ctx->auth_nonce_mask;
  5687. conn->status_code = 401;
  5688. conn->must_close = 1;
  5689. gmt_time_string(date, sizeof(date), &curtime);
  5690. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5691. send_no_cache_header(conn);
  5692. send_additional_header(conn);
  5693. mg_printf(conn,
  5694. "Date: %s\r\n"
  5695. "Connection: %s\r\n"
  5696. "Content-Length: 0\r\n"
  5697. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5698. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5699. date,
  5700. suggest_connection_header(conn),
  5701. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5702. nonce);
  5703. }
  5704. }
  5705. #if !defined(NO_FILES)
  5706. static int
  5707. is_authorized_for_put(struct mg_connection *conn)
  5708. {
  5709. if (conn) {
  5710. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5711. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5712. int ret = 0;
  5713. if (passfile != NULL
  5714. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5715. ret = authorize(conn, &file);
  5716. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5717. }
  5718. return ret;
  5719. }
  5720. return 0;
  5721. }
  5722. #endif
  5723. int
  5724. mg_modify_passwords_file(const char *fname,
  5725. const char *domain,
  5726. const char *user,
  5727. const char *pass)
  5728. {
  5729. int found, i;
  5730. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5731. FILE *fp, *fp2;
  5732. found = 0;
  5733. fp = fp2 = NULL;
  5734. /* Regard empty password as no password - remove user record. */
  5735. if (pass != NULL && pass[0] == '\0') {
  5736. pass = NULL;
  5737. }
  5738. /* Other arguments must not be empty */
  5739. if (fname == NULL || domain == NULL || user == NULL) {
  5740. return 0;
  5741. }
  5742. /* Using the given file format, user name and domain must not contain ':'
  5743. */
  5744. if (strchr(user, ':') != NULL) {
  5745. return 0;
  5746. }
  5747. if (strchr(domain, ':') != NULL) {
  5748. return 0;
  5749. }
  5750. /* Do not allow control characters like newline in user name and domain.
  5751. * Do not allow excessively long names either. */
  5752. for (i = 0; i < 255 && user[i] != 0; i++) {
  5753. if (iscntrl(user[i])) {
  5754. return 0;
  5755. }
  5756. }
  5757. if (user[i]) {
  5758. return 0;
  5759. }
  5760. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5761. if (iscntrl(domain[i])) {
  5762. return 0;
  5763. }
  5764. }
  5765. if (domain[i]) {
  5766. return 0;
  5767. }
  5768. /* The maximum length of the path to the password file is limited */
  5769. if ((strlen(fname) + 4) >= PATH_MAX) {
  5770. return 0;
  5771. }
  5772. /* Create a temporary file name. Length has been checked before. */
  5773. strcpy(tmp, fname);
  5774. strcat(tmp, ".tmp");
  5775. /* Create the file if does not exist */
  5776. /* Use of fopen here is OK, since fname is only ASCII */
  5777. if ((fp = fopen(fname, "a+")) != NULL) {
  5778. (void)fclose(fp);
  5779. }
  5780. /* Open the given file and temporary file */
  5781. if ((fp = fopen(fname, "r")) == NULL) {
  5782. return 0;
  5783. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5784. fclose(fp);
  5785. return 0;
  5786. }
  5787. /* Copy the stuff to temporary file */
  5788. while (fgets(line, sizeof(line), fp) != NULL) {
  5789. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5790. continue;
  5791. }
  5792. u[255] = 0;
  5793. d[255] = 0;
  5794. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5795. found++;
  5796. if (pass != NULL) {
  5797. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5798. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5799. }
  5800. } else {
  5801. fprintf(fp2, "%s", line);
  5802. }
  5803. }
  5804. /* If new user, just add it */
  5805. if (!found && pass != NULL) {
  5806. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5807. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5808. }
  5809. /* Close files */
  5810. fclose(fp);
  5811. fclose(fp2);
  5812. /* Put the temp file in place of real file */
  5813. IGNORE_UNUSED_RESULT(remove(fname));
  5814. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5815. return 1;
  5816. }
  5817. static int
  5818. is_valid_port(unsigned long port)
  5819. {
  5820. return (port <= 0xffff);
  5821. }
  5822. static int
  5823. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5824. {
  5825. struct addrinfo hints, *res, *ressave;
  5826. int func_ret = 0;
  5827. int gai_ret;
  5828. memset(&hints, 0, sizeof(struct addrinfo));
  5829. hints.ai_family = af;
  5830. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5831. if (gai_ret != 0) {
  5832. /* gai_strerror could be used to convert gai_ret to a string */
  5833. /* POSIX return values: see
  5834. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5835. */
  5836. /* Windows return values: see
  5837. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5838. */
  5839. return 0;
  5840. }
  5841. ressave = res;
  5842. while (res) {
  5843. if (dstlen >= res->ai_addrlen) {
  5844. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5845. func_ret = 1;
  5846. }
  5847. res = res->ai_next;
  5848. }
  5849. freeaddrinfo(ressave);
  5850. return func_ret;
  5851. }
  5852. static int
  5853. connect_socket(struct mg_context *ctx /* may be NULL */,
  5854. const char *host,
  5855. int port,
  5856. int use_ssl,
  5857. char *ebuf,
  5858. size_t ebuf_len,
  5859. SOCKET *sock /* output: socket, must not be NULL */,
  5860. union usa *sa /* output: socket address, must not be NULL */
  5861. )
  5862. {
  5863. int ip_ver = 0;
  5864. *sock = INVALID_SOCKET;
  5865. memset(sa, 0, sizeof(*sa));
  5866. if (ebuf_len > 0) {
  5867. *ebuf = 0;
  5868. }
  5869. if (host == NULL) {
  5870. mg_snprintf(NULL,
  5871. NULL, /* No truncation check for ebuf */
  5872. ebuf,
  5873. ebuf_len,
  5874. "%s",
  5875. "NULL host");
  5876. return 0;
  5877. }
  5878. if (port <= 0 || !is_valid_port((unsigned)port)) {
  5879. mg_snprintf(NULL,
  5880. NULL, /* No truncation check for ebuf */
  5881. ebuf,
  5882. ebuf_len,
  5883. "%s",
  5884. "invalid port");
  5885. return 0;
  5886. }
  5887. #if !defined(NO_SSL)
  5888. #if !defined(NO_SSL_DL)
  5889. #ifdef OPENSSL_API_1_1
  5890. if (use_ssl && (TLS_client_method == NULL)) {
  5891. mg_snprintf(NULL,
  5892. NULL, /* No truncation check for ebuf */
  5893. ebuf,
  5894. ebuf_len,
  5895. "%s",
  5896. "SSL is not initialized");
  5897. return 0;
  5898. }
  5899. #else
  5900. if (use_ssl && (SSLv23_client_method == NULL)) {
  5901. mg_snprintf(NULL,
  5902. NULL, /* No truncation check for ebuf */
  5903. ebuf,
  5904. ebuf_len,
  5905. "%s",
  5906. "SSL is not initialized");
  5907. return 0;
  5908. }
  5909. #endif /* OPENSSL_API_1_1 */
  5910. #else
  5911. (void)use_ssl;
  5912. #endif /* NO_SSL_DL */
  5913. #else
  5914. (void)use_ssl;
  5915. #endif /* !defined(NO_SSL) */
  5916. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5917. sa->sin.sin_port = htons((uint16_t)port);
  5918. ip_ver = 4;
  5919. #ifdef USE_IPV6
  5920. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5921. sa->sin6.sin6_port = htons((uint16_t)port);
  5922. ip_ver = 6;
  5923. } else if (host[0] == '[') {
  5924. /* While getaddrinfo on Windows will work with [::1],
  5925. * getaddrinfo on Linux only works with ::1 (without []). */
  5926. size_t l = strlen(host + 1);
  5927. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5928. if (h) {
  5929. h[l - 1] = 0;
  5930. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5931. sa->sin6.sin6_port = htons((uint16_t)port);
  5932. ip_ver = 6;
  5933. }
  5934. mg_free(h);
  5935. }
  5936. #endif
  5937. }
  5938. if (ip_ver == 0) {
  5939. mg_snprintf(NULL,
  5940. NULL, /* No truncation check for ebuf */
  5941. ebuf,
  5942. ebuf_len,
  5943. "%s",
  5944. "host not found");
  5945. return 0;
  5946. }
  5947. if (ip_ver == 4) {
  5948. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5949. }
  5950. #ifdef USE_IPV6
  5951. else if (ip_ver == 6) {
  5952. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5953. }
  5954. #endif
  5955. if (*sock == INVALID_SOCKET) {
  5956. mg_snprintf(NULL,
  5957. NULL, /* No truncation check for ebuf */
  5958. ebuf,
  5959. ebuf_len,
  5960. "socket(): %s",
  5961. strerror(ERRNO));
  5962. return 0;
  5963. }
  5964. set_close_on_exec(*sock, fc(ctx));
  5965. if ((ip_ver == 4)
  5966. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5967. == 0)) {
  5968. /* connected with IPv4 */
  5969. set_blocking_mode(*sock, 0);
  5970. return 1;
  5971. }
  5972. #ifdef USE_IPV6
  5973. if ((ip_ver == 6)
  5974. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5975. == 0)) {
  5976. /* connected with IPv6 */
  5977. set_blocking_mode(*sock, 0);
  5978. return 1;
  5979. }
  5980. #endif
  5981. /* Not connected */
  5982. mg_snprintf(NULL,
  5983. NULL, /* No truncation check for ebuf */
  5984. ebuf,
  5985. ebuf_len,
  5986. "connect(%s:%d): %s",
  5987. host,
  5988. port,
  5989. strerror(ERRNO));
  5990. closesocket(*sock);
  5991. *sock = INVALID_SOCKET;
  5992. return 0;
  5993. }
  5994. int
  5995. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5996. {
  5997. static const char *dont_escape = "._-$,;~()";
  5998. static const char *hex = "0123456789abcdef";
  5999. char *pos = dst;
  6000. const char *end = dst + dst_len - 1;
  6001. for (; *src != '\0' && pos < end; src++, pos++) {
  6002. if (isalnum(*(const unsigned char *)src)
  6003. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  6004. *pos = *src;
  6005. } else if (pos + 2 < end) {
  6006. pos[0] = '%';
  6007. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6008. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6009. pos += 2;
  6010. } else {
  6011. break;
  6012. }
  6013. }
  6014. *pos = '\0';
  6015. return (*src == '\0') ? (int)(pos - dst) : -1;
  6016. }
  6017. static void
  6018. print_dir_entry(struct de *de)
  6019. {
  6020. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6021. struct tm *tm;
  6022. if (de->file.is_directory) {
  6023. mg_snprintf(de->conn,
  6024. NULL, /* Buffer is big enough */
  6025. size,
  6026. sizeof(size),
  6027. "%s",
  6028. "[DIRECTORY]");
  6029. } else {
  6030. /* We use (signed) cast below because MSVC 6 compiler cannot
  6031. * convert unsigned __int64 to double. Sigh. */
  6032. if (de->file.size < 1024) {
  6033. mg_snprintf(de->conn,
  6034. NULL, /* Buffer is big enough */
  6035. size,
  6036. sizeof(size),
  6037. "%d",
  6038. (int)de->file.size);
  6039. } else if (de->file.size < 0x100000) {
  6040. mg_snprintf(de->conn,
  6041. NULL, /* Buffer is big enough */
  6042. size,
  6043. sizeof(size),
  6044. "%.1fk",
  6045. (double)de->file.size / 1024.0);
  6046. } else if (de->file.size < 0x40000000) {
  6047. mg_snprintf(de->conn,
  6048. NULL, /* Buffer is big enough */
  6049. size,
  6050. sizeof(size),
  6051. "%.1fM",
  6052. (double)de->file.size / 1048576);
  6053. } else {
  6054. mg_snprintf(de->conn,
  6055. NULL, /* Buffer is big enough */
  6056. size,
  6057. sizeof(size),
  6058. "%.1fG",
  6059. (double)de->file.size / 1073741824);
  6060. }
  6061. }
  6062. /* Note: mg_snprintf will not cause a buffer overflow above.
  6063. * So, string truncation checks are not required here. */
  6064. tm = localtime(&de->file.last_modified);
  6065. if (tm != NULL) {
  6066. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6067. } else {
  6068. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6069. mod[sizeof(mod) - 1] = '\0';
  6070. }
  6071. mg_url_encode(de->file_name, href, sizeof(href));
  6072. de->conn->num_bytes_sent +=
  6073. mg_printf(de->conn,
  6074. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6075. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6076. de->conn->request_info.local_uri,
  6077. href,
  6078. de->file.is_directory ? "/" : "",
  6079. de->file_name,
  6080. de->file.is_directory ? "/" : "",
  6081. mod,
  6082. size);
  6083. }
  6084. /* This function is called from send_directory() and used for
  6085. * sorting directory entries by size, or name, or modification time.
  6086. * On windows, __cdecl specification is needed in case if project is built
  6087. * with __stdcall convention. qsort always requires __cdels callback. */
  6088. static int WINCDECL
  6089. compare_dir_entries(const void *p1, const void *p2)
  6090. {
  6091. if (p1 && p2) {
  6092. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6093. const char *query_string = a->conn->request_info.query_string;
  6094. int cmp_result = 0;
  6095. if (query_string == NULL) {
  6096. query_string = "na";
  6097. }
  6098. if (a->file.is_directory && !b->file.is_directory) {
  6099. return -1; /* Always put directories on top */
  6100. } else if (!a->file.is_directory && b->file.is_directory) {
  6101. return 1; /* Always put directories on top */
  6102. } else if (*query_string == 'n') {
  6103. cmp_result = strcmp(a->file_name, b->file_name);
  6104. } else if (*query_string == 's') {
  6105. cmp_result = (a->file.size == b->file.size)
  6106. ? 0
  6107. : ((a->file.size > b->file.size) ? 1 : -1);
  6108. } else if (*query_string == 'd') {
  6109. cmp_result =
  6110. (a->file.last_modified == b->file.last_modified)
  6111. ? 0
  6112. : ((a->file.last_modified > b->file.last_modified) ? 1
  6113. : -1);
  6114. }
  6115. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6116. }
  6117. return 0;
  6118. }
  6119. static int
  6120. must_hide_file(struct mg_connection *conn, const char *path)
  6121. {
  6122. if (conn && conn->ctx) {
  6123. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6124. const char *pattern = conn->ctx->config[HIDE_FILES];
  6125. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6126. || (pattern != NULL
  6127. && match_prefix(pattern, strlen(pattern), path) > 0);
  6128. }
  6129. return 0;
  6130. }
  6131. static int
  6132. scan_directory(struct mg_connection *conn,
  6133. const char *dir,
  6134. void *data,
  6135. void (*cb)(struct de *, void *))
  6136. {
  6137. char path[PATH_MAX];
  6138. struct dirent *dp;
  6139. DIR *dirp;
  6140. struct de de;
  6141. int truncated;
  6142. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6143. return 0;
  6144. } else {
  6145. de.conn = conn;
  6146. while ((dp = mg_readdir(dirp)) != NULL) {
  6147. /* Do not show current dir and hidden files */
  6148. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6149. || must_hide_file(conn, dp->d_name)) {
  6150. continue;
  6151. }
  6152. mg_snprintf(
  6153. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6154. /* If we don't memset stat structure to zero, mtime will have
  6155. * garbage and strftime() will segfault later on in
  6156. * print_dir_entry(). memset is required only if mg_stat()
  6157. * fails. For more details, see
  6158. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6159. memset(&de.file, 0, sizeof(de.file));
  6160. if (truncated) {
  6161. /* If the path is not complete, skip processing. */
  6162. continue;
  6163. }
  6164. if (!mg_stat(conn, path, &de.file)) {
  6165. mg_cry(conn,
  6166. "%s: mg_stat(%s) failed: %s",
  6167. __func__,
  6168. path,
  6169. strerror(ERRNO));
  6170. }
  6171. de.file_name = dp->d_name;
  6172. cb(&de, data);
  6173. }
  6174. (void)mg_closedir(dirp);
  6175. }
  6176. return 1;
  6177. }
  6178. #if !defined(NO_FILES)
  6179. static int
  6180. remove_directory(struct mg_connection *conn, const char *dir)
  6181. {
  6182. char path[PATH_MAX];
  6183. struct dirent *dp;
  6184. DIR *dirp;
  6185. struct de de;
  6186. int truncated;
  6187. int ok = 1;
  6188. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6189. return 0;
  6190. } else {
  6191. de.conn = conn;
  6192. while ((dp = mg_readdir(dirp)) != NULL) {
  6193. /* Do not show current dir (but show hidden files as they will
  6194. * also be removed) */
  6195. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6196. continue;
  6197. }
  6198. mg_snprintf(
  6199. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6200. /* If we don't memset stat structure to zero, mtime will have
  6201. * garbage and strftime() will segfault later on in
  6202. * print_dir_entry(). memset is required only if mg_stat()
  6203. * fails. For more details, see
  6204. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6205. memset(&de.file, 0, sizeof(de.file));
  6206. if (truncated) {
  6207. /* Do not delete anything shorter */
  6208. ok = 0;
  6209. continue;
  6210. }
  6211. if (!mg_stat(conn, path, &de.file)) {
  6212. mg_cry(conn,
  6213. "%s: mg_stat(%s) failed: %s",
  6214. __func__,
  6215. path,
  6216. strerror(ERRNO));
  6217. ok = 0;
  6218. }
  6219. if (de.file.is_directory) {
  6220. if (remove_directory(conn, path) == 0) {
  6221. ok = 0;
  6222. }
  6223. } else {
  6224. /* This will fail file is the file is in memory */
  6225. if (mg_remove(conn, path) == 0) {
  6226. ok = 0;
  6227. }
  6228. }
  6229. }
  6230. (void)mg_closedir(dirp);
  6231. IGNORE_UNUSED_RESULT(rmdir(dir));
  6232. }
  6233. return ok;
  6234. }
  6235. #endif
  6236. struct dir_scan_data {
  6237. struct de *entries;
  6238. unsigned int num_entries;
  6239. unsigned int arr_size;
  6240. };
  6241. /* Behaves like realloc(), but frees original pointer on failure */
  6242. static void *
  6243. realloc2(void *ptr, size_t size)
  6244. {
  6245. void *new_ptr = mg_realloc(ptr, size);
  6246. if (new_ptr == NULL) {
  6247. mg_free(ptr);
  6248. }
  6249. return new_ptr;
  6250. }
  6251. static void
  6252. dir_scan_callback(struct de *de, void *data)
  6253. {
  6254. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6255. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6256. dsd->arr_size *= 2;
  6257. dsd->entries =
  6258. (struct de *)realloc2(dsd->entries,
  6259. dsd->arr_size * sizeof(dsd->entries[0]));
  6260. }
  6261. if (dsd->entries == NULL) {
  6262. /* TODO(lsm, low): propagate an error to the caller */
  6263. dsd->num_entries = 0;
  6264. } else {
  6265. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6266. dsd->entries[dsd->num_entries].file = de->file;
  6267. dsd->entries[dsd->num_entries].conn = de->conn;
  6268. dsd->num_entries++;
  6269. }
  6270. }
  6271. static void
  6272. handle_directory_request(struct mg_connection *conn, const char *dir)
  6273. {
  6274. unsigned int i;
  6275. int sort_direction;
  6276. struct dir_scan_data data = {NULL, 0, 128};
  6277. char date[64];
  6278. time_t curtime = time(NULL);
  6279. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6280. send_http_error(conn,
  6281. 500,
  6282. "Error: Cannot open directory\nopendir(%s): %s",
  6283. dir,
  6284. strerror(ERRNO));
  6285. return;
  6286. }
  6287. gmt_time_string(date, sizeof(date), &curtime);
  6288. if (!conn) {
  6289. return;
  6290. }
  6291. sort_direction = ((conn->request_info.query_string != NULL)
  6292. && (conn->request_info.query_string[1] == 'd'))
  6293. ? 'a'
  6294. : 'd';
  6295. conn->must_close = 1;
  6296. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6297. send_static_cache_header(conn);
  6298. send_additional_header(conn);
  6299. mg_printf(conn,
  6300. "Date: %s\r\n"
  6301. "Connection: close\r\n"
  6302. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6303. date);
  6304. conn->num_bytes_sent +=
  6305. mg_printf(conn,
  6306. "<html><head><title>Index of %s</title>"
  6307. "<style>th {text-align: left;}</style></head>"
  6308. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6309. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6310. "<th><a href=\"?d%c\">Modified</a></th>"
  6311. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6312. "<tr><td colspan=\"3\"><hr></td></tr>",
  6313. conn->request_info.local_uri,
  6314. conn->request_info.local_uri,
  6315. sort_direction,
  6316. sort_direction,
  6317. sort_direction);
  6318. /* Print first entry - link to a parent directory */
  6319. conn->num_bytes_sent +=
  6320. mg_printf(conn,
  6321. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6322. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6323. conn->request_info.local_uri,
  6324. "..",
  6325. "Parent directory",
  6326. "-",
  6327. "-");
  6328. /* Sort and print directory entries */
  6329. if (data.entries != NULL) {
  6330. qsort(data.entries,
  6331. (size_t)data.num_entries,
  6332. sizeof(data.entries[0]),
  6333. compare_dir_entries);
  6334. for (i = 0; i < data.num_entries; i++) {
  6335. print_dir_entry(&data.entries[i]);
  6336. mg_free(data.entries[i].file_name);
  6337. }
  6338. mg_free(data.entries);
  6339. }
  6340. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6341. conn->status_code = 200;
  6342. }
  6343. /* Send len bytes from the opened file to the client. */
  6344. static void
  6345. send_file_data(struct mg_connection *conn,
  6346. struct mg_file *filep,
  6347. int64_t offset,
  6348. int64_t len)
  6349. {
  6350. char buf[MG_BUF_LEN];
  6351. int to_read, num_read, num_written;
  6352. int64_t size;
  6353. if (!filep || !conn) {
  6354. return;
  6355. }
  6356. /* Sanity check the offset */
  6357. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6358. : (int64_t)(filep->stat.size);
  6359. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6360. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6361. /* file stored in memory */
  6362. if (len > size - offset) {
  6363. len = size - offset;
  6364. }
  6365. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6366. } else if (len > 0 && filep->access.fp != NULL) {
  6367. /* file stored on disk */
  6368. #if defined(__linux__)
  6369. /* sendfile is only available for Linux */
  6370. if ((conn->ssl == 0) && (conn->throttle == 0)
  6371. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6372. "yes"))) {
  6373. off_t sf_offs = (off_t)offset;
  6374. ssize_t sf_sent;
  6375. int sf_file = fileno(filep->access.fp);
  6376. int loop_cnt = 0;
  6377. do {
  6378. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6379. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6380. size_t sf_tosend =
  6381. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6382. sf_sent =
  6383. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6384. if (sf_sent > 0) {
  6385. conn->num_bytes_sent += sf_sent;
  6386. len -= sf_sent;
  6387. offset += sf_sent;
  6388. } else if (loop_cnt == 0) {
  6389. /* This file can not be sent using sendfile.
  6390. * This might be the case for pseudo-files in the
  6391. * /sys/ and /proc/ file system.
  6392. * Use the regular user mode copy code instead. */
  6393. break;
  6394. } else if (sf_sent == 0) {
  6395. /* No error, but 0 bytes sent. May be EOF? */
  6396. return;
  6397. }
  6398. loop_cnt++;
  6399. } while ((len > 0) && (sf_sent >= 0));
  6400. if (sf_sent > 0) {
  6401. return; /* OK */
  6402. }
  6403. /* sf_sent<0 means error, thus fall back to the classic way */
  6404. /* This is always the case, if sf_file is not a "normal" file,
  6405. * e.g., for sending data from the output of a CGI process. */
  6406. offset = (int64_t)sf_offs;
  6407. }
  6408. #endif
  6409. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6410. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6411. send_http_error(
  6412. conn,
  6413. 500,
  6414. "%s",
  6415. "Error: Unable to access file at requested position.");
  6416. } else {
  6417. while (len > 0) {
  6418. /* Calculate how much to read from the file in the buffer */
  6419. to_read = sizeof(buf);
  6420. if ((int64_t)to_read > len) {
  6421. to_read = (int)len;
  6422. }
  6423. /* Read from file, exit the loop on error */
  6424. if ((num_read =
  6425. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6426. <= 0) {
  6427. break;
  6428. }
  6429. /* Send read bytes to the client, exit the loop on error */
  6430. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6431. != num_read) {
  6432. break;
  6433. }
  6434. /* Both read and were successful, adjust counters */
  6435. conn->num_bytes_sent += num_written;
  6436. len -= num_written;
  6437. }
  6438. }
  6439. }
  6440. }
  6441. static int
  6442. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6443. {
  6444. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6445. }
  6446. static void
  6447. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6448. {
  6449. if (filestat != NULL && buf != NULL) {
  6450. mg_snprintf(NULL,
  6451. NULL, /* All calls to construct_etag use 64 byte buffer */
  6452. buf,
  6453. buf_len,
  6454. "\"%lx.%" INT64_FMT "\"",
  6455. (unsigned long)filestat->last_modified,
  6456. filestat->size);
  6457. }
  6458. }
  6459. static void
  6460. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6461. {
  6462. if (filep != NULL && filep->fp != NULL) {
  6463. #ifdef _WIN32
  6464. (void)conn; /* Unused. */
  6465. #else
  6466. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6467. mg_cry(conn,
  6468. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6469. __func__,
  6470. strerror(ERRNO));
  6471. }
  6472. #endif
  6473. }
  6474. }
  6475. static void
  6476. handle_static_file_request(struct mg_connection *conn,
  6477. const char *path,
  6478. struct mg_file *filep,
  6479. const char *mime_type,
  6480. const char *additional_headers)
  6481. {
  6482. char date[64], lm[64], etag[64];
  6483. char range[128]; /* large enough, so there will be no overflow */
  6484. const char *msg = "OK", *hdr;
  6485. time_t curtime = time(NULL);
  6486. int64_t cl, r1, r2;
  6487. struct vec mime_vec;
  6488. int n, truncated;
  6489. char gz_path[PATH_MAX];
  6490. const char *encoding = "";
  6491. const char *cors1, *cors2, *cors3;
  6492. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6493. return;
  6494. }
  6495. if (mime_type == NULL) {
  6496. get_mime_type(conn->ctx, path, &mime_vec);
  6497. } else {
  6498. mime_vec.ptr = mime_type;
  6499. mime_vec.len = strlen(mime_type);
  6500. }
  6501. if (filep->stat.size > INT64_MAX) {
  6502. send_http_error(conn,
  6503. 500,
  6504. "Error: File size is too large to send\n%" INT64_FMT,
  6505. filep->stat.size);
  6506. }
  6507. cl = (int64_t)filep->stat.size;
  6508. conn->status_code = 200;
  6509. range[0] = '\0';
  6510. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6511. * it's important to rewrite the filename after resolving
  6512. * the mime type from it, to preserve the actual file's type */
  6513. if (filep->stat.is_gzipped) {
  6514. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6515. if (truncated) {
  6516. send_http_error(conn,
  6517. 500,
  6518. "Error: Path of zipped file too long (%s)",
  6519. path);
  6520. return;
  6521. }
  6522. path = gz_path;
  6523. encoding = "Content-Encoding: gzip\r\n";
  6524. }
  6525. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6526. send_http_error(conn,
  6527. 500,
  6528. "Error: Cannot open file\nfopen(%s): %s",
  6529. path,
  6530. strerror(ERRNO));
  6531. return;
  6532. }
  6533. fclose_on_exec(&filep->access, conn);
  6534. /* If Range: header specified, act accordingly */
  6535. r1 = r2 = 0;
  6536. hdr = mg_get_header(conn, "Range");
  6537. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6538. && r2 >= 0) {
  6539. /* actually, range requests don't play well with a pre-gzipped
  6540. * file (since the range is specified in the uncompressed space) */
  6541. if (filep->stat.is_gzipped) {
  6542. send_http_error(
  6543. conn,
  6544. 501,
  6545. "%s",
  6546. "Error: Range requests in gzipped files are not supported");
  6547. (void)mg_fclose(
  6548. &filep->access); /* ignore error on read only file */
  6549. return;
  6550. }
  6551. conn->status_code = 206;
  6552. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6553. mg_snprintf(conn,
  6554. NULL, /* range buffer is big enough */
  6555. range,
  6556. sizeof(range),
  6557. "Content-Range: bytes "
  6558. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6559. r1,
  6560. r1 + cl - 1,
  6561. filep->stat.size);
  6562. msg = "Partial Content";
  6563. }
  6564. hdr = mg_get_header(conn, "Origin");
  6565. if (hdr) {
  6566. /* Cross-origin resource sharing (CORS), see
  6567. * http://www.html5rocks.com/en/tutorials/cors/,
  6568. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6569. * preflight is not supported for files. */
  6570. cors1 = "Access-Control-Allow-Origin: ";
  6571. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6572. cors3 = "\r\n";
  6573. } else {
  6574. cors1 = cors2 = cors3 = "";
  6575. }
  6576. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6577. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6578. gmt_time_string(date, sizeof(date), &curtime);
  6579. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6580. construct_etag(etag, sizeof(etag), &filep->stat);
  6581. (void)mg_printf(conn,
  6582. "HTTP/1.1 %d %s\r\n"
  6583. "%s%s%s"
  6584. "Date: %s\r\n",
  6585. conn->status_code,
  6586. msg,
  6587. cors1,
  6588. cors2,
  6589. cors3,
  6590. date);
  6591. send_static_cache_header(conn);
  6592. send_additional_header(conn);
  6593. (void)mg_printf(conn,
  6594. "Last-Modified: %s\r\n"
  6595. "Etag: %s\r\n"
  6596. "Content-Type: %.*s\r\n"
  6597. "Content-Length: %" INT64_FMT "\r\n"
  6598. "Connection: %s\r\n"
  6599. "Accept-Ranges: bytes\r\n"
  6600. "%s%s",
  6601. lm,
  6602. etag,
  6603. (int)mime_vec.len,
  6604. mime_vec.ptr,
  6605. cl,
  6606. suggest_connection_header(conn),
  6607. range,
  6608. encoding);
  6609. /* The previous code must not add any header starting with X- to make
  6610. * sure no one of the additional_headers is included twice */
  6611. if (additional_headers != NULL) {
  6612. (void)mg_printf(conn,
  6613. "%.*s\r\n\r\n",
  6614. (int)strlen(additional_headers),
  6615. additional_headers);
  6616. } else {
  6617. (void)mg_printf(conn, "\r\n");
  6618. }
  6619. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6620. send_file_data(conn, filep, r1, cl);
  6621. }
  6622. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6623. }
  6624. #if !defined(NO_CACHING)
  6625. static void
  6626. handle_not_modified_static_file_request(struct mg_connection *conn,
  6627. struct mg_file *filep)
  6628. {
  6629. char date[64], lm[64], etag[64];
  6630. time_t curtime = time(NULL);
  6631. if (conn == NULL || filep == NULL) {
  6632. return;
  6633. }
  6634. conn->status_code = 304;
  6635. gmt_time_string(date, sizeof(date), &curtime);
  6636. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6637. construct_etag(etag, sizeof(etag), &filep->stat);
  6638. (void)mg_printf(conn,
  6639. "HTTP/1.1 %d %s\r\n"
  6640. "Date: %s\r\n",
  6641. conn->status_code,
  6642. mg_get_response_code_text(conn, conn->status_code),
  6643. date);
  6644. send_static_cache_header(conn);
  6645. send_additional_header(conn);
  6646. (void)mg_printf(conn,
  6647. "Last-Modified: %s\r\n"
  6648. "Etag: %s\r\n"
  6649. "Connection: %s\r\n"
  6650. "\r\n",
  6651. lm,
  6652. etag,
  6653. suggest_connection_header(conn));
  6654. }
  6655. #endif
  6656. void
  6657. mg_send_file(struct mg_connection *conn, const char *path)
  6658. {
  6659. mg_send_mime_file(conn, path, NULL);
  6660. }
  6661. void
  6662. mg_send_mime_file(struct mg_connection *conn,
  6663. const char *path,
  6664. const char *mime_type)
  6665. {
  6666. mg_send_mime_file2(conn, path, mime_type, NULL);
  6667. }
  6668. void
  6669. mg_send_mime_file2(struct mg_connection *conn,
  6670. const char *path,
  6671. const char *mime_type,
  6672. const char *additional_headers)
  6673. {
  6674. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6675. if (mg_stat(conn, path, &file.stat)) {
  6676. if (file.stat.is_directory) {
  6677. if (!conn) {
  6678. return;
  6679. }
  6680. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6681. "yes")) {
  6682. handle_directory_request(conn, path);
  6683. } else {
  6684. send_http_error(conn,
  6685. 403,
  6686. "%s",
  6687. "Error: Directory listing denied");
  6688. }
  6689. } else {
  6690. handle_static_file_request(
  6691. conn, path, &file, mime_type, additional_headers);
  6692. }
  6693. } else {
  6694. send_http_error(conn, 404, "%s", "Error: File not found");
  6695. }
  6696. }
  6697. /* For a given PUT path, create all intermediate subdirectories.
  6698. * Return 0 if the path itself is a directory.
  6699. * Return 1 if the path leads to a file.
  6700. * Return -1 for if the path is too long.
  6701. * Return -2 if path can not be created.
  6702. */
  6703. static int
  6704. put_dir(struct mg_connection *conn, const char *path)
  6705. {
  6706. char buf[PATH_MAX];
  6707. const char *s, *p;
  6708. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6709. size_t len;
  6710. int res = 1;
  6711. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6712. len = (size_t)(p - path);
  6713. if (len >= sizeof(buf)) {
  6714. /* path too long */
  6715. res = -1;
  6716. break;
  6717. }
  6718. memcpy(buf, path, len);
  6719. buf[len] = '\0';
  6720. /* Try to create intermediate directory */
  6721. DEBUG_TRACE("mkdir(%s)", buf);
  6722. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6723. /* path does not exixt and can not be created */
  6724. res = -2;
  6725. break;
  6726. }
  6727. /* Is path itself a directory? */
  6728. if (p[1] == '\0') {
  6729. res = 0;
  6730. }
  6731. }
  6732. return res;
  6733. }
  6734. static void
  6735. remove_bad_file(const struct mg_connection *conn, const char *path)
  6736. {
  6737. int r = mg_remove(conn, path);
  6738. if (r != 0) {
  6739. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6740. }
  6741. }
  6742. long long
  6743. mg_store_body(struct mg_connection *conn, const char *path)
  6744. {
  6745. char buf[MG_BUF_LEN];
  6746. long long len = 0;
  6747. int ret, n;
  6748. struct mg_file fi;
  6749. if (conn->consumed_content != 0) {
  6750. mg_cry(conn, "%s: Contents already consumed", __func__);
  6751. return -11;
  6752. }
  6753. ret = put_dir(conn, path);
  6754. if (ret < 0) {
  6755. /* -1 for path too long,
  6756. * -2 for path can not be created. */
  6757. return ret;
  6758. }
  6759. if (ret != 1) {
  6760. /* Return 0 means, path itself is a directory. */
  6761. return 0;
  6762. }
  6763. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6764. return -12;
  6765. }
  6766. ret = mg_read(conn, buf, sizeof(buf));
  6767. while (ret > 0) {
  6768. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6769. if (n != ret) {
  6770. (void)mg_fclose(
  6771. &fi.access); /* File is bad and will be removed anyway. */
  6772. remove_bad_file(conn, path);
  6773. return -13;
  6774. }
  6775. ret = mg_read(conn, buf, sizeof(buf));
  6776. }
  6777. /* File is open for writing. If fclose fails, there was probably an
  6778. * error flushing the buffer to disk, so the file on disk might be
  6779. * broken. Delete it and return an error to the caller. */
  6780. if (mg_fclose(&fi.access) != 0) {
  6781. remove_bad_file(conn, path);
  6782. return -14;
  6783. }
  6784. return len;
  6785. }
  6786. /* Parse HTTP headers from the given buffer, advance buf pointer
  6787. * to the point where parsing stopped.
  6788. * All parameters must be valid pointers (not NULL).
  6789. * Return <0 on error. */
  6790. static int
  6791. parse_http_headers(char **buf, struct mg_request_info *ri)
  6792. {
  6793. int i;
  6794. ri->num_headers = 0;
  6795. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6796. char *dp = *buf;
  6797. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6798. dp++;
  6799. }
  6800. if (dp == *buf) {
  6801. /* End of headers reached. */
  6802. break;
  6803. }
  6804. if (*dp != ':') {
  6805. /* This is not a valid field. */
  6806. return -1;
  6807. }
  6808. /* End of header key (*dp == ':') */
  6809. /* Truncate here and set the key name */
  6810. *dp = 0;
  6811. ri->http_headers[i].name = *buf;
  6812. do {
  6813. dp++;
  6814. } while (*dp == ' ');
  6815. /* The rest of the line is the value */
  6816. ri->http_headers[i].value = dp;
  6817. *buf = dp + strcspn(dp, "\r\n");
  6818. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6819. *buf = NULL;
  6820. }
  6821. ri->num_headers = i + 1;
  6822. if (*buf) {
  6823. (*buf)[0] = 0;
  6824. (*buf)[1] = 0;
  6825. *buf += 2;
  6826. } else {
  6827. *buf = dp;
  6828. break;
  6829. }
  6830. if ((*buf)[0] == '\r') {
  6831. /* This is the end of the header */
  6832. break;
  6833. }
  6834. }
  6835. return ri->num_headers;
  6836. }
  6837. static int
  6838. is_valid_http_method(const char *method)
  6839. {
  6840. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6841. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6842. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6843. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6844. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6845. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6846. /* TRACE method (RFC 2616) is not supported for security reasons */
  6847. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6848. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6849. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6850. /* Unsupported WEBDAV Methods: */
  6851. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6852. /* + 11 methods from RFC 3253 */
  6853. /* ORDERPATCH (RFC 3648) */
  6854. /* ACL (RFC 3744) */
  6855. /* SEARCH (RFC 5323) */
  6856. /* + MicroSoft extensions
  6857. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6858. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6859. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6860. }
  6861. /* Parse HTTP request, fill in mg_request_info structure.
  6862. * This function modifies the buffer by NUL-terminating
  6863. * HTTP request components, header names and header values.
  6864. * Parameters:
  6865. * buf (in/out): pointer to the HTTP header to parse and split
  6866. * len (in): length of HTTP header buffer
  6867. * re (out): parsed header as mg_request_info
  6868. * buf and ri must be valid pointers (not NULL), len>0.
  6869. * Returns <0 on error. */
  6870. static int
  6871. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6872. {
  6873. int is_request, request_length;
  6874. char *start_line;
  6875. request_length = get_request_len(buf, len);
  6876. if (request_length > 0) {
  6877. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6878. * remote_port */
  6879. ri->remote_user = ri->request_method = ri->request_uri =
  6880. ri->http_version = NULL;
  6881. ri->num_headers = 0;
  6882. buf[request_length - 1] = '\0';
  6883. /* RFC says that all initial whitespaces should be ingored */
  6884. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6885. buf++;
  6886. }
  6887. start_line = skip(&buf, "\r\n");
  6888. ri->request_method = skip(&start_line, " ");
  6889. ri->request_uri = skip(&start_line, " ");
  6890. ri->http_version = start_line;
  6891. /* HTTP message could be either HTTP request:
  6892. * "GET / HTTP/1.0 ..."
  6893. * or a HTTP response:
  6894. * "HTTP/1.0 200 OK ..."
  6895. * otherwise it is invalid.
  6896. */
  6897. is_request = is_valid_http_method(ri->request_method);
  6898. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6899. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6900. /* Not a valid request or response: invalid */
  6901. return -1;
  6902. }
  6903. if (is_request) {
  6904. ri->http_version += 5;
  6905. }
  6906. if (parse_http_headers(&buf, ri) < 0) {
  6907. /* Error while parsing headers */
  6908. return -1;
  6909. }
  6910. }
  6911. return request_length;
  6912. }
  6913. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6914. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6915. * buffer (which marks the end of HTTP request). Buffer buf may already
  6916. * have some data. The length of the data is stored in nread.
  6917. * Upon every read operation, increase nread by the number of bytes read. */
  6918. static int
  6919. read_request(FILE *fp,
  6920. struct mg_connection *conn,
  6921. char *buf,
  6922. int bufsiz,
  6923. int *nread)
  6924. {
  6925. int request_len, n = 0;
  6926. struct timespec last_action_time;
  6927. double request_timeout;
  6928. if (!conn) {
  6929. return 0;
  6930. }
  6931. memset(&last_action_time, 0, sizeof(last_action_time));
  6932. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6933. /* value of request_timeout is in seconds, config in milliseconds */
  6934. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6935. } else {
  6936. request_timeout = -1.0;
  6937. }
  6938. if (conn->handled_requests > 0) {
  6939. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  6940. request_timeout =
  6941. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  6942. }
  6943. }
  6944. request_len = get_request_len(buf, *nread);
  6945. /* first time reading from this connection */
  6946. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6947. while (request_len == 0) {
  6948. /* Full request not yet received */
  6949. if (conn->ctx->stop_flag != 0) {
  6950. /* Server is to be stopped. */
  6951. return -1;
  6952. }
  6953. if (*nread >= bufsiz) {
  6954. /* Request too long */
  6955. return -2;
  6956. }
  6957. n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6958. if (n < 0) {
  6959. /* Receive error */
  6960. return -1;
  6961. }
  6962. *nread += n;
  6963. request_len = get_request_len(buf, *nread);
  6964. if ((request_len == 0) && (request_timeout >= 0)) {
  6965. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  6966. > request_timeout) {
  6967. /* Timeout */
  6968. return -1;
  6969. }
  6970. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6971. }
  6972. }
  6973. return request_len;
  6974. }
  6975. #if !defined(NO_FILES)
  6976. /* For given directory path, substitute it to valid index file.
  6977. * Return 1 if index file has been found, 0 if not found.
  6978. * If the file is found, it's stats is returned in stp. */
  6979. static int
  6980. substitute_index_file(struct mg_connection *conn,
  6981. char *path,
  6982. size_t path_len,
  6983. struct mg_file *filep)
  6984. {
  6985. if (conn && conn->ctx) {
  6986. const char *list = conn->ctx->config[INDEX_FILES];
  6987. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6988. struct vec filename_vec;
  6989. size_t n = strlen(path);
  6990. int found = 0;
  6991. /* The 'path' given to us points to the directory. Remove all trailing
  6992. * directory separator characters from the end of the path, and
  6993. * then append single directory separator character. */
  6994. while (n > 0 && path[n - 1] == '/') {
  6995. n--;
  6996. }
  6997. path[n] = '/';
  6998. /* Traverse index files list. For each entry, append it to the given
  6999. * path and see if the file exists. If it exists, break the loop */
  7000. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  7001. /* Ignore too long entries that may overflow path buffer */
  7002. if (filename_vec.len > path_len - (n + 2)) {
  7003. continue;
  7004. }
  7005. /* Prepare full path to the index file */
  7006. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  7007. /* Does it exist? */
  7008. if (mg_stat(conn, path, &file.stat)) {
  7009. /* Yes it does, break the loop */
  7010. *filep = file;
  7011. found = 1;
  7012. break;
  7013. }
  7014. }
  7015. /* If no index file exists, restore directory path */
  7016. if (!found) {
  7017. path[n] = '\0';
  7018. }
  7019. return found;
  7020. }
  7021. return 0;
  7022. }
  7023. #endif
  7024. #if !defined(NO_CACHING)
  7025. /* Return True if we should reply 304 Not Modified. */
  7026. static int
  7027. is_not_modified(const struct mg_connection *conn,
  7028. const struct mg_file_stat *filestat)
  7029. {
  7030. char etag[64];
  7031. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7032. const char *inm = mg_get_header(conn, "If-None-Match");
  7033. construct_etag(etag, sizeof(etag), filestat);
  7034. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7035. || ((ims != NULL)
  7036. && (filestat->last_modified <= parse_date_string(ims)));
  7037. }
  7038. #endif /* !NO_CACHING */
  7039. #if !defined(NO_CGI) || !defined(NO_FILES)
  7040. static int
  7041. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7042. {
  7043. const char *expect, *body;
  7044. char buf[MG_BUF_LEN];
  7045. int to_read, nread, success = 0;
  7046. int64_t buffered_len;
  7047. double timeout = -1.0;
  7048. if (!conn) {
  7049. return 0;
  7050. }
  7051. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7052. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7053. }
  7054. expect = mg_get_header(conn, "Expect");
  7055. /* assert(fp != NULL); */
  7056. if (!fp) {
  7057. send_http_error(conn, 500, "%s", "Error: NULL File");
  7058. return 0;
  7059. }
  7060. if (conn->content_len == -1 && !conn->is_chunked) {
  7061. /* Content length is not specified by the client. */
  7062. send_http_error(conn,
  7063. 411,
  7064. "%s",
  7065. "Error: Client did not specify content length");
  7066. } else if ((expect != NULL)
  7067. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7068. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7069. send_http_error(conn,
  7070. 417,
  7071. "Error: Can not fulfill expectation %s",
  7072. expect);
  7073. } else {
  7074. if (expect != NULL) {
  7075. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7076. conn->status_code = 100;
  7077. } else {
  7078. conn->status_code = 200;
  7079. }
  7080. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7081. - conn->consumed_content;
  7082. /* assert(buffered_len >= 0); */
  7083. /* assert(conn->consumed_content == 0); */
  7084. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7085. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7086. return 0;
  7087. }
  7088. if (buffered_len > 0) {
  7089. if ((int64_t)buffered_len > conn->content_len) {
  7090. buffered_len = (int)conn->content_len;
  7091. }
  7092. body = conn->buf + conn->request_len + conn->consumed_content;
  7093. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7094. conn->consumed_content += buffered_len;
  7095. }
  7096. nread = 0;
  7097. while (conn->consumed_content < conn->content_len) {
  7098. to_read = sizeof(buf);
  7099. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7100. to_read = (int)(conn->content_len - conn->consumed_content);
  7101. }
  7102. nread = pull(NULL, conn, buf, to_read, timeout);
  7103. if (nread <= 0
  7104. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7105. break;
  7106. }
  7107. conn->consumed_content += nread;
  7108. }
  7109. if (conn->consumed_content == conn->content_len) {
  7110. success = (nread >= 0);
  7111. }
  7112. /* Each error code path in this function must send an error */
  7113. if (!success) {
  7114. /* NOTE: Maybe some data has already been sent. */
  7115. /* TODO (low): If some data has been sent, a correct error
  7116. * reply can no longer be sent, so just close the connection */
  7117. send_http_error(conn, 500, "%s", "");
  7118. }
  7119. }
  7120. return success;
  7121. }
  7122. #endif
  7123. #if !defined(NO_CGI)
  7124. /* This structure helps to create an environment for the spawned CGI program.
  7125. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7126. * last element must be NULL.
  7127. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7128. * strings must reside in a contiguous buffer. The end of the buffer is
  7129. * marked by two '\0' characters.
  7130. * We satisfy both worlds: we create an envp array (which is vars), all
  7131. * entries are actually pointers inside buf. */
  7132. struct cgi_environment {
  7133. struct mg_connection *conn;
  7134. /* Data block */
  7135. char *buf; /* Environment buffer */
  7136. size_t buflen; /* Space available in buf */
  7137. size_t bufused; /* Space taken in buf */
  7138. /* Index block */
  7139. char **var; /* char **envp */
  7140. size_t varlen; /* Number of variables available in var */
  7141. size_t varused; /* Number of variables stored in var */
  7142. };
  7143. static void addenv(struct cgi_environment *env,
  7144. PRINTF_FORMAT_STRING(const char *fmt),
  7145. ...) PRINTF_ARGS(2, 3);
  7146. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7147. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7148. static void
  7149. addenv(struct cgi_environment *env, const char *fmt, ...)
  7150. {
  7151. size_t n, space;
  7152. int truncated = 0;
  7153. char *added;
  7154. va_list ap;
  7155. /* Calculate how much space is left in the buffer */
  7156. space = (env->buflen - env->bufused);
  7157. /* Calculate an estimate for the required space */
  7158. n = strlen(fmt) + 2 + 128;
  7159. do {
  7160. if (space <= n) {
  7161. /* Allocate new buffer */
  7162. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7163. added = (char *)mg_realloc(env->buf, n);
  7164. if (!added) {
  7165. /* Out of memory */
  7166. mg_cry(env->conn,
  7167. "%s: Cannot allocate memory for CGI variable [%s]",
  7168. __func__,
  7169. fmt);
  7170. return;
  7171. }
  7172. env->buf = added;
  7173. env->buflen = n;
  7174. space = (env->buflen - env->bufused);
  7175. }
  7176. /* Make a pointer to the free space int the buffer */
  7177. added = env->buf + env->bufused;
  7178. /* Copy VARIABLE=VALUE\0 string into the free space */
  7179. va_start(ap, fmt);
  7180. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7181. va_end(ap);
  7182. /* Do not add truncated strings to the environment */
  7183. if (truncated) {
  7184. /* Reallocate the buffer */
  7185. space = 0;
  7186. n = 1;
  7187. }
  7188. } while (truncated);
  7189. /* Calculate number of bytes added to the environment */
  7190. n = strlen(added) + 1;
  7191. env->bufused += n;
  7192. /* Now update the variable index */
  7193. space = (env->varlen - env->varused);
  7194. if (space < 2) {
  7195. mg_cry(env->conn,
  7196. "%s: Cannot register CGI variable [%s]",
  7197. __func__,
  7198. fmt);
  7199. return;
  7200. }
  7201. /* Append a pointer to the added string into the envp array */
  7202. env->var[env->varused] = added;
  7203. env->varused++;
  7204. }
  7205. static void
  7206. prepare_cgi_environment(struct mg_connection *conn,
  7207. const char *prog,
  7208. struct cgi_environment *env)
  7209. {
  7210. const char *s;
  7211. struct vec var_vec;
  7212. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7213. int i, truncated, uri_len;
  7214. if (conn == NULL || prog == NULL || env == NULL) {
  7215. return;
  7216. }
  7217. env->conn = conn;
  7218. env->buflen = CGI_ENVIRONMENT_SIZE;
  7219. env->bufused = 0;
  7220. env->buf = (char *)mg_malloc(env->buflen);
  7221. env->varlen = MAX_CGI_ENVIR_VARS;
  7222. env->varused = 0;
  7223. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7224. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7225. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7226. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7227. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7228. /* Prepare the environment block */
  7229. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7230. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7231. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7232. #if defined(USE_IPV6)
  7233. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7234. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7235. } else
  7236. #endif
  7237. {
  7238. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7239. }
  7240. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7241. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7242. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7243. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7244. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7245. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7246. /* SCRIPT_NAME */
  7247. uri_len = (int)strlen(conn->request_info.local_uri);
  7248. if (conn->path_info == NULL) {
  7249. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7250. /* URI: /path_to_script/script.cgi */
  7251. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7252. } else {
  7253. /* URI: /path_to_script/ ... using index.cgi */
  7254. char *index_file = strrchr(prog, '/');
  7255. if (index_file) {
  7256. addenv(env,
  7257. "SCRIPT_NAME=%s%s",
  7258. conn->request_info.local_uri,
  7259. index_file + 1);
  7260. }
  7261. }
  7262. } else {
  7263. /* URI: /path_to_script/script.cgi/path_info */
  7264. addenv(env,
  7265. "SCRIPT_NAME=%.*s",
  7266. uri_len - (int)strlen(conn->path_info),
  7267. conn->request_info.local_uri);
  7268. }
  7269. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7270. if (conn->path_info == NULL) {
  7271. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7272. } else {
  7273. addenv(env,
  7274. "PATH_TRANSLATED=%s%s",
  7275. conn->ctx->config[DOCUMENT_ROOT],
  7276. conn->path_info);
  7277. }
  7278. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7279. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7280. addenv(env, "CONTENT_TYPE=%s", s);
  7281. }
  7282. if (conn->request_info.query_string != NULL) {
  7283. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7284. }
  7285. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7286. addenv(env, "CONTENT_LENGTH=%s", s);
  7287. }
  7288. if ((s = getenv("PATH")) != NULL) {
  7289. addenv(env, "PATH=%s", s);
  7290. }
  7291. if (conn->path_info != NULL) {
  7292. addenv(env, "PATH_INFO=%s", conn->path_info);
  7293. }
  7294. if (conn->status_code > 0) {
  7295. /* CGI error handler should show the status code */
  7296. addenv(env, "STATUS=%d", conn->status_code);
  7297. }
  7298. #if defined(_WIN32)
  7299. if ((s = getenv("COMSPEC")) != NULL) {
  7300. addenv(env, "COMSPEC=%s", s);
  7301. }
  7302. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7303. addenv(env, "SYSTEMROOT=%s", s);
  7304. }
  7305. if ((s = getenv("SystemDrive")) != NULL) {
  7306. addenv(env, "SystemDrive=%s", s);
  7307. }
  7308. if ((s = getenv("ProgramFiles")) != NULL) {
  7309. addenv(env, "ProgramFiles=%s", s);
  7310. }
  7311. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7312. addenv(env, "ProgramFiles(x86)=%s", s);
  7313. }
  7314. #else
  7315. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7316. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7317. }
  7318. #endif /* _WIN32 */
  7319. if ((s = getenv("PERLLIB")) != NULL) {
  7320. addenv(env, "PERLLIB=%s", s);
  7321. }
  7322. if (conn->request_info.remote_user != NULL) {
  7323. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7324. addenv(env, "%s", "AUTH_TYPE=Digest");
  7325. }
  7326. /* Add all headers as HTTP_* variables */
  7327. for (i = 0; i < conn->request_info.num_headers; i++) {
  7328. (void)mg_snprintf(conn,
  7329. &truncated,
  7330. http_var_name,
  7331. sizeof(http_var_name),
  7332. "HTTP_%s",
  7333. conn->request_info.http_headers[i].name);
  7334. if (truncated) {
  7335. mg_cry(conn,
  7336. "%s: HTTP header variable too long [%s]",
  7337. __func__,
  7338. conn->request_info.http_headers[i].name);
  7339. continue;
  7340. }
  7341. /* Convert variable name into uppercase, and change - to _ */
  7342. for (p = http_var_name; *p != '\0'; p++) {
  7343. if (*p == '-') {
  7344. *p = '_';
  7345. }
  7346. *p = (char)toupper(*(unsigned char *)p);
  7347. }
  7348. addenv(env,
  7349. "%s=%s",
  7350. http_var_name,
  7351. conn->request_info.http_headers[i].value);
  7352. }
  7353. /* Add user-specified variables */
  7354. s = conn->ctx->config[CGI_ENVIRONMENT];
  7355. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7356. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7357. }
  7358. env->var[env->varused] = NULL;
  7359. env->buf[env->bufused] = '\0';
  7360. }
  7361. static void
  7362. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7363. {
  7364. char *buf;
  7365. size_t buflen;
  7366. int headers_len, data_len, i, truncated;
  7367. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7368. const char *status, *status_text, *connection_state;
  7369. char *pbuf, dir[PATH_MAX], *p;
  7370. struct mg_request_info ri;
  7371. struct cgi_environment blk;
  7372. FILE *in = NULL, *out = NULL, *err = NULL;
  7373. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7374. pid_t pid = (pid_t)-1;
  7375. if (conn == NULL) {
  7376. return;
  7377. }
  7378. buf = NULL;
  7379. buflen = 16384;
  7380. prepare_cgi_environment(conn, prog, &blk);
  7381. /* CGI must be executed in its own directory. 'dir' must point to the
  7382. * directory containing executable program, 'p' must point to the
  7383. * executable program name relative to 'dir'. */
  7384. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7385. if (truncated) {
  7386. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7387. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7388. goto done;
  7389. }
  7390. if ((p = strrchr(dir, '/')) != NULL) {
  7391. *p++ = '\0';
  7392. } else {
  7393. dir[0] = '.', dir[1] = '\0';
  7394. p = (char *)prog;
  7395. }
  7396. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7397. status = strerror(ERRNO);
  7398. mg_cry(conn,
  7399. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7400. prog,
  7401. status);
  7402. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7403. goto done;
  7404. }
  7405. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7406. if (pid == (pid_t)-1) {
  7407. status = strerror(ERRNO);
  7408. mg_cry(conn,
  7409. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7410. prog,
  7411. status);
  7412. send_http_error(conn,
  7413. 500,
  7414. "Error: Cannot spawn CGI process [%s]: %s",
  7415. prog,
  7416. status);
  7417. goto done;
  7418. }
  7419. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7420. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7421. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7422. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7423. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7424. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7425. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7426. /* Parent closes only one side of the pipes.
  7427. * If we don't mark them as closed, close() attempt before
  7428. * return from this function throws an exception on Windows.
  7429. * Windows does not like when closed descriptor is closed again. */
  7430. (void)close(fdin[0]);
  7431. (void)close(fdout[1]);
  7432. (void)close(fderr[1]);
  7433. fdin[0] = fdout[1] = fderr[1] = -1;
  7434. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7435. status = strerror(ERRNO);
  7436. mg_cry(conn,
  7437. "Error: CGI program \"%s\": Can not open stdin: %s",
  7438. prog,
  7439. status);
  7440. send_http_error(conn,
  7441. 500,
  7442. "Error: CGI can not open fdin\nfopen: %s",
  7443. status);
  7444. goto done;
  7445. }
  7446. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7447. status = strerror(ERRNO);
  7448. mg_cry(conn,
  7449. "Error: CGI program \"%s\": Can not open stdout: %s",
  7450. prog,
  7451. status);
  7452. send_http_error(conn,
  7453. 500,
  7454. "Error: CGI can not open fdout\nfopen: %s",
  7455. status);
  7456. goto done;
  7457. }
  7458. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7459. status = strerror(ERRNO);
  7460. mg_cry(conn,
  7461. "Error: CGI program \"%s\": Can not open stderr: %s",
  7462. prog,
  7463. status);
  7464. send_http_error(conn,
  7465. 500,
  7466. "Error: CGI can not open fdout\nfopen: %s",
  7467. status);
  7468. goto done;
  7469. }
  7470. setbuf(in, NULL);
  7471. setbuf(out, NULL);
  7472. setbuf(err, NULL);
  7473. fout.access.fp = out;
  7474. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7475. /* This is a POST/PUT request, or another request with body data. */
  7476. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7477. /* Error sending the body data */
  7478. mg_cry(conn,
  7479. "Error: CGI program \"%s\": Forward body data failed",
  7480. prog);
  7481. goto done;
  7482. }
  7483. }
  7484. /* Close so child gets an EOF. */
  7485. fclose(in);
  7486. in = NULL;
  7487. fdin[1] = -1;
  7488. /* Now read CGI reply into a buffer. We need to set correct
  7489. * status code, thus we need to see all HTTP headers first.
  7490. * Do not send anything back to client, until we buffer in all
  7491. * HTTP headers. */
  7492. data_len = 0;
  7493. buf = (char *)mg_malloc(buflen);
  7494. if (buf == NULL) {
  7495. send_http_error(conn,
  7496. 500,
  7497. "Error: Not enough memory for CGI buffer (%u bytes)",
  7498. (unsigned int)buflen);
  7499. mg_cry(conn,
  7500. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7501. "bytes)",
  7502. prog,
  7503. (unsigned int)buflen);
  7504. goto done;
  7505. }
  7506. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7507. if (headers_len <= 0) {
  7508. /* Could not parse the CGI response. Check if some error message on
  7509. * stderr. */
  7510. i = pull_all(err, conn, buf, (int)buflen);
  7511. if (i > 0) {
  7512. mg_cry(conn,
  7513. "Error: CGI program \"%s\" sent error "
  7514. "message: [%.*s]",
  7515. prog,
  7516. i,
  7517. buf);
  7518. send_http_error(conn,
  7519. 500,
  7520. "Error: CGI program \"%s\" sent error "
  7521. "message: [%.*s]",
  7522. prog,
  7523. i,
  7524. buf);
  7525. } else {
  7526. mg_cry(conn,
  7527. "Error: CGI program sent malformed or too big "
  7528. "(>%u bytes) HTTP headers: [%.*s]",
  7529. (unsigned)buflen,
  7530. data_len,
  7531. buf);
  7532. send_http_error(conn,
  7533. 500,
  7534. "Error: CGI program sent malformed or too big "
  7535. "(>%u bytes) HTTP headers: [%.*s]",
  7536. (unsigned)buflen,
  7537. data_len,
  7538. buf);
  7539. }
  7540. goto done;
  7541. }
  7542. pbuf = buf;
  7543. buf[headers_len - 1] = '\0';
  7544. parse_http_headers(&pbuf, &ri);
  7545. /* Make up and send the status line */
  7546. status_text = "OK";
  7547. if ((status = get_header(&ri, "Status")) != NULL) {
  7548. conn->status_code = atoi(status);
  7549. status_text = status;
  7550. while (isdigit(*(const unsigned char *)status_text)
  7551. || *status_text == ' ') {
  7552. status_text++;
  7553. }
  7554. } else if (get_header(&ri, "Location") != NULL) {
  7555. conn->status_code = 302;
  7556. } else {
  7557. conn->status_code = 200;
  7558. }
  7559. connection_state = get_header(&ri, "Connection");
  7560. if (!header_has_option(connection_state, "keep-alive")) {
  7561. conn->must_close = 1;
  7562. }
  7563. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7564. /* Send headers */
  7565. for (i = 0; i < ri.num_headers; i++) {
  7566. mg_printf(conn,
  7567. "%s: %s\r\n",
  7568. ri.http_headers[i].name,
  7569. ri.http_headers[i].value);
  7570. }
  7571. mg_write(conn, "\r\n", 2);
  7572. /* Send chunk of data that may have been read after the headers */
  7573. conn->num_bytes_sent +=
  7574. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7575. /* Read the rest of CGI output and send to the client */
  7576. send_file_data(conn, &fout, 0, INT64_MAX);
  7577. done:
  7578. mg_free(blk.var);
  7579. mg_free(blk.buf);
  7580. if (pid != (pid_t)-1) {
  7581. kill(pid, SIGKILL);
  7582. #if !defined(_WIN32)
  7583. {
  7584. int st;
  7585. while (waitpid(pid, &st, 0) != -1)
  7586. ; /* clean zombies */
  7587. }
  7588. #endif
  7589. }
  7590. if (fdin[0] != -1) {
  7591. close(fdin[0]);
  7592. }
  7593. if (fdout[1] != -1) {
  7594. close(fdout[1]);
  7595. }
  7596. if (in != NULL) {
  7597. fclose(in);
  7598. } else if (fdin[1] != -1) {
  7599. close(fdin[1]);
  7600. }
  7601. if (out != NULL) {
  7602. fclose(out);
  7603. } else if (fdout[0] != -1) {
  7604. close(fdout[0]);
  7605. }
  7606. if (err != NULL) {
  7607. fclose(err);
  7608. } else if (fderr[0] != -1) {
  7609. close(fderr[0]);
  7610. }
  7611. if (buf != NULL) {
  7612. mg_free(buf);
  7613. }
  7614. }
  7615. #endif /* !NO_CGI */
  7616. #if !defined(NO_FILES)
  7617. static void
  7618. mkcol(struct mg_connection *conn, const char *path)
  7619. {
  7620. int rc, body_len;
  7621. struct de de;
  7622. char date[64];
  7623. time_t curtime = time(NULL);
  7624. if (conn == NULL) {
  7625. return;
  7626. }
  7627. /* TODO (mid): Check the send_http_error situations in this function */
  7628. memset(&de.file, 0, sizeof(de.file));
  7629. if (!mg_stat(conn, path, &de.file)) {
  7630. mg_cry(conn,
  7631. "%s: mg_stat(%s) failed: %s",
  7632. __func__,
  7633. path,
  7634. strerror(ERRNO));
  7635. }
  7636. if (de.file.last_modified) {
  7637. /* TODO (mid): This check does not seem to make any sense ! */
  7638. /* TODO (mid): Add a webdav unit test first, before changing
  7639. * anything here. */
  7640. send_http_error(
  7641. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7642. return;
  7643. }
  7644. body_len = conn->data_len - conn->request_len;
  7645. if (body_len > 0) {
  7646. send_http_error(
  7647. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7648. return;
  7649. }
  7650. rc = mg_mkdir(conn, path, 0755);
  7651. if (rc == 0) {
  7652. conn->status_code = 201;
  7653. gmt_time_string(date, sizeof(date), &curtime);
  7654. mg_printf(conn,
  7655. "HTTP/1.1 %d Created\r\n"
  7656. "Date: %s\r\n",
  7657. conn->status_code,
  7658. date);
  7659. send_static_cache_header(conn);
  7660. send_additional_header(conn);
  7661. mg_printf(conn,
  7662. "Content-Length: 0\r\n"
  7663. "Connection: %s\r\n\r\n",
  7664. suggest_connection_header(conn));
  7665. } else if (rc == -1) {
  7666. if (errno == EEXIST) {
  7667. send_http_error(
  7668. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7669. } else if (errno == EACCES) {
  7670. send_http_error(
  7671. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7672. } else if (errno == ENOENT) {
  7673. send_http_error(
  7674. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7675. } else {
  7676. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7677. }
  7678. }
  7679. }
  7680. static void
  7681. put_file(struct mg_connection *conn, const char *path)
  7682. {
  7683. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7684. const char *range;
  7685. int64_t r1, r2;
  7686. int rc;
  7687. char date[64];
  7688. time_t curtime = time(NULL);
  7689. if (conn == NULL) {
  7690. return;
  7691. }
  7692. if (mg_stat(conn, path, &file.stat)) {
  7693. /* File already exists */
  7694. conn->status_code = 200;
  7695. if (file.stat.is_directory) {
  7696. /* This is an already existing directory,
  7697. * so there is nothing to do for the server. */
  7698. rc = 0;
  7699. } else {
  7700. /* File exists and is not a directory. */
  7701. /* Can it be replaced? */
  7702. if (file.access.membuf != NULL) {
  7703. /* This is an "in-memory" file, that can not be replaced */
  7704. send_http_error(
  7705. conn,
  7706. 405,
  7707. "Error: Put not possible\nReplacing %s is not supported",
  7708. path);
  7709. return;
  7710. }
  7711. /* Check if the server may write this file */
  7712. if (access(path, W_OK) == 0) {
  7713. /* Access granted */
  7714. conn->status_code = 200;
  7715. rc = 1;
  7716. } else {
  7717. send_http_error(
  7718. conn,
  7719. 403,
  7720. "Error: Put not possible\nReplacing %s is not allowed",
  7721. path);
  7722. return;
  7723. }
  7724. }
  7725. } else {
  7726. /* File should be created */
  7727. conn->status_code = 201;
  7728. rc = put_dir(conn, path);
  7729. }
  7730. if (rc == 0) {
  7731. /* put_dir returns 0 if path is a directory */
  7732. gmt_time_string(date, sizeof(date), &curtime);
  7733. mg_printf(conn,
  7734. "HTTP/1.1 %d %s\r\n",
  7735. conn->status_code,
  7736. mg_get_response_code_text(NULL, conn->status_code));
  7737. send_no_cache_header(conn);
  7738. send_additional_header(conn);
  7739. mg_printf(conn,
  7740. "Date: %s\r\n"
  7741. "Content-Length: 0\r\n"
  7742. "Connection: %s\r\n\r\n",
  7743. date,
  7744. suggest_connection_header(conn));
  7745. /* Request to create a directory has been fulfilled successfully.
  7746. * No need to put a file. */
  7747. return;
  7748. }
  7749. if (rc == -1) {
  7750. /* put_dir returns -1 if the path is too long */
  7751. send_http_error(conn,
  7752. 414,
  7753. "Error: Path too long\nput_dir(%s): %s",
  7754. path,
  7755. strerror(ERRNO));
  7756. return;
  7757. }
  7758. if (rc == -2) {
  7759. /* put_dir returns -2 if the directory can not be created */
  7760. send_http_error(conn,
  7761. 500,
  7762. "Error: Can not create directory\nput_dir(%s): %s",
  7763. path,
  7764. strerror(ERRNO));
  7765. return;
  7766. }
  7767. /* A file should be created or overwritten. */
  7768. /* Currently CivetWeb does not nead read+write access. */
  7769. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7770. || file.access.fp == NULL) {
  7771. (void)mg_fclose(&file.access);
  7772. send_http_error(conn,
  7773. 500,
  7774. "Error: Can not create file\nfopen(%s): %s",
  7775. path,
  7776. strerror(ERRNO));
  7777. return;
  7778. }
  7779. fclose_on_exec(&file.access, conn);
  7780. range = mg_get_header(conn, "Content-Range");
  7781. r1 = r2 = 0;
  7782. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7783. conn->status_code = 206; /* Partial content */
  7784. fseeko(file.access.fp, r1, SEEK_SET);
  7785. }
  7786. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7787. /* forward_body_data failed.
  7788. * The error code has already been sent to the client,
  7789. * and conn->status_code is already set. */
  7790. (void)mg_fclose(&file.access);
  7791. return;
  7792. }
  7793. if (mg_fclose(&file.access) != 0) {
  7794. /* fclose failed. This might have different reasons, but a likely
  7795. * one is "no space on disk", http 507. */
  7796. conn->status_code = 507;
  7797. }
  7798. gmt_time_string(date, sizeof(date), &curtime);
  7799. mg_printf(conn,
  7800. "HTTP/1.1 %d %s\r\n",
  7801. conn->status_code,
  7802. mg_get_response_code_text(NULL, conn->status_code));
  7803. send_no_cache_header(conn);
  7804. send_additional_header(conn);
  7805. mg_printf(conn,
  7806. "Date: %s\r\n"
  7807. "Content-Length: 0\r\n"
  7808. "Connection: %s\r\n\r\n",
  7809. date,
  7810. suggest_connection_header(conn));
  7811. }
  7812. static void
  7813. delete_file(struct mg_connection *conn, const char *path)
  7814. {
  7815. struct de de;
  7816. memset(&de.file, 0, sizeof(de.file));
  7817. if (!mg_stat(conn, path, &de.file)) {
  7818. /* mg_stat returns 0 if the file does not exist */
  7819. send_http_error(conn,
  7820. 404,
  7821. "Error: Cannot delete file\nFile %s not found",
  7822. path);
  7823. return;
  7824. }
  7825. #if 0 /* Ignore if a file in memory is inside a folder */
  7826. if (de.access.membuf != NULL) {
  7827. /* the file is cached in memory */
  7828. send_http_error(
  7829. conn,
  7830. 405,
  7831. "Error: Delete not possible\nDeleting %s is not supported",
  7832. path);
  7833. return;
  7834. }
  7835. #endif
  7836. if (de.file.is_directory) {
  7837. if (remove_directory(conn, path)) {
  7838. /* Delete is successful: Return 204 without content. */
  7839. send_http_error(conn, 204, "%s", "");
  7840. } else {
  7841. /* Delete is not successful: Return 500 (Server error). */
  7842. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7843. }
  7844. return;
  7845. }
  7846. /* This is an existing file (not a directory).
  7847. * Check if write permission is granted. */
  7848. if (access(path, W_OK) != 0) {
  7849. /* File is read only */
  7850. send_http_error(
  7851. conn,
  7852. 403,
  7853. "Error: Delete not possible\nDeleting %s is not allowed",
  7854. path);
  7855. return;
  7856. }
  7857. /* Try to delete it. */
  7858. if (mg_remove(conn, path) == 0) {
  7859. /* Delete was successful: Return 204 without content. */
  7860. send_http_error(conn, 204, "%s", "");
  7861. } else {
  7862. /* Delete not successful (file locked). */
  7863. send_http_error(conn,
  7864. 423,
  7865. "Error: Cannot delete file\nremove(%s): %s",
  7866. path,
  7867. strerror(ERRNO));
  7868. }
  7869. }
  7870. #endif /* !NO_FILES */
  7871. static void
  7872. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7873. static void
  7874. do_ssi_include(struct mg_connection *conn,
  7875. const char *ssi,
  7876. char *tag,
  7877. int include_level)
  7878. {
  7879. char file_name[MG_BUF_LEN], path[512], *p;
  7880. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7881. size_t len;
  7882. int truncated = 0;
  7883. if (conn == NULL) {
  7884. return;
  7885. }
  7886. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7887. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7888. * always < MG_BUF_LEN. */
  7889. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7890. /* File name is relative to the webserver root */
  7891. file_name[511] = 0;
  7892. (void)mg_snprintf(conn,
  7893. &truncated,
  7894. path,
  7895. sizeof(path),
  7896. "%s/%s",
  7897. conn->ctx->config[DOCUMENT_ROOT],
  7898. file_name);
  7899. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7900. /* File name is relative to the webserver working directory
  7901. * or it is absolute system path */
  7902. file_name[511] = 0;
  7903. (void)
  7904. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7905. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7906. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7907. /* File name is relative to the currect document */
  7908. file_name[511] = 0;
  7909. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7910. if (!truncated) {
  7911. if ((p = strrchr(path, '/')) != NULL) {
  7912. p[1] = '\0';
  7913. }
  7914. len = strlen(path);
  7915. (void)mg_snprintf(conn,
  7916. &truncated,
  7917. path + len,
  7918. sizeof(path) - len,
  7919. "%s",
  7920. file_name);
  7921. }
  7922. } else {
  7923. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7924. return;
  7925. }
  7926. if (truncated) {
  7927. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7928. return;
  7929. }
  7930. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7931. mg_cry(conn,
  7932. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7933. tag,
  7934. path,
  7935. strerror(ERRNO));
  7936. } else {
  7937. fclose_on_exec(&file.access, conn);
  7938. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7939. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7940. path) > 0) {
  7941. send_ssi_file(conn, path, &file, include_level + 1);
  7942. } else {
  7943. send_file_data(conn, &file, 0, INT64_MAX);
  7944. }
  7945. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7946. }
  7947. }
  7948. #if !defined(NO_POPEN)
  7949. static void
  7950. do_ssi_exec(struct mg_connection *conn, char *tag)
  7951. {
  7952. char cmd[1024] = "";
  7953. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7954. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7955. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7956. } else {
  7957. cmd[1023] = 0;
  7958. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  7959. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7960. } else {
  7961. send_file_data(conn, &file, 0, INT64_MAX);
  7962. pclose(file.access.fp);
  7963. }
  7964. }
  7965. }
  7966. #endif /* !NO_POPEN */
  7967. static int
  7968. mg_fgetc(struct mg_file *filep, int offset)
  7969. {
  7970. if (filep == NULL) {
  7971. return EOF;
  7972. }
  7973. if (filep->access.membuf != NULL && offset >= 0
  7974. && ((unsigned int)(offset)) < filep->stat.size) {
  7975. return ((const unsigned char *)filep->access.membuf)[offset];
  7976. } else if (filep->access.fp != NULL) {
  7977. return fgetc(filep->access.fp);
  7978. } else {
  7979. return EOF;
  7980. }
  7981. }
  7982. static void
  7983. send_ssi_file(struct mg_connection *conn,
  7984. const char *path,
  7985. struct mg_file *filep,
  7986. int include_level)
  7987. {
  7988. char buf[MG_BUF_LEN];
  7989. int ch, offset, len, in_ssi_tag;
  7990. if (include_level > 10) {
  7991. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7992. return;
  7993. }
  7994. in_ssi_tag = len = offset = 0;
  7995. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7996. if (in_ssi_tag && ch == '>') {
  7997. in_ssi_tag = 0;
  7998. buf[len++] = (char)ch;
  7999. buf[len] = '\0';
  8000. /* assert(len <= (int) sizeof(buf)); */
  8001. if (len > (int)sizeof(buf)) {
  8002. break;
  8003. }
  8004. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  8005. /* Not an SSI tag, pass it */
  8006. (void)mg_write(conn, buf, (size_t)len);
  8007. } else {
  8008. if (!memcmp(buf + 5, "include", 7)) {
  8009. do_ssi_include(conn, path, buf + 12, include_level);
  8010. #if !defined(NO_POPEN)
  8011. } else if (!memcmp(buf + 5, "exec", 4)) {
  8012. do_ssi_exec(conn, buf + 9);
  8013. #endif /* !NO_POPEN */
  8014. } else {
  8015. mg_cry(conn,
  8016. "%s: unknown SSI "
  8017. "command: \"%s\"",
  8018. path,
  8019. buf);
  8020. }
  8021. }
  8022. len = 0;
  8023. } else if (in_ssi_tag) {
  8024. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8025. /* Not an SSI tag */
  8026. in_ssi_tag = 0;
  8027. } else if (len == (int)sizeof(buf) - 2) {
  8028. mg_cry(conn, "%s: SSI tag is too large", path);
  8029. len = 0;
  8030. }
  8031. buf[len++] = (char)(ch & 0xff);
  8032. } else if (ch == '<') {
  8033. in_ssi_tag = 1;
  8034. if (len > 0) {
  8035. mg_write(conn, buf, (size_t)len);
  8036. }
  8037. len = 0;
  8038. buf[len++] = (char)(ch & 0xff);
  8039. } else {
  8040. buf[len++] = (char)(ch & 0xff);
  8041. if (len == (int)sizeof(buf)) {
  8042. mg_write(conn, buf, (size_t)len);
  8043. len = 0;
  8044. }
  8045. }
  8046. }
  8047. /* Send the rest of buffered data */
  8048. if (len > 0) {
  8049. mg_write(conn, buf, (size_t)len);
  8050. }
  8051. }
  8052. static void
  8053. handle_ssi_file_request(struct mg_connection *conn,
  8054. const char *path,
  8055. struct mg_file *filep)
  8056. {
  8057. char date[64];
  8058. time_t curtime = time(NULL);
  8059. const char *cors1, *cors2, *cors3;
  8060. if (conn == NULL || path == NULL || filep == NULL) {
  8061. return;
  8062. }
  8063. if (mg_get_header(conn, "Origin")) {
  8064. /* Cross-origin resource sharing (CORS). */
  8065. cors1 = "Access-Control-Allow-Origin: ";
  8066. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8067. cors3 = "\r\n";
  8068. } else {
  8069. cors1 = cors2 = cors3 = "";
  8070. }
  8071. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8072. /* File exists (precondition for calling this function),
  8073. * but can not be opened by the server. */
  8074. send_http_error(conn,
  8075. 500,
  8076. "Error: Cannot read file\nfopen(%s): %s",
  8077. path,
  8078. strerror(ERRNO));
  8079. } else {
  8080. conn->must_close = 1;
  8081. gmt_time_string(date, sizeof(date), &curtime);
  8082. fclose_on_exec(&filep->access, conn);
  8083. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8084. send_no_cache_header(conn);
  8085. send_additional_header(conn);
  8086. mg_printf(conn,
  8087. "%s%s%s"
  8088. "Date: %s\r\n"
  8089. "Content-Type: text/html\r\n"
  8090. "Connection: %s\r\n\r\n",
  8091. cors1,
  8092. cors2,
  8093. cors3,
  8094. date,
  8095. suggest_connection_header(conn));
  8096. send_ssi_file(conn, path, filep, 0);
  8097. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8098. }
  8099. }
  8100. #if !defined(NO_FILES)
  8101. static void
  8102. send_options(struct mg_connection *conn)
  8103. {
  8104. char date[64];
  8105. time_t curtime = time(NULL);
  8106. if (!conn) {
  8107. return;
  8108. }
  8109. conn->status_code = 200;
  8110. conn->must_close = 1;
  8111. gmt_time_string(date, sizeof(date), &curtime);
  8112. /* We do not set a "Cache-Control" header here, but leave the default.
  8113. * Since browsers do not send an OPTIONS request, we can not test the
  8114. * effect anyway. */
  8115. mg_printf(conn,
  8116. "HTTP/1.1 200 OK\r\n"
  8117. "Date: %s\r\n"
  8118. "Connection: %s\r\n"
  8119. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8120. "PROPFIND, MKCOL\r\n"
  8121. "DAV: 1\r\n",
  8122. date,
  8123. suggest_connection_header(conn));
  8124. send_additional_header(conn);
  8125. mg_printf(conn, "\r\n");
  8126. }
  8127. /* Writes PROPFIND properties for a collection element */
  8128. static void
  8129. print_props(struct mg_connection *conn,
  8130. const char *uri,
  8131. struct mg_file_stat *filep)
  8132. {
  8133. char mtime[64];
  8134. if (conn == NULL || uri == NULL || filep == NULL) {
  8135. return;
  8136. }
  8137. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8138. conn->num_bytes_sent +=
  8139. mg_printf(conn,
  8140. "<d:response>"
  8141. "<d:href>%s</d:href>"
  8142. "<d:propstat>"
  8143. "<d:prop>"
  8144. "<d:resourcetype>%s</d:resourcetype>"
  8145. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8146. "<d:getlastmodified>%s</d:getlastmodified>"
  8147. "</d:prop>"
  8148. "<d:status>HTTP/1.1 200 OK</d:status>"
  8149. "</d:propstat>"
  8150. "</d:response>\n",
  8151. uri,
  8152. filep->is_directory ? "<d:collection/>" : "",
  8153. filep->size,
  8154. mtime);
  8155. }
  8156. static void
  8157. print_dav_dir_entry(struct de *de, void *data)
  8158. {
  8159. char href[PATH_MAX];
  8160. char href_encoded[PATH_MAX * 3 /* worst case */];
  8161. int truncated;
  8162. struct mg_connection *conn = (struct mg_connection *)data;
  8163. if (!de || !conn) {
  8164. return;
  8165. }
  8166. mg_snprintf(conn,
  8167. &truncated,
  8168. href,
  8169. sizeof(href),
  8170. "%s%s",
  8171. conn->request_info.local_uri,
  8172. de->file_name);
  8173. if (!truncated) {
  8174. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8175. print_props(conn, href_encoded, &de->file);
  8176. }
  8177. }
  8178. static void
  8179. handle_propfind(struct mg_connection *conn,
  8180. const char *path,
  8181. struct mg_file_stat *filep)
  8182. {
  8183. const char *depth = mg_get_header(conn, "Depth");
  8184. char date[64];
  8185. time_t curtime = time(NULL);
  8186. gmt_time_string(date, sizeof(date), &curtime);
  8187. if (!conn || !path || !filep || !conn->ctx) {
  8188. return;
  8189. }
  8190. conn->must_close = 1;
  8191. conn->status_code = 207;
  8192. mg_printf(conn,
  8193. "HTTP/1.1 207 Multi-Status\r\n"
  8194. "Date: %s\r\n",
  8195. date);
  8196. send_static_cache_header(conn);
  8197. send_additional_header(conn);
  8198. mg_printf(conn,
  8199. "Connection: %s\r\n"
  8200. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8201. suggest_connection_header(conn));
  8202. conn->num_bytes_sent +=
  8203. mg_printf(conn,
  8204. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8205. "<d:multistatus xmlns:d='DAV:'>\n");
  8206. /* Print properties for the requested resource itself */
  8207. print_props(conn, conn->request_info.local_uri, filep);
  8208. /* If it is a directory, print directory entries too if Depth is not 0 */
  8209. if (filep && filep->is_directory
  8210. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8211. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8212. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8213. }
  8214. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8215. }
  8216. #endif
  8217. void
  8218. mg_lock_connection(struct mg_connection *conn)
  8219. {
  8220. if (conn) {
  8221. (void)pthread_mutex_lock(&conn->mutex);
  8222. }
  8223. }
  8224. void
  8225. mg_unlock_connection(struct mg_connection *conn)
  8226. {
  8227. if (conn) {
  8228. (void)pthread_mutex_unlock(&conn->mutex);
  8229. }
  8230. }
  8231. void
  8232. mg_lock_context(struct mg_context *ctx)
  8233. {
  8234. if (ctx) {
  8235. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8236. }
  8237. }
  8238. void
  8239. mg_unlock_context(struct mg_context *ctx)
  8240. {
  8241. if (ctx) {
  8242. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8243. }
  8244. }
  8245. #if defined(USE_TIMERS)
  8246. #include "timer.inl"
  8247. #endif /* USE_TIMERS */
  8248. #ifdef USE_LUA
  8249. #include "mod_lua.inl"
  8250. #endif /* USE_LUA */
  8251. #ifdef USE_DUKTAPE
  8252. #include "mod_duktape.inl"
  8253. #endif /* USE_DUKTAPE */
  8254. #if defined(USE_WEBSOCKET)
  8255. #if !defined(NO_SSL_DL)
  8256. #define SHA_API static
  8257. #include "sha1.inl"
  8258. #endif
  8259. static int
  8260. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8261. {
  8262. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8263. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8264. SHA_CTX sha_ctx;
  8265. int truncated;
  8266. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8267. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8268. if (truncated) {
  8269. conn->must_close = 1;
  8270. return 0;
  8271. }
  8272. SHA1_Init(&sha_ctx);
  8273. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8274. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8275. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8276. mg_printf(conn,
  8277. "HTTP/1.1 101 Switching Protocols\r\n"
  8278. "Upgrade: websocket\r\n"
  8279. "Connection: Upgrade\r\n"
  8280. "Sec-WebSocket-Accept: %s\r\n",
  8281. b64_sha);
  8282. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8283. mg_printf(conn,
  8284. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8285. conn->request_info.acceptedWebSocketSubprotocol);
  8286. } else {
  8287. mg_printf(conn, "%s", "\r\n");
  8288. }
  8289. return 1;
  8290. }
  8291. static void
  8292. read_websocket(struct mg_connection *conn,
  8293. mg_websocket_data_handler ws_data_handler,
  8294. void *callback_data)
  8295. {
  8296. /* Pointer to the beginning of the portion of the incoming websocket
  8297. * message queue.
  8298. * The original websocket upgrade request is never removed, so the queue
  8299. * begins after it. */
  8300. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8301. int n, error, exit_by_callback;
  8302. /* body_len is the length of the entire queue in bytes
  8303. * len is the length of the current message
  8304. * data_len is the length of the current message's data payload
  8305. * header_len is the length of the current message's header */
  8306. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8307. /* "The masking key is a 32-bit value chosen at random by the client."
  8308. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8309. */
  8310. unsigned char mask[4];
  8311. /* data points to the place where the message is stored when passed to
  8312. * the
  8313. * websocket_data callback. This is either mem on the stack, or a
  8314. * dynamically allocated buffer if it is too large. */
  8315. unsigned char mem[4096];
  8316. unsigned char *data = mem;
  8317. unsigned char mop; /* mask flag and opcode */
  8318. double timeout = -1.0;
  8319. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8320. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8321. }
  8322. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8323. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8324. }
  8325. mg_set_thread_name("wsock");
  8326. /* Loop continuously, reading messages from the socket, invoking the
  8327. * callback, and waiting repeatedly until an error occurs. */
  8328. while (!conn->ctx->stop_flag) {
  8329. header_len = 0;
  8330. assert(conn->data_len >= conn->request_len);
  8331. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8332. len = buf[1] & 127;
  8333. mask_len = (buf[1] & 128) ? 4 : 0;
  8334. if ((len < 126) && (body_len >= mask_len)) {
  8335. data_len = len;
  8336. header_len = 2 + mask_len;
  8337. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8338. header_len = 4 + mask_len;
  8339. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8340. } else if (body_len >= (10 + mask_len)) {
  8341. header_len = 10 + mask_len;
  8342. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8343. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8344. }
  8345. }
  8346. if (header_len > 0 && body_len >= header_len) {
  8347. /* Allocate space to hold websocket payload */
  8348. data = mem;
  8349. if (data_len > sizeof(mem)) {
  8350. data = (unsigned char *)mg_malloc(data_len);
  8351. if (data == NULL) {
  8352. /* Allocation failed, exit the loop and then close the
  8353. * connection */
  8354. mg_cry(conn, "websocket out of memory; closing connection");
  8355. break;
  8356. }
  8357. }
  8358. /* Copy the mask before we shift the queue and destroy it */
  8359. if (mask_len > 0) {
  8360. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8361. } else {
  8362. memset(mask, 0, sizeof(mask));
  8363. }
  8364. /* Read frame payload from the first message in the queue into
  8365. * data and advance the queue by moving the memory in place. */
  8366. assert(body_len >= header_len);
  8367. if (data_len + header_len > body_len) {
  8368. mop = buf[0]; /* current mask and opcode */
  8369. /* Overflow case */
  8370. len = body_len - header_len;
  8371. memcpy(data, buf + header_len, len);
  8372. error = 0;
  8373. while (len < data_len) {
  8374. n = pull(NULL,
  8375. conn,
  8376. (char *)(data + len),
  8377. (int)(data_len - len),
  8378. timeout);
  8379. if (n <= 0) {
  8380. error = 1;
  8381. break;
  8382. }
  8383. len += (size_t)n;
  8384. }
  8385. if (error) {
  8386. mg_cry(conn, "Websocket pull failed; closing connection");
  8387. break;
  8388. }
  8389. conn->data_len = conn->request_len;
  8390. } else {
  8391. mop = buf[0]; /* current mask and opcode, overwritten by
  8392. * memmove() */
  8393. /* Length of the message being read at the front of the
  8394. * queue */
  8395. len = data_len + header_len;
  8396. /* Copy the data payload into the data pointer for the
  8397. * callback */
  8398. memcpy(data, buf + header_len, data_len);
  8399. /* Move the queue forward len bytes */
  8400. memmove(buf, buf + len, body_len - len);
  8401. /* Mark the queue as advanced */
  8402. conn->data_len -= (int)len;
  8403. }
  8404. /* Apply mask if necessary */
  8405. if (mask_len > 0) {
  8406. for (i = 0; i < data_len; ++i) {
  8407. data[i] ^= mask[i & 3];
  8408. }
  8409. }
  8410. /* Exit the loop if callback signals to exit (server side),
  8411. * or "connection close" opcode received (client side). */
  8412. exit_by_callback = 0;
  8413. if ((ws_data_handler != NULL)
  8414. && !ws_data_handler(
  8415. conn, mop, (char *)data, data_len, callback_data)) {
  8416. exit_by_callback = 1;
  8417. }
  8418. if (data != mem) {
  8419. mg_free(data);
  8420. }
  8421. if (exit_by_callback
  8422. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8423. /* Opcode == 8, connection close */
  8424. break;
  8425. }
  8426. /* Not breaking the loop, process next websocket frame. */
  8427. } else {
  8428. /* Read from the socket into the next available location in the
  8429. * message queue. */
  8430. if ((n = pull(NULL,
  8431. conn,
  8432. conn->buf + conn->data_len,
  8433. conn->buf_size - conn->data_len,
  8434. timeout)) <= 0) {
  8435. /* Error, no bytes read */
  8436. break;
  8437. }
  8438. conn->data_len += n;
  8439. }
  8440. }
  8441. mg_set_thread_name("worker");
  8442. }
  8443. static int
  8444. mg_websocket_write_exec(struct mg_connection *conn,
  8445. int opcode,
  8446. const char *data,
  8447. size_t dataLen,
  8448. uint32_t masking_key)
  8449. {
  8450. unsigned char header[14];
  8451. size_t headerLen = 1;
  8452. int retval = -1;
  8453. #if defined(__GNUC__) || defined(__MINGW32__)
  8454. /* Disable spurious conversion warning for GCC */
  8455. #pragma GCC diagnostic push
  8456. #pragma GCC diagnostic ignored "-Wconversion"
  8457. #endif
  8458. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8459. #if defined(__GNUC__) || defined(__MINGW32__)
  8460. #pragma GCC diagnostic pop
  8461. #endif
  8462. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8463. if (dataLen < 126) {
  8464. /* inline 7-bit length field */
  8465. header[1] = (unsigned char)dataLen;
  8466. headerLen = 2;
  8467. } else if (dataLen <= 0xFFFF) {
  8468. /* 16-bit length field */
  8469. uint16_t len = htons((uint16_t)dataLen);
  8470. header[1] = 126;
  8471. memcpy(header + 2, &len, 2);
  8472. headerLen = 4;
  8473. } else {
  8474. /* 64-bit length field */
  8475. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8476. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8477. header[1] = 127;
  8478. memcpy(header + 2, &len1, 4);
  8479. memcpy(header + 6, &len2, 4);
  8480. headerLen = 10;
  8481. }
  8482. if (masking_key) {
  8483. /* add mask */
  8484. header[1] |= 0x80;
  8485. memcpy(header + headerLen, &masking_key, 4);
  8486. headerLen += 4;
  8487. }
  8488. /* Note that POSIX/Winsock's send() is threadsafe
  8489. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8490. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8491. * push(), although that is only a problem if the packet is large or
  8492. * outgoing buffer is full). */
  8493. (void)mg_lock_connection(conn);
  8494. retval = mg_write(conn, header, headerLen);
  8495. if (dataLen > 0) {
  8496. retval = mg_write(conn, data, dataLen);
  8497. }
  8498. mg_unlock_connection(conn);
  8499. return retval;
  8500. }
  8501. int
  8502. mg_websocket_write(struct mg_connection *conn,
  8503. int opcode,
  8504. const char *data,
  8505. size_t dataLen)
  8506. {
  8507. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8508. }
  8509. static void
  8510. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8511. {
  8512. size_t i = 0;
  8513. i = 0;
  8514. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8515. /* Convert in 32 bit words, if data is 4 byte aligned */
  8516. while (i < (in_len - 3)) {
  8517. *(uint32_t *)(void *)(out + i) =
  8518. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8519. i += 4;
  8520. }
  8521. }
  8522. if (i != in_len) {
  8523. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8524. while (i < in_len) {
  8525. *(uint8_t *)(void *)(out + i) =
  8526. *(uint8_t *)(void *)(in + i)
  8527. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8528. i++;
  8529. }
  8530. }
  8531. }
  8532. int
  8533. mg_websocket_client_write(struct mg_connection *conn,
  8534. int opcode,
  8535. const char *data,
  8536. size_t dataLen)
  8537. {
  8538. int retval = -1;
  8539. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8540. uint32_t masking_key = (uint32_t)get_random();
  8541. if (masked_data == NULL) {
  8542. /* Return -1 in an error case */
  8543. mg_cry(conn,
  8544. "Cannot allocate buffer for masked websocket response: "
  8545. "Out of memory");
  8546. return -1;
  8547. }
  8548. mask_data(data, dataLen, masking_key, masked_data);
  8549. retval = mg_websocket_write_exec(
  8550. conn, opcode, masked_data, dataLen, masking_key);
  8551. mg_free(masked_data);
  8552. return retval;
  8553. }
  8554. static void
  8555. handle_websocket_request(struct mg_connection *conn,
  8556. const char *path,
  8557. int is_callback_resource,
  8558. struct mg_websocket_subprotocols *subprotocols,
  8559. mg_websocket_connect_handler ws_connect_handler,
  8560. mg_websocket_ready_handler ws_ready_handler,
  8561. mg_websocket_data_handler ws_data_handler,
  8562. mg_websocket_close_handler ws_close_handler,
  8563. void *cbData)
  8564. {
  8565. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8566. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8567. int lua_websock = 0;
  8568. #if !defined(USE_LUA)
  8569. (void)path;
  8570. #endif
  8571. /* Step 1: Check websocket protocol version. */
  8572. /* Step 1.1: Check Sec-WebSocket-Key. */
  8573. if (!websock_key) {
  8574. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8575. * requires a Sec-WebSocket-Key header.
  8576. */
  8577. /* It could be the hixie draft version
  8578. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8579. */
  8580. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8581. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8582. char key3[8];
  8583. if ((key1 != NULL) && (key2 != NULL)) {
  8584. /* This version uses 8 byte body data in a GET request */
  8585. conn->content_len = 8;
  8586. if (8 == mg_read(conn, key3, 8)) {
  8587. /* This is the hixie version */
  8588. send_http_error(conn,
  8589. 426,
  8590. "%s",
  8591. "Protocol upgrade to RFC 6455 required");
  8592. return;
  8593. }
  8594. }
  8595. /* This is an unknown version */
  8596. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8597. return;
  8598. }
  8599. /* Step 1.2: Check websocket protocol version. */
  8600. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8601. if (version == NULL || strcmp(version, "13") != 0) {
  8602. /* Reject wrong versions */
  8603. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8604. return;
  8605. }
  8606. /* Step 1.3: Could check for "Host", but we do not really nead this
  8607. * value for anything, so just ignore it. */
  8608. /* Step 2: If a callback is responsible, call it. */
  8609. if (is_callback_resource) {
  8610. /* Step 2.1 check and select subprotocol */
  8611. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8612. if (protocol && subprotocols) {
  8613. int idx;
  8614. unsigned long len;
  8615. const char *sep, *curSubProtocol,
  8616. *acceptedWebSocketSubprotocol = NULL;
  8617. /* look for matching subprotocol */
  8618. do {
  8619. sep = strchr(protocol, ',');
  8620. curSubProtocol = protocol;
  8621. len = sep ? (unsigned long)(sep - protocol)
  8622. : (unsigned long)strlen(protocol);
  8623. while (sep && isspace(*++sep)) {
  8624. ; /* ignore leading whitespaces */
  8625. }
  8626. protocol = sep;
  8627. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8628. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8629. && (strncmp(curSubProtocol,
  8630. subprotocols->subprotocols[idx],
  8631. len) == 0)) {
  8632. acceptedWebSocketSubprotocol =
  8633. subprotocols->subprotocols[idx];
  8634. break;
  8635. }
  8636. }
  8637. } while (sep && !acceptedWebSocketSubprotocol);
  8638. conn->request_info.acceptedWebSocketSubprotocol =
  8639. acceptedWebSocketSubprotocol;
  8640. } else if (protocol) {
  8641. /* keep legacy behavior */
  8642. /* The protocol is a comma seperated list of names. */
  8643. /* The server must only return one value from this list. */
  8644. /* First check if it is a list or just a single value. */
  8645. const char *sep = strrchr(protocol, ',');
  8646. if (sep == NULL) {
  8647. /* Just a single protocol -> accept it. */
  8648. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8649. } else {
  8650. /* Multiple protocols -> accept the last one. */
  8651. /* This is just a quick fix if the client offers multiple
  8652. * protocols. The handler should have a list of accepted
  8653. * protocols on his own
  8654. * and use it to select one protocol among those the client has
  8655. * offered.
  8656. */
  8657. while (isspace(*++sep)) {
  8658. ; /* ignore leading whitespaces */
  8659. }
  8660. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8661. }
  8662. }
  8663. if (ws_connect_handler != NULL
  8664. && ws_connect_handler(conn, cbData) != 0) {
  8665. /* C callback has returned non-zero, do not proceed with
  8666. * handshake.
  8667. */
  8668. /* Note that C callbacks are no longer called when Lua is
  8669. * responsible, so C can no longer filter callbacks for Lua. */
  8670. return;
  8671. }
  8672. }
  8673. #if defined(USE_LUA)
  8674. /* Step 3: No callback. Check if Lua is responsible. */
  8675. else {
  8676. /* Step 3.1: Check if Lua is responsible. */
  8677. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8678. lua_websock =
  8679. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8680. strlen(
  8681. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8682. path);
  8683. }
  8684. if (lua_websock) {
  8685. /* Step 3.2: Lua is responsible: call it. */
  8686. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8687. if (!conn->lua_websocket_state) {
  8688. /* Lua rejected the new client */
  8689. return;
  8690. }
  8691. }
  8692. }
  8693. #endif
  8694. /* Step 4: Check if there is a responsible websocket handler. */
  8695. if (!is_callback_resource && !lua_websock) {
  8696. /* There is no callback, and Lua is not responsible either. */
  8697. /* Reply with a 404 Not Found. We are still at a standard
  8698. * HTTP request here, before the websocket handshake, so
  8699. * we can still send standard HTTP error replies. */
  8700. send_http_error(conn, 404, "%s", "Not found");
  8701. return;
  8702. }
  8703. /* Step 5: The websocket connection has been accepted */
  8704. if (!send_websocket_handshake(conn, websock_key)) {
  8705. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8706. return;
  8707. }
  8708. /* Step 6: Call the ready handler */
  8709. if (is_callback_resource) {
  8710. if (ws_ready_handler != NULL) {
  8711. ws_ready_handler(conn, cbData);
  8712. }
  8713. #if defined(USE_LUA)
  8714. } else if (lua_websock) {
  8715. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8716. /* the ready handler returned false */
  8717. return;
  8718. }
  8719. #endif
  8720. }
  8721. /* Step 7: Enter the read loop */
  8722. if (is_callback_resource) {
  8723. read_websocket(conn, ws_data_handler, cbData);
  8724. #if defined(USE_LUA)
  8725. } else if (lua_websock) {
  8726. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8727. #endif
  8728. }
  8729. /* Step 8: Call the close handler */
  8730. if (ws_close_handler) {
  8731. ws_close_handler(conn, cbData);
  8732. }
  8733. }
  8734. static int
  8735. is_websocket_protocol(const struct mg_connection *conn)
  8736. {
  8737. const char *upgrade, *connection;
  8738. /* A websocket protocoll has the following HTTP headers:
  8739. *
  8740. * Connection: Upgrade
  8741. * Upgrade: Websocket
  8742. */
  8743. upgrade = mg_get_header(conn, "Upgrade");
  8744. if (upgrade == NULL) {
  8745. return 0; /* fail early, don't waste time checking other header
  8746. * fields
  8747. */
  8748. }
  8749. if (!mg_strcasestr(upgrade, "websocket")) {
  8750. return 0;
  8751. }
  8752. connection = mg_get_header(conn, "Connection");
  8753. if (connection == NULL) {
  8754. return 0;
  8755. }
  8756. if (!mg_strcasestr(connection, "upgrade")) {
  8757. return 0;
  8758. }
  8759. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8760. * "Sec-WebSocket-Version" are also required.
  8761. * Don't check them here, since even an unsupported websocket protocol
  8762. * request still IS a websocket request (in contrast to a standard HTTP
  8763. * request). It will fail later in handle_websocket_request.
  8764. */
  8765. return 1;
  8766. }
  8767. #endif /* !USE_WEBSOCKET */
  8768. static int
  8769. isbyte(int n)
  8770. {
  8771. return n >= 0 && n <= 255;
  8772. }
  8773. static int
  8774. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8775. {
  8776. int n, a, b, c, d, slash = 32, len = 0;
  8777. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8778. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8779. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8780. && slash < 33) {
  8781. len = n;
  8782. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8783. | (uint32_t)d;
  8784. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8785. }
  8786. return len;
  8787. }
  8788. static int
  8789. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8790. {
  8791. int throttle = 0;
  8792. struct vec vec, val;
  8793. uint32_t net, mask;
  8794. char mult;
  8795. double v;
  8796. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8797. mult = ',';
  8798. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8799. || (v < 0) || ((lowercase(&mult) != 'k')
  8800. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8801. continue;
  8802. }
  8803. v *= (lowercase(&mult) == 'k')
  8804. ? 1024
  8805. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8806. if (vec.len == 1 && vec.ptr[0] == '*') {
  8807. throttle = (int)v;
  8808. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8809. if ((remote_ip & mask) == net) {
  8810. throttle = (int)v;
  8811. }
  8812. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8813. throttle = (int)v;
  8814. }
  8815. }
  8816. return throttle;
  8817. }
  8818. static uint32_t
  8819. get_remote_ip(const struct mg_connection *conn)
  8820. {
  8821. if (!conn) {
  8822. return 0;
  8823. }
  8824. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8825. }
  8826. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8827. #include "handle_form.inl"
  8828. #if defined(MG_LEGACY_INTERFACE)
  8829. /* Implement the deprecated mg_upload function by calling the new
  8830. * mg_handle_form_request function. While mg_upload could only handle
  8831. * HTML forms sent as POST request in multipart/form-data format
  8832. * containing only file input elements, mg_handle_form_request can
  8833. * handle all form input elements and all standard request methods. */
  8834. struct mg_upload_user_data {
  8835. struct mg_connection *conn;
  8836. const char *destination_dir;
  8837. int num_uploaded_files;
  8838. };
  8839. /* Helper function for deprecated mg_upload. */
  8840. static int
  8841. mg_upload_field_found(const char *key,
  8842. const char *filename,
  8843. char *path,
  8844. size_t pathlen,
  8845. void *user_data)
  8846. {
  8847. int truncated = 0;
  8848. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8849. (void)key;
  8850. if (!filename) {
  8851. mg_cry(fud->conn, "%s: No filename set", __func__);
  8852. return FORM_FIELD_STORAGE_ABORT;
  8853. }
  8854. mg_snprintf(fud->conn,
  8855. &truncated,
  8856. path,
  8857. pathlen - 1,
  8858. "%s/%s",
  8859. fud->destination_dir,
  8860. filename);
  8861. if (!truncated) {
  8862. mg_cry(fud->conn, "%s: File path too long", __func__);
  8863. return FORM_FIELD_STORAGE_ABORT;
  8864. }
  8865. return FORM_FIELD_STORAGE_STORE;
  8866. }
  8867. /* Helper function for deprecated mg_upload. */
  8868. static int
  8869. mg_upload_field_get(const char *key,
  8870. const char *value,
  8871. size_t value_size,
  8872. void *user_data)
  8873. {
  8874. /* Function should never be called */
  8875. (void)key;
  8876. (void)value;
  8877. (void)value_size;
  8878. (void)user_data;
  8879. return 0;
  8880. }
  8881. /* Helper function for deprecated mg_upload. */
  8882. static int
  8883. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8884. {
  8885. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8886. (void)file_size;
  8887. fud->num_uploaded_files++;
  8888. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8889. return 0;
  8890. }
  8891. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8892. int
  8893. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8894. {
  8895. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8896. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8897. mg_upload_field_get,
  8898. mg_upload_field_stored,
  8899. 0};
  8900. int ret;
  8901. fdh.user_data = (void *)&fud;
  8902. ret = mg_handle_form_request(conn, &fdh);
  8903. if (ret < 0) {
  8904. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8905. }
  8906. return fud.num_uploaded_files;
  8907. }
  8908. #endif
  8909. static int
  8910. get_first_ssl_listener_index(const struct mg_context *ctx)
  8911. {
  8912. unsigned int i;
  8913. int idx = -1;
  8914. if (ctx) {
  8915. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8916. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8917. }
  8918. }
  8919. return idx;
  8920. }
  8921. static void
  8922. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8923. {
  8924. char host[1025];
  8925. const char *host_header;
  8926. size_t hostlen;
  8927. host_header = mg_get_header(conn, "Host");
  8928. hostlen = sizeof(host);
  8929. if (host_header != NULL) {
  8930. char *pos;
  8931. mg_strlcpy(host, host_header, hostlen);
  8932. host[hostlen - 1] = '\0';
  8933. pos = strchr(host, ':');
  8934. if (pos != NULL) {
  8935. *pos = '\0';
  8936. }
  8937. } else {
  8938. /* Cannot get host from the Host: header.
  8939. * Fallback to our IP address. */
  8940. if (conn) {
  8941. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8942. }
  8943. }
  8944. /* Send host, port, uri and (if it exists) ?query_string */
  8945. if (conn) {
  8946. mg_printf(conn,
  8947. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8948. host,
  8949. #if defined(USE_IPV6)
  8950. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8951. == AF_INET6)
  8952. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8953. .lsa.sin6.sin6_port)
  8954. :
  8955. #endif
  8956. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8957. .lsa.sin.sin_port),
  8958. conn->request_info.local_uri,
  8959. (conn->request_info.query_string == NULL) ? "" : "?",
  8960. (conn->request_info.query_string == NULL)
  8961. ? ""
  8962. : conn->request_info.query_string);
  8963. }
  8964. }
  8965. static void
  8966. mg_set_handler_type(struct mg_context *ctx,
  8967. const char *uri,
  8968. int handler_type,
  8969. int is_delete_request,
  8970. mg_request_handler handler,
  8971. struct mg_websocket_subprotocols *subprotocols,
  8972. mg_websocket_connect_handler connect_handler,
  8973. mg_websocket_ready_handler ready_handler,
  8974. mg_websocket_data_handler data_handler,
  8975. mg_websocket_close_handler close_handler,
  8976. mg_authorization_handler auth_handler,
  8977. void *cbdata)
  8978. {
  8979. struct mg_handler_info *tmp_rh, **lastref;
  8980. size_t urilen = strlen(uri);
  8981. if (handler_type == WEBSOCKET_HANDLER) {
  8982. /* assert(handler == NULL); */
  8983. /* assert(is_delete_request || connect_handler!=NULL ||
  8984. * ready_handler!=NULL || data_handler!=NULL ||
  8985. * close_handler!=NULL);
  8986. */
  8987. /* assert(auth_handler == NULL); */
  8988. if (handler != NULL) {
  8989. return;
  8990. }
  8991. if (!is_delete_request && connect_handler == NULL
  8992. && ready_handler == NULL
  8993. && data_handler == NULL
  8994. && close_handler == NULL) {
  8995. return;
  8996. }
  8997. if (auth_handler != NULL) {
  8998. return;
  8999. }
  9000. } else if (handler_type == REQUEST_HANDLER) {
  9001. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9002. * data_handler==NULL && close_handler==NULL); */
  9003. /* assert(is_delete_request || (handler!=NULL));
  9004. */
  9005. /* assert(auth_handler == NULL); */
  9006. if (connect_handler != NULL || ready_handler != NULL
  9007. || data_handler != NULL
  9008. || close_handler != NULL) {
  9009. return;
  9010. }
  9011. if (!is_delete_request && (handler == NULL)) {
  9012. return;
  9013. }
  9014. if (auth_handler != NULL) {
  9015. return;
  9016. }
  9017. } else { /* AUTH_HANDLER */
  9018. /* assert(handler == NULL); */
  9019. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9020. * data_handler==NULL && close_handler==NULL); */
  9021. /* assert(auth_handler != NULL); */
  9022. if (handler != NULL) {
  9023. return;
  9024. }
  9025. if (connect_handler != NULL || ready_handler != NULL
  9026. || data_handler != NULL
  9027. || close_handler != NULL) {
  9028. return;
  9029. }
  9030. if (!is_delete_request && (auth_handler == NULL)) {
  9031. return;
  9032. }
  9033. }
  9034. if (!ctx) {
  9035. return;
  9036. }
  9037. mg_lock_context(ctx);
  9038. /* first try to find an existing handler */
  9039. lastref = &(ctx->handlers);
  9040. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9041. if (tmp_rh->handler_type == handler_type) {
  9042. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9043. if (!is_delete_request) {
  9044. /* update existing handler */
  9045. if (handler_type == REQUEST_HANDLER) {
  9046. tmp_rh->handler = handler;
  9047. } else if (handler_type == WEBSOCKET_HANDLER) {
  9048. tmp_rh->subprotocols = subprotocols;
  9049. tmp_rh->connect_handler = connect_handler;
  9050. tmp_rh->ready_handler = ready_handler;
  9051. tmp_rh->data_handler = data_handler;
  9052. tmp_rh->close_handler = close_handler;
  9053. } else { /* AUTH_HANDLER */
  9054. tmp_rh->auth_handler = auth_handler;
  9055. }
  9056. tmp_rh->cbdata = cbdata;
  9057. } else {
  9058. /* remove existing handler */
  9059. *lastref = tmp_rh->next;
  9060. mg_free(tmp_rh->uri);
  9061. mg_free(tmp_rh);
  9062. }
  9063. mg_unlock_context(ctx);
  9064. return;
  9065. }
  9066. }
  9067. lastref = &(tmp_rh->next);
  9068. }
  9069. if (is_delete_request) {
  9070. /* no handler to set, this was a remove request to a non-existing
  9071. * handler */
  9072. mg_unlock_context(ctx);
  9073. return;
  9074. }
  9075. tmp_rh =
  9076. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  9077. if (tmp_rh == NULL) {
  9078. mg_unlock_context(ctx);
  9079. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9080. return;
  9081. }
  9082. tmp_rh->uri = mg_strdup(uri);
  9083. if (!tmp_rh->uri) {
  9084. mg_unlock_context(ctx);
  9085. mg_free(tmp_rh);
  9086. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9087. return;
  9088. }
  9089. tmp_rh->uri_len = urilen;
  9090. if (handler_type == REQUEST_HANDLER) {
  9091. tmp_rh->handler = handler;
  9092. } else if (handler_type == WEBSOCKET_HANDLER) {
  9093. tmp_rh->subprotocols = subprotocols;
  9094. tmp_rh->connect_handler = connect_handler;
  9095. tmp_rh->ready_handler = ready_handler;
  9096. tmp_rh->data_handler = data_handler;
  9097. tmp_rh->close_handler = close_handler;
  9098. } else { /* AUTH_HANDLER */
  9099. tmp_rh->auth_handler = auth_handler;
  9100. }
  9101. tmp_rh->cbdata = cbdata;
  9102. tmp_rh->handler_type = handler_type;
  9103. tmp_rh->next = NULL;
  9104. *lastref = tmp_rh;
  9105. mg_unlock_context(ctx);
  9106. }
  9107. void
  9108. mg_set_request_handler(struct mg_context *ctx,
  9109. const char *uri,
  9110. mg_request_handler handler,
  9111. void *cbdata)
  9112. {
  9113. mg_set_handler_type(ctx,
  9114. uri,
  9115. REQUEST_HANDLER,
  9116. handler == NULL,
  9117. handler,
  9118. NULL,
  9119. NULL,
  9120. NULL,
  9121. NULL,
  9122. NULL,
  9123. NULL,
  9124. cbdata);
  9125. }
  9126. void
  9127. mg_set_websocket_handler(struct mg_context *ctx,
  9128. const char *uri,
  9129. mg_websocket_connect_handler connect_handler,
  9130. mg_websocket_ready_handler ready_handler,
  9131. mg_websocket_data_handler data_handler,
  9132. mg_websocket_close_handler close_handler,
  9133. void *cbdata)
  9134. {
  9135. mg_set_websocket_handler_with_subprotocols(ctx,
  9136. uri,
  9137. NULL,
  9138. connect_handler,
  9139. ready_handler,
  9140. data_handler,
  9141. close_handler,
  9142. cbdata);
  9143. }
  9144. void
  9145. mg_set_websocket_handler_with_subprotocols(
  9146. struct mg_context *ctx,
  9147. const char *uri,
  9148. struct mg_websocket_subprotocols *subprotocols,
  9149. mg_websocket_connect_handler connect_handler,
  9150. mg_websocket_ready_handler ready_handler,
  9151. mg_websocket_data_handler data_handler,
  9152. mg_websocket_close_handler close_handler,
  9153. void *cbdata)
  9154. {
  9155. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9156. && (data_handler == NULL)
  9157. && (close_handler == NULL);
  9158. mg_set_handler_type(ctx,
  9159. uri,
  9160. WEBSOCKET_HANDLER,
  9161. is_delete_request,
  9162. NULL,
  9163. subprotocols,
  9164. connect_handler,
  9165. ready_handler,
  9166. data_handler,
  9167. close_handler,
  9168. NULL,
  9169. cbdata);
  9170. }
  9171. void
  9172. mg_set_auth_handler(struct mg_context *ctx,
  9173. const char *uri,
  9174. mg_request_handler handler,
  9175. void *cbdata)
  9176. {
  9177. mg_set_handler_type(ctx,
  9178. uri,
  9179. AUTH_HANDLER,
  9180. handler == NULL,
  9181. NULL,
  9182. NULL,
  9183. NULL,
  9184. NULL,
  9185. NULL,
  9186. NULL,
  9187. handler,
  9188. cbdata);
  9189. }
  9190. static int
  9191. get_request_handler(struct mg_connection *conn,
  9192. int handler_type,
  9193. mg_request_handler *handler,
  9194. struct mg_websocket_subprotocols **subprotocols,
  9195. mg_websocket_connect_handler *connect_handler,
  9196. mg_websocket_ready_handler *ready_handler,
  9197. mg_websocket_data_handler *data_handler,
  9198. mg_websocket_close_handler *close_handler,
  9199. mg_authorization_handler *auth_handler,
  9200. void **cbdata)
  9201. {
  9202. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9203. if (request_info) {
  9204. const char *uri = request_info->local_uri;
  9205. size_t urilen = strlen(uri);
  9206. struct mg_handler_info *tmp_rh;
  9207. if (!conn || !conn->ctx) {
  9208. return 0;
  9209. }
  9210. mg_lock_context(conn->ctx);
  9211. /* first try for an exact match */
  9212. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9213. tmp_rh = tmp_rh->next) {
  9214. if (tmp_rh->handler_type == handler_type) {
  9215. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9216. if (handler_type == WEBSOCKET_HANDLER) {
  9217. *subprotocols = tmp_rh->subprotocols;
  9218. *connect_handler = tmp_rh->connect_handler;
  9219. *ready_handler = tmp_rh->ready_handler;
  9220. *data_handler = tmp_rh->data_handler;
  9221. *close_handler = tmp_rh->close_handler;
  9222. } else if (handler_type == REQUEST_HANDLER) {
  9223. *handler = tmp_rh->handler;
  9224. } else { /* AUTH_HANDLER */
  9225. *auth_handler = tmp_rh->auth_handler;
  9226. }
  9227. *cbdata = tmp_rh->cbdata;
  9228. mg_unlock_context(conn->ctx);
  9229. return 1;
  9230. }
  9231. }
  9232. }
  9233. /* next try for a partial match, we will accept uri/something */
  9234. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9235. tmp_rh = tmp_rh->next) {
  9236. if (tmp_rh->handler_type == handler_type) {
  9237. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9238. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9239. if (handler_type == WEBSOCKET_HANDLER) {
  9240. *subprotocols = tmp_rh->subprotocols;
  9241. *connect_handler = tmp_rh->connect_handler;
  9242. *ready_handler = tmp_rh->ready_handler;
  9243. *data_handler = tmp_rh->data_handler;
  9244. *close_handler = tmp_rh->close_handler;
  9245. } else if (handler_type == REQUEST_HANDLER) {
  9246. *handler = tmp_rh->handler;
  9247. } else { /* AUTH_HANDLER */
  9248. *auth_handler = tmp_rh->auth_handler;
  9249. }
  9250. *cbdata = tmp_rh->cbdata;
  9251. mg_unlock_context(conn->ctx);
  9252. return 1;
  9253. }
  9254. }
  9255. }
  9256. /* finally try for pattern match */
  9257. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9258. tmp_rh = tmp_rh->next) {
  9259. if (tmp_rh->handler_type == handler_type) {
  9260. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9261. if (handler_type == WEBSOCKET_HANDLER) {
  9262. *subprotocols = tmp_rh->subprotocols;
  9263. *connect_handler = tmp_rh->connect_handler;
  9264. *ready_handler = tmp_rh->ready_handler;
  9265. *data_handler = tmp_rh->data_handler;
  9266. *close_handler = tmp_rh->close_handler;
  9267. } else if (handler_type == REQUEST_HANDLER) {
  9268. *handler = tmp_rh->handler;
  9269. } else { /* AUTH_HANDLER */
  9270. *auth_handler = tmp_rh->auth_handler;
  9271. }
  9272. *cbdata = tmp_rh->cbdata;
  9273. mg_unlock_context(conn->ctx);
  9274. return 1;
  9275. }
  9276. }
  9277. }
  9278. mg_unlock_context(conn->ctx);
  9279. }
  9280. return 0; /* none found */
  9281. }
  9282. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9283. static int
  9284. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9285. void *cbdata)
  9286. {
  9287. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9288. if (pcallbacks->websocket_connect) {
  9289. return pcallbacks->websocket_connect(conn);
  9290. }
  9291. /* No handler set - assume "OK" */
  9292. return 0;
  9293. }
  9294. static void
  9295. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9296. {
  9297. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9298. if (pcallbacks->websocket_ready) {
  9299. pcallbacks->websocket_ready(conn);
  9300. }
  9301. }
  9302. static int
  9303. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9304. int bits,
  9305. char *data,
  9306. size_t len,
  9307. void *cbdata)
  9308. {
  9309. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9310. if (pcallbacks->websocket_data) {
  9311. return pcallbacks->websocket_data(conn, bits, data, len);
  9312. }
  9313. /* No handler set - assume "OK" */
  9314. return 1;
  9315. }
  9316. #endif
  9317. /* This is the heart of the Civetweb's logic.
  9318. * This function is called when the request is read, parsed and validated,
  9319. * and Civetweb must decide what action to take: serve a file, or
  9320. * a directory, or call embedded function, etcetera. */
  9321. static void
  9322. handle_request(struct mg_connection *conn)
  9323. {
  9324. struct mg_request_info *ri = &conn->request_info;
  9325. char path[PATH_MAX];
  9326. int uri_len, ssl_index;
  9327. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9328. is_put_or_delete_request = 0, is_callback_resource = 0;
  9329. int i;
  9330. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9331. mg_request_handler callback_handler = NULL;
  9332. struct mg_websocket_subprotocols *subprotocols;
  9333. mg_websocket_connect_handler ws_connect_handler = NULL;
  9334. mg_websocket_ready_handler ws_ready_handler = NULL;
  9335. mg_websocket_data_handler ws_data_handler = NULL;
  9336. mg_websocket_close_handler ws_close_handler = NULL;
  9337. void *callback_data = NULL;
  9338. mg_authorization_handler auth_handler = NULL;
  9339. void *auth_callback_data = NULL;
  9340. #if !defined(NO_FILES)
  9341. time_t curtime = time(NULL);
  9342. char date[64];
  9343. #endif
  9344. path[0] = 0;
  9345. if (!ri) {
  9346. return;
  9347. }
  9348. /* 1. get the request url */
  9349. /* 1.1. split into url and query string */
  9350. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9351. != NULL) {
  9352. *((char *)conn->request_info.query_string++) = '\0';
  9353. }
  9354. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9355. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9356. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9357. if (ssl_index >= 0) {
  9358. redirect_to_https_port(conn, ssl_index);
  9359. } else {
  9360. /* A http to https forward port has been specified,
  9361. * but no https port to forward to. */
  9362. send_http_error(conn,
  9363. 503,
  9364. "%s",
  9365. "Error: SSL forward not configured properly");
  9366. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9367. }
  9368. return;
  9369. }
  9370. uri_len = (int)strlen(ri->local_uri);
  9371. /* 1.3. decode url (if config says so) */
  9372. if (should_decode_url(conn)) {
  9373. mg_url_decode(
  9374. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9375. }
  9376. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9377. * not possible */
  9378. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9379. /* step 1. completed, the url is known now */
  9380. uri_len = (int)strlen(ri->local_uri);
  9381. DEBUG_TRACE("URL: %s", ri->local_uri);
  9382. /* 3. if this ip has limited speed, set it for this connection */
  9383. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9384. get_remote_ip(conn),
  9385. ri->local_uri);
  9386. /* 4. call a "handle everything" callback, if registered */
  9387. if (conn->ctx->callbacks.begin_request != NULL) {
  9388. /* Note that since V1.7 the "begin_request" function is called
  9389. * before an authorization check. If an authorization check is
  9390. * required, use a request_handler instead. */
  9391. i = conn->ctx->callbacks.begin_request(conn);
  9392. if (i > 0) {
  9393. /* callback already processed the request. Store the
  9394. return value as a status code for the access log. */
  9395. conn->status_code = i;
  9396. discard_unread_request_data(conn);
  9397. return;
  9398. } else if (i == 0) {
  9399. /* civetweb should process the request */
  9400. } else {
  9401. /* unspecified - may change with the next version */
  9402. return;
  9403. }
  9404. }
  9405. /* request not yet handled by a handler or redirect, so the request
  9406. * is processed here */
  9407. /* 5. interpret the url to find out how the request must be handled
  9408. */
  9409. /* 5.1. first test, if the request targets the regular http(s)://
  9410. * protocol namespace or the websocket ws(s):// protocol namespace.
  9411. */
  9412. is_websocket_request = is_websocket_protocol(conn);
  9413. /* 5.2. check if the request will be handled by a callback */
  9414. if (get_request_handler(conn,
  9415. is_websocket_request ? WEBSOCKET_HANDLER
  9416. : REQUEST_HANDLER,
  9417. &callback_handler,
  9418. &subprotocols,
  9419. &ws_connect_handler,
  9420. &ws_ready_handler,
  9421. &ws_data_handler,
  9422. &ws_close_handler,
  9423. NULL,
  9424. &callback_data)) {
  9425. /* 5.2.1. A callback will handle this request. All requests
  9426. * handled
  9427. * by a callback have to be considered as requests to a script
  9428. * resource. */
  9429. is_callback_resource = 1;
  9430. is_script_resource = 1;
  9431. is_put_or_delete_request = is_put_or_delete_method(conn);
  9432. } else {
  9433. no_callback_resource:
  9434. /* 5.2.2. No callback is responsible for this request. The URI
  9435. * addresses a file based resource (static content or Lua/cgi
  9436. * scripts in the file system). */
  9437. is_callback_resource = 0;
  9438. interpret_uri(conn,
  9439. path,
  9440. sizeof(path),
  9441. &file.stat,
  9442. &is_found,
  9443. &is_script_resource,
  9444. &is_websocket_request,
  9445. &is_put_or_delete_request);
  9446. }
  9447. /* 6. authorization check */
  9448. /* 6.1. a custom authorization handler is installed */
  9449. if (get_request_handler(conn,
  9450. AUTH_HANDLER,
  9451. NULL,
  9452. NULL,
  9453. NULL,
  9454. NULL,
  9455. NULL,
  9456. NULL,
  9457. &auth_handler,
  9458. &auth_callback_data)) {
  9459. if (!auth_handler(conn, auth_callback_data)) {
  9460. return;
  9461. }
  9462. } else if (is_put_or_delete_request && !is_script_resource
  9463. && !is_callback_resource) {
  9464. /* 6.2. this request is a PUT/DELETE to a real file */
  9465. /* 6.2.1. thus, the server must have real files */
  9466. #if defined(NO_FILES)
  9467. if (1) {
  9468. #else
  9469. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9470. #endif
  9471. /* This server does not have any real files, thus the
  9472. * PUT/DELETE methods are not valid. */
  9473. send_http_error(conn,
  9474. 405,
  9475. "%s method not allowed",
  9476. conn->request_info.request_method);
  9477. return;
  9478. }
  9479. #if !defined(NO_FILES)
  9480. /* 6.2.2. Check if put authorization for static files is
  9481. * available.
  9482. */
  9483. if (!is_authorized_for_put(conn)) {
  9484. send_authorization_request(conn);
  9485. return;
  9486. }
  9487. #endif
  9488. } else {
  9489. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9490. * or it is a PUT or DELETE request to a resource that does not
  9491. * correspond to a file. Check authorization. */
  9492. if (!check_authorization(conn, path)) {
  9493. send_authorization_request(conn);
  9494. return;
  9495. }
  9496. }
  9497. /* request is authorized or does not need authorization */
  9498. /* 7. check if there are request handlers for this uri */
  9499. if (is_callback_resource) {
  9500. if (!is_websocket_request) {
  9501. i = callback_handler(conn, callback_data);
  9502. if (i > 0) {
  9503. /* Do nothing, callback has served the request. Store
  9504. * the
  9505. * return value as status code for the log and discard
  9506. * all
  9507. * data from the client not used by the callback. */
  9508. conn->status_code = i;
  9509. discard_unread_request_data(conn);
  9510. } else {
  9511. /* TODO (high): what if the handler did NOT handle the
  9512. * request */
  9513. /* The last version did handle this as a file request,
  9514. * but
  9515. * since a file request is not always a script resource,
  9516. * the authorization check might be different */
  9517. interpret_uri(conn,
  9518. path,
  9519. sizeof(path),
  9520. &file.stat,
  9521. &is_found,
  9522. &is_script_resource,
  9523. &is_websocket_request,
  9524. &is_put_or_delete_request);
  9525. callback_handler = NULL;
  9526. /* Here we are at a dead end:
  9527. * According to URI matching, a callback should be
  9528. * responsible for handling the request,
  9529. * we called it, but the callback declared itself
  9530. * not responsible.
  9531. * We use a goto here, to get out of this dead end,
  9532. * and continue with the default handling.
  9533. * A goto here is simpler and better to understand
  9534. * than some curious loop. */
  9535. goto no_callback_resource;
  9536. }
  9537. } else {
  9538. #if defined(USE_WEBSOCKET)
  9539. handle_websocket_request(conn,
  9540. path,
  9541. is_callback_resource,
  9542. subprotocols,
  9543. ws_connect_handler,
  9544. ws_ready_handler,
  9545. ws_data_handler,
  9546. ws_close_handler,
  9547. callback_data);
  9548. #endif
  9549. }
  9550. return;
  9551. }
  9552. /* 8. handle websocket requests */
  9553. #if defined(USE_WEBSOCKET)
  9554. if (is_websocket_request) {
  9555. if (is_script_resource) {
  9556. /* Websocket Lua script */
  9557. handle_websocket_request(conn,
  9558. path,
  9559. 0 /* Lua Script */,
  9560. NULL,
  9561. NULL,
  9562. NULL,
  9563. NULL,
  9564. NULL,
  9565. &conn->ctx->callbacks);
  9566. } else {
  9567. #if defined(MG_LEGACY_INTERFACE)
  9568. handle_websocket_request(
  9569. conn,
  9570. path,
  9571. !is_script_resource /* could be deprecated global callback */,
  9572. NULL,
  9573. deprecated_websocket_connect_wrapper,
  9574. deprecated_websocket_ready_wrapper,
  9575. deprecated_websocket_data_wrapper,
  9576. NULL,
  9577. &conn->ctx->callbacks);
  9578. #else
  9579. send_http_error(conn, 404, "%s", "Not found");
  9580. #endif
  9581. }
  9582. return;
  9583. } else
  9584. #endif
  9585. #if defined(NO_FILES)
  9586. /* 9a. In case the server uses only callbacks, this uri is
  9587. * unknown.
  9588. * Then, all request handling ends here. */
  9589. send_http_error(conn, 404, "%s", "Not Found");
  9590. #else
  9591. /* 9b. This request is either for a static file or resource handled
  9592. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9593. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9594. send_http_error(conn, 404, "%s", "Not Found");
  9595. return;
  9596. }
  9597. /* 10. File is handled by a script. */
  9598. if (is_script_resource) {
  9599. handle_file_based_request(conn, path, &file);
  9600. return;
  9601. }
  9602. /* 11. Handle put/delete/mkcol requests */
  9603. if (is_put_or_delete_request) {
  9604. /* 11.1. PUT method */
  9605. if (!strcmp(ri->request_method, "PUT")) {
  9606. put_file(conn, path);
  9607. return;
  9608. }
  9609. /* 11.2. DELETE method */
  9610. if (!strcmp(ri->request_method, "DELETE")) {
  9611. delete_file(conn, path);
  9612. return;
  9613. }
  9614. /* 11.3. MKCOL method */
  9615. if (!strcmp(ri->request_method, "MKCOL")) {
  9616. mkcol(conn, path);
  9617. return;
  9618. }
  9619. /* 11.4. PATCH method
  9620. * This method is not supported for static resources,
  9621. * only for scripts (Lua, CGI) and callbacks. */
  9622. send_http_error(conn,
  9623. 405,
  9624. "%s method not allowed",
  9625. conn->request_info.request_method);
  9626. return;
  9627. }
  9628. /* 11. File does not exist, or it was configured that it should be
  9629. * hidden */
  9630. if (!is_found || (must_hide_file(conn, path))) {
  9631. send_http_error(conn, 404, "%s", "Not found");
  9632. return;
  9633. }
  9634. /* 12. Directory uris should end with a slash */
  9635. if (file.stat.is_directory && (uri_len > 0)
  9636. && (ri->local_uri[uri_len - 1] != '/')) {
  9637. gmt_time_string(date, sizeof(date), &curtime);
  9638. mg_printf(conn,
  9639. "HTTP/1.1 301 Moved Permanently\r\n"
  9640. "Location: %s/\r\n"
  9641. "Date: %s\r\n"
  9642. /* "Cache-Control: private\r\n" (= default) */
  9643. "Content-Length: 0\r\n"
  9644. "Connection: %s\r\n",
  9645. ri->request_uri,
  9646. date,
  9647. suggest_connection_header(conn));
  9648. send_additional_header(conn);
  9649. mg_printf(conn, "\r\n");
  9650. return;
  9651. }
  9652. /* 13. Handle other methods than GET/HEAD */
  9653. /* 13.1. Handle PROPFIND */
  9654. if (!strcmp(ri->request_method, "PROPFIND")) {
  9655. handle_propfind(conn, path, &file.stat);
  9656. return;
  9657. }
  9658. /* 13.2. Handle OPTIONS for files */
  9659. if (!strcmp(ri->request_method, "OPTIONS")) {
  9660. /* This standard handler is only used for real files.
  9661. * Scripts should support the OPTIONS method themselves, to allow a
  9662. * maximum flexibility.
  9663. * Lua and CGI scripts may fully support CORS this way (including
  9664. * preflights). */
  9665. send_options(conn);
  9666. return;
  9667. }
  9668. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9669. if (0 != strcmp(ri->request_method, "GET")
  9670. && 0 != strcmp(ri->request_method, "HEAD")) {
  9671. send_http_error(conn,
  9672. 405,
  9673. "%s method not allowed",
  9674. conn->request_info.request_method);
  9675. return;
  9676. }
  9677. /* 14. directories */
  9678. if (file.stat.is_directory) {
  9679. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9680. /* 14.1. use a substitute file */
  9681. /* TODO (high): substitute index may be a script resource.
  9682. * define what should be possible in this case. */
  9683. } else {
  9684. /* 14.2. no substitute file */
  9685. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9686. "yes")) {
  9687. handle_directory_request(conn, path);
  9688. } else {
  9689. send_http_error(conn,
  9690. 403,
  9691. "%s",
  9692. "Error: Directory listing denied");
  9693. }
  9694. return;
  9695. }
  9696. }
  9697. handle_file_based_request(conn, path, &file);
  9698. #endif /* !defined(NO_FILES) */
  9699. #if 0
  9700. /* Perform redirect and auth checks before calling begin_request()
  9701. * handler.
  9702. * Otherwise, begin_request() would need to perform auth checks and
  9703. * redirects. */
  9704. #endif
  9705. }
  9706. static void
  9707. handle_file_based_request(struct mg_connection *conn,
  9708. const char *path,
  9709. struct mg_file *file)
  9710. {
  9711. if (!conn || !conn->ctx) {
  9712. return;
  9713. }
  9714. if (0) {
  9715. #ifdef USE_LUA
  9716. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9717. strlen(
  9718. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9719. path) > 0) {
  9720. /* Lua server page: an SSI like page containing mostly plain html
  9721. * code
  9722. * plus some tags with server generated contents. */
  9723. handle_lsp_request(conn, path, file, NULL);
  9724. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9725. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9726. path) > 0) {
  9727. /* Lua in-server module script: a CGI like script used to generate
  9728. * the
  9729. * entire reply. */
  9730. mg_exec_lua_script(conn, path, NULL);
  9731. #endif
  9732. #if defined(USE_DUKTAPE)
  9733. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9734. strlen(
  9735. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9736. path) > 0) {
  9737. /* Call duktape to generate the page */
  9738. mg_exec_duktape_script(conn, path);
  9739. #endif
  9740. #if !defined(NO_CGI)
  9741. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9742. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9743. path) > 0) {
  9744. /* CGI scripts may support all HTTP methods */
  9745. handle_cgi_request(conn, path);
  9746. #endif /* !NO_CGI */
  9747. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9748. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9749. path) > 0) {
  9750. handle_ssi_file_request(conn, path, file);
  9751. #if !defined(NO_CACHING)
  9752. } else if ((!conn->in_error_handler)
  9753. && is_not_modified(conn, &file->stat)) {
  9754. /* Send 304 "Not Modified" - this must not send any body data */
  9755. handle_not_modified_static_file_request(conn, file);
  9756. #endif /* !NO_CACHING */
  9757. } else {
  9758. handle_static_file_request(conn, path, file, NULL, NULL);
  9759. }
  9760. }
  9761. static void
  9762. close_all_listening_sockets(struct mg_context *ctx)
  9763. {
  9764. unsigned int i;
  9765. if (!ctx) {
  9766. return;
  9767. }
  9768. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9769. closesocket(ctx->listening_sockets[i].sock);
  9770. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9771. }
  9772. mg_free(ctx->listening_sockets);
  9773. ctx->listening_sockets = NULL;
  9774. mg_free(ctx->listening_socket_fds);
  9775. ctx->listening_socket_fds = NULL;
  9776. }
  9777. /* Valid listening port specification is: [ip_address:]port[s]
  9778. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9779. * Examples for IPv6: [::]:80, [::1]:80,
  9780. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9781. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9782. * In order to bind to both, IPv4 and IPv6, you can either add
  9783. * both ports using 8080,[::]:8080, or the short form +8080.
  9784. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9785. * one only accepting IPv4 the other only IPv6. +8080 creates
  9786. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9787. * environment, they might work differently, or might not work
  9788. * at all - it must be tested what options work best in the
  9789. * relevant network environment.
  9790. */
  9791. static int
  9792. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9793. {
  9794. unsigned int a, b, c, d, port;
  9795. int ch, len;
  9796. #if defined(USE_IPV6)
  9797. char buf[100] = {0};
  9798. #endif
  9799. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9800. * Also, all-zeroes in the socket address means binding to all addresses
  9801. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9802. memset(so, 0, sizeof(*so));
  9803. so->lsa.sin.sin_family = AF_INET;
  9804. *ip_version = 0;
  9805. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9806. == 5) {
  9807. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9808. so->lsa.sin.sin_addr.s_addr =
  9809. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9810. so->lsa.sin.sin_port = htons((uint16_t)port);
  9811. *ip_version = 4;
  9812. #if defined(USE_IPV6)
  9813. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9814. && mg_inet_pton(
  9815. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9816. /* IPv6 address, examples: see above */
  9817. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9818. */
  9819. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9820. *ip_version = 6;
  9821. #endif
  9822. } else if ((vec->ptr[0] == '+')
  9823. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9824. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9825. /* Add 1 to len for the + character we skipped before */
  9826. len++;
  9827. #if defined(USE_IPV6)
  9828. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9829. so->lsa.sin6.sin6_family = AF_INET6;
  9830. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9831. *ip_version = 4 + 6;
  9832. #else
  9833. /* Bind to IPv4 only, since IPv6 is not built in. */
  9834. so->lsa.sin.sin_port = htons((uint16_t)port);
  9835. *ip_version = 4;
  9836. #endif
  9837. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9838. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9839. so->lsa.sin.sin_port = htons((uint16_t)port);
  9840. *ip_version = 4;
  9841. } else {
  9842. /* Parsing failure. Make port invalid. */
  9843. port = 0;
  9844. len = 0;
  9845. }
  9846. /* sscanf and the option splitting code ensure the following condition
  9847. */
  9848. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9849. *ip_version = 0;
  9850. return 0;
  9851. }
  9852. ch = vec->ptr[len]; /* Next character after the port number */
  9853. so->is_ssl = (ch == 's');
  9854. so->ssl_redir = (ch == 'r');
  9855. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9856. if (is_valid_port(port)
  9857. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9858. return 1;
  9859. }
  9860. /* Reset ip_version to 0 of there is an error */
  9861. *ip_version = 0;
  9862. return 0;
  9863. }
  9864. static int
  9865. set_ports_option(struct mg_context *ctx)
  9866. {
  9867. const char *list;
  9868. int on = 1;
  9869. #if defined(USE_IPV6)
  9870. int off = 0;
  9871. #endif
  9872. struct vec vec;
  9873. struct socket so, *ptr;
  9874. struct pollfd *pfd;
  9875. union usa usa;
  9876. socklen_t len;
  9877. int ip_version;
  9878. int portsTotal = 0;
  9879. int portsOk = 0;
  9880. if (!ctx) {
  9881. return 0;
  9882. }
  9883. memset(&so, 0, sizeof(so));
  9884. memset(&usa, 0, sizeof(usa));
  9885. len = sizeof(usa);
  9886. list = ctx->config[LISTENING_PORTS];
  9887. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9888. portsTotal++;
  9889. if (!parse_port_string(&vec, &so, &ip_version)) {
  9890. mg_cry(fc(ctx),
  9891. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9892. (int)vec.len,
  9893. vec.ptr,
  9894. portsTotal,
  9895. "[IP_ADDRESS:]PORT[s|r]");
  9896. continue;
  9897. }
  9898. #if !defined(NO_SSL)
  9899. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9900. mg_cry(fc(ctx),
  9901. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9902. "option set?",
  9903. portsTotal);
  9904. continue;
  9905. }
  9906. #endif
  9907. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9908. == INVALID_SOCKET) {
  9909. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9910. continue;
  9911. }
  9912. #ifdef _WIN32
  9913. /* Windows SO_REUSEADDR lets many procs binds to a
  9914. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9915. * if someone already has the socket -- DTL */
  9916. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9917. * Windows might need a few seconds before
  9918. * the same port can be used again in the
  9919. * same process, so a short Sleep may be
  9920. * required between mg_stop and mg_start.
  9921. */
  9922. if (setsockopt(so.sock,
  9923. SOL_SOCKET,
  9924. SO_EXCLUSIVEADDRUSE,
  9925. (SOCK_OPT_TYPE)&on,
  9926. sizeof(on)) != 0) {
  9927. /* Set reuse option, but don't abort on errors. */
  9928. mg_cry(fc(ctx),
  9929. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9930. portsTotal);
  9931. }
  9932. #else
  9933. if (setsockopt(so.sock,
  9934. SOL_SOCKET,
  9935. SO_REUSEADDR,
  9936. (SOCK_OPT_TYPE)&on,
  9937. sizeof(on)) != 0) {
  9938. /* Set reuse option, but don't abort on errors. */
  9939. mg_cry(fc(ctx),
  9940. "cannot set socket option SO_REUSEADDR (entry %i)",
  9941. portsTotal);
  9942. }
  9943. #endif
  9944. if (ip_version > 4) {
  9945. #if defined(USE_IPV6)
  9946. if (ip_version == 6) {
  9947. if (so.lsa.sa.sa_family == AF_INET6
  9948. && setsockopt(so.sock,
  9949. IPPROTO_IPV6,
  9950. IPV6_V6ONLY,
  9951. (void *)&off,
  9952. sizeof(off)) != 0) {
  9953. /* Set IPv6 only option, but don't abort on errors. */
  9954. mg_cry(fc(ctx),
  9955. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9956. portsTotal);
  9957. }
  9958. }
  9959. #else
  9960. mg_cry(fc(ctx), "IPv6 not available");
  9961. closesocket(so.sock);
  9962. so.sock = INVALID_SOCKET;
  9963. continue;
  9964. #endif
  9965. }
  9966. if (so.lsa.sa.sa_family == AF_INET) {
  9967. len = sizeof(so.lsa.sin);
  9968. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9969. mg_cry(fc(ctx),
  9970. "cannot bind to %.*s: %d (%s)",
  9971. (int)vec.len,
  9972. vec.ptr,
  9973. (int)ERRNO,
  9974. strerror(errno));
  9975. closesocket(so.sock);
  9976. so.sock = INVALID_SOCKET;
  9977. continue;
  9978. }
  9979. }
  9980. #if defined(USE_IPV6)
  9981. else if (so.lsa.sa.sa_family == AF_INET6) {
  9982. len = sizeof(so.lsa.sin6);
  9983. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9984. mg_cry(fc(ctx),
  9985. "cannot bind to IPv6 %.*s: %d (%s)",
  9986. (int)vec.len,
  9987. vec.ptr,
  9988. (int)ERRNO,
  9989. strerror(errno));
  9990. closesocket(so.sock);
  9991. so.sock = INVALID_SOCKET;
  9992. continue;
  9993. }
  9994. }
  9995. #endif
  9996. else {
  9997. mg_cry(fc(ctx),
  9998. "cannot bind: address family not supported (entry %i)",
  9999. portsTotal);
  10000. continue;
  10001. }
  10002. if (listen(so.sock, SOMAXCONN) != 0) {
  10003. mg_cry(fc(ctx),
  10004. "cannot listen to %.*s: %d (%s)",
  10005. (int)vec.len,
  10006. vec.ptr,
  10007. (int)ERRNO,
  10008. strerror(errno));
  10009. closesocket(so.sock);
  10010. so.sock = INVALID_SOCKET;
  10011. continue;
  10012. }
  10013. if (getsockname(so.sock, &(usa.sa), &len) != 0
  10014. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  10015. int err = (int)ERRNO;
  10016. mg_cry(fc(ctx),
  10017. "call to getsockname failed %.*s: %d (%s)",
  10018. (int)vec.len,
  10019. vec.ptr,
  10020. err,
  10021. strerror(errno));
  10022. closesocket(so.sock);
  10023. so.sock = INVALID_SOCKET;
  10024. continue;
  10025. }
  10026. /* Update lsa port in case of random free ports */
  10027. #if defined(USE_IPV6)
  10028. if (so.lsa.sa.sa_family == AF_INET6) {
  10029. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10030. } else
  10031. #endif
  10032. {
  10033. so.lsa.sin.sin_port = usa.sin.sin_port;
  10034. }
  10035. if ((ptr = (struct socket *)
  10036. mg_realloc(ctx->listening_sockets,
  10037. (ctx->num_listening_sockets + 1)
  10038. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  10039. mg_cry(fc(ctx), "%s", "Out of memory");
  10040. closesocket(so.sock);
  10041. so.sock = INVALID_SOCKET;
  10042. continue;
  10043. }
  10044. if ((pfd = (struct pollfd *)mg_realloc(
  10045. ctx->listening_socket_fds,
  10046. (ctx->num_listening_sockets + 1)
  10047. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  10048. mg_cry(fc(ctx), "%s", "Out of memory");
  10049. closesocket(so.sock);
  10050. so.sock = INVALID_SOCKET;
  10051. mg_free(ptr);
  10052. continue;
  10053. }
  10054. set_close_on_exec(so.sock, fc(ctx));
  10055. ctx->listening_sockets = ptr;
  10056. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10057. ctx->listening_socket_fds = pfd;
  10058. ctx->num_listening_sockets++;
  10059. portsOk++;
  10060. }
  10061. if (portsOk != portsTotal) {
  10062. close_all_listening_sockets(ctx);
  10063. portsOk = 0;
  10064. }
  10065. return portsOk;
  10066. }
  10067. static const char *
  10068. header_val(const struct mg_connection *conn, const char *header)
  10069. {
  10070. const char *header_value;
  10071. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10072. return "-";
  10073. } else {
  10074. return header_value;
  10075. }
  10076. }
  10077. static void
  10078. log_access(const struct mg_connection *conn)
  10079. {
  10080. const struct mg_request_info *ri;
  10081. struct mg_file fi;
  10082. char date[64], src_addr[IP_ADDR_STR_LEN];
  10083. struct tm *tm;
  10084. const char *referer;
  10085. const char *user_agent;
  10086. char buf[4096];
  10087. if (!conn || !conn->ctx) {
  10088. return;
  10089. }
  10090. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10091. if (mg_fopen(conn,
  10092. conn->ctx->config[ACCESS_LOG_FILE],
  10093. MG_FOPEN_MODE_APPEND,
  10094. &fi) == 0) {
  10095. fi.access.fp = NULL;
  10096. }
  10097. } else {
  10098. fi.access.fp = NULL;
  10099. }
  10100. /* Log is written to a file and/or a callback. If both are not set,
  10101. * executing the rest of the function is pointless. */
  10102. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10103. return;
  10104. }
  10105. tm = localtime(&conn->conn_birth_time);
  10106. if (tm != NULL) {
  10107. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10108. } else {
  10109. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10110. date[sizeof(date) - 1] = '\0';
  10111. }
  10112. ri = &conn->request_info;
  10113. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10114. referer = header_val(conn, "Referer");
  10115. user_agent = header_val(conn, "User-Agent");
  10116. mg_snprintf(conn,
  10117. NULL, /* Ignore truncation in access log */
  10118. buf,
  10119. sizeof(buf),
  10120. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10121. src_addr,
  10122. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10123. date,
  10124. ri->request_method ? ri->request_method : "-",
  10125. ri->request_uri ? ri->request_uri : "-",
  10126. ri->query_string ? "?" : "",
  10127. ri->query_string ? ri->query_string : "",
  10128. ri->http_version,
  10129. conn->status_code,
  10130. conn->num_bytes_sent,
  10131. referer,
  10132. user_agent);
  10133. if (conn->ctx->callbacks.log_access) {
  10134. conn->ctx->callbacks.log_access(conn, buf);
  10135. }
  10136. if (fi.access.fp) {
  10137. int ok = 1;
  10138. flockfile(fi.access.fp);
  10139. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10140. ok = 0;
  10141. }
  10142. if (fflush(fi.access.fp) != 0) {
  10143. ok = 0;
  10144. }
  10145. funlockfile(fi.access.fp);
  10146. if (mg_fclose(&fi.access) != 0) {
  10147. ok = 0;
  10148. }
  10149. if (!ok) {
  10150. mg_cry(conn,
  10151. "Error writing log file %s",
  10152. conn->ctx->config[ACCESS_LOG_FILE]);
  10153. }
  10154. }
  10155. }
  10156. /* Verify given socket address against the ACL.
  10157. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10158. */
  10159. static int
  10160. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10161. {
  10162. int allowed, flag;
  10163. uint32_t net, mask;
  10164. struct vec vec;
  10165. if (ctx) {
  10166. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10167. /* If any ACL is set, deny by default */
  10168. allowed = (list == NULL) ? '+' : '-';
  10169. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10170. flag = vec.ptr[0];
  10171. if ((flag != '+' && flag != '-')
  10172. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10173. mg_cry(fc(ctx),
  10174. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10175. __func__);
  10176. return -1;
  10177. }
  10178. if (net == (remote_ip & mask)) {
  10179. allowed = flag;
  10180. }
  10181. }
  10182. return allowed == '+';
  10183. }
  10184. return -1;
  10185. }
  10186. #if !defined(_WIN32)
  10187. static int
  10188. set_uid_option(struct mg_context *ctx)
  10189. {
  10190. struct passwd *pw;
  10191. if (ctx) {
  10192. const char *uid = ctx->config[RUN_AS_USER];
  10193. int success = 0;
  10194. if (uid == NULL) {
  10195. success = 1;
  10196. } else {
  10197. if ((pw = getpwnam(uid)) == NULL) {
  10198. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10199. } else if (setgid(pw->pw_gid) == -1) {
  10200. mg_cry(fc(ctx),
  10201. "%s: setgid(%s): %s",
  10202. __func__,
  10203. uid,
  10204. strerror(errno));
  10205. } else if (setgroups(0, NULL)) {
  10206. mg_cry(fc(ctx),
  10207. "%s: setgroups(): %s",
  10208. __func__,
  10209. strerror(errno));
  10210. } else if (setuid(pw->pw_uid) == -1) {
  10211. mg_cry(fc(ctx),
  10212. "%s: setuid(%s): %s",
  10213. __func__,
  10214. uid,
  10215. strerror(errno));
  10216. } else {
  10217. success = 1;
  10218. }
  10219. }
  10220. return success;
  10221. }
  10222. return 0;
  10223. }
  10224. #endif /* !_WIN32 */
  10225. static void
  10226. tls_dtor(void *key)
  10227. {
  10228. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10229. /* key == pthread_getspecific(sTlsKey); */
  10230. if (tls) {
  10231. if (tls->is_master == 2) {
  10232. tls->is_master = -3; /* Mark memory as dead */
  10233. mg_free(tls);
  10234. }
  10235. }
  10236. pthread_setspecific(sTlsKey, NULL);
  10237. }
  10238. #if !defined(NO_SSL)
  10239. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10240. static const char *ssl_error(void);
  10241. static int
  10242. refresh_trust(struct mg_connection *conn)
  10243. {
  10244. static int reload_lock = 0;
  10245. static long int data_check = 0;
  10246. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10247. struct stat cert_buf;
  10248. long int t;
  10249. char *pem;
  10250. int should_verify_peer;
  10251. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10252. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10253. * refresh_trust still can not work. */
  10254. return 0;
  10255. }
  10256. t = data_check;
  10257. if (stat(pem, &cert_buf) != -1) {
  10258. t = (long int)cert_buf.st_mtime;
  10259. }
  10260. if (data_check != t) {
  10261. data_check = t;
  10262. should_verify_peer =
  10263. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10264. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10265. == 0);
  10266. if (should_verify_peer) {
  10267. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10268. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10269. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10270. ca_file,
  10271. ca_path) != 1) {
  10272. mg_cry(fc(conn->ctx),
  10273. "SSL_CTX_load_verify_locations error: %s "
  10274. "ssl_verify_peer requires setting "
  10275. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10276. "present in "
  10277. "the .conf file?",
  10278. ssl_error());
  10279. return 0;
  10280. }
  10281. }
  10282. if (1 == mg_atomic_inc(p_reload_lock)) {
  10283. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10284. return 0;
  10285. }
  10286. *p_reload_lock = 0;
  10287. }
  10288. }
  10289. /* lock while cert is reloading */
  10290. while (*p_reload_lock) {
  10291. sleep(1);
  10292. }
  10293. return 1;
  10294. }
  10295. #ifdef OPENSSL_API_1_1
  10296. #else
  10297. static pthread_mutex_t *ssl_mutexes;
  10298. #endif /* OPENSSL_API_1_1 */
  10299. static int
  10300. sslize(struct mg_connection *conn,
  10301. SSL_CTX *s,
  10302. int (*func)(SSL *),
  10303. volatile int *stop_server)
  10304. {
  10305. int ret, err;
  10306. int short_trust;
  10307. unsigned i;
  10308. if (!conn) {
  10309. return 0;
  10310. }
  10311. short_trust =
  10312. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10313. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10314. if (short_trust) {
  10315. int trust_ret = refresh_trust(conn);
  10316. if (!trust_ret) {
  10317. return trust_ret;
  10318. }
  10319. }
  10320. conn->ssl = SSL_new(s);
  10321. if (conn->ssl == NULL) {
  10322. return 0;
  10323. }
  10324. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10325. if (ret != 1) {
  10326. err = SSL_get_error(conn->ssl, ret);
  10327. (void)err; /* TODO: set some error message */
  10328. SSL_free(conn->ssl);
  10329. conn->ssl = NULL;
  10330. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10331. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10332. #ifndef OPENSSL_API_1_1
  10333. ERR_remove_state(0);
  10334. #endif
  10335. return 0;
  10336. }
  10337. /* SSL functions may fail and require to be called again:
  10338. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10339. * Here "func" could be SSL_connect or SSL_accept. */
  10340. for (i = 16; i <= 1024; i *= 2) {
  10341. ret = func(conn->ssl);
  10342. if (ret != 1) {
  10343. err = SSL_get_error(conn->ssl, ret);
  10344. if ((err == SSL_ERROR_WANT_CONNECT)
  10345. || (err == SSL_ERROR_WANT_ACCEPT)
  10346. || (err == SSL_ERROR_WANT_READ)
  10347. || (err == SSL_ERROR_WANT_WRITE)) {
  10348. /* Need to retry the function call "later".
  10349. * See https://linux.die.net/man/3/ssl_get_error
  10350. * This is typical for non-blocking sockets. */
  10351. if (*stop_server) {
  10352. /* Don't wait if the server is going to be stopped. */
  10353. break;
  10354. }
  10355. mg_sleep(i);
  10356. } else if (err == SSL_ERROR_SYSCALL) {
  10357. /* This is an IO error. Look at errno. */
  10358. err = errno;
  10359. /* TODO: set some error message */
  10360. break;
  10361. } else {
  10362. /* This is an SSL specific error */
  10363. /* TODO: set some error message */
  10364. break;
  10365. }
  10366. } else {
  10367. /* success */
  10368. break;
  10369. }
  10370. }
  10371. if (ret != 1) {
  10372. SSL_free(conn->ssl);
  10373. conn->ssl = NULL;
  10374. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10375. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10376. #ifndef OPENSSL_API_1_1
  10377. ERR_remove_state(0);
  10378. #endif
  10379. return 0;
  10380. }
  10381. return 1;
  10382. }
  10383. /* Return OpenSSL error message (from CRYPTO lib) */
  10384. static const char *
  10385. ssl_error(void)
  10386. {
  10387. unsigned long err;
  10388. err = ERR_get_error();
  10389. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10390. }
  10391. static int
  10392. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10393. {
  10394. int i;
  10395. const char hexdigit[] = "0123456789abcdef";
  10396. if (memlen <= 0 || buflen <= 0) {
  10397. return 0;
  10398. }
  10399. if (buflen < (3 * memlen)) {
  10400. return 0;
  10401. }
  10402. for (i = 0; i < memlen; i++) {
  10403. if (i > 0) {
  10404. buf[3 * i - 1] = ' ';
  10405. }
  10406. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10407. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10408. }
  10409. buf[3 * memlen - 1] = 0;
  10410. return 1;
  10411. }
  10412. static void
  10413. ssl_get_client_cert_info(struct mg_connection *conn)
  10414. {
  10415. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10416. if (cert) {
  10417. char str_subject[1024];
  10418. char str_issuer[1024];
  10419. char str_finger[1024];
  10420. unsigned char buf[256];
  10421. char *str_serial = NULL;
  10422. unsigned int ulen;
  10423. /* Handle to algorithm used for fingerprint */
  10424. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10425. /* Get Subject and issuer */
  10426. X509_NAME *subj = X509_get_subject_name(cert);
  10427. X509_NAME *iss = X509_get_issuer_name(cert);
  10428. /* Get serial number */
  10429. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10430. /* Translate serial number to a hex string */
  10431. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10432. str_serial = BN_bn2hex(serial_bn);
  10433. BN_free(serial_bn);
  10434. /* Translate subject and issuer to a string */
  10435. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10436. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10437. /* Calculate SHA1 fingerprint and store as a hex string */
  10438. ulen = 0;
  10439. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10440. if (!hexdump2string(
  10441. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10442. *str_finger = 0;
  10443. }
  10444. conn->request_info.client_cert =
  10445. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10446. if (conn->request_info.client_cert) {
  10447. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10448. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10449. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10450. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10451. } else {
  10452. /* TODO: write some OOM message */
  10453. }
  10454. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10455. * see https://linux.die.net/man/3/bn_bn2hex */
  10456. OPENSSL_free(str_serial);
  10457. /* Free certificate memory */
  10458. X509_free(cert);
  10459. }
  10460. }
  10461. #ifdef OPENSSL_API_1_1
  10462. #else
  10463. static void
  10464. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10465. {
  10466. (void)line;
  10467. (void)file;
  10468. if (mode & 1) {
  10469. /* 1 is CRYPTO_LOCK */
  10470. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10471. } else {
  10472. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10473. }
  10474. }
  10475. #endif /* OPENSSL_API_1_1 */
  10476. #if !defined(NO_SSL_DL)
  10477. static void *
  10478. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10479. {
  10480. union {
  10481. void *p;
  10482. void (*fp)(void);
  10483. } u;
  10484. void *dll_handle;
  10485. struct ssl_func *fp;
  10486. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10487. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10488. return NULL;
  10489. }
  10490. for (fp = sw; fp->name != NULL; fp++) {
  10491. #ifdef _WIN32
  10492. /* GetProcAddress() returns pointer to function */
  10493. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10494. #else
  10495. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10496. * pointers to function pointers. We need to use a union to make a
  10497. * cast. */
  10498. u.p = dlsym(dll_handle, fp->name);
  10499. #endif /* _WIN32 */
  10500. if (u.fp == NULL) {
  10501. mg_cry(fc(ctx),
  10502. "%s: %s: cannot find %s",
  10503. __func__,
  10504. dll_name,
  10505. fp->name);
  10506. dlclose(dll_handle);
  10507. return NULL;
  10508. } else {
  10509. fp->ptr = u.fp;
  10510. }
  10511. }
  10512. return dll_handle;
  10513. }
  10514. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10515. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10516. #endif /* NO_SSL_DL */
  10517. #if defined(SSL_ALREADY_INITIALIZED)
  10518. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10519. #else
  10520. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10521. #endif
  10522. static int
  10523. initialize_ssl(struct mg_context *ctx)
  10524. {
  10525. #ifdef OPENSSL_API_1_1
  10526. #if !defined(NO_SSL_DL)
  10527. if (!cryptolib_dll_handle) {
  10528. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10529. if (!cryptolib_dll_handle) {
  10530. return 0;
  10531. }
  10532. }
  10533. #else
  10534. (void)ctx;
  10535. #endif /* NO_SSL_DL */
  10536. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10537. return 1;
  10538. }
  10539. #else
  10540. int i;
  10541. size_t size;
  10542. #if !defined(NO_SSL_DL)
  10543. if (!cryptolib_dll_handle) {
  10544. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10545. if (!cryptolib_dll_handle) {
  10546. return 0;
  10547. }
  10548. }
  10549. #else
  10550. (void)ctx;
  10551. #endif /* NO_SSL_DL */
  10552. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10553. return 1;
  10554. }
  10555. /* Initialize locking callbacks, needed for thread safety.
  10556. * http://www.openssl.org/support/faq.html#PROG1
  10557. */
  10558. i = CRYPTO_num_locks();
  10559. if (i < 0) {
  10560. i = 0;
  10561. }
  10562. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10563. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10564. mg_cry(fc(ctx),
  10565. "%s: cannot allocate mutexes: %s",
  10566. __func__,
  10567. ssl_error());
  10568. return 0;
  10569. }
  10570. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10571. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10572. }
  10573. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10574. CRYPTO_set_id_callback(&mg_current_thread_id);
  10575. #endif /* OPENSSL_API_1_1 */
  10576. return 1;
  10577. }
  10578. static int
  10579. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10580. {
  10581. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10582. mg_cry(fc(ctx),
  10583. "%s: cannot open certificate file %s: %s",
  10584. __func__,
  10585. pem,
  10586. ssl_error());
  10587. return 0;
  10588. }
  10589. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10590. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10591. mg_cry(fc(ctx),
  10592. "%s: cannot open private key file %s: %s",
  10593. __func__,
  10594. pem,
  10595. ssl_error());
  10596. return 0;
  10597. }
  10598. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10599. mg_cry(fc(ctx),
  10600. "%s: certificate and private key do not match: %s",
  10601. __func__,
  10602. pem);
  10603. return 0;
  10604. }
  10605. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10606. mg_cry(fc(ctx),
  10607. "%s: cannot use certificate chain file %s: %s",
  10608. __func__,
  10609. pem,
  10610. ssl_error());
  10611. return 0;
  10612. }
  10613. return 1;
  10614. }
  10615. #ifdef OPENSSL_API_1_1
  10616. static unsigned long
  10617. ssl_get_protocol(int version_id)
  10618. {
  10619. long unsigned ret = SSL_OP_ALL;
  10620. if (version_id > 0)
  10621. ret |= SSL_OP_NO_SSLv2;
  10622. if (version_id > 1)
  10623. ret |= SSL_OP_NO_SSLv3;
  10624. if (version_id > 2)
  10625. ret |= SSL_OP_NO_TLSv1;
  10626. if (version_id > 3)
  10627. ret |= SSL_OP_NO_TLSv1_1;
  10628. return ret;
  10629. }
  10630. #else
  10631. static long
  10632. ssl_get_protocol(int version_id)
  10633. {
  10634. long ret = SSL_OP_ALL;
  10635. if (version_id > 0)
  10636. ret |= SSL_OP_NO_SSLv2;
  10637. if (version_id > 1)
  10638. ret |= SSL_OP_NO_SSLv3;
  10639. if (version_id > 2)
  10640. ret |= SSL_OP_NO_TLSv1;
  10641. if (version_id > 3)
  10642. ret |= SSL_OP_NO_TLSv1_1;
  10643. return ret;
  10644. }
  10645. #endif /* OPENSSL_API_1_1 */
  10646. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10647. static int
  10648. set_ssl_option(struct mg_context *ctx)
  10649. {
  10650. const char *pem;
  10651. int callback_ret;
  10652. int should_verify_peer;
  10653. const char *ca_path;
  10654. const char *ca_file;
  10655. int use_default_verify_paths;
  10656. int verify_depth;
  10657. time_t now_rt = time(NULL);
  10658. struct timespec now_mt;
  10659. md5_byte_t ssl_context_id[16];
  10660. md5_state_t md5state;
  10661. int protocol_ver;
  10662. /* If PEM file is not specified and the init_ssl callback
  10663. * is not specified, skip SSL initialization. */
  10664. if (!ctx) {
  10665. return 0;
  10666. }
  10667. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10668. && ctx->callbacks.init_ssl == NULL) {
  10669. return 1;
  10670. }
  10671. if (!initialize_ssl(ctx)) {
  10672. return 0;
  10673. }
  10674. #if !defined(NO_SSL_DL)
  10675. if (!ssllib_dll_handle) {
  10676. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10677. if (!ssllib_dll_handle) {
  10678. return 0;
  10679. }
  10680. }
  10681. #endif /* NO_SSL_DL */
  10682. #ifdef OPENSSL_API_1_1
  10683. /* Initialize SSL library */
  10684. OPENSSL_init_ssl(0, NULL);
  10685. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  10686. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  10687. NULL);
  10688. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  10689. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10690. return 0;
  10691. }
  10692. #else
  10693. /* Initialize SSL library */
  10694. SSL_library_init();
  10695. SSL_load_error_strings();
  10696. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10697. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10698. return 0;
  10699. }
  10700. #endif /* OPENSSL_API_1_1 */
  10701. SSL_CTX_clear_options(ctx->ssl_ctx,
  10702. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10703. | SSL_OP_NO_TLSv1_1);
  10704. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10705. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10706. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10707. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10708. #if !defined(NO_SSL_DL)
  10709. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10710. #endif /* NO_SSL_DL */
  10711. /* If a callback has been specified, call it. */
  10712. callback_ret =
  10713. (ctx->callbacks.init_ssl == NULL)
  10714. ? 0
  10715. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10716. /* If callback returns 0, civetweb sets up the SSL certificate.
  10717. * If it returns 1, civetweb assumes the calback already did this.
  10718. * If it returns -1, initializing ssl fails. */
  10719. if (callback_ret < 0) {
  10720. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10721. return 0;
  10722. }
  10723. if (callback_ret > 0) {
  10724. if (pem != NULL) {
  10725. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10726. }
  10727. return 1;
  10728. }
  10729. /* Use some UID as session context ID. */
  10730. md5_init(&md5state);
  10731. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10732. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10733. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10734. md5_append(&md5state,
  10735. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10736. strlen(ctx->config[LISTENING_PORTS]));
  10737. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10738. md5_finish(&md5state, ssl_context_id);
  10739. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10740. (const unsigned char *)&ssl_context_id,
  10741. sizeof(ssl_context_id));
  10742. if (pem != NULL) {
  10743. if (!ssl_use_pem_file(ctx, pem)) {
  10744. return 0;
  10745. }
  10746. }
  10747. should_verify_peer =
  10748. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10749. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10750. use_default_verify_paths =
  10751. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10752. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10753. if (should_verify_peer) {
  10754. ca_path = ctx->config[SSL_CA_PATH];
  10755. ca_file = ctx->config[SSL_CA_FILE];
  10756. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10757. != 1) {
  10758. mg_cry(fc(ctx),
  10759. "SSL_CTX_load_verify_locations error: %s "
  10760. "ssl_verify_peer requires setting "
  10761. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10762. "present in "
  10763. "the .conf file?",
  10764. ssl_error());
  10765. return 0;
  10766. }
  10767. SSL_CTX_set_verify(ctx->ssl_ctx,
  10768. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10769. NULL);
  10770. if (use_default_verify_paths
  10771. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10772. mg_cry(fc(ctx),
  10773. "SSL_CTX_set_default_verify_paths error: %s",
  10774. ssl_error());
  10775. return 0;
  10776. }
  10777. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10778. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10779. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10780. }
  10781. }
  10782. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10783. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10784. != 1) {
  10785. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10786. }
  10787. }
  10788. return 1;
  10789. }
  10790. static void
  10791. uninitialize_ssl(struct mg_context *ctx)
  10792. {
  10793. #ifdef OPENSSL_API_1_1
  10794. (void)ctx;
  10795. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10796. /* Shutdown according to
  10797. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10798. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10799. */
  10800. CONF_modules_unload(1);
  10801. #else
  10802. int i;
  10803. (void)ctx;
  10804. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10805. /* Shutdown according to
  10806. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10807. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10808. */
  10809. CRYPTO_set_locking_callback(NULL);
  10810. CRYPTO_set_id_callback(NULL);
  10811. ENGINE_cleanup();
  10812. CONF_modules_unload(1);
  10813. ERR_free_strings();
  10814. EVP_cleanup();
  10815. CRYPTO_cleanup_all_ex_data();
  10816. ERR_remove_state(0);
  10817. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10818. pthread_mutex_destroy(&ssl_mutexes[i]);
  10819. }
  10820. mg_free(ssl_mutexes);
  10821. ssl_mutexes = NULL;
  10822. #endif /* OPENSSL_API_1_1 */
  10823. }
  10824. }
  10825. #endif /* !NO_SSL */
  10826. static int
  10827. set_gpass_option(struct mg_context *ctx)
  10828. {
  10829. if (ctx) {
  10830. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10831. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10832. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10833. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10834. return 0;
  10835. }
  10836. return 1;
  10837. }
  10838. return 0;
  10839. }
  10840. static int
  10841. set_acl_option(struct mg_context *ctx)
  10842. {
  10843. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10844. }
  10845. static void
  10846. reset_per_request_attributes(struct mg_connection *conn)
  10847. {
  10848. if (!conn) {
  10849. return;
  10850. }
  10851. conn->path_info = NULL;
  10852. conn->num_bytes_sent = conn->consumed_content = 0;
  10853. conn->status_code = -1;
  10854. conn->is_chunked = 0;
  10855. conn->must_close = conn->request_len = conn->throttle = 0;
  10856. conn->request_info.content_length = -1;
  10857. conn->request_info.remote_user = NULL;
  10858. conn->request_info.request_method = NULL;
  10859. conn->request_info.request_uri = NULL;
  10860. conn->request_info.local_uri = NULL;
  10861. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10862. * local_uri and request_uri */
  10863. conn->request_info.http_version = NULL;
  10864. conn->request_info.num_headers = 0;
  10865. conn->data_len = 0;
  10866. conn->chunk_remainder = 0;
  10867. }
  10868. #if 0
  10869. /* Note: set_sock_timeout is not required for non-blocking sockets.
  10870. * Leave this function here (commented out) for reference until
  10871. * CivetWeb 1.9 is tested, and the tests confirme this function is
  10872. * no longer required.
  10873. */
  10874. static int
  10875. set_sock_timeout(SOCKET sock, int milliseconds)
  10876. {
  10877. int r0 = 0, r1, r2;
  10878. #ifdef _WIN32
  10879. /* Windows specific */
  10880. DWORD tv = (DWORD)milliseconds;
  10881. #else
  10882. /* Linux, ... (not Windows) */
  10883. struct timeval tv;
  10884. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10885. * max. time waiting for the acknowledged of TCP data before the connection
  10886. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10887. * If this option is not set, the default timeout of 20-30 minutes is used.
  10888. */
  10889. /* #define TCP_USER_TIMEOUT (18) */
  10890. #if defined(TCP_USER_TIMEOUT)
  10891. unsigned int uto = (unsigned int)milliseconds;
  10892. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10893. #endif
  10894. memset(&tv, 0, sizeof(tv));
  10895. tv.tv_sec = milliseconds / 1000;
  10896. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10897. #endif /* _WIN32 */
  10898. r1 = setsockopt(
  10899. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10900. r2 = setsockopt(
  10901. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10902. return r0 || r1 || r2;
  10903. }
  10904. #endif
  10905. static int
  10906. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10907. {
  10908. if (setsockopt(sock,
  10909. IPPROTO_TCP,
  10910. TCP_NODELAY,
  10911. (SOCK_OPT_TYPE)&nodelay_on,
  10912. sizeof(nodelay_on)) != 0) {
  10913. /* Error */
  10914. return 1;
  10915. }
  10916. /* OK */
  10917. return 0;
  10918. }
  10919. static void
  10920. close_socket_gracefully(struct mg_connection *conn)
  10921. {
  10922. #if defined(_WIN32)
  10923. char buf[MG_BUF_LEN];
  10924. int n;
  10925. #endif
  10926. struct linger linger;
  10927. int error_code = 0;
  10928. int linger_timeout = -2;
  10929. socklen_t opt_len = sizeof(error_code);
  10930. if (!conn) {
  10931. return;
  10932. }
  10933. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  10934. * "Note that enabling a nonzero timeout on a nonblocking socket
  10935. * is not recommended.", so set it to blocking now */
  10936. set_blocking_mode(conn->client.sock, 1);
  10937. /* Send FIN to the client */
  10938. shutdown(conn->client.sock, SHUTDOWN_WR);
  10939. #if defined(_WIN32)
  10940. /* Read and discard pending incoming data. If we do not do that and
  10941. * close
  10942. * the socket, the data in the send buffer may be discarded. This
  10943. * behaviour is seen on Windows, when client keeps sending data
  10944. * when server decides to close the connection; then when client
  10945. * does recv() it gets no data back. */
  10946. do {
  10947. n = pull(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  10948. } while (n > 0);
  10949. #endif
  10950. if (conn->ctx->config[LINGER_TIMEOUT]) {
  10951. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  10952. }
  10953. /* Set linger option according to configuration */
  10954. if (linger_timeout >= 0) {
  10955. /* Set linger option to avoid socket hanging out after close. This
  10956. * prevent ephemeral port exhaust problem under high QPS. */
  10957. linger.l_onoff = 1;
  10958. #if defined(_MSC_VER)
  10959. #pragma warning(push)
  10960. #pragma warning(disable : 4244)
  10961. #endif
  10962. linger.l_linger = (linger_timeout + 999) / 1000;
  10963. #if defined(_MSC_VER)
  10964. #pragma warning(pop)
  10965. #endif
  10966. } else {
  10967. linger.l_onoff = 0;
  10968. linger.l_linger = 0;
  10969. }
  10970. if (linger_timeout < -1) {
  10971. /* Default: don't configure any linger */
  10972. } else if (getsockopt(conn->client.sock,
  10973. SOL_SOCKET,
  10974. SO_ERROR,
  10975. (char *)&error_code,
  10976. &opt_len) != 0) {
  10977. /* Cannot determine if socket is already closed. This should
  10978. * not occur and never did in a test. Log an error message
  10979. * and continue. */
  10980. mg_cry(conn,
  10981. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10982. __func__,
  10983. strerror(ERRNO));
  10984. } else if (error_code == ECONNRESET) {
  10985. /* Socket already closed by client/peer, close socket without linger */
  10986. } else {
  10987. /* Set linger timeout */
  10988. if (setsockopt(conn->client.sock,
  10989. SOL_SOCKET,
  10990. SO_LINGER,
  10991. (char *)&linger,
  10992. sizeof(linger)) != 0) {
  10993. mg_cry(conn,
  10994. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  10995. __func__,
  10996. linger.l_onoff,
  10997. linger.l_linger,
  10998. strerror(ERRNO));
  10999. }
  11000. }
  11001. /* Now we know that our FIN is ACK-ed, safe to close */
  11002. closesocket(conn->client.sock);
  11003. conn->client.sock = INVALID_SOCKET;
  11004. }
  11005. static void
  11006. close_connection(struct mg_connection *conn)
  11007. {
  11008. if (!conn || !conn->ctx) {
  11009. return;
  11010. }
  11011. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11012. if (conn->lua_websocket_state) {
  11013. lua_websocket_close(conn, conn->lua_websocket_state);
  11014. conn->lua_websocket_state = NULL;
  11015. }
  11016. #endif
  11017. /* call the connection_close callback if assigned */
  11018. if ((conn->ctx->callbacks.connection_close != NULL)
  11019. && (conn->ctx->context_type == 1)) {
  11020. conn->ctx->callbacks.connection_close(conn);
  11021. }
  11022. mg_lock_connection(conn);
  11023. conn->must_close = 1;
  11024. #ifndef NO_SSL
  11025. if (conn->ssl != NULL) {
  11026. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11027. */
  11028. SSL_shutdown(conn->ssl);
  11029. SSL_free(conn->ssl);
  11030. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11031. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11032. #ifndef OPENSSL_API_1_1
  11033. ERR_remove_state(0);
  11034. #endif
  11035. conn->ssl = NULL;
  11036. }
  11037. #endif
  11038. if (conn->client.sock != INVALID_SOCKET) {
  11039. close_socket_gracefully(conn);
  11040. conn->client.sock = INVALID_SOCKET;
  11041. }
  11042. mg_unlock_connection(conn);
  11043. }
  11044. void
  11045. mg_close_connection(struct mg_connection *conn)
  11046. {
  11047. struct mg_context *client_ctx = NULL;
  11048. if (conn == NULL) {
  11049. return;
  11050. }
  11051. #if defined(USE_WEBSOCKET)
  11052. if (conn->ctx->context_type == 2) {
  11053. unsigned int i;
  11054. /* ws/wss client */
  11055. client_ctx = conn->ctx;
  11056. /* client context: loops must end */
  11057. conn->ctx->stop_flag = 1;
  11058. /* We need to get the client thread out of the select/recv call here. */
  11059. /* Since we use a sleep quantum of some seconds to check for recv
  11060. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11061. /* join worker thread */
  11062. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11063. if (client_ctx->worker_threadids[i] != 0) {
  11064. mg_join_thread(client_ctx->worker_threadids[i]);
  11065. }
  11066. }
  11067. }
  11068. #else
  11069. (void)client_ctx;
  11070. #endif
  11071. close_connection(conn);
  11072. #ifndef NO_SSL
  11073. if (conn->client_ssl_ctx != NULL) {
  11074. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11075. }
  11076. #endif
  11077. if (client_ctx != NULL) {
  11078. /* free context */
  11079. mg_free(client_ctx->worker_threadids);
  11080. mg_free(client_ctx);
  11081. (void)pthread_mutex_destroy(&conn->mutex);
  11082. mg_free(conn);
  11083. }
  11084. }
  11085. static struct mg_connection *
  11086. mg_connect_client_impl(const struct mg_client_options *client_options,
  11087. int use_ssl,
  11088. char *ebuf,
  11089. size_t ebuf_len)
  11090. {
  11091. static struct mg_context fake_ctx;
  11092. struct mg_connection *conn = NULL;
  11093. SOCKET sock;
  11094. union usa sa;
  11095. if (!connect_socket(&fake_ctx,
  11096. client_options->host,
  11097. client_options->port,
  11098. use_ssl,
  11099. ebuf,
  11100. ebuf_len,
  11101. &sock,
  11102. &sa)) {
  11103. ;
  11104. } else if ((conn = (struct mg_connection *)
  11105. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  11106. mg_snprintf(NULL,
  11107. NULL, /* No truncation check for ebuf */
  11108. ebuf,
  11109. ebuf_len,
  11110. "calloc(): %s",
  11111. strerror(ERRNO));
  11112. closesocket(sock);
  11113. #ifndef NO_SSL
  11114. #ifdef OPENSSL_API_1_1
  11115. } else if (use_ssl
  11116. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method()))
  11117. == NULL) {
  11118. mg_snprintf(NULL,
  11119. NULL, /* No truncation check for ebuf */
  11120. ebuf,
  11121. ebuf_len,
  11122. "SSL_CTX_new error");
  11123. closesocket(sock);
  11124. mg_free(conn);
  11125. conn = NULL;
  11126. #else
  11127. } else if (use_ssl
  11128. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11129. == NULL) {
  11130. mg_snprintf(NULL,
  11131. NULL, /* No truncation check for ebuf */
  11132. ebuf,
  11133. ebuf_len,
  11134. "SSL_CTX_new error");
  11135. closesocket(sock);
  11136. mg_free(conn);
  11137. conn = NULL;
  11138. #endif /* OPENSSL_API_1_1 */
  11139. #endif /* NO_SSL */
  11140. } else {
  11141. #ifdef USE_IPV6
  11142. socklen_t len = (sa.sa.sa_family == AF_INET)
  11143. ? sizeof(conn->client.rsa.sin)
  11144. : sizeof(conn->client.rsa.sin6);
  11145. struct sockaddr *psa =
  11146. (sa.sa.sa_family == AF_INET)
  11147. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11148. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11149. #else
  11150. socklen_t len = sizeof(conn->client.rsa.sin);
  11151. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11152. #endif
  11153. conn->buf_size = MAX_REQUEST_SIZE;
  11154. conn->buf = (char *)(conn + 1);
  11155. conn->ctx = &fake_ctx;
  11156. conn->client.sock = sock;
  11157. conn->client.lsa = sa;
  11158. if (getsockname(sock, psa, &len) != 0) {
  11159. mg_cry(conn,
  11160. "%s: getsockname() failed: %s",
  11161. __func__,
  11162. strerror(ERRNO));
  11163. }
  11164. conn->client.is_ssl = use_ssl ? 1 : 0;
  11165. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11166. #ifndef NO_SSL
  11167. if (use_ssl) {
  11168. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  11169. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11170. * SSL_CTX_set_verify call is needed to switch off server
  11171. * certificate checking, which is off by default in OpenSSL and
  11172. * on in yaSSL. */
  11173. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11174. * SSL_VERIFY_PEER, verify_ssl_server); */
  11175. if (client_options->client_cert) {
  11176. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  11177. mg_snprintf(NULL,
  11178. NULL, /* No truncation check for ebuf */
  11179. ebuf,
  11180. ebuf_len,
  11181. "Can not use SSL client certificate");
  11182. SSL_CTX_free(conn->client_ssl_ctx);
  11183. closesocket(sock);
  11184. mg_free(conn);
  11185. conn = NULL;
  11186. }
  11187. }
  11188. if (client_options->server_cert) {
  11189. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11190. client_options->server_cert,
  11191. NULL);
  11192. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11193. } else {
  11194. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11195. }
  11196. if (!sslize(conn,
  11197. conn->client_ssl_ctx,
  11198. SSL_connect,
  11199. &(conn->ctx->stop_flag))) {
  11200. mg_snprintf(NULL,
  11201. NULL, /* No truncation check for ebuf */
  11202. ebuf,
  11203. ebuf_len,
  11204. "SSL connection error");
  11205. SSL_CTX_free(conn->client_ssl_ctx);
  11206. closesocket(sock);
  11207. mg_free(conn);
  11208. conn = NULL;
  11209. }
  11210. }
  11211. #endif
  11212. }
  11213. if (conn) {
  11214. set_blocking_mode(sock, 0);
  11215. }
  11216. return conn;
  11217. }
  11218. CIVETWEB_API struct mg_connection *
  11219. mg_connect_client_secure(const struct mg_client_options *client_options,
  11220. char *error_buffer,
  11221. size_t error_buffer_size)
  11222. {
  11223. return mg_connect_client_impl(client_options,
  11224. 1,
  11225. error_buffer,
  11226. error_buffer_size);
  11227. }
  11228. struct mg_connection *
  11229. mg_connect_client(const char *host,
  11230. int port,
  11231. int use_ssl,
  11232. char *error_buffer,
  11233. size_t error_buffer_size)
  11234. {
  11235. struct mg_client_options opts;
  11236. memset(&opts, 0, sizeof(opts));
  11237. opts.host = host;
  11238. opts.port = port;
  11239. return mg_connect_client_impl(&opts,
  11240. use_ssl,
  11241. error_buffer,
  11242. error_buffer_size);
  11243. }
  11244. static const struct {
  11245. const char *proto;
  11246. size_t proto_len;
  11247. unsigned default_port;
  11248. } abs_uri_protocols[] = {{"http://", 7, 80},
  11249. {"https://", 8, 443},
  11250. {"ws://", 5, 80},
  11251. {"wss://", 6, 443},
  11252. {NULL, 0, 0}};
  11253. /* Check if the uri is valid.
  11254. * return 0 for invalid uri,
  11255. * return 1 for *,
  11256. * return 2 for relative uri,
  11257. * return 3 for absolute uri without port,
  11258. * return 4 for absolute uri with port */
  11259. static int
  11260. get_uri_type(const char *uri)
  11261. {
  11262. int i;
  11263. char *hostend, *portbegin, *portend;
  11264. unsigned long port;
  11265. /* According to the HTTP standard
  11266. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11267. * URI can be an asterisk (*) or should start with slash (relative uri),
  11268. * or it should start with the protocol (absolute uri). */
  11269. if (uri[0] == '*' && uri[1] == '\0') {
  11270. /* asterisk */
  11271. return 1;
  11272. }
  11273. /* Valid URIs according to RFC 3986
  11274. * (https://www.ietf.org/rfc/rfc3986.txt)
  11275. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11276. * and unreserved characters A-Z a-z 0-9 and -._~
  11277. * and % encoded symbols.
  11278. */
  11279. for (i = 0; uri[i] != 0; i++) {
  11280. if (uri[i] < 33) {
  11281. /* control characters and spaces are invalid */
  11282. return 0;
  11283. }
  11284. if (uri[i] > 126) {
  11285. /* non-ascii characters must be % encoded */
  11286. return 0;
  11287. } else {
  11288. switch (uri[i]) {
  11289. case '"': /* 34 */
  11290. case '<': /* 60 */
  11291. case '>': /* 62 */
  11292. case '\\': /* 92 */
  11293. case '^': /* 94 */
  11294. case '`': /* 96 */
  11295. case '{': /* 123 */
  11296. case '|': /* 124 */
  11297. case '}': /* 125 */
  11298. return 0;
  11299. default:
  11300. /* character is ok */
  11301. break;
  11302. }
  11303. }
  11304. }
  11305. /* A relative uri starts with a / character */
  11306. if (uri[0] == '/') {
  11307. /* relative uri */
  11308. return 2;
  11309. }
  11310. /* It could be an absolute uri: */
  11311. /* This function only checks if the uri is valid, not if it is
  11312. * addressing the current server. So civetweb can also be used
  11313. * as a proxy server. */
  11314. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11315. if (mg_strncasecmp(uri,
  11316. abs_uri_protocols[i].proto,
  11317. abs_uri_protocols[i].proto_len) == 0) {
  11318. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11319. if (!hostend) {
  11320. return 0;
  11321. }
  11322. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11323. if (!portbegin) {
  11324. return 3;
  11325. }
  11326. port = strtoul(portbegin + 1, &portend, 10);
  11327. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11328. return 0;
  11329. }
  11330. return 4;
  11331. }
  11332. }
  11333. return 0;
  11334. }
  11335. /* Return NULL or the relative uri at the current server */
  11336. static const char *
  11337. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11338. {
  11339. const char *server_domain;
  11340. size_t server_domain_len;
  11341. size_t request_domain_len = 0;
  11342. unsigned long port = 0;
  11343. int i, auth_domain_check_enabled;
  11344. const char *hostbegin = NULL;
  11345. const char *hostend = NULL;
  11346. const char *portbegin;
  11347. char *portend;
  11348. auth_domain_check_enabled =
  11349. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  11350. /* DNS is case insensitive, so use case insensitive string compare here
  11351. */
  11352. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11353. if (!server_domain && auth_domain_check_enabled) {
  11354. return 0;
  11355. }
  11356. server_domain_len = strlen(server_domain);
  11357. if (!server_domain_len) {
  11358. return 0;
  11359. }
  11360. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11361. if (mg_strncasecmp(uri,
  11362. abs_uri_protocols[i].proto,
  11363. abs_uri_protocols[i].proto_len) == 0) {
  11364. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11365. hostend = strchr(hostbegin, '/');
  11366. if (!hostend) {
  11367. return 0;
  11368. }
  11369. portbegin = strchr(hostbegin, ':');
  11370. if ((!portbegin) || (portbegin > hostend)) {
  11371. port = abs_uri_protocols[i].default_port;
  11372. request_domain_len = (size_t)(hostend - hostbegin);
  11373. } else {
  11374. port = strtoul(portbegin + 1, &portend, 10);
  11375. if ((portend != hostend) || (port <= 0)
  11376. || !is_valid_port(port)) {
  11377. return 0;
  11378. }
  11379. request_domain_len = (size_t)(portbegin - hostbegin);
  11380. }
  11381. /* protocol found, port set */
  11382. break;
  11383. }
  11384. }
  11385. if (!port) {
  11386. /* port remains 0 if the protocol is not found */
  11387. return 0;
  11388. }
  11389. /* Check if the request is directed to a different server. */
  11390. /* First check if the port is the same (IPv4 and IPv6). */
  11391. #if defined(USE_IPV6)
  11392. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11393. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11394. /* Request is directed to a different port */
  11395. return 0;
  11396. }
  11397. } else
  11398. #endif
  11399. {
  11400. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11401. /* Request is directed to a different port */
  11402. return 0;
  11403. }
  11404. }
  11405. /* Finally check if the server corresponds to the authentication
  11406. * domain of the server (the server domain).
  11407. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11408. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11409. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11410. * or http://mydomain.com.fake/path/file.ext).
  11411. */
  11412. if (auth_domain_check_enabled) {
  11413. if ((request_domain_len == server_domain_len)
  11414. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11415. /* Request is directed to this server - full name match. */
  11416. } else {
  11417. if (request_domain_len < (server_domain_len + 2)) {
  11418. /* Request is directed to another server: The server name is
  11419. * longer
  11420. * than
  11421. * the request name. Drop this case here to avoid overflows in
  11422. * the
  11423. * following checks. */
  11424. return 0;
  11425. }
  11426. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11427. /* Request is directed to another server: It could be a
  11428. * substring
  11429. * like notmyserver.com */
  11430. return 0;
  11431. }
  11432. if (0 != memcmp(server_domain,
  11433. hostbegin + request_domain_len - server_domain_len,
  11434. server_domain_len)) {
  11435. /* Request is directed to another server:
  11436. * The server name is different. */
  11437. return 0;
  11438. }
  11439. }
  11440. }
  11441. return hostend;
  11442. }
  11443. static int
  11444. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11445. {
  11446. const char *cl;
  11447. if (ebuf_len > 0) {
  11448. ebuf[0] = '\0';
  11449. }
  11450. *err = 0;
  11451. reset_per_request_attributes(conn);
  11452. if (!conn) {
  11453. mg_snprintf(conn,
  11454. NULL, /* No truncation check for ebuf */
  11455. ebuf,
  11456. ebuf_len,
  11457. "%s",
  11458. "Internal error");
  11459. *err = 500;
  11460. return 0;
  11461. }
  11462. /* Set the time the request was received. This value should be used for
  11463. * timeouts. */
  11464. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11465. conn->request_len =
  11466. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11467. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11468. */
  11469. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11470. mg_snprintf(conn,
  11471. NULL, /* No truncation check for ebuf */
  11472. ebuf,
  11473. ebuf_len,
  11474. "%s",
  11475. "Invalid request size");
  11476. *err = 500;
  11477. return 0;
  11478. }
  11479. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11480. mg_snprintf(conn,
  11481. NULL, /* No truncation check for ebuf */
  11482. ebuf,
  11483. ebuf_len,
  11484. "%s",
  11485. "Request Too Large");
  11486. *err = 413;
  11487. return 0;
  11488. } else if (conn->request_len <= 0) {
  11489. if (conn->data_len > 0) {
  11490. mg_snprintf(conn,
  11491. NULL, /* No truncation check for ebuf */
  11492. ebuf,
  11493. ebuf_len,
  11494. "%s",
  11495. "Client sent malformed request");
  11496. *err = 400;
  11497. } else {
  11498. /* Server did not recv anything -> just close the connection */
  11499. conn->must_close = 1;
  11500. mg_snprintf(conn,
  11501. NULL, /* No truncation check for ebuf */
  11502. ebuf,
  11503. ebuf_len,
  11504. "%s",
  11505. "Client did not send a request");
  11506. *err = 0;
  11507. }
  11508. return 0;
  11509. } else if (parse_http_message(conn->buf,
  11510. conn->buf_size,
  11511. &conn->request_info) <= 0) {
  11512. mg_snprintf(conn,
  11513. NULL, /* No truncation check for ebuf */
  11514. ebuf,
  11515. ebuf_len,
  11516. "%s",
  11517. "Bad Request");
  11518. *err = 400;
  11519. return 0;
  11520. } else {
  11521. /* Message is a valid request or response */
  11522. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11523. /* Request/response has content length set */
  11524. char *endptr = NULL;
  11525. conn->content_len = strtoll(cl, &endptr, 10);
  11526. if (endptr == cl) {
  11527. mg_snprintf(conn,
  11528. NULL, /* No truncation check for ebuf */
  11529. ebuf,
  11530. ebuf_len,
  11531. "%s",
  11532. "Bad Request");
  11533. *err = 411;
  11534. return 0;
  11535. }
  11536. /* Publish the content length back to the request info. */
  11537. conn->request_info.content_length = conn->content_len;
  11538. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11539. != NULL
  11540. && !mg_strcasecmp(cl, "chunked")) {
  11541. conn->is_chunked = 1;
  11542. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11543. || !mg_strcasecmp(conn->request_info.request_method,
  11544. "PUT")) {
  11545. /* POST or PUT request without content length set */
  11546. conn->content_len = -1;
  11547. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11548. "HTTP/",
  11549. 5)) {
  11550. /* Response without content length set */
  11551. conn->content_len = -1;
  11552. } else {
  11553. /* Other request */
  11554. conn->content_len = 0;
  11555. }
  11556. }
  11557. return 1;
  11558. }
  11559. int
  11560. mg_get_response(struct mg_connection *conn,
  11561. char *ebuf,
  11562. size_t ebuf_len,
  11563. int timeout)
  11564. {
  11565. if (conn) {
  11566. /* Implementation of API function for HTTP clients */
  11567. int err, ret;
  11568. struct mg_context *octx = conn->ctx;
  11569. struct mg_context rctx = *(conn->ctx);
  11570. char txt[32]; /* will not overflow */
  11571. if (timeout >= 0) {
  11572. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11573. rctx.config[REQUEST_TIMEOUT] = txt;
  11574. /* Not required for non-blocking sockets.
  11575. set_sock_timeout(conn->client.sock, timeout);
  11576. */
  11577. } else {
  11578. rctx.config[REQUEST_TIMEOUT] = NULL;
  11579. }
  11580. conn->ctx = &rctx;
  11581. ret = getreq(conn, ebuf, ebuf_len, &err);
  11582. conn->ctx = octx;
  11583. /* TODO: 1) uri is deprecated;
  11584. * 2) here, ri.uri is the http response code */
  11585. conn->request_info.uri = conn->request_info.request_uri;
  11586. /* TODO (mid): Define proper return values - maybe return length?
  11587. * For the first test use <0 for error and >0 for OK */
  11588. return (ret == 0) ? -1 : +1;
  11589. }
  11590. return -1;
  11591. }
  11592. struct mg_connection *
  11593. mg_download(const char *host,
  11594. int port,
  11595. int use_ssl,
  11596. char *ebuf,
  11597. size_t ebuf_len,
  11598. const char *fmt,
  11599. ...)
  11600. {
  11601. struct mg_connection *conn;
  11602. va_list ap;
  11603. int i;
  11604. int reqerr;
  11605. va_start(ap, fmt);
  11606. ebuf[0] = '\0';
  11607. /* open a connection */
  11608. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11609. if (conn != NULL) {
  11610. i = mg_vprintf(conn, fmt, ap);
  11611. if (i <= 0) {
  11612. mg_snprintf(conn,
  11613. NULL, /* No truncation check for ebuf */
  11614. ebuf,
  11615. ebuf_len,
  11616. "%s",
  11617. "Error sending request");
  11618. } else {
  11619. getreq(conn, ebuf, ebuf_len, &reqerr);
  11620. /* TODO: 1) uri is deprecated;
  11621. * 2) here, ri.uri is the http response code */
  11622. conn->request_info.uri = conn->request_info.request_uri;
  11623. }
  11624. }
  11625. /* if an error occured, close the connection */
  11626. if (ebuf[0] != '\0' && conn != NULL) {
  11627. mg_close_connection(conn);
  11628. conn = NULL;
  11629. }
  11630. va_end(ap);
  11631. return conn;
  11632. }
  11633. struct websocket_client_thread_data {
  11634. struct mg_connection *conn;
  11635. mg_websocket_data_handler data_handler;
  11636. mg_websocket_close_handler close_handler;
  11637. void *callback_data;
  11638. };
  11639. #if defined(USE_WEBSOCKET)
  11640. #ifdef _WIN32
  11641. static unsigned __stdcall websocket_client_thread(void *data)
  11642. #else
  11643. static void *
  11644. websocket_client_thread(void *data)
  11645. #endif
  11646. {
  11647. struct websocket_client_thread_data *cdata =
  11648. (struct websocket_client_thread_data *)data;
  11649. mg_set_thread_name("ws-clnt");
  11650. if (cdata->conn->ctx) {
  11651. if (cdata->conn->ctx->callbacks.init_thread) {
  11652. /* 3 indicates a websocket client thread */
  11653. /* TODO: check if conn->ctx can be set */
  11654. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11655. }
  11656. }
  11657. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11658. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11659. if (cdata->close_handler != NULL) {
  11660. cdata->close_handler(cdata->conn, cdata->callback_data);
  11661. }
  11662. /* The websocket_client context has only this thread. If it runs out,
  11663. set the stop_flag to 2 (= "stopped"). */
  11664. cdata->conn->ctx->stop_flag = 2;
  11665. mg_free((void *)cdata);
  11666. #ifdef _WIN32
  11667. return 0;
  11668. #else
  11669. return NULL;
  11670. #endif
  11671. }
  11672. #endif
  11673. struct mg_connection *
  11674. mg_connect_websocket_client(const char *host,
  11675. int port,
  11676. int use_ssl,
  11677. char *error_buffer,
  11678. size_t error_buffer_size,
  11679. const char *path,
  11680. const char *origin,
  11681. mg_websocket_data_handler data_func,
  11682. mg_websocket_close_handler close_func,
  11683. void *user_data)
  11684. {
  11685. struct mg_connection *conn = NULL;
  11686. #if defined(USE_WEBSOCKET)
  11687. struct mg_context *newctx = NULL;
  11688. struct websocket_client_thread_data *thread_data;
  11689. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11690. static const char *handshake_req;
  11691. if (origin != NULL) {
  11692. handshake_req = "GET %s HTTP/1.1\r\n"
  11693. "Host: %s\r\n"
  11694. "Upgrade: websocket\r\n"
  11695. "Connection: Upgrade\r\n"
  11696. "Sec-WebSocket-Key: %s\r\n"
  11697. "Sec-WebSocket-Version: 13\r\n"
  11698. "Origin: %s\r\n"
  11699. "\r\n";
  11700. } else {
  11701. handshake_req = "GET %s HTTP/1.1\r\n"
  11702. "Host: %s\r\n"
  11703. "Upgrade: websocket\r\n"
  11704. "Connection: Upgrade\r\n"
  11705. "Sec-WebSocket-Key: %s\r\n"
  11706. "Sec-WebSocket-Version: 13\r\n"
  11707. "\r\n";
  11708. }
  11709. /* Establish the client connection and request upgrade */
  11710. conn = mg_download(host,
  11711. port,
  11712. use_ssl,
  11713. error_buffer,
  11714. error_buffer_size,
  11715. handshake_req,
  11716. path,
  11717. host,
  11718. magic,
  11719. origin);
  11720. /* Connection object will be null if something goes wrong */
  11721. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11722. if (!*error_buffer) {
  11723. /* if there is a connection, but it did not return 101,
  11724. * error_buffer is not yet set */
  11725. mg_snprintf(conn,
  11726. NULL, /* No truncation check for ebuf */
  11727. error_buffer,
  11728. error_buffer_size,
  11729. "Unexpected server reply");
  11730. }
  11731. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11732. if (conn != NULL) {
  11733. mg_free(conn);
  11734. conn = NULL;
  11735. }
  11736. return conn;
  11737. }
  11738. /* For client connections, mg_context is fake. Since we need to set a
  11739. * callback function, we need to create a copy and modify it. */
  11740. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11741. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11742. newctx->user_data = user_data;
  11743. newctx->context_type = 2; /* ws/wss client context type */
  11744. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11745. newctx->worker_threadids =
  11746. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11747. conn->ctx = newctx;
  11748. thread_data = (struct websocket_client_thread_data *)
  11749. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11750. thread_data->conn = conn;
  11751. thread_data->data_handler = data_func;
  11752. thread_data->close_handler = close_func;
  11753. thread_data->callback_data = NULL;
  11754. /* Start a thread to read the websocket client connection
  11755. * This thread will automatically stop when mg_disconnect is
  11756. * called on the client connection */
  11757. if (mg_start_thread_with_id(websocket_client_thread,
  11758. (void *)thread_data,
  11759. newctx->worker_threadids) != 0) {
  11760. mg_free((void *)thread_data);
  11761. mg_free((void *)newctx->worker_threadids);
  11762. mg_free((void *)newctx);
  11763. mg_free((void *)conn);
  11764. conn = NULL;
  11765. DEBUG_TRACE("%s",
  11766. "Websocket client connect thread could not be started\r\n");
  11767. }
  11768. #else
  11769. /* Appease "unused parameter" warnings */
  11770. (void)host;
  11771. (void)port;
  11772. (void)use_ssl;
  11773. (void)error_buffer;
  11774. (void)error_buffer_size;
  11775. (void)path;
  11776. (void)origin;
  11777. (void)user_data;
  11778. (void)data_func;
  11779. (void)close_func;
  11780. #endif
  11781. return conn;
  11782. }
  11783. static void
  11784. process_new_connection(struct mg_connection *conn)
  11785. {
  11786. if (conn && conn->ctx) {
  11787. struct mg_request_info *ri = &conn->request_info;
  11788. int keep_alive_enabled, keep_alive, discard_len;
  11789. char ebuf[100];
  11790. const char *hostend;
  11791. int reqerr, uri_type;
  11792. keep_alive_enabled =
  11793. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11794. /* Important: on new connection, reset the receiving buffer. Credit
  11795. * goes to crule42. */
  11796. conn->data_len = 0;
  11797. conn->handled_requests = 0;
  11798. do {
  11799. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11800. conn->handled_requests + 1);
  11801. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11802. /* The request sent by the client could not be understood by
  11803. * the server, or it was incomplete or a timeout. Send an
  11804. * error message and close the connection. */
  11805. if (reqerr > 0) {
  11806. /*assert(ebuf[0] != '\0');*/
  11807. send_http_error(conn, reqerr, "%s", ebuf);
  11808. }
  11809. } else if (strcmp(ri->http_version, "1.0")
  11810. && strcmp(ri->http_version, "1.1")) {
  11811. mg_snprintf(conn,
  11812. NULL, /* No truncation check for ebuf */
  11813. ebuf,
  11814. sizeof(ebuf),
  11815. "Bad HTTP version: [%s]",
  11816. ri->http_version);
  11817. send_http_error(conn, 505, "%s", ebuf);
  11818. }
  11819. if (ebuf[0] == '\0') {
  11820. uri_type = get_uri_type(conn->request_info.request_uri);
  11821. switch (uri_type) {
  11822. case 1:
  11823. /* Asterisk */
  11824. conn->request_info.local_uri = NULL;
  11825. break;
  11826. case 2:
  11827. /* relative uri */
  11828. conn->request_info.local_uri =
  11829. conn->request_info.request_uri;
  11830. break;
  11831. case 3:
  11832. case 4:
  11833. /* absolute uri (with/without port) */
  11834. hostend = get_rel_url_at_current_server(
  11835. conn->request_info.request_uri, conn);
  11836. if (hostend) {
  11837. conn->request_info.local_uri = hostend;
  11838. } else {
  11839. conn->request_info.local_uri = NULL;
  11840. }
  11841. break;
  11842. default:
  11843. mg_snprintf(conn,
  11844. NULL, /* No truncation check for ebuf */
  11845. ebuf,
  11846. sizeof(ebuf),
  11847. "Invalid URI");
  11848. send_http_error(conn, 400, "%s", ebuf);
  11849. conn->request_info.local_uri = NULL;
  11850. break;
  11851. }
  11852. /* TODO: cleanup uri, local_uri and request_uri */
  11853. conn->request_info.uri = conn->request_info.local_uri;
  11854. }
  11855. DEBUG_TRACE("http: %s, error: %s",
  11856. (ri->http_version ? ri->http_version : "none"),
  11857. (ebuf[0] ? ebuf : "none"));
  11858. if (ebuf[0] == '\0') {
  11859. if (conn->request_info.local_uri) {
  11860. /* handle request to local server */
  11861. handle_request(conn);
  11862. DEBUG_TRACE("%s", "handle_request done");
  11863. if (conn->ctx->callbacks.end_request != NULL) {
  11864. conn->ctx->callbacks.end_request(conn,
  11865. conn->status_code);
  11866. DEBUG_TRACE("%s", "end_request callback done");
  11867. }
  11868. log_access(conn);
  11869. } else {
  11870. /* TODO: handle non-local request (PROXY) */
  11871. conn->must_close = 1;
  11872. }
  11873. } else {
  11874. conn->must_close = 1;
  11875. }
  11876. if (ri->remote_user != NULL) {
  11877. mg_free((void *)ri->remote_user);
  11878. /* Important! When having connections with and without auth
  11879. * would cause double free and then crash */
  11880. ri->remote_user = NULL;
  11881. }
  11882. /* NOTE(lsm): order is important here. should_keep_alive() call
  11883. * is
  11884. * using parsed request, which will be invalid after memmove's
  11885. * below.
  11886. * Therefore, memorize should_keep_alive() result now for later
  11887. * use
  11888. * in loop exit condition. */
  11889. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11890. && (conn->content_len >= 0) && should_keep_alive(conn);
  11891. /* Discard all buffered data for this request */
  11892. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11893. && ((conn->request_len + conn->content_len)
  11894. < (int64_t)conn->data_len))
  11895. ? (int)(conn->request_len + conn->content_len)
  11896. : conn->data_len;
  11897. /*assert(discard_len >= 0);*/
  11898. if (discard_len < 0) {
  11899. DEBUG_TRACE("internal error: discard_len = %li",
  11900. (long int)discard_len);
  11901. break;
  11902. }
  11903. conn->data_len -= discard_len;
  11904. if (conn->data_len > 0) {
  11905. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  11906. memmove(conn->buf,
  11907. conn->buf + discard_len,
  11908. (size_t)conn->data_len);
  11909. }
  11910. /* assert(conn->data_len >= 0); */
  11911. /* assert(conn->data_len <= conn->buf_size); */
  11912. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11913. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  11914. (long int)conn->data_len,
  11915. (long int)conn->buf_size);
  11916. break;
  11917. }
  11918. conn->handled_requests++;
  11919. } while (keep_alive);
  11920. }
  11921. }
  11922. #if defined(ALTERNATIVE_QUEUE)
  11923. static void
  11924. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11925. {
  11926. unsigned int i;
  11927. for (;;) {
  11928. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11929. /* find a free worker slot and signal it */
  11930. if (ctx->client_socks[i].in_use == 0) {
  11931. ctx->client_socks[i] = *sp;
  11932. ctx->client_socks[i].in_use = 1;
  11933. event_signal(ctx->client_wait_events[i]);
  11934. return;
  11935. }
  11936. }
  11937. /* queue is full */
  11938. mg_sleep(1);
  11939. }
  11940. }
  11941. static int
  11942. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11943. {
  11944. DEBUG_TRACE("%s", "going idle");
  11945. ctx->client_socks[thread_index].in_use = 0;
  11946. event_wait(ctx->client_wait_events[thread_index]);
  11947. *sp = ctx->client_socks[thread_index];
  11948. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11949. return !ctx->stop_flag;
  11950. }
  11951. #else /* ALTERNATIVE_QUEUE */
  11952. /* Worker threads take accepted socket from the queue */
  11953. static int
  11954. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11955. {
  11956. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11957. (void)thread_index;
  11958. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11959. DEBUG_TRACE("%s", "going idle");
  11960. /* If the queue is empty, wait. We're idle at this point. */
  11961. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11962. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11963. }
  11964. /* If we're stopping, sq_head may be equal to sq_tail. */
  11965. if (ctx->sq_head > ctx->sq_tail) {
  11966. /* Copy socket from the queue and increment tail */
  11967. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11968. ctx->sq_tail++;
  11969. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11970. /* Wrap pointers if needed */
  11971. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11972. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11973. ctx->sq_head -= QUEUE_SIZE(ctx);
  11974. }
  11975. }
  11976. (void)pthread_cond_signal(&ctx->sq_empty);
  11977. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11978. return !ctx->stop_flag;
  11979. #undef QUEUE_SIZE
  11980. }
  11981. /* Master thread adds accepted socket to a queue */
  11982. static void
  11983. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11984. {
  11985. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11986. if (!ctx) {
  11987. return;
  11988. }
  11989. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11990. /* If the queue is full, wait */
  11991. while (ctx->stop_flag == 0
  11992. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11993. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11994. }
  11995. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11996. /* Copy socket to the queue and increment head */
  11997. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11998. ctx->sq_head++;
  11999. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12000. }
  12001. (void)pthread_cond_signal(&ctx->sq_full);
  12002. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12003. #undef QUEUE_SIZE
  12004. }
  12005. #endif /* ALTERNATIVE_QUEUE */
  12006. struct worker_thread_args {
  12007. struct mg_context *ctx;
  12008. int index;
  12009. };
  12010. static void *
  12011. worker_thread_run(struct worker_thread_args *thread_args)
  12012. {
  12013. struct mg_context *ctx = thread_args->ctx;
  12014. struct mg_connection *conn;
  12015. struct mg_workerTLS tls;
  12016. #if defined(MG_LEGACY_INTERFACE)
  12017. uint32_t addr;
  12018. #endif
  12019. mg_set_thread_name("worker");
  12020. tls.is_master = 0;
  12021. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12022. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12023. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12024. #endif
  12025. /* Initialize thread local storage before calling any callback */
  12026. pthread_setspecific(sTlsKey, &tls);
  12027. if (ctx->callbacks.init_thread) {
  12028. /* call init_thread for a worker thread (type 1) */
  12029. ctx->callbacks.init_thread(ctx, 1);
  12030. }
  12031. /* Connection structure has been pre-allocated */
  12032. if (((int)thread_args->index < 0)
  12033. || ((unsigned)thread_args->index
  12034. >= (unsigned)ctx->cfg_worker_threads)) {
  12035. mg_cry(fc(ctx),
  12036. "Internal error: Invalid worker index %i",
  12037. (int)thread_args->index);
  12038. return NULL;
  12039. }
  12040. conn = ctx->worker_connections + thread_args->index;
  12041. /* Request buffers are not pre-allocated. They are private to the
  12042. * request and do not contain any state information that might be
  12043. * of interest to anyone observing a server status. */
  12044. conn->buf = (char *)mg_malloc(MAX_REQUEST_SIZE);
  12045. if (conn->buf == NULL) {
  12046. mg_cry(fc(ctx),
  12047. "Out of memory: Cannot allocate buffer for worker %i",
  12048. (int)thread_args->index);
  12049. return NULL;
  12050. }
  12051. conn->buf_size = MAX_REQUEST_SIZE;
  12052. conn->ctx = ctx;
  12053. conn->thread_index = thread_args->index;
  12054. conn->request_info.user_data = ctx->user_data;
  12055. /* Allocate a mutex for this connection to allow communication both
  12056. * within the request handler and from elsewhere in the application
  12057. */
  12058. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12059. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12060. * signal sq_empty condvar to wake up the master waiting in
  12061. * produce_socket() */
  12062. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12063. conn->conn_birth_time = time(NULL);
  12064. /* Fill in IP, port info early so even if SSL setup below fails,
  12065. * error handler would have the corresponding info.
  12066. * Thanks to Johannes Winkelmann for the patch.
  12067. */
  12068. #if defined(USE_IPV6)
  12069. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12070. conn->request_info.remote_port =
  12071. ntohs(conn->client.rsa.sin6.sin6_port);
  12072. } else
  12073. #endif
  12074. {
  12075. conn->request_info.remote_port =
  12076. ntohs(conn->client.rsa.sin.sin_port);
  12077. }
  12078. sockaddr_to_string(conn->request_info.remote_addr,
  12079. sizeof(conn->request_info.remote_addr),
  12080. &conn->client.rsa);
  12081. DEBUG_TRACE("Start processing connection from %s",
  12082. conn->request_info.remote_addr);
  12083. #if defined(MG_LEGACY_INTERFACE)
  12084. /* This legacy interface only works for the IPv4 case */
  12085. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12086. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12087. #endif
  12088. conn->request_info.is_ssl = conn->client.is_ssl;
  12089. if (conn->client.is_ssl) {
  12090. #ifndef NO_SSL
  12091. /* HTTPS connection */
  12092. if (sslize(conn,
  12093. conn->ctx->ssl_ctx,
  12094. SSL_accept,
  12095. &(conn->ctx->stop_flag))) {
  12096. /* Get SSL client certificate information (if set) */
  12097. ssl_get_client_cert_info(conn);
  12098. /* process HTTPS connection */
  12099. process_new_connection(conn);
  12100. /* Free client certificate info */
  12101. if (conn->request_info.client_cert) {
  12102. mg_free((void *)(conn->request_info.client_cert->subject));
  12103. mg_free((void *)(conn->request_info.client_cert->issuer));
  12104. mg_free((void *)(conn->request_info.client_cert->serial));
  12105. mg_free((void *)(conn->request_info.client_cert->finger));
  12106. conn->request_info.client_cert->subject = 0;
  12107. conn->request_info.client_cert->issuer = 0;
  12108. conn->request_info.client_cert->serial = 0;
  12109. conn->request_info.client_cert->finger = 0;
  12110. mg_free(conn->request_info.client_cert);
  12111. conn->request_info.client_cert = 0;
  12112. }
  12113. }
  12114. #endif
  12115. } else {
  12116. /* process HTTP connection */
  12117. process_new_connection(conn);
  12118. }
  12119. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12120. conn->request_info.remote_addr,
  12121. difftime(time(NULL), conn->conn_birth_time));
  12122. close_connection(conn);
  12123. DEBUG_TRACE("%s", "Connection closed");
  12124. }
  12125. pthread_setspecific(sTlsKey, NULL);
  12126. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12127. CloseHandle(tls.pthread_cond_helper_mutex);
  12128. #endif
  12129. pthread_mutex_destroy(&conn->mutex);
  12130. /* Free the request buffer. */
  12131. conn->buf_size = 0;
  12132. mg_free(conn->buf);
  12133. conn->buf = NULL;
  12134. DEBUG_TRACE("%s", "exiting");
  12135. return NULL;
  12136. }
  12137. /* Threads have different return types on Windows and Unix. */
  12138. #ifdef _WIN32
  12139. static unsigned __stdcall worker_thread(void *thread_func_param)
  12140. {
  12141. struct worker_thread_args *pwta =
  12142. (struct worker_thread_args *)thread_func_param;
  12143. worker_thread_run(pwta);
  12144. mg_free(thread_func_param);
  12145. return 0;
  12146. }
  12147. #else
  12148. static void *
  12149. worker_thread(void *thread_func_param)
  12150. {
  12151. struct worker_thread_args *pwta =
  12152. (struct worker_thread_args *)thread_func_param;
  12153. worker_thread_run(pwta);
  12154. mg_free(thread_func_param);
  12155. return NULL;
  12156. }
  12157. #endif /* _WIN32 */
  12158. static void
  12159. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12160. {
  12161. struct socket so;
  12162. char src_addr[IP_ADDR_STR_LEN];
  12163. socklen_t len = sizeof(so.rsa);
  12164. int on = 1;
  12165. if (!listener) {
  12166. return;
  12167. }
  12168. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12169. == INVALID_SOCKET) {
  12170. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12171. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12172. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12173. closesocket(so.sock);
  12174. so.sock = INVALID_SOCKET;
  12175. } else {
  12176. /* Put so socket structure into the queue */
  12177. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12178. set_close_on_exec(so.sock, fc(ctx));
  12179. so.is_ssl = listener->is_ssl;
  12180. so.ssl_redir = listener->ssl_redir;
  12181. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12182. mg_cry(fc(ctx),
  12183. "%s: getsockname() failed: %s",
  12184. __func__,
  12185. strerror(ERRNO));
  12186. }
  12187. /* Set TCP keep-alive. This is needed because if HTTP-level
  12188. * keep-alive
  12189. * is enabled, and client resets the connection, server won't get
  12190. * TCP FIN or RST and will keep the connection open forever. With
  12191. * TCP keep-alive, next keep-alive handshake will figure out that
  12192. * the client is down and will close the server end.
  12193. * Thanks to Igor Klopov who suggested the patch. */
  12194. if (setsockopt(so.sock,
  12195. SOL_SOCKET,
  12196. SO_KEEPALIVE,
  12197. (SOCK_OPT_TYPE)&on,
  12198. sizeof(on)) != 0) {
  12199. mg_cry(fc(ctx),
  12200. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12201. __func__,
  12202. strerror(ERRNO));
  12203. }
  12204. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12205. * to effectively fill up the underlying IP packet payload and
  12206. * reduce the overhead of sending lots of small buffers. However
  12207. * this hurts the server's throughput (ie. operations per second)
  12208. * when HTTP 1.1 persistent connections are used and the responses
  12209. * are relatively small (eg. less than 1400 bytes).
  12210. */
  12211. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12212. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12213. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12214. mg_cry(fc(ctx),
  12215. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12216. __func__,
  12217. strerror(ERRNO));
  12218. }
  12219. }
  12220. /* We are using non-blocking sockets. Thus, the
  12221. * set_sock_timeout(so.sock, timeout);
  12222. * call is no longer required. */
  12223. set_blocking_mode(so.sock, 0);
  12224. produce_socket(ctx, &so);
  12225. }
  12226. }
  12227. static void
  12228. master_thread_run(void *thread_func_param)
  12229. {
  12230. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12231. struct mg_workerTLS tls;
  12232. struct pollfd *pfd;
  12233. unsigned int i;
  12234. unsigned int workerthreadcount;
  12235. if (!ctx) {
  12236. return;
  12237. }
  12238. mg_set_thread_name("master");
  12239. /* Increase priority of the master thread */
  12240. #if defined(_WIN32)
  12241. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12242. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12243. int min_prio = sched_get_priority_min(SCHED_RR);
  12244. int max_prio = sched_get_priority_max(SCHED_RR);
  12245. if ((min_prio >= 0) && (max_prio >= 0)
  12246. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12247. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12248. struct sched_param sched_param = {0};
  12249. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12250. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12251. }
  12252. #endif
  12253. /* Initialize thread local storage */
  12254. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12255. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12256. #endif
  12257. tls.is_master = 1;
  12258. pthread_setspecific(sTlsKey, &tls);
  12259. if (ctx->callbacks.init_thread) {
  12260. /* Callback for the master thread (type 0) */
  12261. ctx->callbacks.init_thread(ctx, 0);
  12262. }
  12263. /* Server starts *now* */
  12264. ctx->start_time = time(NULL);
  12265. /* Start the server */
  12266. pfd = ctx->listening_socket_fds;
  12267. while (ctx->stop_flag == 0) {
  12268. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12269. pfd[i].fd = ctx->listening_sockets[i].sock;
  12270. pfd[i].events = POLLIN;
  12271. }
  12272. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12273. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12274. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12275. * successful poll, and POLLIN is defined as
  12276. * (POLLRDNORM | POLLRDBAND)
  12277. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12278. * pfd[i].revents == POLLIN. */
  12279. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12280. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12281. }
  12282. }
  12283. }
  12284. }
  12285. /* Here stop_flag is 1 - Initiate shutdown. */
  12286. DEBUG_TRACE("%s", "stopping workers");
  12287. /* Stop signal received: somebody called mg_stop. Quit. */
  12288. close_all_listening_sockets(ctx);
  12289. /* Wakeup workers that are waiting for connections to handle. */
  12290. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12291. #if defined(ALTERNATIVE_QUEUE)
  12292. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12293. event_signal(ctx->client_wait_events[i]);
  12294. /* Since we know all sockets, we can shutdown the connections. */
  12295. if (ctx->client_socks[i].in_use) {
  12296. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12297. }
  12298. }
  12299. #else
  12300. pthread_cond_broadcast(&ctx->sq_full);
  12301. #endif
  12302. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12303. /* Join all worker threads to avoid leaking threads. */
  12304. workerthreadcount = ctx->cfg_worker_threads;
  12305. for (i = 0; i < workerthreadcount; i++) {
  12306. if (ctx->worker_threadids[i] != 0) {
  12307. mg_join_thread(ctx->worker_threadids[i]);
  12308. }
  12309. }
  12310. #if defined(USE_LUA)
  12311. /* Free Lua state of lua background task */
  12312. if (ctx->lua_background_state) {
  12313. lua_close((lua_State *)ctx->lua_background_state);
  12314. ctx->lua_background_state = 0;
  12315. }
  12316. #endif
  12317. #if !defined(NO_SSL)
  12318. if (ctx->ssl_ctx != NULL) {
  12319. uninitialize_ssl(ctx);
  12320. }
  12321. #endif
  12322. DEBUG_TRACE("%s", "exiting");
  12323. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12324. CloseHandle(tls.pthread_cond_helper_mutex);
  12325. #endif
  12326. pthread_setspecific(sTlsKey, NULL);
  12327. /* Signal mg_stop() that we're done.
  12328. * WARNING: This must be the very last thing this
  12329. * thread does, as ctx becomes invalid after this line. */
  12330. ctx->stop_flag = 2;
  12331. }
  12332. /* Threads have different return types on Windows and Unix. */
  12333. #ifdef _WIN32
  12334. static unsigned __stdcall master_thread(void *thread_func_param)
  12335. {
  12336. master_thread_run(thread_func_param);
  12337. return 0;
  12338. }
  12339. #else
  12340. static void *
  12341. master_thread(void *thread_func_param)
  12342. {
  12343. master_thread_run(thread_func_param);
  12344. return NULL;
  12345. }
  12346. #endif /* _WIN32 */
  12347. static void
  12348. free_context(struct mg_context *ctx)
  12349. {
  12350. int i;
  12351. struct mg_handler_info *tmp_rh;
  12352. if (ctx == NULL) {
  12353. return;
  12354. }
  12355. if (ctx->callbacks.exit_context) {
  12356. ctx->callbacks.exit_context(ctx);
  12357. }
  12358. /* All threads exited, no sync is needed. Destroy thread mutex and
  12359. * condvars
  12360. */
  12361. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12362. #if defined(ALTERNATIVE_QUEUE)
  12363. mg_free(ctx->client_socks);
  12364. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12365. event_destroy(ctx->client_wait_events[i]);
  12366. }
  12367. mg_free(ctx->client_wait_events);
  12368. #else
  12369. (void)pthread_cond_destroy(&ctx->sq_empty);
  12370. (void)pthread_cond_destroy(&ctx->sq_full);
  12371. #endif
  12372. /* Destroy other context global data structures mutex */
  12373. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12374. #if defined(USE_TIMERS)
  12375. timers_exit(ctx);
  12376. #endif
  12377. /* Deallocate config parameters */
  12378. for (i = 0; i < NUM_OPTIONS; i++) {
  12379. if (ctx->config[i] != NULL) {
  12380. #if defined(_MSC_VER)
  12381. #pragma warning(suppress : 6001)
  12382. #endif
  12383. mg_free(ctx->config[i]);
  12384. }
  12385. }
  12386. /* Deallocate request handlers */
  12387. while (ctx->handlers) {
  12388. tmp_rh = ctx->handlers;
  12389. ctx->handlers = tmp_rh->next;
  12390. mg_free(tmp_rh->uri);
  12391. mg_free(tmp_rh);
  12392. }
  12393. #ifndef NO_SSL
  12394. /* Deallocate SSL context */
  12395. if (ctx->ssl_ctx != NULL) {
  12396. SSL_CTX_free(ctx->ssl_ctx);
  12397. }
  12398. #endif /* !NO_SSL */
  12399. /* Deallocate worker thread ID array */
  12400. if (ctx->worker_threadids != NULL) {
  12401. mg_free(ctx->worker_threadids);
  12402. }
  12403. /* Deallocate worker thread ID array */
  12404. if (ctx->worker_connections != NULL) {
  12405. mg_free(ctx->worker_connections);
  12406. }
  12407. /* Deallocate the tls variable */
  12408. if (mg_atomic_dec(&sTlsInit) == 0) {
  12409. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12410. DeleteCriticalSection(&global_log_file_lock);
  12411. #endif /* _WIN32 && !__SYMBIAN32__ */
  12412. #if !defined(_WIN32)
  12413. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12414. #endif
  12415. pthread_key_delete(sTlsKey);
  12416. #if defined(USE_LUA)
  12417. lua_exit_optional_libraries();
  12418. #endif
  12419. }
  12420. /* deallocate system name string */
  12421. mg_free(ctx->systemName);
  12422. /* Deallocate context itself */
  12423. mg_free(ctx);
  12424. }
  12425. void
  12426. mg_stop(struct mg_context *ctx)
  12427. {
  12428. pthread_t mt;
  12429. if (!ctx) {
  12430. return;
  12431. }
  12432. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12433. * two threads is not allowed. */
  12434. mt = ctx->masterthreadid;
  12435. if (mt == 0) {
  12436. return;
  12437. }
  12438. ctx->masterthreadid = 0;
  12439. /* Set stop flag, so all threads know they have to exit. */
  12440. ctx->stop_flag = 1;
  12441. /* Wait until everything has stopped. */
  12442. while (ctx->stop_flag != 2) {
  12443. (void)mg_sleep(10);
  12444. }
  12445. mg_join_thread(mt);
  12446. free_context(ctx);
  12447. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12448. (void)WSACleanup();
  12449. #endif /* _WIN32 && !__SYMBIAN32__ */
  12450. }
  12451. static void
  12452. get_system_name(char **sysName)
  12453. {
  12454. #if defined(_WIN32)
  12455. #if !defined(__SYMBIAN32__)
  12456. #if defined(_WIN32_WCE)
  12457. *sysName = mg_strdup("WinCE");
  12458. #else
  12459. char name[128];
  12460. DWORD dwVersion = 0;
  12461. DWORD dwMajorVersion = 0;
  12462. DWORD dwMinorVersion = 0;
  12463. DWORD dwBuild = 0;
  12464. #ifdef _MSC_VER
  12465. #pragma warning(push)
  12466. /* GetVersion was declared deprecated */
  12467. #pragma warning(disable : 4996)
  12468. #endif
  12469. dwVersion = GetVersion();
  12470. #ifdef _MSC_VER
  12471. #pragma warning(pop)
  12472. #endif
  12473. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12474. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12475. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12476. (void)dwBuild;
  12477. sprintf(name,
  12478. "Windows %u.%u",
  12479. (unsigned)dwMajorVersion,
  12480. (unsigned)dwMinorVersion);
  12481. *sysName = mg_strdup(name);
  12482. #endif
  12483. #else
  12484. *sysName = mg_strdup("Symbian");
  12485. #endif
  12486. #else
  12487. struct utsname name;
  12488. memset(&name, 0, sizeof(name));
  12489. uname(&name);
  12490. *sysName = mg_strdup(name.sysname);
  12491. #endif
  12492. }
  12493. struct mg_context *
  12494. mg_start(const struct mg_callbacks *callbacks,
  12495. void *user_data,
  12496. const char **options)
  12497. {
  12498. struct mg_context *ctx;
  12499. const char *name, *value, *default_value;
  12500. int idx, ok, workerthreadcount;
  12501. unsigned int i;
  12502. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12503. struct mg_workerTLS tls;
  12504. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12505. WSADATA data;
  12506. WSAStartup(MAKEWORD(2, 2), &data);
  12507. #endif /* _WIN32 && !__SYMBIAN32__ */
  12508. /* Allocate context and initialize reasonable general case defaults. */
  12509. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12510. return NULL;
  12511. }
  12512. /* Random number generator will initialize at the first call */
  12513. ctx->auth_nonce_mask =
  12514. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12515. if (mg_atomic_inc(&sTlsInit) == 1) {
  12516. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12517. InitializeCriticalSection(&global_log_file_lock);
  12518. #endif /* _WIN32 && !__SYMBIAN32__ */
  12519. #if !defined(_WIN32)
  12520. pthread_mutexattr_init(&pthread_mutex_attr);
  12521. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12522. #endif
  12523. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12524. /* Fatal error - abort start. However, this situation should
  12525. * never
  12526. * occur in practice. */
  12527. mg_atomic_dec(&sTlsInit);
  12528. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12529. mg_free(ctx);
  12530. return NULL;
  12531. }
  12532. #if defined(USE_LUA)
  12533. lua_init_optional_libraries();
  12534. #endif
  12535. } else {
  12536. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12537. * initialized. */
  12538. mg_sleep(1);
  12539. }
  12540. tls.is_master = -1;
  12541. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12542. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12543. tls.pthread_cond_helper_mutex = NULL;
  12544. #endif
  12545. pthread_setspecific(sTlsKey, &tls);
  12546. /* Dummy use this function - in some #ifdef combinations it's used,
  12547. * while it's not used in others, but GCC seems to stupid to understand
  12548. * #pragma GCC diagnostic ignored "-Wunused-function"
  12549. * in cases the function is unused, and it also complains on
  12550. * __attribute((unused))__ in cases it is used.
  12551. * So dummy use it, to have our peace. */
  12552. (void)mg_current_thread_id();
  12553. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12554. #if !defined(ALTERNATIVE_QUEUE)
  12555. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12556. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12557. #endif
  12558. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12559. if (!ok) {
  12560. /* Fatal error - abort start. However, this situation should never
  12561. * occur in practice. */
  12562. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12563. mg_free(ctx);
  12564. pthread_setspecific(sTlsKey, NULL);
  12565. return NULL;
  12566. }
  12567. if (callbacks) {
  12568. ctx->callbacks = *callbacks;
  12569. exit_callback = callbacks->exit_context;
  12570. ctx->callbacks.exit_context = 0;
  12571. }
  12572. ctx->user_data = user_data;
  12573. ctx->handlers = NULL;
  12574. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12575. ctx->shared_lua_websockets = 0;
  12576. #endif
  12577. while (options && (name = *options++) != NULL) {
  12578. if ((idx = get_option_index(name)) == -1) {
  12579. mg_cry(fc(ctx), "Invalid option: %s", name);
  12580. free_context(ctx);
  12581. pthread_setspecific(sTlsKey, NULL);
  12582. return NULL;
  12583. } else if ((value = *options++) == NULL) {
  12584. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12585. free_context(ctx);
  12586. pthread_setspecific(sTlsKey, NULL);
  12587. return NULL;
  12588. }
  12589. if (ctx->config[idx] != NULL) {
  12590. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12591. mg_free(ctx->config[idx]);
  12592. }
  12593. ctx->config[idx] = mg_strdup(value);
  12594. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12595. }
  12596. /* Set default value if needed */
  12597. for (i = 0; config_options[i].name != NULL; i++) {
  12598. default_value = config_options[i].default_value;
  12599. if (ctx->config[i] == NULL && default_value != NULL) {
  12600. ctx->config[i] = mg_strdup(default_value);
  12601. }
  12602. }
  12603. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12604. if (workerthreadcount > MAX_WORKER_THREADS) {
  12605. mg_cry(fc(ctx), "Too many worker threads");
  12606. free_context(ctx);
  12607. pthread_setspecific(sTlsKey, NULL);
  12608. return NULL;
  12609. }
  12610. if (workerthreadcount <= 0) {
  12611. mg_cry(fc(ctx), "Invalid number of worker threads");
  12612. free_context(ctx);
  12613. pthread_setspecific(sTlsKey, NULL);
  12614. return NULL;
  12615. }
  12616. #if defined(NO_FILES)
  12617. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12618. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12619. free_context(ctx);
  12620. pthread_setspecific(sTlsKey, NULL);
  12621. return NULL;
  12622. }
  12623. #endif
  12624. get_system_name(&ctx->systemName);
  12625. #if defined(USE_LUA)
  12626. /* If a Lua background script has been configured, start it. */
  12627. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  12628. char ebuf[256];
  12629. void *state = (void *)mg_prepare_lua_context_script(
  12630. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  12631. if (!state) {
  12632. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  12633. free_context(ctx);
  12634. pthread_setspecific(sTlsKey, NULL);
  12635. return NULL;
  12636. }
  12637. ctx->lua_background_state = state;
  12638. } else {
  12639. ctx->lua_background_state = 0;
  12640. }
  12641. #endif
  12642. /* NOTE(lsm): order is important here. SSL certificates must
  12643. * be initialized before listening ports. UID must be set last. */
  12644. if (!set_gpass_option(ctx) ||
  12645. #if !defined(NO_SSL)
  12646. !set_ssl_option(ctx) ||
  12647. #endif
  12648. !set_ports_option(ctx) ||
  12649. #if !defined(_WIN32)
  12650. !set_uid_option(ctx) ||
  12651. #endif
  12652. !set_acl_option(ctx)) {
  12653. free_context(ctx);
  12654. pthread_setspecific(sTlsKey, NULL);
  12655. return NULL;
  12656. }
  12657. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12658. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12659. * won't kill the whole process. */
  12660. (void)signal(SIGPIPE, SIG_IGN);
  12661. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12662. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12663. ctx->worker_threadids =
  12664. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12665. if (ctx->worker_threadids == NULL) {
  12666. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12667. free_context(ctx);
  12668. pthread_setspecific(sTlsKey, NULL);
  12669. return NULL;
  12670. }
  12671. ctx->worker_connections =
  12672. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  12673. sizeof(struct mg_connection));
  12674. if (ctx->worker_connections == NULL) {
  12675. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  12676. free_context(ctx);
  12677. pthread_setspecific(sTlsKey, NULL);
  12678. return NULL;
  12679. }
  12680. #if defined(ALTERNATIVE_QUEUE)
  12681. ctx->client_wait_events =
  12682. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  12683. if (ctx->client_wait_events == NULL) {
  12684. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12685. mg_free(ctx->worker_threadids);
  12686. free_context(ctx);
  12687. pthread_setspecific(sTlsKey, NULL);
  12688. return NULL;
  12689. }
  12690. ctx->client_socks =
  12691. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12692. if (ctx->client_wait_events == NULL) {
  12693. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12694. mg_free(ctx->client_socks);
  12695. mg_free(ctx->worker_threadids);
  12696. free_context(ctx);
  12697. pthread_setspecific(sTlsKey, NULL);
  12698. return NULL;
  12699. }
  12700. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12701. ctx->client_wait_events[i] = event_create();
  12702. if (ctx->client_wait_events[i] == 0) {
  12703. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12704. while (i > 0) {
  12705. i--;
  12706. event_destroy(ctx->client_wait_events[i]);
  12707. }
  12708. mg_free(ctx->client_socks);
  12709. mg_free(ctx->worker_threadids);
  12710. free_context(ctx);
  12711. pthread_setspecific(sTlsKey, NULL);
  12712. return NULL;
  12713. }
  12714. }
  12715. #endif
  12716. #if defined(USE_TIMERS)
  12717. if (timers_init(ctx) != 0) {
  12718. mg_cry(fc(ctx), "Error creating timers");
  12719. free_context(ctx);
  12720. pthread_setspecific(sTlsKey, NULL);
  12721. return NULL;
  12722. }
  12723. #endif
  12724. /* Context has been created - init user libraries */
  12725. if (ctx->callbacks.init_context) {
  12726. ctx->callbacks.init_context(ctx);
  12727. }
  12728. ctx->callbacks.exit_context = exit_callback;
  12729. ctx->context_type = 1; /* server context */
  12730. /* Start master (listening) thread */
  12731. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12732. /* Start worker threads */
  12733. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12734. struct worker_thread_args *wta =
  12735. mg_malloc(sizeof(struct worker_thread_args));
  12736. if (wta) {
  12737. wta->ctx = ctx;
  12738. wta->index = (int)i;
  12739. }
  12740. if ((wta == NULL)
  12741. || (mg_start_thread_with_id(worker_thread,
  12742. wta,
  12743. &ctx->worker_threadids[i]) != 0)) {
  12744. /* thread was not created */
  12745. if (wta != NULL) {
  12746. mg_free(wta);
  12747. }
  12748. if (i > 0) {
  12749. mg_cry(fc(ctx),
  12750. "Cannot start worker thread %i: error %ld",
  12751. i + 1,
  12752. (long)ERRNO);
  12753. } else {
  12754. mg_cry(fc(ctx),
  12755. "Cannot create threads: error %ld",
  12756. (long)ERRNO);
  12757. free_context(ctx);
  12758. pthread_setspecific(sTlsKey, NULL);
  12759. return NULL;
  12760. }
  12761. break;
  12762. }
  12763. }
  12764. pthread_setspecific(sTlsKey, NULL);
  12765. return ctx;
  12766. }
  12767. /* Feature check API function */
  12768. unsigned
  12769. mg_check_feature(unsigned feature)
  12770. {
  12771. static const unsigned feature_set = 0
  12772. /* Set bits for available features according to API documentation.
  12773. * This bit mask is created at compile time, according to the active
  12774. * preprocessor defines. It is a single const value at runtime. */
  12775. #if !defined(NO_FILES)
  12776. | 0x0001u
  12777. #endif
  12778. #if !defined(NO_SSL)
  12779. | 0x0002u
  12780. #endif
  12781. #if !defined(NO_CGI)
  12782. | 0x0004u
  12783. #endif
  12784. #if defined(USE_IPV6)
  12785. | 0x0008u
  12786. #endif
  12787. #if defined(USE_WEBSOCKET)
  12788. | 0x0010u
  12789. #endif
  12790. #if defined(USE_LUA)
  12791. | 0x0020u
  12792. #endif
  12793. #if defined(USE_DUKTAPE)
  12794. | 0x0040u
  12795. #endif
  12796. #if !defined(NO_CACHING)
  12797. | 0x0080u
  12798. #endif
  12799. /* Set some extra bits not defined in the API documentation.
  12800. * These bits may change without further notice. */
  12801. #if defined(MG_LEGACY_INTERFACE)
  12802. | 0x8000u
  12803. #endif
  12804. #if defined(MEMORY_DEBUGGING)
  12805. | 0x0100u
  12806. #endif
  12807. #if defined(USE_TIMERS)
  12808. | 0x0200u
  12809. #endif
  12810. #if !defined(NO_NONCE_CHECK)
  12811. | 0x0400u
  12812. #endif
  12813. #if !defined(NO_POPEN)
  12814. | 0x0800u
  12815. #endif
  12816. ;
  12817. return (feature & feature_set);
  12818. }
  12819. /* Get system information. It can be printed or stored by the caller.
  12820. * Return the size of available information. */
  12821. static int
  12822. mg_get_system_info_impl(char *buffer, int buflen)
  12823. {
  12824. char block[256];
  12825. int system_info_length = 0;
  12826. #if defined(_WIN32)
  12827. const char *eol = "\r\n";
  12828. #else
  12829. const char *eol = "\n";
  12830. #endif
  12831. /* Server version */
  12832. {
  12833. const char *version = mg_version();
  12834. mg_snprintf(NULL,
  12835. NULL,
  12836. block,
  12837. sizeof(block),
  12838. "Server Version: %s%s",
  12839. version,
  12840. eol);
  12841. system_info_length += (int)strlen(block);
  12842. if (system_info_length < buflen) {
  12843. strcat(buffer, block);
  12844. }
  12845. }
  12846. /* System info */
  12847. {
  12848. #if defined(_WIN32)
  12849. #if !defined(__SYMBIAN32__)
  12850. DWORD dwVersion = 0;
  12851. DWORD dwMajorVersion = 0;
  12852. DWORD dwMinorVersion = 0;
  12853. SYSTEM_INFO si;
  12854. GetSystemInfo(&si);
  12855. #ifdef _MSC_VER
  12856. #pragma warning(push)
  12857. /* GetVersion was declared deprecated */
  12858. #pragma warning(disable : 4996)
  12859. #endif
  12860. dwVersion = GetVersion();
  12861. #ifdef _MSC_VER
  12862. #pragma warning(pop)
  12863. #endif
  12864. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12865. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12866. mg_snprintf(NULL,
  12867. NULL,
  12868. block,
  12869. sizeof(block),
  12870. "Windows %u.%u%s",
  12871. (unsigned)dwMajorVersion,
  12872. (unsigned)dwMinorVersion,
  12873. eol);
  12874. system_info_length += (int)strlen(block);
  12875. if (system_info_length < buflen) {
  12876. strcat(buffer, block);
  12877. }
  12878. mg_snprintf(NULL,
  12879. NULL,
  12880. block,
  12881. sizeof(block),
  12882. "CPU: type %u, cores %u, mask %x%s",
  12883. (unsigned)si.wProcessorArchitecture,
  12884. (unsigned)si.dwNumberOfProcessors,
  12885. (unsigned)si.dwActiveProcessorMask,
  12886. eol);
  12887. system_info_length += (int)strlen(block);
  12888. if (system_info_length < buflen) {
  12889. strcat(buffer, block);
  12890. }
  12891. #else
  12892. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  12893. system_info_length += (int)strlen(block);
  12894. if (system_info_length < buflen) {
  12895. strcat(buffer, block);
  12896. }
  12897. #endif
  12898. #else
  12899. struct utsname name;
  12900. memset(&name, 0, sizeof(name));
  12901. uname(&name);
  12902. mg_snprintf(NULL,
  12903. NULL,
  12904. block,
  12905. sizeof(block),
  12906. "%s %s (%s) - %s%s",
  12907. name.sysname,
  12908. name.version,
  12909. name.release,
  12910. name.machine,
  12911. eol);
  12912. system_info_length += (int)strlen(block);
  12913. if (system_info_length < buflen) {
  12914. strcat(buffer, block);
  12915. }
  12916. #endif
  12917. }
  12918. /* Features */
  12919. {
  12920. mg_snprintf(NULL,
  12921. NULL,
  12922. block,
  12923. sizeof(block),
  12924. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  12925. mg_check_feature(0xFFFFFFFFu),
  12926. eol,
  12927. mg_check_feature(1) ? " Files" : "",
  12928. mg_check_feature(2) ? " HTTPS" : "",
  12929. mg_check_feature(4) ? " CGI" : "",
  12930. mg_check_feature(8) ? " IPv6" : "",
  12931. mg_check_feature(16) ? " WebSockets" : "",
  12932. mg_check_feature(32) ? " Lua" : "",
  12933. mg_check_feature(64) ? " JavaScript" : "",
  12934. mg_check_feature(128) ? " Cache" : "",
  12935. eol);
  12936. system_info_length += (int)strlen(block);
  12937. if (system_info_length < buflen) {
  12938. strcat(buffer, block);
  12939. }
  12940. #ifdef USE_LUA
  12941. mg_snprintf(NULL,
  12942. NULL,
  12943. block,
  12944. sizeof(block),
  12945. "Lua Version: %u (%s)%s",
  12946. (unsigned)LUA_VERSION_NUM,
  12947. LUA_RELEASE,
  12948. eol);
  12949. system_info_length += (int)strlen(block);
  12950. if (system_info_length < buflen) {
  12951. strcat(buffer, block);
  12952. }
  12953. #endif
  12954. #if defined(USE_DUKTAPE)
  12955. mg_snprintf(NULL,
  12956. NULL,
  12957. block,
  12958. sizeof(block),
  12959. "JavaScript: Duktape %u.%u.%u%s",
  12960. (unsigned)DUK_VERSION / 10000,
  12961. ((unsigned)DUK_VERSION / 100) % 100,
  12962. (unsigned)DUK_VERSION % 100,
  12963. eol);
  12964. system_info_length += (int)strlen(block);
  12965. if (system_info_length < buflen) {
  12966. strcat(buffer, block);
  12967. }
  12968. #endif
  12969. }
  12970. /* Build date */
  12971. {
  12972. mg_snprintf(
  12973. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  12974. system_info_length += (int)strlen(block);
  12975. if (system_info_length < buflen) {
  12976. strcat(buffer, block);
  12977. }
  12978. }
  12979. /* Compiler information */
  12980. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  12981. {
  12982. #if defined(_MSC_VER)
  12983. mg_snprintf(NULL,
  12984. NULL,
  12985. block,
  12986. sizeof(block),
  12987. "MSC: %u (%u)%s",
  12988. (unsigned)_MSC_VER,
  12989. (unsigned)_MSC_FULL_VER,
  12990. eol);
  12991. system_info_length += (int)strlen(block);
  12992. if (system_info_length < buflen) {
  12993. strcat(buffer, block);
  12994. }
  12995. #elif defined(__MINGW64__)
  12996. mg_snprintf(NULL,
  12997. NULL,
  12998. block,
  12999. sizeof(block),
  13000. "MinGW64: %u.%u%s",
  13001. (unsigned)__MINGW64_VERSION_MAJOR,
  13002. (unsigned)__MINGW64_VERSION_MINOR,
  13003. eol);
  13004. system_info_length += (int)strlen(block);
  13005. if (system_info_length < buflen) {
  13006. strcat(buffer, block);
  13007. }
  13008. mg_snprintf(NULL,
  13009. NULL,
  13010. block,
  13011. sizeof(block),
  13012. "MinGW32: %u.%u%s",
  13013. (unsigned)__MINGW32_MAJOR_VERSION,
  13014. (unsigned)__MINGW32_MINOR_VERSION,
  13015. eol);
  13016. system_info_length += (int)strlen(block);
  13017. if (system_info_length < buflen) {
  13018. strcat(buffer, block);
  13019. }
  13020. #elif defined(__MINGW32__)
  13021. mg_snprintf(NULL,
  13022. NULL,
  13023. block,
  13024. sizeof(block),
  13025. "MinGW32: %u.%u%s",
  13026. (unsigned)__MINGW32_MAJOR_VERSION,
  13027. (unsigned)__MINGW32_MINOR_VERSION,
  13028. eol);
  13029. system_info_length += (int)strlen(block);
  13030. if (system_info_length < buflen) {
  13031. strcat(buffer, block);
  13032. }
  13033. #elif defined(__clang__)
  13034. mg_snprintf(NULL,
  13035. NULL,
  13036. block,
  13037. sizeof(block),
  13038. "clang: %u.%u.%u (%s)%s",
  13039. __clang_major__,
  13040. __clang_minor__,
  13041. __clang_patchlevel__,
  13042. __clang_version__,
  13043. eol);
  13044. system_info_length += (int)strlen(block);
  13045. if (system_info_length < buflen) {
  13046. strcat(buffer, block);
  13047. }
  13048. #elif defined(__GNUC__)
  13049. mg_snprintf(NULL,
  13050. NULL,
  13051. block,
  13052. sizeof(block),
  13053. "gcc: %u.%u.%u%s",
  13054. (unsigned)__GNUC__,
  13055. (unsigned)__GNUC_MINOR__,
  13056. (unsigned)__GNUC_PATCHLEVEL__,
  13057. eol);
  13058. system_info_length += (int)strlen(block);
  13059. if (system_info_length < buflen) {
  13060. strcat(buffer, block);
  13061. }
  13062. #elif defined(__INTEL_COMPILER)
  13063. mg_snprintf(NULL,
  13064. NULL,
  13065. block,
  13066. sizeof(block),
  13067. "Intel C/C++: %u%s",
  13068. (unsigned)__INTEL_COMPILER,
  13069. eol);
  13070. system_info_length += (int)strlen(block);
  13071. if (system_info_length < buflen) {
  13072. strcat(buffer, block);
  13073. }
  13074. #elif defined(__BORLANDC__)
  13075. mg_snprintf(NULL,
  13076. NULL,
  13077. block,
  13078. sizeof(block),
  13079. "Borland C: 0x%x%s",
  13080. (unsigned)__BORLANDC__,
  13081. eol);
  13082. system_info_length += (int)strlen(block);
  13083. if (system_info_length < buflen) {
  13084. strcat(buffer, block);
  13085. }
  13086. #elif defined(__SUNPRO_C)
  13087. mg_snprintf(NULL,
  13088. NULL,
  13089. block,
  13090. sizeof(block),
  13091. "Solaris: 0x%x%s",
  13092. (unsigned)__SUNPRO_C,
  13093. eol);
  13094. system_info_length += (int)strlen(block);
  13095. if (system_info_length < buflen) {
  13096. strcat(buffer, block);
  13097. }
  13098. #else
  13099. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13100. system_info_length += (int)strlen(block);
  13101. if (system_info_length < buflen) {
  13102. strcat(buffer, block);
  13103. }
  13104. #endif
  13105. }
  13106. /* Determine 32/64 bit data mode.
  13107. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13108. {
  13109. mg_snprintf(NULL,
  13110. NULL,
  13111. block,
  13112. sizeof(block),
  13113. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13114. "ptr:%u, size:%u, time:%u%s",
  13115. (unsigned)sizeof(short),
  13116. (unsigned)sizeof(int),
  13117. (unsigned)sizeof(long),
  13118. (unsigned)sizeof(long long),
  13119. (unsigned)sizeof(float),
  13120. (unsigned)sizeof(double),
  13121. (unsigned)sizeof(long double),
  13122. (unsigned)sizeof(char),
  13123. (unsigned)sizeof(wchar_t),
  13124. (unsigned)sizeof(void *),
  13125. (unsigned)sizeof(size_t),
  13126. (unsigned)sizeof(time_t),
  13127. eol);
  13128. system_info_length += (int)strlen(block);
  13129. if (system_info_length < buflen) {
  13130. strcat(buffer, block);
  13131. }
  13132. }
  13133. return system_info_length;
  13134. }
  13135. /* Get system information. It can be printed or stored by the caller.
  13136. * Return the size of available information. */
  13137. int
  13138. mg_get_system_info(char *buffer, int buflen)
  13139. {
  13140. if ((buffer == NULL) || (buflen < 1)) {
  13141. return mg_get_system_info_impl(NULL, 0);
  13142. } else {
  13143. /* Reset buffer, so we can always use strcat. */
  13144. buffer[0] = 0;
  13145. return mg_get_system_info_impl(buffer, buflen);
  13146. }
  13147. }
  13148. /* mg_init_library counter */
  13149. static int mg_init_library_called = 0;
  13150. /* Initialize this library. This function does not need to be thread safe. */
  13151. unsigned
  13152. mg_init_library(unsigned features)
  13153. {
  13154. /* Currently we do nothing here. This is planned for Version 1.10.
  13155. * For now, we just add this function, so clients can be changed early. */
  13156. if (mg_init_library_called <= 0) {
  13157. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13158. WSADATA data;
  13159. WSAStartup(MAKEWORD(2, 2), &data);
  13160. #endif /* _WIN32 && !__SYMBIAN32__ */
  13161. mg_init_library_called = 1;
  13162. } else {
  13163. mg_init_library_called++;
  13164. }
  13165. return mg_check_feature(features & 0xFFu);
  13166. }
  13167. /* Un-initialize this library. */
  13168. unsigned
  13169. mg_exit_library(void)
  13170. {
  13171. if (mg_init_library_called <= 0) {
  13172. return 0;
  13173. }
  13174. mg_init_library_called--;
  13175. if (mg_init_library_called == 0) {
  13176. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13177. (void)WSACleanup();
  13178. #endif /* _WIN32 && !__SYMBIAN32__ */
  13179. }
  13180. return 1;
  13181. }
  13182. /* End of civetweb.c */